@thoshpathi/utils-smartapi
Version:
Extended utilities for Angel One's smartapi-javascript SDK, including custom methods and helpers for market data like candles, P&L, and more.
194 lines (190 loc) • 6.34 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/smartapi/smartapi_enhanced.ts
var smartapi_enhanced_exports = {};
__export(smartapi_enhanced_exports, {
SmartApiEnhanced: () => SmartApiEnhanced,
SmartApiError: () => SmartApiError,
default: () => SmartApiEnhanced
});
module.exports = __toCommonJS(smartapi_enhanced_exports);
var import_smartapi_javascript = require("@thoshpathi/smartapi-javascript");
// src/smartapi/ohlc_data.ts
var OHLCData = class {
constructor(date, open, high, low, close) {
const parsedDate = new Date(date);
if (isNaN(parsedDate.getTime())) {
throw new Error("Invalid date");
}
if ([open, high, low, close].some((value) => isNaN(value))) {
throw new Error("Open, High, Low, and Close must be valid numbers");
}
if (low > high) {
throw new Error("Low cannot be greater than High");
}
this.date = parsedDate;
this.open = open;
this.high = high;
this.low = low;
this.close = close;
}
};
// src/smartapi/smartapi_enhanced.ts
var import_date_fns = require("date-fns");
var SmartApiError = class extends Error {
constructor(message, errorCode) {
super(message);
this.errorCode = errorCode;
}
};
var SmartApiEnhanced = class extends import_smartapi_javascript.SmartAPI {
constructor(params, apiRetryDelayMs, logger) {
super(params);
this.apiRetryDelayMs = apiRetryDelayMs;
this.logger = logger;
this.apiRetryDelayMs = apiRetryDelayMs;
this.logger = logger;
}
getData(response) {
if (response.status && response.errorcode === "") return response.data;
this.logger?.e("smart api error response", response);
throw new SmartApiError(response.message, response.errorcode);
}
async retryCallback(callback) {
let response = await callback();
if ("status" in response && response.status === 500) {
this.logger?.w("smart api 500 error. retry once");
await new Promise((resolve) => setTimeout(resolve, this.apiRetryDelayMs));
response = await callback();
}
return this.getData(response);
}
async generateSession_e(clientCode, clientMpin, totp) {
const response = await this.generateSession(
clientCode,
clientMpin,
totp
);
return this.getData(response);
}
async logout_e(clientCode) {
const response = await this.logout(clientCode);
return this.getData(response);
}
fetchProfile() {
return this.retryCallback(() => this.getProfile());
}
fetchRMS() {
return this.retryCallback(() => this.getRMS());
}
fetchOrderBook() {
return this.retryCallback(() => this.getOrderBook());
}
async fetchMarketData(params) {
const { mode = "LTP", exchangeTokens } = params;
for (const prop in exchangeTokens) {
exchangeTokens[prop] = [...new Set(exchangeTokens[prop])];
}
const responseData = await this.retryCallback(
() => this.marketData({ mode, exchangeTokens })
);
return responseData.fetched;
}
fetchTokensLtp(exchangeTokens) {
return this.fetchMarketData({ mode: "LTP", exchangeTokens });
}
fetchTokensOhlc(exchangeTokens) {
return this.fetchMarketData({ mode: "OHLC", exchangeTokens });
}
fetchTokensQuote(exchangeTokens) {
return this.fetchMarketData({ mode: "FULL", exchangeTokens });
}
placeOrder_e(params) {
return this.retryCallback(() => this.placeOrder(params));
}
fetchCandlesDatetimeString(date) {
return (0, import_date_fns.format)(date, "yyyy-MM-dd HH:mm");
}
async fetchCandleData(params) {
const {
symboltoken,
fromdate,
todate,
exchange = "NSE",
interval = "FIFTEEN_MINUTE"
} = params;
const responseData = await this.retryCallback(
() => this.getCandleData({
symboltoken,
fromdate: this.fetchCandlesDatetimeString(fromdate),
todate: this.fetchCandlesDatetimeString(todate),
exchange,
interval
})
);
return responseData.map((data) => {
const date = new Date(data[0]), open = data[1], high = data[2], low = data[3], close = data[4];
return new OHLCData(date, +open, +high, +low, +close);
});
}
async fetchCompletedOrders(orderResponses) {
const ordersBook = await this.fetchOrderBook();
if (ordersBook == null || ordersBook.length <= 0) {
this.logger?.c("failed to get orders book");
return null;
}
const orderIds = orderResponses.map((v) => v.orderid);
const filteredOrders = ordersBook.filter(
(v) => orderIds.includes(v.orderid)
);
if (filteredOrders == null || filteredOrders.length <= 0) {
this.logger?.w("specific orders not exist in order book", orderIds);
return null;
}
const completedOrders = filteredOrders.filter(
(v) => v.status === "complete"
);
if (completedOrders.length <= 0) {
this.logger?.c("all orders are not completed", orderIds);
return null;
}
return completedOrders;
}
async fetchOptionGreeks(params) {
const response = await this.optionGreek(params);
return this.getData(response);
}
async fetchGainersLosers(params) {
const response = await this.gainersLosers(params);
return this.getData(response);
}
async fetchPutCallRatio() {
const response = await this.putCallRatio();
return this.getData(response);
}
async fetchOIBuildup(params) {
const response = await this.oIBuildup(params);
return this.getData(response);
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
SmartApiEnhanced,
SmartApiError
});