Registry / communication / smartapi-javascript

smartapi-javascript

JSON →
library1.0.27jsnpmunverified

The `smartapi-javascript` package provides a client-side SDK for programmatic interaction with the SmartAPI platform, an initiative by Angel One (formerly Angel Broking) for the Indian stock market. It offers a comprehensive suite of functionalities, including user authentication and session management, fetching profile and real-time margin (RMS) details, executing various order types (place, modify, cancel, order book, trade book), managing portfolio holdings and positions, converting positions, and handling Good Till Triggered (GTT) orders. Additionally, it provides access to historical candle data and includes WebSocket functionality for real-time market updates. The current stable version is 1.0.27. As an official client library for a specific financial service, its release cadence typically aligns with updates to the SmartAPI platform itself. A key differentiator is its direct and tailored integration with Angel One's trading ecosystem, simplifying development for users targeting this platform. The library currently emphasizes CommonJS `require` syntax for module imports, as demonstrated in its official documentation.

npm install smartapi-javascript
INSTALL
IMPORT
SIG · SMARTAPI-JAVASCRIP
S
smartapi-javascript
communicationjavascriptv1.0.27
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SmartAPI
const { SmartAPI } = require('smartapi-javascript');
import { SmartAPI } from 'smartapi-javascript';
The official documentation for version 1.x predominantly uses CommonJS `require`. While ESM `import` might be supported in future versions or via bundlers, direct usage without transpliation may lead to errors in Node.js environments.
WebSocket
const { WebSocket } = require('smartapi-javascript');
import { WebSocket } from 'smartapi-javascript';
Used for real-time market data. Note the existence of `WebSocketV2`, which may be a newer or preferred implementation.
WebSocketV2
const { WebSocketV2 } = require('smartapi-javascript');
import { WebSocketV2 } from 'smartapi-javascript';
Introduced as a potentially enhanced version of the WebSocket client. It is advisable to review the official documentation for differences and preferred usage between `WebSocket` and `WebSocketV2`.

This quickstart demonstrates how to initialize the SmartAPI client, securely generate a user session with credentials (client code, password, TOTP), and then use the authenticated session to fetch the user's profile details. It also includes commented-out examples for various trading operations like placing orders and retrieving the order book, along with a custom session expiry hook to manage re-authentication.

const { SmartAPI } = require('smartapi-javascript'); // IMPORTANT: Replace with your actual credentials. For production, use environment variables. const API_KEY = process.env.SMARTAPI_API_KEY || 'smartapi_key'; const CLIENT_CODE = process.env.SMARTAPI_CLIENT_CODE || 'YOUR_CLIENT_CODE'; const PASSWORD = process.env.SMARTAPI_PASSWORD || 'YOUR_PASSWORD'; const TOTP_SECRET = process.env.SMARTAPI_TOTP_SECRET || 'YOUR_TOTP_VALUE'; // If using TOTP let smart_api = new SmartAPI({ api_key: API_KEY }); // Function to handle session expiry, can be used to re-authenticate or log out function customSessionHook() { console.log('SmartAPI session expired. Please re-authenticate.'); // Implement re-authentication logic here or notify the user. } smart_api.setSessionExpiryHook(customSessionHook); smart_api .generateSession(CLIENT_CODE, PASSWORD, TOTP_SECRET) .then(async (data) => { console.log('Session generated successfully:', data); // Now you can make authenticated API calls const profile = await smart_api.getProfile(); console.log('User Profile:', profile); // Example: Place a mock order (UNCOMMENT AND ADJUST FOR REAL TRADING) /* const placeOrderResponse = await smart_api.placeOrder({ "variety": "NORMAL", "tradingsymbol": "SBIN-EQ", "symboltoken": "3045", "transactiontype": "BUY", "exchange": "NSE", "ordertype": "LIMIT", "producttype": "INTRADAY", "duration": "DAY", "price": "19500", "squareoff": "0", "stoploss": "0", "quantity": "1" }); console.log('Order Placement Response:', placeOrderResponse); */ // Example: Get Order Book // const orderBook = await smart_api.getOrderBook(); // console.log('Order Book:', orderBook); }) .catch((ex) => { console.error('Error during SmartAPI session generation or API call:', ex); if (ex && ex.response && ex.response.data) { console.error('API Error Details:', ex.response.data); } });
Debug
Known issues
gotchaHardcoding sensitive credentials (API keys, client codes, passwords, TOTP values) directly in your source code is a significant security risk. These should always be loaded from environment variables or a secure configuration management system.
fix
Store credentials in environment variables (e.g., `process.env.SMARTAPI_API_KEY`) and access them at runtime. Never commit sensitive data to version control.
affects: >=1.0.0
gotchaSession expiry is a common occurrence due to inactivity or server-side invalidation. Failing to handle it gracefully will lead to API call failures.
fix
Implement the `setSessionExpiryHook` callback to catch session expiry events. Within this hook, trigger your re-authentication flow (e.g., by calling `generateSession` again) or inform the user.
affects: >=1.0.0
gotchaThe `README` uses `require` statements for module imports. Attempting to use ES Modules `import` syntax directly in a CommonJS-only environment (e.g., older Node.js versions or project configurations) will result in errors.
fix
Ensure your Node.js project is configured for CommonJS if using `require`. If you intend to use `import`, ensure your project is set up for ES Modules (e.g., by setting `"type": "module"` in `package.json` and potentially using transpilers) or verify if a dual package is provided.
affects: >=1.0.0
gotchaThe SDK provides both `WebSocket` and `WebSocketV2` classes. Without clear documentation differentiating them, developers might use an older or less feature-rich version.
fix
Consult the official SmartAPI documentation or SDK source code to understand the differences between `WebSocket` and `WebSocketV2` and determine which is the most current or appropriate for your specific real-time data needs.
affects: >=1.0.0
Errors
Common errors & fixes
Error during SmartAPI session generation or API call: AxiosError: Request failed with status code 401
Invalid API key, client code, password, or TOTP value provided during `generateSession` or subsequent API calls due to an expired session.
fix
Double-check all credentials (API key, client code, password, TOTP) for correctness. Ensure your session has not expired; if so, trigger re-authentication. Verify that the API key is active for your account.
ReferenceError: require is not defined in ES module scope
Attempting to use `require` in a JavaScript file that is being interpreted as an ES Module (e.g., due to `"type": "module"` in `package.json` or a `.mjs` extension).
fix
For this SDK version, switch to CommonJS by ensuring your file is `.js` and your `package.json` does not declare `"type": "module"`. If you must use ESM, you might need to dynamically `import()` the SDK or find an ESM-compatible wrapper.
TypeError: Cannot read properties of undefined (reading 'access_token')
This typically occurs if the `generateSession` call failed, meaning the `smart_api` object was not properly initialized with access and refresh tokens, and subsequent authenticated calls are made.
fix
Ensure that `smart_api.generateSession()` successfully completes before attempting any further API calls. Handle the `.catch()` block of `generateSession` to debug credential issues.
Upgrade
Version history
1.0.27latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
15 hits · last 30 days
node
12
OpenAI (training)
1
Resources
smartapi-javascript — npm install smartapi-javascript · libregistry