@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:
- WealthyApi - REST API client for trading operations
- 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 descriptionPackage 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
@dilip3121namespace - Built files are distributed in the
dist/directory - TypeScript definitions are included for IntelliSense support
- Dependencies:
axiosfor HTTP requests,typescriptfor 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 tokengetLoginUrl()- Returns login URL for OAuth flowgetCheckUsers()- Validates user authentication //will remove thisgetProfile()- Retrieves user profile information
2. Watchlist Management
getWatchlistNames()- Fetches all watchlist namesgetWatchlistDetails(watchlistName: string)- Gets stocks in a watchlistaddStocksToWatchlist(watchlistName: string, keys: string[])- Adds stocks to watchlist
3. Trading Reports & Data
getOrders()- Retrieves all ordersgetTrades()- Fetches trade historygetHoldings()- Gets current holdingsgetPositions()- Retrieves position datagetFunds()- Gets account fund informationgetOrderHistory(orderId)- Detailed order historygetTradesForOrder(orderId)- Trades for specific order
4. Order Management
placeOrder(order: Order)- Places a new ordermodifyOrder(order: ModifyOrderParams)- Modifies existing ordercancelOrder(orderId: string, orderType: number)- Cancels an orderorderMargin(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:
request()- Core request method with full configurationget()- Optimized for GET requestspostOrPutOrDelete()- 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 confirmationtf/tk- Tick/price updatesdf/dk- Depth/market data updatesom- Order status updatesuok/uk/udk- Unsubscribe confirmations
Event System The feed uses an event-driven architecture with these events:
connect- WebSocket connection establishedauth- Authentication successfulpriceUpdate- Market data receivedorderUpdate- Order status changeddisconnect/error/close- Connection issuesreconnect/noreconnect- Reconnection events
WebSocket Workflow
Connection Initialization
connectSocket(feedPayload: string)- Creates WebSocket connection
- Sets up event handlers
- Initiates authentication
Authentication
authenticate(payload: string)- Parses authentication payload
- Extracts account ID
- Sends authentication message
Subscription Management
subscribe(tokens: string[], feedMessageType: FeedMessageType)- Subscribes to specific instruments
- Formats token strings (exchange|symbol format)
- Sends subscription requests
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 metadatagetUserAgent()- 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 artifactsError Handling Strategy
The library implements comprehensive error handling:
- Network Errors - Axios interceptors catch and format network issues
- API Errors - Server responses are validated and error objects are standardized
- WebSocket Errors - Connection issues trigger reconnection logic
- 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.
