Skip to content

About

TypeScript SDK for Angel One SmartAPI: orders, market data and live WebSocket feeds.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

112 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ“ˆ 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.

Installation β€’ Quick Start β€’ API Reference β€’ WebSockets β€’ Examples β€’ Contributing


✨ 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

About

TypeScript SDK for Angel One SmartAPI: orders, market data and live WebSocket feeds.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages