npm package: @killswitch_018/wealthyjslib
Description: Wealthy API JS SDK
Author: brijeshpandey18@gmail.com
Latest version: 1.0.12

# 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
```json
{
  "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
```typescript
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**
   ```typescript
   connectSocket(feedPayload: string)
   ```
   - Creates WebSocket connection
   - Sets up event handlers
   - Initiates authentication

2. **Authentication**
   ```typescript
   authenticate(payload: string)
   ```
   - Parses authentication payload
   - Extracts account ID
   - Sends authentication message

3. **Subscription Management**
   ```typescript
   subscribe(tokens: string[], feedMessageType: FeedMessageType)
   ```
   - Subscribes to specific instruments
   - Formats token strings (exchange|symbol format)
   - Sends subscription requests

4. **Auto-Reconnection**
   ```typescript
   attemptReconnection()
   ```
   - Implements exponential backoff strategy
   - Limits maximum retry attempts
   - Maintains connection state

## Type System & Interfaces

### Core Enums

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

**Order Management**
```typescript
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**
```typescript
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**
```typescript
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
```typescript
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:

```typescript
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
```typescript
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
```typescript
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
```typescript
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
```bash
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.