npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@backstacked/smartapi-typescript

v1.0.30

Published

TypeScript SDK for Angel One SmartAPI - A comprehensive trading and market data API client

Downloads

24

Readme

📈 SmartAPI TypeScript SDK

Unofficial TypeScript/JavaScript SDK for Angel One SmartAPI

npm version npm downloads License: ISC TypeScript Node

A comprehensive trading and market data API client with full type safety and modern JavaScript features.

InstallationQuick StartAPI ReferenceWebSocketsExamplesContributing


✨ Features

  • 🎯 Full TypeScript Support - Complete type definitions for all APIs
  • 🔒 Type Safety - Compile-time type checking and IntelliSense
  • 🚀 Modern JavaScript - ES2021 target with async/await support
  • 📡 WebSocket Feeds - Real-time market data with multiple protocols
  • 🔄 Auto Session Management - Automatic token refresh and session handling
  • 📚 Comprehensive Documentation - Detailed examples and type hints
  • 🧪 Well Tested - Migrated from battle-tested JavaScript SDK
  • 🌐 Browser & Node.js - Works in both environments

📦 Installation

npm install @backstacked/smartapi-typescript

Or using yarn:

yarn add @backstacked/smartapi-typescript

🚀 Quick Start

Basic Setup

import { SmartAPI } from "@backstacked/smartapi-typescript";

// Initialize the client
const smartApi = new SmartAPI({
  api_key: "your_api_key",
});

// Optional: Initialize public IP for better tracking
await smartApi.initPublicIp();

// Generate session with credentials
const session = await smartApi.generateSession(
  "CLIENT_CODE",
  "PASSWORD",
  "TOTP_CODE"
);

console.log("Session:", session);

// Fetch user profile
const profile = await smartApi.getProfile();
console.log("Profile:", profile);

Session Management

// Use existing tokens
const smartApi = new SmartAPI({
  api_key: "your_api_key",
  access_token: "your_access_token",
  refresh_token: "your_refresh_token",
});

// Handle session expiry
smartApi.setSessionExpiryHook(() => {
  console.log("Session expired! Re-authenticating...");
  // Implement your re-authentication logic here
});

📊 API Methods

Trading Operations

Place Order

const orderResponse = await smartApi.placeOrder({
  variety: "NORMAL",
  tradingsymbol: "SBIN-EQ",
  symboltoken: "3045",
  transactiontype: "BUY",
  exchange: "NSE",
  ordertype: "LIMIT",
  producttype: "INTRADAY",
  duration: "DAY",
  price: "500.00",
  squareoff: "0",
  stoploss: "0",
  quantity: "1",
});

Modify Order

const modifyResponse = await smartApi.modifyOrder({
  variety: "NORMAL",
  orderid: "211013000000001",
  tradingsymbol: "SBIN-EQ",
  symboltoken: "3045",
  transactiontype: "BUY",
  exchange: "NSE",
  ordertype: "LIMIT",
  producttype: "INTRADAY",
  duration: "DAY",
  price: "505.00",
  squareoff: "0",
  stoploss: "0",
  quantity: "1",
});

Cancel Order

const cancelResponse = await smartApi.cancelOrder({
  variety: "NORMAL",
  orderid: "211013000000001",
});

Portfolio Management

Get Holdings

const holdings = await smartApi.getHolding();
console.log("Holdings:", holdings);

Get Positions

const positions = await smartApi.getPosition();
console.log("Positions:", positions);

Convert Position

const convertResponse = await smartApi.convertPosition({
  exchange: "NSE",
  oldproducttype: "DELIVERY",
  newproducttype: "MARGIN",
  tradingsymbol: "SBIN-EQ",
  transactiontype: "BUY",
  quantity: 1,
  type: "DAY",
});

Order Book & Trade Book

// Get order book
const orderBook = await smartApi.getOrderBook();

// Get trade book
const tradeBook = await smartApi.getTradeBook();

// Get RMS (Risk Management System) limits
const rms = await smartApi.getRMS();

Market Data

Get Historical Candle Data

const candleData = await smartApi.getCandleData({
  exchange: "NSE",
  symboltoken: "3045",
  interval: "ONE_DAY",
  fromdate: "2023-01-01 09:15",
  todate: "2023-12-31 15:30",
});

Search Scrip

const searchResults = await smartApi.searchScrip({
  exchange: "NSE",
  searchscrip: "RELIANCE",
});

Get Market Data

const marketData = await smartApi.marketData({
  mode: "FULL",
  exchangeTokens: {
    NSE: ["3045", "2885"],
  },
});

GTT (Good Till Triggered) Orders

Create GTT Rule

const gttRule = await smartApi.createRule({
  tradingsymbol: "SBIN-EQ",
  symboltoken: "3045",
  exchange: "NSE",
  producttype: "DELIVERY",
  transactiontype: "BUY",
  price: 500,
  qty: 10,
  disclosedqty: 10,
  triggerprice: 490,
  timeperiod: 365,
});

Get GTT Rule List

const gttList = await smartApi.ruleList({
  status: ["NEW", "CANCELLED"],
  page: 1,
  count: 10,
});

📡 WebSocket Feeds

WebSocket V2 (Recommended)

The most advanced WebSocket implementation with binary data parsing.

import {
  WebSocketV2,
  ACTION,
  MODE,
  EXCHANGES,
} from "@backstacked/smartapi-typescript";

const ws = new WebSocketV2({
  jwttoken: "YOUR_JWT_TOKEN",
  apikey: "YOUR_API_KEY",
  clientcode: "YOUR_CLIENT_CODE",
  feedtype: "order_feed",
});

// Connect to WebSocket
await ws.connect();

// Subscribe to market data
ws.fetchData({
  correlationID: "unique_correlation_id",
  action: ACTION.Subscribe,
  mode: MODE.LTP, // LTP, Quote, SnapQuote, or Depth
  exchangeType: EXCHANGES.nse_cm,
  tokens: ["3045", "2885"], // Stock tokens
});

// Listen for tick data
ws.on("tick", (data) => {
  console.log("Market Data:", data);
});

// Unsubscribe from tokens
ws.fetchData({
  correlationID: "unique_correlation_id",
  action: ACTION.Unsubscribe,
  mode: MODE.LTP,
  exchangeType: EXCHANGES.nse_cm,
  tokens: ["3045"],
});

// Enable reconnection with exponential backoff
ws.reconnection("exponential", 3000, 2);

// Close connection
ws.close();

WebSocket Client

For order feed and other updates.

import { WebSocketClient } from "@backstacked/smartapi-typescript";

const wsClient = new WebSocketClient({
  clientcode: "YOUR_CLIENT_CODE",
  jwttoken: "YOUR_JWT_TOKEN",
  apikey: "YOUR_API_KEY",
  feedtype: "order_feed",
});

await wsClient.connect();

wsClient.on("tick", (data) => {
  console.log("Order Update:", data);
});

wsClient.fetchData("subscribe", "order_feed");

Legacy WebSocket

For backward compatibility with compressed data feeds.

import { WebSocket } from "@backstacked/smartapi-typescript";

const ws = new WebSocket({
  client_code: "YOUR_CLIENT_CODE",
  feed_token: "YOUR_FEED_TOKEN",
});

await ws.connect();

ws.on("tick", (data) => {
  console.log("Market Tick:", data);
});

// Subscribe to market watch
ws.runScript("nse_cm|2885&nse_cm|3045", "mw");

🎯 TypeScript Types

All methods come with complete type definitions:

import {
  SmartAPIParams,
  OrderParams,
  ModifyOrderParams,
  CancelOrderParams,
  ConvertPositionParams,
  GTTRuleParams,
  CandleDataParams,
  WebSocketV2Params,
  FetchDataRequest,
  ACTION,
  MODE,
  EXCHANGES,
} from "@backstacked/smartapi-typescript";

// Full IntelliSense support
const orderParams: OrderParams = {
  variety: "NORMAL",
  tradingsymbol: "SBIN-EQ",
  symboltoken: "3045",
  transactiontype: "BUY",
  exchange: "NSE",
  ordertype: "LIMIT",
  producttype: "INTRADAY",
  duration: "DAY",
  price: "500.00",
  squareoff: "0",
  stoploss: "0",
  quantity: "1",
};

💡 Examples

Complete Trading Flow

import { SmartAPI } from "@backstacked/smartapi-typescript";

async function tradingExample() {
  const smartApi = new SmartAPI({ api_key: "your_api_key" });

  try {
    // 1. Generate session
    const session = await smartApi.generateSession(
      "CLIENT_CODE",
      "PASSWORD",
      "TOTP"
    );
    console.log("Logged in successfully");

    // 2. Get account profile
    const profile = await smartApi.getProfile();
    console.log("Account:", profile.data.name);

    // 3. Search for stock
    const scrip = await smartApi.searchScrip({
      exchange: "NSE",
      searchscrip: "RELIANCE",
    });

    // 4. Place buy order
    const order = await smartApi.placeOrder({
      variety: "NORMAL",
      tradingsymbol: scrip[0].tradingsymbol,
      symboltoken: scrip[0].symboltoken,
      transactiontype: "BUY",
      exchange: "NSE",
      ordertype: "MARKET",
      producttype: "INTRADAY",
      duration: "DAY",
      price: "0",
      squareoff: "0",
      stoploss: "0",
      quantity: "1",
    });
    console.log("Order placed:", order.data.orderid);

    // 5. Check order status
    const orderBook = await smartApi.getOrderBook();
    console.log("Order Book:", orderBook);

    // 6. Get positions
    const positions = await smartApi.getPosition();
    console.log("Current Positions:", positions);
  } catch (error) {
    console.error("Trading Error:", error);
  }
}

tradingExample();

Real-time Market Monitoring

import {
  WebSocketV2,
  ACTION,
  MODE,
  EXCHANGES,
} from "@backstacked/smartapi-typescript";

async function monitorMarket() {
  const ws = new WebSocketV2({
    jwttoken: "YOUR_JWT_TOKEN",
    apikey: "YOUR_API_KEY",
    clientcode: "YOUR_CLIENT_CODE",
    feedtype: "order_feed",
  });

  await ws.connect();

  // Subscribe to multiple stocks with different modes
  const stocks = {
    nifty50: { token: "99926000", name: "NIFTY 50" },
    reliance: { token: "2885", name: "RELIANCE" },
    tcs: { token: "11536", name: "TCS" },
  };

  ws.fetchData({
    correlationID: "market_monitor",
    action: ACTION.Subscribe,
    mode: MODE.SnapQuote,
    exchangeType: EXCHANGES.nse_cm,
    tokens: Object.values(stocks).map((s) => s.token),
  });

  ws.on("tick", (data) => {
    const stock = Object.values(stocks).find(
      (s) => s.token === data.token?.toString()
    );
    console.log(`${stock?.name}: LTP=${data.last_traded_price}`);
  });

  // Auto-reconnect on disconnect
  ws.reconnection("exponential", 3000, 2);
}

monitorMarket();

🛠️ Development

Building from Source

# Clone the repository
git clone https://github.com/backstacked/smartapi-typescript.git
cd smartapi-typescript

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

Project Structure

smartapi-typescript/
├── lib/                    # TypeScript source files
│   ├── index.ts           # Main entry point
│   ├── smartapi-connect.ts # Core API client
│   ├── types.ts           # Type definitions
│   ├── websocket.ts       # Legacy WebSocket
│   ├── websocket_client.ts # WebSocket client
│   ├── websocket2.0.ts    # WebSocket V2
│   ├── ws_orderupdates.ts # Order updates WebSocket
│   └── winston_log.ts     # Logger
├── config/                 # Configuration files
│   ├── api.ts             # API endpoints
│   └── constant.ts        # Constants
├── dist/                   # Compiled JavaScript output
├── test/                   # Test files
├── tsconfig.json          # TypeScript configuration
└── package.json           # Package metadata

🤝 Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Contribution Guidelines

  • Follow TypeScript best practices
  • Add tests for new features
  • Update documentation
  • Maintain backward compatibility
  • Use meaningful commit messages

📝 Changelog

Version 1.0.30 (Current)

  • 📚 Updated comprehensive README documentation
  • ✨ Added detailed API examples and usage guides
  • 🎨 Enhanced formatting with badges and navigation
  • 📖 Added complete WebSocket implementation examples
  • 💡 Included real-world trading flow examples
  • 🤝 Added contribution guidelines and project structure

Version 1.0.29

  • 📝 Enhanced README with comprehensive documentation
  • 🎨 Added badges and better formatting

Version 1.0.28

  • ✨ Full TypeScript migration complete
  • ✨ Scoped package: @backstacked/smartapi-typescript
  • ✨ Added comprehensive type definitions
  • ✨ ES2021 target for modern features
  • 🔧 Improved type safety across all modules
  • 🔧 Refactored async operations outside constructors
  • 🔧 Enhanced string handling and escaping

⚠️ Disclaimer

This is an unofficial SDK and is not affiliated with, endorsed by, or connected to Angel One Ltd. Use at your own risk.

  • This SDK is for educational and development purposes
  • Always test in a sandbox/paper trading environment first
  • The authors are not responsible for any financial losses
  • Review Angel One's terms of service before using their API

📄 License

ISC License - see LICENSE file for details


🔗 Links


💬 Support

If you find this project helpful, please give it a ⭐️ on GitHub!

For questions and support:


Made with ❤️ by the community