@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
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-typescriptOr 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 testProject 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:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- NPM Package: @backstacked/smartapi-typescript
- GitHub Repository: backstacked/smartapi-typescript
- Angel One SmartAPI Docs: smartapi.angelbroking.com
- Issues & Bug Reports: GitHub Issues
💬 Support
If you find this project helpful, please give it a ⭐️ on GitHub!
For questions and support:
- Open an issue
- Check existing discussions
Made with ❤️ by the community
