Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrument snapshots
instrumentSnapshots/

# Environment variables
.env
.env.test
.env.production

# Dependency directory
node_modules/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# parcel-bundler cache files
.cache

# Next.js build output
.next
out

# Nuxt.js build output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
DynamoDBLocal.jar
DynamoDBLocal_lib/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# Mac OS
.DS_Store
.AppleDouble
.LSOverride

# Thumbnails
._*
Thumbs.db

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
Desktop.ini

# Optional IDEA files
.idea/
*.iml
*.iws

# Optional Komodo files
*.komodoproject

# Optional Netbeans files
/nbproject/

# Optional Sublime Text files
*.sublime-project
*.sublime-workspace

# Optional Atom files
.atom/

# Optional Eclipse files
.classpath
.project
.settings/

# Optional Rider files
.idea
*.sln.DotSettings.user

# Optional Emacs files
*~
*.elc
auto-save-list

# Build files
build/
dist/

# Coverage directory
coverage/
102 changes: 102 additions & 0 deletions PRD.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Product Requirements Document: XTS Interactive API - Enhancement Project

## 1. Introduction

The `xts-interactive-api` is the official JavaScript client library for the Symphony Fintech Trading APIs. It enables developers to integrate trading functionalities into their Node.js applications.

This document outlines the requirements for the initial phase of an enhancement project aimed at modernizing the library, improving its reliability, maintainability, security, and overall quality.

## 2. Goals

The primary goals for this enhancement project are:

* **Modernize Core Dependencies:** Replace outdated and deprecated libraries with modern, secure, and well-maintained alternatives.
* **Enhance Code Quality & Robustness:** Introduce a comprehensive test suite to ensure reliability and facilitate future development.
* **Improve Security:** Eliminate known vulnerabilities associated with deprecated dependencies.
* **Ensure Long-Term Maintainability:** Refactor code for clarity, reduce complexity, and adopt best practices.
* **Maintain API Stability:** Ensure that essential functionalities remain backward compatible or that any breaking changes are clearly documented and justified.

## 3. Target Audience

* Developers building applications that interact with the Symphony Fintech Trading APIs using JavaScript or Node.js.
* Internal teams at Symphony Fintech responsible for maintaining and supporting the API client.

## 4. Scope of Work (Phase 1 - Initial Enhancements)

This phase will focus on the most critical improvements:

### 4.1. Dependency Modernization

* **HTTP Client Replacement:**
* **Current:** `request` (deprecated, known security vulnerabilities), `request-promise`.
* **Task:** Replace `request` and `request-promise` with a modern HTTP client.
* **Recommendation:** `axios` is a strong candidate due to its popularity, feature set, and promise-based API. (Awaiting final confirmation - see Q&A.md).
* **Affected Modules:** Primarily `lib/request.js`, which will impact `lib/interactiveRestAPI.js`.
* **WebSocket Client Update:**
* **Current:** `socket.io-client` version ~2.2.0 (outdated).
* **Task:** Update `socket.io-client` to the latest stable version (currently 4.x.x).
* **Considerations:** This is a major version update and may involve breaking changes. Thorough testing will be required.
* **Affected Modules:** `lib/interactiveSocket.js`.

### 4.2. Test Suite Implementation

* **Current:** No automated test suite exists (`"test": "echo \"Error: no test specified\" && exit 1"`).
* **Task:**
1. Select and configure a testing framework (e.g., Jest, Mocha). (Jest is a common recommendation).
2. Develop unit tests for core modules, starting with:
* `lib/request.js` (after HTTP client replacement).
* `lib/interactiveRestAPI.js` (key public methods).
* `lib/interactiveSocket.js` (connection, event handling).
* `lib/customError.js`.
* `lib/logger.js`.
3. Begin developing integration tests to cover common API interaction flows.
* **Goal:** Achieve foundational test coverage to build confidence in changes and prevent regressions.

### 4.3. Dependency Review

* **`linq` library:**
* **Task:** Analyze the usage of the `linq` library throughout the codebase.
* **Goal:** Determine if its functionality can be replaced with native JavaScript array methods (ES6+) or other modern utility functions to potentially reduce the dependency footprint and simplify the code.

### 4.4. Code Quality & Refactoring (Opportunistic)

* **Large Files:** The file `lib/interactiveRestAPI.js` (766 lines) is quite large. As we work on it, identify opportunities for logical decomposition into smaller, more focused modules if it improves readability and maintainability.
* **Logging:** Review and enhance logging in `logger.js` and its usage, ensuring that logs are informative for debugging and monitoring.
* **Error Handling:** Ensure consistent and robust error handling using `customError.js` and standard JavaScript error patterns.

## 5. Success Metrics (Phase 1)

* **Dependency Health:**
* `request` and `request-promise` successfully removed and replaced.
* `socket.io-client` updated to a stable 4.x version.
* `npm audit` (or equivalent) reports no critical or high-severity vulnerabilities related to project dependencies.
* **Test Coverage:**
* A testing framework is successfully integrated.
* Initial unit test coverage for critical modules (e.g., `lib/request.js`, `lib/interactiveRestAPI.js`, `lib/interactiveSocket.js`) reaches a target of at least 50% (to be refined).
* At least 2-3 key end-to-end API flows are covered by integration tests.
* **Functionality:**
* The library maintains backward compatibility for core public API methods, or any necessary breaking changes are minimal, justified, and well-documented.
* Key trading operations (e.g., login, order placement, market data subscription – *specifics to be confirmed based on API capabilities*) are fully functional after changes.
* **`linq` Dependency:** A decision is made regarding the `linq` library (retain or replace), with a clear rationale.

## 6. Open Questions & Future Considerations

*(Refer to `Q&A.md` for an ongoing list of detailed questions)*

* **Q1:** What is the preferred modern HTTP client? (`axios` proposed).
* **Q2:** What is the preferred testing framework? (Jest proposed).
* **Q3:** Are there specific Node.js versions the library must support? (This influences choices like using native `fetch` vs. a library).
* **Q4:** What are the most critical API functionalities/workflows that must be covered by integration tests in Phase 1?
* **Q5:** Are there any performance benchmarks to meet?

**Future Considerations (Post-Phase 1):**

* Comprehensive API documentation (e.g., using JSDoc, generating a static site).
* TypeScript conversion for improved type safety and developer experience.
* Advanced mocking strategies for tests.
* Continuous Integration (CI) pipeline setup for automated testing and builds.
* More granular refactoring of large modules.
* Expansion of test coverage.

---
This PRD will be a living document and will be updated as the project progresses and more information becomes available.
20 changes: 20 additions & 0 deletions Q&A.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Q&A Log

This file will store questions and answers that arise during our development session.

## Questions:

1. **Dependency Replacement (HTTP Client):** The `request` and `request-promise` libraries are deprecated. What is the preferred modern HTTP client to replace them with? Common choices include `axios`, `node-fetch` (or built-in `fetch` if Node.js version supports it well for this library's needs), or `got`. Please specify or indicate if there's a project standard.
* **Answer:** `axios` has been implemented as the replacement. (User confirmed 'yes' to proceed with `axios` proposal).

2. **Preferred Testing Framework:** What is the preferred testing framework for implementing the test suite? Common choices include Jest, Mocha, Jasmine, etc. (PRD proposes Jest).
* **Answer:** Jest has been set up as the testing framework based on the PRD proposal and implicit user approval to proceed.

3. **Supported Node.js Versions:** Are there specific Node.js versions that this library must support? This information will influence decisions such as whether to use native `fetch` or a library-based HTTP client.
* **Answer:** (Pending)

4. **Critical API Functionalities for Testing:** What are the most critical API functionalities or user workflows that must be covered by integration tests in Phase 1 of the enhancement project? (e.g., login, order placement, market data subscription).
* **Answer:** (Pending)

5. **Performance Benchmarks:** Are there any specific performance benchmarks or expectations that the library needs to meet after the planned enhancements?
* **Answer:** (Pending)
56 changes: 47 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ https://symphonyfintech.com/xts-trading-front-end-api/

The XTS Trading API provides developer, data-scientist, financial analyst and investor the functionality necessary to create automated trading strategies, as well as other trading related applications with support of XTS OEMS hosted by Financial Institutions to trade with Indian electronic exchanges.

With the use of the socket.io library, the API has streaming capability and will push data notifications in a JSON format. Your application can place orders and receive real-time trade notification.
With the use of the socket.io-client library (v4.x), the API has streaming capability and will push data notifications in a JSON format. Your application can place orders and receive real-time trade notification.

There is also an examples folder available which illustrates how to create a connection to XTS OEMS hosted by Brokers to subscribe to real-time events.
Please request for apikeys with Symphony Fintech developer support team to start integrating your application with XTS OEMS.
Expand All @@ -27,13 +27,12 @@ var XTSInteractive = require('xts-interactive-api').Interactive;
Creating the instance of xtsInteractive

```js
xtsInteractive = new XTSInteractive(https://api.symphonyfintech.com);
xtsInteractive = new XTSInteractive("https://api.symphonyfintech.com");
```

call the login API to generate the token

```js

var loginRequest ={
"userID": "PAVAN",
"password": "Abcd@123",
Expand All @@ -44,25 +43,45 @@ var loginRequest ={
let logIn = await xtsInteractive.logIn(loginRequest);
```

Once the token is generated you can call any api provided in the documentation. All APIs are easy to integrate and implemented with async-await mechanism.
Once the token is generated you can call any api provided in the documentation. All API's are easy to integrate and implemented with async-await mechanism.
Below is the sample Code snippet which calls the balance API.

```js
let balance = await xtsInteractive.getBalance();

console.log(balance);
```

Alternatively, if you already have a valid session token and user ID (e.g., from a previous session or a different authentication mechanism), you can initialize the SDK using `loginWithToken`:

```js
// Assuming xtsInteractive is already instantiated: const xtsInteractive = new XTSInteractive("YOUR_API_URL_OR_LEAVE_UNDEFINED_FOR_DEFAULT");
const userIDForTokenLogin = "YOUR_USER_ID";
const existingToken = "YOUR_EXISTING_TOKEN";

try {
const loginResponseWithToken = await xtsInteractive.loginWithToken(userIDForTokenLogin, existingToken);
if (loginResponseWithToken.type === 'success') {
console.log("Successfully logged in with token.");
// You can now use other API methods, e.g., xtsInteractive.getProfile();
} else {
console.error("Failed to login with token:", loginResponseWithToken);
}
} catch (error) {
console.error("Error during loginWithToken:", error);
}
```

## Instantiating the XTSInteractiveWS

This component provides functionality to access the socket related events. All real-time events can be registered via XTSInteractiveWS.
After token is generated, you can access the socket component and instantiate the socket Instance and call the init method of the socket like below

```js
var XTSInteractiveWS = require('xts-interactive-api').WS;
xtsInteractiveWS = new XTSInteractiveWS(https://api.symphonyfintech.com);
xtsInteractiveWS = new XTSInteractiveWS("https://api.symphonyfintech.com");
var socketInitRequest = {
userID: PAVAN,
userID: "PAVAN",
token: logIn.result.token // Token Generated after successful LogIn
}
xtsInteractiveWS.init(socketInitRequest);
Expand Down Expand Up @@ -99,7 +118,7 @@ xtsInteractiveWS.onLogout((logoutData) => {

## Detailed explanation of API and socket related events

Below is the brief information related to api’s provided by XTS-Interactive-API SDK.
Below is the brief information related to APIs provided by XTS-Interactive-API SDK.

## Orders API
## placeOrder
Expand Down Expand Up @@ -171,7 +190,7 @@ let response = await xtsInteractive.placeCoverOrder({
Calls PUT /order/cover.

```js
let response = await xtsInteractive.exitCoverOrder("2426016103"));
let response = await xtsInteractive.exitCoverOrder({ appOrderID: "2426016103" });
```
## getOrderBook

Expand Down Expand Up @@ -249,7 +268,7 @@ Calls GET /users/profile
let response = await xtsInteractive.getProfile();
```

Below is the brief information related to streaming events provided by XTS-Interactive-API SDK.
Below is the brief information related to streaming events provided by XTS-Interactive-API SDK.

```js
xtsInteractiveWS.init(socketInitRequest); // Init the socket instance
Expand All @@ -265,3 +284,22 @@ xtsInteractiveWS.onLogout((logoutData) => {});//registering for Logout event
We do have a market data component which will provide the streaming of our real-time streaming market data. For more info please check the following link.

https://symphonyfintech.com/xts-market-data-front-end-api/

## getOrderHistory

Retrieves the history for a specific order.

```js
const appOrderID = "YOUR_APP_ORDER_ID"; // Replace with the actual AppOrderID
let response = await xtsInteractive.getOrderHistory(appOrderID);
console.log(response);
```

## Testing

This library uses Jest for testing. To run the tests:

1. Ensure you have installed the development dependencies: `npm install` (if you haven't already).
2. Run the test script: `npm test`

This will execute all test suites and provide a summary of the results.
Loading