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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@killswitch_018/wealthyjslib

v1.0.12

Published

Wealthy API JS SDK

Downloads

1

Readme

WealthyJSLib - Complete Codebase Documentation

Overview

WealthyJSLib is a comprehensive TypeScript SDK (Software Development Kit) for the Wealthy Trading API. It provides a robust interface for traders and developers to interact with the Wealthy trading platform programmatically. The library consists of two main components:

  1. WealthyApi - REST API client for trading operations
  2. WealthyFeed - WebSocket client for real-time market data feeds

Project Structure

wealthyjslib/
├── src/                    # Core implementation files
│   ├── api.ts             # Main API client class
│   ├── feed.ts            # WebSocket feed client class
│   ├── index.ts           # Library entry point
│   └── utils.ts           # Utility functions
├── interfaces/            # TypeScript type definitions
│   ├── api.ts            # API-related interfaces and enums
│   ├── feed.ts           # Feed-related interfaces
│   ├── anyType.ts        # Generic type definitions
│   └── index.ts          # Interface exports
├── constants/            # Application constants
│   └── index.ts         # API routes and default configurations
├── package.json         # Package configuration
├── tsconfig.json        # TypeScript configuration
└── README.md           # Basic project description

Package Configuration

package.json Analysis

{
  "name": "@dilip3121/wealthyjslib",
  "version": "1.0.12",
  "description": "Wealthy API JS SDK",
  "main": "dist/src/index.js",
  "types": "dist/src/index.d.ts"
}

Key Points:

  • Published as scoped package under @dilip3121 namespace
  • Built files are distributed in the dist/ directory
  • TypeScript definitions are included for IntelliSense support
  • Dependencies: axios for HTTP requests, typescript for compilation

Core Components Deep Dive

1. WealthyApi Class (src/api.ts)

The main API client that handles all REST API operations with the Wealthy trading platform.

Class Structure

class WealthyApi implements WealthyConnectionInterface {
    root?: string;                    // API base URL
    debug?: boolean;                  // Debug mode flag
    timeout?: number;                 // Request timeout
    accessToken?: string | null;      // Authentication token
    defaultConnectionUrl: string | undefined;  // Login URL
    sessionExpiryHook?: string | null; // Session expiry callback
    requestInstance: AxiosInstance;    // Axios HTTP client
}

Constructor & Initialization

The constructor accepts WealthyConnectionParams and sets up:

  • Base configuration from parameters
  • Axios instance with interceptors for response/error handling
  • Authentication headers
  • Request/response transformation logic

Core Functionality Categories

1. Authentication & Session Management

  • setAccessToken(accessToken: string) - Sets authentication token
  • getLoginUrl() - Returns login URL for OAuth flow
  • getCheckUsers() - Validates user authentication //will remove this
  • getProfile() - Retrieves user profile information

2. Watchlist Management

  • getWatchlistNames() - Fetches all watchlist names
  • getWatchlistDetails(watchlistName: string) - Gets stocks in a watchlist
  • addStocksToWatchlist(watchlistName: string, keys: string[]) - Adds stocks to watchlist

3. Trading Reports & Data

  • getOrders() - Retrieves all orders
  • getTrades() - Fetches trade history
  • getHoldings() - Gets current holdings
  • getPositions() - Retrieves position data
  • getFunds() - Gets account fund information
  • getOrderHistory(orderId) - Detailed order history
  • getTradesForOrder(orderId) - Trades for specific order

4. Order Management

  • placeOrder(order: Order) - Places a new order
  • modifyOrder(order: ModifyOrderParams) - Modifies existing order
  • cancelOrder(orderId: string, orderType: number) - Cancels an order
  • orderMargin(orders: Order[]) - Calculates margin requirements

5. WebSocket Integration

  • getWsUrl() - Retrieves WebSocket connection URL for real-time feeds

HTTP Request Architecture

The class implements a sophisticated HTTP request system with three main methods:

  1. request() - Core request method with full configuration
  2. get() - Optimized for GET requests
  3. postOrPutOrDelete() - Handles POST, PUT, DELETE operations

Each method includes:

  • URL parameter replacement for RESTful endpoints
  • Automatic authentication header injection
  • Content-type management (JSON/form-encoded)
  • Error handling and response transformation

2. WealthyFeed Class (src/feed.ts)

Manages real-time WebSocket connections for market data feeds and order updates.

Key Features

Connection Management

  • Automatic reconnection with exponential backoff
  • Connection state monitoring
  • Error handling and recovery

Message Types Supported // Need to hide these from user. create human readable

  • ck - Authentication confirmation
  • tf/tk - Tick/price updates
  • df/dk - Depth/market data updates
  • om - Order status updates
  • uok/uk/udk - Unsubscribe confirmations

Event System The feed uses an event-driven architecture with these events:

  • connect - WebSocket connection established
  • auth - Authentication successful
  • priceUpdate - Market data received
  • orderUpdate - Order status changed
  • disconnect/error/close - Connection issues
  • reconnect/noreconnect - Reconnection events

WebSocket Workflow

  1. Connection Initialization

    connectSocket(feedPayload: string)
    • Creates WebSocket connection
    • Sets up event handlers
    • Initiates authentication
  2. Authentication

    authenticate(payload: string)
    • Parses authentication payload
    • Extracts account ID
    • Sends authentication message
  3. Subscription Management

    subscribe(tokens: string[], feedMessageType: FeedMessageType)
    • Subscribes to specific instruments
    • Formats token strings (exchange|symbol format)
    • Sends subscription requests
  4. Auto-Reconnection

    attemptReconnection()
    • Implements exponential backoff strategy
    • Limits maximum retry attempts
    • Maintains connection state

Type System & Interfaces

Core Enums

Exchange Types

enum Exchange {
    NSE = 1,    // National Stock Exchange
    NFO = 2,    // NSE Futures & Options
    BSE = 3,    // Bombay Stock Exchange
    BFO = 4     // BSE Futures & Options
}

Order Management

enum OrderStatus { CREATED, OPEN, PENDING, COMPLETED, CANCELLED, REJECTED, INVALID_STATUS, TRIGGER_PENDING }
enum OrderValidity { DAY, IOS, EOS, GTT, GTD }
enum PriceType { LIMIT, MARKET, STOPLOSSLIMIT, STOPLOSSMARKET, SPREAD, TWOLEGGEDORDER, THREEGGEDORDER }
enum OrderType { CNC, INTRADAY, NRML, CO, BO }
enum TransactionType { BUY, SELL }

Feed Message Types

enum FeedMessageType {
    t = 1,    // Ticker data
    u = 2,    // Unsubscribe ticker
    d = 3,    // Depth data
    ud = 4,   // Unsubscribe depth
    o = 5,    // Order updates
    uo = 6    // Unsubscribe orders
}

Key Interfaces

Order Structure

interface Order {
    Exchange: Exchange;
    TradingSymbol: string;
    transactiontype: TransactionType;
    quantity: string | number;
    orderType: OrderType;
    priceType: PriceType;
    price?: number | string;
    triggerPrice?: number | string;
    validity: OrderValidity;
    // ... additional fields for stop-loss, target price, etc.
}

Constants & Configuration

API Routes (constants/index.ts)

The library defines comprehensive API endpoints:

Authentication Routes

  • /session/token - Token management
  • /session/refresh_token - Token renewal

User & Profile Routes

  • /user/ - User profile
  • /user/check/ - User validation

Trading Routes

  • /order/create/ - Order placement
  • /order/{orderID} - Order modification/cancellation
  • /order/margin/ - Margin calculations

Data & Reports Routes

  • /report/orders/ - Order history
  • /report/trades/ - Trade history
  • /report/holdings/ - Holdings data
  • /report/positions/ - Position data

Real-time Data

  • /auth/ws-url/ - WebSocket URL endpoint

Default Configuration

const DEFAULTS = {
    'root': 'https://api.wealthy.in/broking/api/v0',
    'loginUrl': 'https://api.wealthy.in/wealthyauth/dashboard/login',
    'debug': false,
    'timeout': 7000
}

Utility Functions (src/utils.ts)

Package Information

  • getPackageInfo() - Returns package.json metadata
  • getUserAgent() - Generates user agent string for API requests

String Validation

  • isEmptyOrSpaces(str: String) - Validates non-empty strings

Library Entry Point (src/index.ts)

The main export provides access to all library components:

export default {
    WealthyFeed,        // WebSocket feed client
    WealthyApi,         // REST API client
    getPackageInfo,     // Package utilities
    getUserAgent,
    isEmptyOrSpaces,
    FeedMessageType,    // Enum for feed subscriptions
}

Usage Patterns

Basic API Client Setup

import WealthySDK from '@dilip3121/wealthyjslib';

const api = new WealthySDK.WealthyApi({
    root: 'https://api.wealthy.in/broking/api/v0',
    accessToken: 'your-access-token',
    debug: false,
    timeout: 7000
});

WebSocket Feed Setup

const feed = new WealthySDK.WealthyFeed({
    wealthyApi: api,
    reconnect: true,
    maxRetries: 30,
    maxDelay: 5000,
    debug: false
});

// Set up event handlers
feed.onEvent('connect', () => console.log('Connected'));
feed.onEvent('priceUpdate', (data) => console.log('Price update:', data));

Order Placement Workflow

const order = {
    Exchange: Exchange.NSE,
    TradingSymbol: 'RELIANCE',
    transactiontype: TransactionType.BUY,
    quantity: 1,
    orderType: OrderType.INTRADAY,
    priceType: PriceType.MARKET,
    validity: OrderValidity.DAY,
    // ... other required fields
};

api.placeOrder(order)
    .then(response => console.log('Order placed:', response))
    .catch(error => console.error('Order failed:', error));

Build & Distribution

TypeScript Configuration

  • Target: ES2015 for broad compatibility
  • Module: CommonJS for Node.js compatibility
  • Declaration: True (generates .d.ts files)
  • Output: dist/ directory

Build Process

npm run build    # Compiles TypeScript to JavaScript
npm run clean    # Cleans build artifacts

Error Handling Strategy

The library implements comprehensive error handling:

  1. Network Errors - Axios interceptors catch and format network issues
  2. API Errors - Server responses are validated and error objects are standardized
  3. WebSocket Errors - Connection issues trigger reconnection logic
  4. Authentication Errors - Token expiry is detected and can trigger callbacks

Security Considerations

  • Access tokens are stored securely and included in request headers
  • WebSocket connections use secure protocols (WSS)
  • Request/response data is validated and sanitized
  • Session expiry hooks allow for graceful authentication renewal

Performance Features

  • HTTP request pooling through Axios instances
  • WebSocket connection reuse and management
  • Exponential backoff for reconnections
  • Configurable timeouts and retry limits
  • Efficient message serialization/deserialization

Conclusion

WealthyJSLib provides a complete, production-ready solution for integrating with the Wealthy trading platform. Its architecture supports both REST API operations and real-time data feeds, making it suitable for everything from simple portfolio management to sophisticated algorithmic trading applications.

The library's TypeScript foundation ensures type safety and excellent developer experience, while its comprehensive error handling and reconnection logic provide the reliability needed for financial applications.