{"id":12044,"library":"smartapi-javascript","title":"SmartAPI JavaScript Client SDK","description":"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.","status":"active","version":"1.0.27","language":"javascript","source_language":"en","source_url":"https://github.com/angelbroking-github/smartapi-javascript","tags":["javascript"],"install":[{"cmd":"npm install smartapi-javascript","lang":"bash","label":"npm"},{"cmd":"yarn add smartapi-javascript","lang":"bash","label":"yarn"},{"cmd":"pnpm add smartapi-javascript","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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.","wrong":"import { SmartAPI } from 'smartapi-javascript';","symbol":"SmartAPI","correct":"const { SmartAPI } = require('smartapi-javascript');"},{"note":"Used for real-time market data. Note the existence of `WebSocketV2`, which may be a newer or preferred implementation.","wrong":"import { WebSocket } from 'smartapi-javascript';","symbol":"WebSocket","correct":"const { WebSocket } = require('smartapi-javascript');"},{"note":"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`.","wrong":"import { WebSocketV2 } from 'smartapi-javascript';","symbol":"WebSocketV2","correct":"const { WebSocketV2 } = require('smartapi-javascript');"}],"quickstart":{"code":"const { SmartAPI } = require('smartapi-javascript');\n\n// IMPORTANT: Replace with your actual credentials. For production, use environment variables.\nconst API_KEY = process.env.SMARTAPI_API_KEY || 'smartapi_key';\nconst CLIENT_CODE = process.env.SMARTAPI_CLIENT_CODE || 'YOUR_CLIENT_CODE';\nconst PASSWORD = process.env.SMARTAPI_PASSWORD || 'YOUR_PASSWORD';\nconst TOTP_SECRET = process.env.SMARTAPI_TOTP_SECRET || 'YOUR_TOTP_VALUE'; // If using TOTP\n\nlet smart_api = new SmartAPI({\n\tapi_key: API_KEY\n});\n\n// Function to handle session expiry, can be used to re-authenticate or log out\nfunction customSessionHook() {\n\tconsole.log('SmartAPI session expired. Please re-authenticate.');\n\t// Implement re-authentication logic here or notify the user.\n}\n\nsmart_api.setSessionExpiryHook(customSessionHook);\n\nsmart_api\n\t.generateSession(CLIENT_CODE, PASSWORD, TOTP_SECRET)\n\t.then(async (data) => {\n\t\tconsole.log('Session generated successfully:', data);\n\t\t// Now you can make authenticated API calls\n\t\tconst profile = await smart_api.getProfile();\n\t\tconsole.log('User Profile:', profile);\n\n\t\t// Example: Place a mock order (UNCOMMENT AND ADJUST FOR REAL TRADING)\n\t\t/*\n\t\tconst placeOrderResponse = await smart_api.placeOrder({\n\t\t    \"variety\": \"NORMAL\",\n\t\t    \"tradingsymbol\": \"SBIN-EQ\",\n\t\t    \"symboltoken\": \"3045\",\n\t\t    \"transactiontype\": \"BUY\",\n\t\t    \"exchange\": \"NSE\",\n\t\t    \"ordertype\": \"LIMIT\",\t\n\t\t    \"producttype\": \"INTRADAY\",\n\t\t    \"duration\": \"DAY\",\n\t\t    \"price\": \"19500\",\n\t\t    \"squareoff\": \"0\",\n\t\t    \"stoploss\": \"0\",\t\n\t\t    \"quantity\": \"1\"\n\t\t});\n\t\tconsole.log('Order Placement Response:', placeOrderResponse);\n\t\t*/\n\n\t\t// Example: Get Order Book\n\t\t// const orderBook = await smart_api.getOrderBook();\n\t\t// console.log('Order Book:', orderBook);\n\n\t})\n\t.catch((ex) => {\n\t\tconsole.error('Error during SmartAPI session generation or API call:', ex);\n\t\tif (ex && ex.response && ex.response.data) {\n\t\t\tconsole.error('API Error Details:', ex.response.data);\n\t\t}\n\t});\n","lang":"javascript","description":"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."},"warnings":[{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Session expiry is a common occurrence due to inactivity or server-side invalidation. Failing to handle it gracefully will lead to API call failures.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The SDK provides both `WebSocket` and `WebSocketV2` classes. Without clear documentation differentiating them, developers might use an older or less feature-rich version.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"Invalid API key, client code, password, or TOTP value provided during `generateSession` or subsequent API calls due to an expired session.","error":"Error during SmartAPI session generation or API call: AxiosError: Request failed with status code 401"},{"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.","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).","error":"ReferenceError: require is not defined in ES module scope"},{"fix":"Ensure that `smart_api.generateSession()` successfully completes before attempting any further API calls. Handle the `.catch()` block of `generateSession` to debug credential issues.","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.","error":"TypeError: Cannot read properties of undefined (reading 'access_token')"}],"ecosystem":"npm"}