npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xts-interactive-api-multi-session

v1.0.3

Published

A Node.js SDK for interacting with the XTS Interactive API (Multi Session Model) By Rukku

Downloads

104

Readme

xts-interactive-api (Multi Session Model) By Rugmesh/OPEQ

A Node.js SDK for interacting with the XTS Interactive API, enabling multi-session management with features such as token renewal, controlled WebSocket connections, dynamic user addition/removal, and robust error handling.

Table of Contents


Features

  • Multi-Session Management: Handle multiple user sessions concurrently.
  • Token Renewal: Automatically renew tokens before they expire (tokens expire every 12 hours).
  • Controlled WebSocket Connections: Start WebSocket connections explicitly when needed.
  • Dynamic User Management: Add and remove users individually.
  • Robust Error Handling: Gracefully handle API errors, token expirations, and socket disconnections.
  • Event Handling: Listen to real-time updates through event emitters.

Installation

Prerequisites

  • Node.js (version 12 or above)
  • npm (Node Package Manager)

Installing the SDK

If the SDK is published on npm (replace xts-interactive-api-multi-session with the actual package name):

npm install xts-interactive-api-multi-session

If you're using it locally, include it as a local dependency:

npm install /path/to/xts-interactive-api-multi-session

Getting Started

This SDK helps you interact with the XTS Interactive API by managing multiple user sessions. It provides classes to handle user sessions, token renewals, WebSocket connections, and more.

Usage

Importing the SDK

const { SessionManager, UserSession } = require('xts-interactive-api-multi-session');

Creating a SessionManager Instance

const sessionManager = new SessionManager();

Adding a User

const userConfig = {
  secretKey: 'your-secret-key',
  appKey: 'your-app-key',
  source: 'WebAPI',
  url: 'https://api.example.com', // Replace with the actual API URL
  userID: 'User1',
};

const session = await sessionManager.addUser(userConfig);

if (session) {
  console.log(`User ${session.userID} added successfully.`);
}

Starting the WebSocket Connection

await session.startWebSocket();

Listening to Events

session.on('order', ({ userID, data }) => {
  console.log(`Received order event for user ${userID}:`, data);
});

// Similarly for other events: 'trade', 'position', 'connect', 'disconnect', 'error', 'logout'

Performing API Actions

// Get Profile
const profile = await session.getProfile({ clientID: session.userID });
console.log(`Profile for user ${session.userID}:`, profile);

// Get Balance
const balance = await session.getBalance();
console.log(`Balance for user ${session.userID}:`, balance);

// Place an Order
const placeOrderRequest = {
  exchangeSegment: 'NSECM',
  exchangeInstrumentID: 22,
  productType: 'NRML',
  orderType: 'MARKET',
  orderSide: 'BUY',
  timeInForce: 'DAY',
  disclosedQuantity: 0,
  orderQuantity: 10,
  limitPrice: 1500.0,
  stopPrice: 0.0,
  orderUniqueIdentifier: `Order_${session.userID}_${Date.now()}`,
  clientID: session.userID,
};

const orderResponse = await session.placeOrder(placeOrderRequest);
console.log(`Order placed for user ${session.userID}:`, orderResponse);

Performing Actions for All Users

await sessionManager.performActionForAllUsers(async (session) => {
  const positions = await session.getPositions({ dayOrNet: 'NetWise' });
  console.log(`Positions for user ${session.userID}:`, positions);
});

Removing a User

await sessionManager.removeUser('User1');

Stopping All Sessions

await sessionManager.stopAllSessions();

Example Application

// app.js

const { SessionManager } = require('xts-interactive-api-multi-session');

async function main() {
  const sessionManager = new SessionManager();

  // User configurations
  const usersConfig = [
    {
      secretKey: 'your-secret-key-1',
      appKey: 'your-app-key-1',
      source: 'WebAPI',
      url: 'https://api.example.com',
      userID: 'User1',
    },
    {
      secretKey: 'your-secret-key-2',
      appKey: 'your-app-key-2',
      source: 'WebAPI',
      url: 'https://api.example.com',
      userID: 'User2',
    },
  ];

  // Add users and log in
  for (const userConfig of usersConfig) {
    const session = await sessionManager.addUser(userConfig);
    if (session) {
      // Start WebSocket for users when needed
      if (userConfig.userID === 'User1') {
        await session.startWebSocket();
        // Listen to events
        session.on('order', ({ userID, data }) => {
          console.log(`Received order event for user ${userID}:`, data);
        });
      }
    }
  }

  // Perform actions for all users
  await sessionManager.performActionForAllUsers(async (session) => {
    const balance = await session.getBalance();
    console.log(`Balance for user ${session.userID}:`, balance);
  });

  // Remove a user
  await sessionManager.removeUser('User1');

  // Stop all sessions
  await sessionManager.stopAllSessions();
}

main().catch((error) => {
  console.error('Error in main function:', error);
});

Classes Overview

UserSession Class

Purpose: Manages individual user sessions, including API interactions, token renewal, and WebSocket connections.

Key Methods:

  • login(): Logs in the user and obtains a token.
  • startWebSocket(): Starts the WebSocket connection.
  • logout(): Logs out the user and cleans up resources.
  • makeApiCall(apiFunction, ...args): Handles API calls with error handling and retries.
  • API Methods: getProfile(), getBalance(), getPositions(), placeOrder(), etc.

Event Emitters: Extends EventEmitter to emit events like order, trade, position, connect, disconnect, error, and logout.

SessionManager Class

Purpose: Manages multiple UserSession instances.

Key Methods:

  • addUser(userConfig): Adds a new user session.
  • removeUser(userID): Removes a user session.
  • performActionForUser(userID, action): Performs an action for a specific user.
  • performActionForAllUsers(action): Performs an action for all users.
  • stopAllSessions(): Stops all sessions and cleans up resources.

Handling Tokens and Errors

  • Token Renewal: Tokens are automatically renewed 5 minutes before expiration.
  • Error Handling: The SDK handles token expiration, transient errors, and API errors gracefully.
  • WebSocket Reconnection: Attempts to reconnect the WebSocket on disconnection with exponential backoff.

Best Practices

  • Store Sensitive Data Securely: Use environment variables or a secure vault to store API keys and secrets.

    const userConfig = {
      secretKey: process.env.SECRET_KEY,
      appKey: process.env.APP_KEY,
      // ...
    };
  • Handle Events Appropriately: Implement event handlers to process real-time updates according to your application's needs.

  • Clean Up Resources: Always call logout() or removeUser() when a session is no longer needed.

  • Error Handling: Wrap your asynchronous calls in try-catch blocks to handle exceptions.

Customization

  • Add Additional API Methods: You can extend the UserSession class to include additional API methods as required.
  • Modify Event Handling: Customize the registerEvents() method in UserSession to handle events differently.
  • Logging: Replace console.log statements with a logging library like winston for better logging.

Dependencies

  • xts-interactive-api: The base API package for interacting with XTS Interactive API.
  • axios: Used for HTTP requests and error handling.
  • events: Node.js's built-in module for event handling.

License

This project is licensed under the MIT License.

Author

  • Rukku

Acknowledgments

  • XTS Interactive API: For providing the base API and SDK.

Note: Replace placeholder values (e.g., 'your-secret-key', 'your-app-key', 'https://api.example.com') with actual values provided by the XTS Interactive API.