SmartAPI JavaScript Client SDK
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.
Common errors
-
Error during SmartAPI session generation or API call: AxiosError: Request failed with status code 401
cause Invalid API key, client code, password, or TOTP value provided during `generateSession` or subsequent API calls due to an expired session.fixDouble-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
cause 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).fixFor 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')
cause 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.fixEnsure that `smart_api.generateSession()` successfully completes before attempting any further API calls. Handle the `.catch()` block of `generateSession` to debug credential issues.
Warnings
- gotcha Hardcoding 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.
- gotcha Session expiry is a common occurrence due to inactivity or server-side invalidation. Failing to handle it gracefully will lead to API call failures.
- gotcha The `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.
- gotcha The SDK provides both `WebSocket` and `WebSocketV2` classes. Without clear documentation differentiating them, developers might use an older or less feature-rich version.
Install
-
npm install smartapi-javascript -
yarn add smartapi-javascript -
pnpm add smartapi-javascript
Imports
- SmartAPI
import { SmartAPI } from 'smartapi-javascript';const { SmartAPI } = require('smartapi-javascript'); - WebSocket
import { WebSocket } from 'smartapi-javascript';const { WebSocket } = require('smartapi-javascript'); - WebSocketV2
import { WebSocketV2 } from 'smartapi-javascript';const { WebSocketV2 } = require('smartapi-javascript');
Quickstart
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);
}
});