Skip to content

upstox/upstox-nodejs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Upstox Node Js SDK for API v2

Introduction

The official Node.js client for communicating with the Upstox API.

Upstox API is a set of rest APIs that provide data required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (using Websocket), and more, with the easy to understand API collection.

  • API version: v2
  • Build package: io.swagger.codegen.v3.generators.javascript.JavaScriptClientCodegen

This SDK is automatically generated by the Swagger Codegen project.

Documentation.

Upstox API Documentation

Installation

npm

npm install upstox-js-sdk --save

Examples

Sample Implementations can be found within /examples folder.

Sandbox Mode

We recommend using the sandbox environment for testing purposes. To enable sandbox mode, set the sandbox flag to true in the client object.

let UpstoxClient = require("upstox-js-sdk");
let sandboxClient = new UpstoxClient.ApiClient(true);
sandboxClient.authentications["OAUTH2"].accessToken = "SANDBOX_ACCESS_TOKEN";


let apiInstance = new UpstoxClient.OrderApiV3();
let body = new UpstoxClient.PlaceOrderV3Request(1,UpstoxClient.PlaceOrderV3Request.ProductEnum.D,
    UpstoxClient.PlaceOrderV3Request.ValidityEnum.DAY, 0,"NSE_EQ|INE528G01035",UpstoxClient.PlaceOrderV3Request.OrderTypeEnum.MARKET,
    UpstoxClient.PlaceOrderV3Request.TransactionTypeEnum.BUY,0,0,true);
let opt = {"slice": true}
apiInstance.placeOrder(body, opt, (error, data, response) => {
  if (error) {
    console.log("error->" + JSON.stringify(error));
  } else {
    console.log('API called successfully. Returned data: ' + JSON.stringify(data));
  }
});

To learn more about the sandbox environment and the available sandbox APIs, please visit the Upstox API documentation - Sandbox.

Documentation for API Endpoints

All URIs are relative to https://api.upstox.com

Class Method HTTP request Description
UpstoxClient.ChargeApi getBrokerage GET /v2/charges/brokerage Brokerage details
UpstoxClient.ChargeApi postMargin POST /v2/charges/margin Calculate Margin
UpstoxClient.ExpiredInstrumentApi getExpiredFutureContracts GET /v2/expired-instruments/future/contract Expired instruments - Get future contracts
UpstoxClient.ExpiredInstrumentApi getExpiredHistoricalCandleData GET /v2/expired-instruments/historical-candle/{expired_instrument_key}/{interval}/{to_date}/{from_date} Expired Historical candle data
UpstoxClient.ExpiredInstrumentApi getExpiredOptionContracts GET /v2/expired-instruments/option/contract Get expired option contracts
UpstoxClient.ExpiredInstrumentApi getExpiries GET /v2/expired-instruments/expiries Expired instruments - Get expiries
UpstoxClient.HistoryApi getHistoricalCandleData2 GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date} Historical candle data
UpstoxClient.HistoryApi getHistoricalCandleData3 GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date}/{from_date} Historical candle data
UpstoxClient.HistoryApi getIntraDayCandleData1 GET /v2/historical-candle/intraday/{instrumentKey}/{interval} Intra day candle data
UpstoxClient.HistoryV3Api getHistoricalCandleData GET /v3/historical-candle/{instrumentKey}/{unit}/{interval}/{to_date} Historical candle data
UpstoxClient.HistoryV3Api getHistoricalCandleData1 GET /v3/historical-candle/{instrumentKey}/{unit}/{interval}/{to_date}/{from_date} Historical candle data
UpstoxClient.HistoryV3Api getIntraDayCandleData GET /v3/historical-candle/intraday/{instrumentKey}/{unit}/{interval} Intra day candle data
UpstoxClient.LoginApi authorize GET /v2/login/authorization/dialog Authorize API
UpstoxClient.LoginApi initTokenRequestForIndieUser POST /v3/login/auth/token/request/{client_id} Init token API
UpstoxClient.LoginApi logout DELETE /v2/logout Logout
UpstoxClient.LoginApi token POST /v2/login/authorization/token Get token API
UpstoxClient.MarketHolidaysAndTimingsApi getExchangeTimings GET /v2/market/timings/{date} Get Exchange Timings on particular date
UpstoxClient.MarketHolidaysAndTimingsApi getHoliday GET /v2/market/holidays/{date} Get Holiday on particular date
UpstoxClient.MarketHolidaysAndTimingsApi getHolidays GET /v2/market/holidays Get Holiday list of current year
UpstoxClient.MarketHolidaysAndTimingsApi getMarketStatus GET /v2/market/status/{exchange} Get Market status for particular exchange
UpstoxClient.MarketQuoteApi getFullMarketQuote GET /v2/market-quote/quotes Market quotes and instruments - Full market quotes
UpstoxClient.MarketQuoteApi getMarketQuoteOHLC GET /v2/market-quote/ohlc Market quotes and instruments - OHLC quotes
UpstoxClient.MarketQuoteApi ltp GET /v2/market-quote/ltp Market quotes and instruments - LTP quotes.
UpstoxClient.MarketQuoteV3Api getLtp GET /v3/market-quote/ltp Market quotes and instruments - LTP quotes.
UpstoxClient.MarketQuoteV3Api getMarketQuoteOHLC GET /v3/market-quote/ohlc Market quotes and instruments - OHLC quotes
UpstoxClient.MarketQuoteV3Api getMarketQuoteOptionGreek GET /v3/market-quote/option-greek Market quotes and instruments - Option Greek
UpstoxClient.OptionsApi getOptionContracts GET /v2/option/contract Get option contracts
UpstoxClient.OptionsApi getPutCallOptionChain GET /v2/option/chain Get option chain
UpstoxClient.OrderApi cancelMultiOrder DELETE /v2/order/multi/cancel Cancel multi order
UpstoxClient.OrderApi cancelOrder DELETE /v2/order/cancel Cancel order
UpstoxClient.OrderApi exitPositions POST /v2/order/positions/exit Exit all positions
UpstoxClient.OrderApi getOrderBook GET /v2/order/retrieve-all Get order book
UpstoxClient.OrderApi getOrderDetails GET /v2/order/history Get order history
UpstoxClient.OrderApi getOrderStatus GET /v2/order/details Get order details
UpstoxClient.OrderApi getTradeHistory GET /v2/order/trades/get-trades-for-day Get trades
UpstoxClient.OrderApi getTradesByOrder GET /v2/order/trades Get trades for order
UpstoxClient.OrderApi modifyOrder PUT /v2/order/modify Modify order
UpstoxClient.OrderApi placeMultiOrder POST /v2/order/multi/place Place multi order
UpstoxClient.OrderApi placeOrder1 POST /v2/order/place Place order
UpstoxClient.OrderControllerV3Api cancelGTTOrder DELETE /v3/order/gtt/cancel Cancel GTT order
UpstoxClient.OrderControllerV3Api cancelOrder DELETE /v3/order/cancel
UpstoxClient.OrderControllerV3Api getGttOrderDetails GET /v3/order/gtt Get GTT order details
UpstoxClient.OrderControllerV3Api modifyGTTOrder PUT /v3/order/gtt/modify Modify GTT order
UpstoxClient.OrderControllerV3Api modifyOrder PUT /v3/order/modify
UpstoxClient.OrderControllerV3Api placeGTTOrder POST /v3/order/gtt/place Place GTT order
UpstoxClient.OrderControllerV3Api placeOrder POST /v3/order/place
UpstoxClient.PortfolioApi convertPositions PUT /v2/portfolio/convert-position Convert Positions
UpstoxClient.PortfolioApi getHoldings GET /v2/portfolio/long-term-holdings Get Holdings
UpstoxClient.PortfolioApi getMtfPositions GET /v3/portfolio/mtf-positions Get MTF positions
UpstoxClient.PortfolioApi getPositions GET /v2/portfolio/short-term-positions Get Positions
UpstoxClient.PostTradeApi getTradesByDateRange GET /v2/charges/historical-trades
UpstoxClient.TradeProfitAndLossApi getProfitAndLossCharges GET /v2/trade/profit-loss/charges Get profit and loss on trades
UpstoxClient.TradeProfitAndLossApi getTradeWiseProfitAndLossData GET /v2/trade/profit-loss/data Get Trade-wise Profit and Loss Report Data
UpstoxClient.TradeProfitAndLossApi getTradeWiseProfitAndLossMetaData GET /v2/trade/profit-loss/metadata Get profit and loss meta data on trades
UpstoxClient.UserApi getProfile GET /v2/user/profile Get profile
UpstoxClient.UserApi getUserFundMargin GET /v2/user/get-funds-and-margin Get User Fund And Margin
UpstoxClient.WebsocketApi getMarketDataFeed GET /v2/feed/market-data-feed Market Data Feed
UpstoxClient.WebsocketApi getMarketDataFeedAuthorize GET /v2/feed/market-data-feed/authorize Market Data Feed Authorize
UpstoxClient.WebsocketApi getPortfolioStreamFeed GET /v2/feed/portfolio-stream-feed Portfolio Stream Feed
UpstoxClient.WebsocketApi getPortfolioStreamFeedAuthorize GET /v2/feed/portfolio-stream-feed/authorize Portfolio Stream Feed Authorize

Documentation for Feeder Functions

Connecting to the WebSocket for market and portfolio updates is streamlined through two primary Feeder functions:

  1. MarketDataStreamer: Offers real-time market updates, providing a seamless way to receive instantaneous information on various market instruments.
  2. PortfolioDataStreamer: Delivers updates related to the user's orders, enhancing the ability to track order status and portfolio changes effectively.

Both functions are designed to simplify the process of subscribing to essential data streams, ensuring users have quick and easy access to the information they need.

Detailed Explanation of Feeder Functions

MarketDataStreamer

V3

The MarketDataStreamerV3 function is designed for effortless connection to the market WebSocket, enabling users to receive instantaneous updates on various instruments. The following example demonstrates how to quickly set up and start receiving market updates for selected instrument keys:

let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3(["MCX_FO|426268", "MCX_FO|427608"], "full");
streamer.connect();

streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

In this example, you first authenticate using an access token, then instantiate MarketDataStreamerV3 with specific instrument keys and a subscription mode. Upon connecting, the streamer listens for market updates, which are logged to the console as they arrive.

Feel free to adjust the access token placeholder and any other specifics to better fit your actual implementation or usage scenario.

Exploring the MarketDataStreamerV3 Functionality

Modes

  • ltpc: ltpc provides information solely about the most recent trade, encompassing details such as the last trade price, time of the last trade, quantity traded, and the closing price from the previous day.
  • full: The full option offers comprehensive information, including the latest trade prices, D5 depth, 1-minute, 30-minute, and daily candlestick data, along with some additional details.
  • full_d30: full_d30 includes Full mode data plus 30 market level quotes.
  • option_greeks: Contains only option greeks.

Functions

  1. constructor MarketDataStreamerV3(instrumentKeys, mode): Initializes the streamer with optional instrument keys and mode (full, ltpc, full_d30 or option_greeks).
  2. connect(): Establishes the WebSocket connection.
  3. subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
  4. unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
  5. changeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
  6. disconnect(): Ends the active WebSocket connection.
  7. autoReconnect(enable, interval, retryCount): Customizes auto-reconnect functionality. Parameters include a flag to enable/disable it, the interval(in seconds) between attempts, and the maximum number of retries.

Events

  • open: Emitted upon successful connection establishment.
  • close: Indicates the WebSocket connection has been closed.
  • message: Delivers market updates.
  • error: Signals an error has occurred.
  • reconnecting: Announced when a reconnect attempt is initiated.
  • autoReconnectStopped: Informs when auto-reconnect efforts have ceased after exhausting the retry count.

The following documentation includes examples to illustrate the usage of these functions and events, providing a practical understanding of how to interact with the MarketDataStreamerV3 effectively.


  1. Subscribing to Market Data on Connection Open with MarketDataStreameV3
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3();
streamer.connect();

// Subscribe to instrument keys upon the 'open' event
streamer.on("open", () => {
  streamer.subscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full");
});

// Handle incoming market data messages
streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

  1. Subscribing to Instruments with Delays
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3();
streamer.connect();

// Subscribe to the first set of instrument keys immediately upon connection
streamer.on("open", () => {
  streamer.subscribe(["NSE_EQ|INE020B01018"], "full");
  
  // Subscribe to another set of instrument keys after a delay
  setTimeout(() => {
    streamer.subscribe(["NSE_EQ|INE467B01029"], "full");
  }, 5000); // 5-second delay before subscribing to the second set
});

// Handle incoming market data messages
streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

  1. Subscribing and Unsubscribing to Instruments
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3();
streamer.connect();

// Subscribe to instrument keys immediately upon connection
streamer.on("open", () => {
  console.log("Connected. Subscribing to instrument keys.");
  streamer.subscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full");
  
  // Unsubscribe after a delay
  setTimeout(() => {
    console.log("Unsubscribing from instrument keys.");
    streamer.unsubscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"]);
  }, 5000); // Adjust delay as needed
});

streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log("Market Update:", feed);
});

  1. Subscribe, Change Mode and Unsubscribe
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3();
streamer.connect();

// Initially subscribe to instrument keys in 'full' mode
streamer.on("open", async () => {
  console.log("Connected. Subscribing in full mode...");
  streamer.subscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full");

  // Change mode to 'ltpc' after a short delay
  setTimeout(() => {
    console.log("Changing subscription mode to ltpc...");
    streamer.changeMode(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "ltpc");
  }, 5000); // 5-second delay

  // Unsubscribe after another delay
  setTimeout(() => {
    console.log("Unsubscribing...");
    streamer.unsubscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"]);
  }, 10000); // 10 seconds after subscription
});

// Setup event listeners to log messages, errors, and closure
streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log("Market Update:", feed);
});
streamer.on("error", (error) => console.error("Error:", error));
streamer.on("close", () => console.log("Connection closed."));

  1. Disable Auto-Reconnect
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3();
streamer.connect();

// Disable auto-reconnect feature
streamer.autoReconnect(false);

streamer.on("autoReconnectStopped", (data) => {
  console.log(data);
});

  1. Modify Auto-Reconnect parameters
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamerV3();
streamer.connect();

// Modify auto-reconnect parameters: enable it, set interval to 10 seconds, and retry count to 3
streamer.autoReconnect(true, 10, 3);

V2

The MarketDataStreamer function is designed for effortless connection to the market WebSocket, enabling users to receive instantaneous updates on various instruments. The following example demonstrates how to quickly set up and start receiving market updates for selected instrument keys:

let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer(["MCX_FO|426268", "MCX_FO|427608"], "full");
streamer.connect();

streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

In this example, you first authenticate using an access token, then instantiate MarketDataStreamer with specific instrument keys and a subscription mode. Upon connecting, the streamer listens for market updates, which are logged to the console as they arrive.

Feel free to adjust the access token placeholder and any other specifics to better fit your actual implementation or usage scenario.

Exploring the MarketDataStreamer Functionality

Modes

  • ltpc: ltpc provides information solely about the most recent trade, encompassing details such as the last trade price, time of the last trade, quantity traded, and the closing price from the previous day.
  • full: The full option offers comprehensive information, including the latest trade prices, D5 depth, 1-minute, 30-minute, and daily candlestick data, along with some additional details.

Functions

  1. constructor MarketDataStreamer(instrumentKeys, mode): Initializes the streamer with optional instrument keys and mode (full or ltpc).
  2. connect(): Establishes the WebSocket connection.
  3. subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
  4. unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
  5. changeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
  6. disconnect(): Ends the active WebSocket connection.
  7. autoReconnect(enable, interval, retryCount): Customizes auto-reconnect functionality. Parameters include a flag to enable/disable it, the interval(in seconds) between attempts, and the maximum number of retries.

Events

  • open: Emitted upon successful connection establishment.
  • close: Indicates the WebSocket connection has been closed.
  • message: Delivers market updates.
  • error: Signals an error has occurred.
  • reconnecting: Announced when a reconnect attempt is initiated.
  • autoReconnectStopped: Informs when auto-reconnect efforts have ceased after exhausting the retry count.

The following documentation includes examples to illustrate the usage of these functions and events, providing a practical understanding of how to interact with the MarketDataStreamer effectively.


  1. Subscribing to Market Data on Connection Open with MarketDataStreamer
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer();
streamer.connect();

// Subscribe to instrument keys upon the 'open' event
streamer.on("open", () => {
  streamer.subscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full");
});

// Handle incoming market data messages
streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

  1. Subscribing to Instruments with Delays
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer();
streamer.connect();

// Subscribe to the first set of instrument keys immediately upon connection
streamer.on("open", () => {
  streamer.subscribe(["NSE_EQ|INE020B01018"], "full");
  
  // Subscribe to another set of instrument keys after a delay
  setTimeout(() => {
    streamer.subscribe(["NSE_EQ|INE467B01029"], "full");
  }, 5000); // 5-second delay before subscribing to the second set
});

// Handle incoming market data messages
streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

  1. Subscribing and Unsubscribing to Instruments
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer();
streamer.connect();

// Subscribe to instrument keys immediately upon connection
streamer.on("open", () => {
  console.log("Connected. Subscribing to instrument keys.");
  streamer.subscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full");
  
  // Unsubscribe after a delay
  setTimeout(() => {
    console.log("Unsubscribing from instrument keys.");
    streamer.unsubscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"]);
  }, 5000); // Adjust delay as needed
});

streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log("Market Update:", feed);
});

  1. Subscribe, Change Mode and Unsubscribe
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer();
streamer.connect();

// Initially subscribe to instrument keys in 'full' mode
streamer.on("open", async () => {
  console.log("Connected. Subscribing in full mode...");
  streamer.subscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full");

  // Change mode to 'ltpc' after a short delay
  setTimeout(() => {
    console.log("Changing subscription mode to ltpc...");
    streamer.changeMode(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "ltpc");
  }, 5000); // 5-second delay

  // Unsubscribe after another delay
  setTimeout(() => {
    console.log("Unsubscribing...");
    streamer.unsubscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"]);
  }, 10000); // 10 seconds after subscription
});

// Setup event listeners to log messages, errors, and closure
streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log("Market Update:", feed);
});
streamer.on("error", (error) => console.error("Error:", error));
streamer.on("close", () => console.log("Connection closed."));

  1. Disable Auto-Reconnect
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer();
streamer.connect();

// Disable auto-reconnect feature
streamer.autoReconnect(false);

streamer.on("autoReconnectStopped", (data) => {
  console.log(data);
});

  1. Modify Auto-Reconnect parameters
let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = <ACCESS_TOKEN>;

const streamer = new UpstoxClient.MarketDataStreamer();
streamer.connect();

// Modify auto-reconnect parameters: enable it, set interval to 10 seconds, and retry count to 3
streamer.autoReconnect(true, 10, 3);

PortfolioDataStreamer

Connecting to the Portfolio WebSocket for real-time order updates is straightforward with the PortfolioDataStreamer function. Below is a concise guide to get you started on receiving updates:

let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = "<ACCESS_TOKEN>";

const streamer = new UpstoxClient.PortfolioDataStreamer();
streamer.connect();

streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

This example demonstrates initializing the PortfolioDataStreamer, connecting it to the WebSocket, and setting up an event listener to receive and print order updates. Replace <ACCESS_TOKEN> with your valid access token to authenticate the session.

Exploring the PortfolioDataStreamer Functionality

Functions

  1. constructor PortfolioDataStreamer(orderUpdate = true, positionUpdate = false, holdingUpdate = false, gttUpdate = false): Initializes the streamer with options to receive different types of updates.
  2. connect(): Establishes the WebSocket connection.
  3. disconnect(): Ends the active WebSocket connection.
  4. autoReconnect(enable, interval, retryCount): Customizes auto-reconnect functionality. Parameters include a flag to enable/disable it, the interval(in seconds) between attempts, and the maximum number of retries.

Update Types

  • orderUpdate: Receive regular order updates (enabled by default)
  • positionUpdate: Receive position updates (disabled by default)
  • holdingUpdate: Receive holding updates (disabled by default)
  • gttUpdate: Receive GTT order updates (disabled by default)

Events

  • open: Emitted upon successful connection establishment.
  • close: Indicates the WebSocket connection has been closed.
  • message: Delivers portfolio updates.
  • error: Signals an error has occurred.
  • reconnecting: Announced when a reconnect attempt is initiated.
  • autoReconnectStopped: Informs when auto-reconnect efforts have ceased after exhausting the retry count.

Example with all update types enabled:

let UpstoxClient = require("upstox-js-sdk");
let defaultClient = UpstoxClient.ApiClient.instance;
var OAUTH2 = defaultClient.authentications["OAUTH2"];
OAUTH2.accessToken = "<ACCESS_TOKEN>";

// Enable all update types: orders, positions, holdings, and GTT orders
const streamer = new UpstoxClient.PortfolioDataStreamer(true, true, true, true);
streamer.connect();

streamer.on("message", (data) => {
  const feed = data.toString("utf-8");
  console.log(feed);
});

Documentation for Models

About

Official NodeJS library for accessing Upstox APIs

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 9