stock-nse-india
Version:
This package will help us to get equity/index details and historical data from National Stock Exchange of India.
306 lines • 12.3 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRetryableEquityEndpointError = exports.mapChartingToIntradayData = exports.mapIntradayApiResponse = exports.isIntradayDataShape = exports.equityRefererSymbol = exports.mapPreOpenRowToEquityTradeInfo = exports.mapQuoteEquityTradeInfoResponse = exports.isEquityTradeInfoShape = exports.mapPreOpenRowToEquityDetails = exports.applyEquityDetailsEnrichment = exports.mapQuoteEquityResponse = exports.isEquityDetailsShape = void 0;
function num(value, fallback = 0) {
return typeof value === 'number' && !Number.isNaN(value) ? value : fallback;
}
function str(value, fallback = '') {
return typeof value === 'string' ? value : fallback;
}
function isEquityDetailsShape(raw) {
if (!raw || typeof raw !== 'object')
return false;
const o = raw;
return typeof o.info === 'object' && o.info !== null && typeof o.priceInfo === 'object';
}
exports.isEquityDetailsShape = isEquityDetailsShape;
/** Pass-through when NSE returns standard quote-equity JSON. */
function mapQuoteEquityResponse(raw) {
if (!isEquityDetailsShape(raw)) {
throw new Error('Response is not a valid quote-equity payload');
}
return raw;
}
exports.mapQuoteEquityResponse = mapQuoteEquityResponse;
function normalizePreOpenMarket(detail) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
const po = (_a = detail === null || detail === void 0 ? void 0 : detail.preOpenMarket) !== null && _a !== void 0 ? _a : {};
const atoRaw = (_b = po.ato) !== null && _b !== void 0 ? _b : {};
return {
preopen: (_c = po.preopen) !== null && _c !== void 0 ? _c : [],
ato: {
buy: (_e = (_d = atoRaw.buy) !== null && _d !== void 0 ? _d : atoRaw.totalBuyQuantity) !== null && _e !== void 0 ? _e : 0,
sell: (_g = (_f = atoRaw.sell) !== null && _f !== void 0 ? _f : atoRaw.totalSellQuantity) !== null && _g !== void 0 ? _g : 0
},
IEP: (_h = po.IEP) !== null && _h !== void 0 ? _h : 0,
totalTradedVolume: (_j = po.totalTradedVolume) !== null && _j !== void 0 ? _j : 0,
finalPrice: (_k = po.finalPrice) !== null && _k !== void 0 ? _k : 0,
finalQuantity: (_l = po.finalQuantity) !== null && _l !== void 0 ? _l : 0,
lastUpdateTime: (_m = po.lastUpdateTime) !== null && _m !== void 0 ? _m : '',
totalBuyQuantity: (_o = po.totalBuyQuantity) !== null && _o !== void 0 ? _o : 0,
totalSellQuantity: (_p = po.totalSellQuantity) !== null && _p !== void 0 ? _p : 0,
atoBuyQty: (_q = po.atoBuyQty) !== null && _q !== void 0 ? _q : 0,
atoSellQty: (_r = po.atoSellQty) !== null && _r !== void 0 ? _r : 0
};
}
function applyEquityDetailsEnrichment(details, enrichment) {
var _a, _b, _c;
const companyName = (_a = enrichment.companyName) === null || _a === void 0 ? void 0 : _a.trim();
const isin = (_b = enrichment.isin) === null || _b === void 0 ? void 0 : _b.trim();
const industry = (_c = enrichment.industry) === null || _c === void 0 ? void 0 : _c.trim();
const next = {
...details,
info: { ...details.info },
metadata: { ...details.metadata },
industryInfo: { ...details.industryInfo }
};
if (enrichment.currentMarketType) {
next.currentMarketType = enrichment.currentMarketType;
}
if (companyName) {
next.info.companyName = companyName;
}
if (isin) {
next.info.isin = isin;
next.metadata.isin = isin;
}
if (industry && industry !== '-') {
next.info.industry = industry;
next.metadata.industry = industry;
next.industryInfo.industry = industry;
next.industryInfo.basicIndustry = industry;
}
return next;
}
exports.applyEquityDetailsEnrichment = applyEquityDetailsEnrichment;
function mapPreOpenRowToEquityDetails(row, symbol, currentMarketType = 'preOpen') {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
const meta = ((_a = row.metadata) !== null && _a !== void 0 ? _a : {});
const upper = symbol.toUpperCase();
const series = str(meta.series, 'EQ');
const lastPrice = num(meta.lastPrice, num((_b = row.priceInfo) === null || _b === void 0 ? void 0 : _b.lastPrice));
const change = num(meta.change, num((_c = row.priceInfo) === null || _c === void 0 ? void 0 : _c.change));
const pChange = num(meta.pChange, num((_d = row.priceInfo) === null || _d === void 0 ? void 0 : _d.pChange));
const previousClose = num(meta.previousClose, num((_e = row.priceInfo) === null || _e === void 0 ? void 0 : _e.prevClose, lastPrice));
const yearHigh = num(meta.yearHigh, lastPrice);
const yearLow = num(meta.yearLow, lastPrice);
return {
info: {
symbol: upper,
companyName: str(meta.companyName, upper),
industry: str(meta.industry),
activeSeries: [series],
debtSeries: [],
tempSuspendedSeries: [],
isFNOSec: false,
isCASec: false,
isSLBSec: false,
isDebtSec: false,
isSuspended: false,
isETFSec: false,
isDelisted: false,
isin: str(meta.isinCode),
slb_isin: '',
listingDate: str(meta.listingDate),
isMunicipalBond: false,
isHybridSymbol: false,
segment: 'CM',
isTop10: false,
identifier: str(meta.identifier, `${upper}${series}`)
},
metadata: {
series,
symbol: upper,
isin: str(meta.isinCode),
status: str(meta.status, 'Active'),
listingDate: str(meta.listingDate),
industry: str(meta.industry),
lastUpdateTime: str(meta.lastUpdateTime),
pdSectorPe: 0,
pdSymbolPe: 0,
pdSectorInd: '',
pdSectorIndAll: []
},
securityInfo: {
boardStatus: 'Active',
tradingStatus: 'Active',
tradingSegment: 'CM',
sessionNo: '',
slb: 'No',
classOfShare: 'Equity',
derivatives: 'Yes',
surveillance: { surv: null, desc: null },
faceValue: 0,
issuedSize: 0
},
sddDetails: { SDDAuditor: '', SDDStatus: '' },
currentMarketType,
priceInfo: {
lastPrice,
change,
pChange,
previousClose,
open: (_g = (_f = row.priceInfo) === null || _f === void 0 ? void 0 : _f.open) !== null && _g !== void 0 ? _g : lastPrice,
close: (_j = (_h = row.priceInfo) === null || _h === void 0 ? void 0 : _h.close) !== null && _j !== void 0 ? _j : lastPrice,
vwap: lastPrice,
stockIndClosePrice: 0,
lowerCP: '',
upperCP: '',
pPriceBand: '',
basePrice: previousClose,
intraDayHighLow: { min: yearLow, max: yearHigh, value: lastPrice },
weekHighLow: {
min: yearLow,
minDate: '',
max: yearHigh,
maxDate: '',
value: lastPrice
},
iNavValue: null,
checkINAV: false,
tickSize: 0.05,
ieq: ''
},
industryInfo: {
macro: '',
sector: '',
industry: str(meta.industry),
basicIndustry: str(meta.industry)
},
preOpenMarket: normalizePreOpenMarket(row.detail)
};
}
exports.mapPreOpenRowToEquityDetails = mapPreOpenRowToEquityDetails;
function isEquityTradeInfoShape(raw) {
if (!raw || typeof raw !== 'object')
return false;
const o = raw;
return typeof o.marketDeptOrderBook === 'object' && o.marketDeptOrderBook !== null;
}
exports.isEquityTradeInfoShape = isEquityTradeInfoShape;
/** Pass-through when NSE returns standard quote-equity trade_info JSON. */
function mapQuoteEquityTradeInfoResponse(raw) {
if (!isEquityTradeInfoShape(raw)) {
throw new Error('Response is not a valid quote-equity trade_info payload');
}
return raw;
}
exports.mapQuoteEquityTradeInfoResponse = mapQuoteEquityTradeInfoResponse;
const emptyValueAtRisk = {
securityVar: 0,
indexVar: 0,
varMargin: 0,
extremeLossMargin: 0,
adhocMargin: 0,
applicableMargin: 0
};
/**
* Build EquityTradeInfo from pre-open row when quote-equity trade_info is blocked.
*/
function mapPreOpenRowToEquityTradeInfo(row, symbol) {
var _a;
const meta = ((_a = row.metadata) !== null && _a !== void 0 ? _a : {});
const po = normalizePreOpenMarket(row.detail);
const series = str(meta.series, 'EQ');
const preopen = po.preopen;
const bid = preopen
.filter((level) => level.buyQty > 0)
.map((level) => ({ price: level.price, quantity: level.buyQty }));
const ask = preopen
.filter((level) => level.sellQty > 0)
.map((level) => ({ price: level.price, quantity: level.sellQty }));
const totalTradedVolume = num(po.totalTradedVolume, num(meta.finalQuantity));
const totalTurnover = num(meta.totalTurnover);
const totalTradedValue = totalTurnover > 0 ? totalTurnover / 100000 : 0;
const marketCapRaw = meta.marketCap;
const totalMarketCap = typeof marketCapRaw === 'number'
? marketCapRaw
: num(marketCapRaw, 0);
const open = num(po.finalPrice, num(meta.iep, num(meta.lastPrice)));
return {
noBlockDeals: true,
bulkBlockDeals: [],
marketDeptOrderBook: {
totalBuyQuantity: po.totalBuyQuantity,
totalSellQuantity: po.totalSellQuantity,
open,
bid,
ask,
tradeInfo: {
totalTradedVolume,
totalTradedValue,
totalMarketCap,
ffmc: 0,
impactCost: 0,
cmDailyVolatility: '',
cmAnnualVolatility: '',
marketLot: '',
activeSeries: series
},
valueAtRisk: { ...emptyValueAtRisk }
},
securityWiseDP: {
quantityTraded: totalTradedVolume,
deliveryQuantity: 0,
deliveryToTradedQuantity: 0,
seriesRemarks: null,
secWiseDelPosDate: po.lastUpdateTime || ''
}
};
}
exports.mapPreOpenRowToEquityTradeInfo = mapPreOpenRowToEquityTradeInfo;
/** Map NSE API/charting symbol param to equity page symbol for Referer warm-up. */
function equityRefererSymbol(apiSymbol) {
const s = apiSymbol.trim().toUpperCase();
if (/^[A-Z0-9&-]+-EQ$/i.test(s)) {
return s.replace(/-EQ$/i, '');
}
const identifierMatch = /^(.*?)(EQ|BE|BL|BZ|IL|RL|W3|GB|GS|SM|ST)N$/i.exec(s);
if (identifierMatch && identifierMatch[1].length > 0) {
return identifierMatch[1];
}
return s;
}
exports.equityRefererSymbol = equityRefererSymbol;
function isIntradayDataShape(raw) {
if (!raw || typeof raw !== 'object')
return false;
const o = raw;
return Array.isArray(o.grapthData);
}
exports.isIntradayDataShape = isIntradayDataShape;
function mapIntradayApiResponse(raw, symbol) {
if (!isIntradayDataShape(raw)) {
throw new Error('Response is not a valid intraday chart payload');
}
return {
...raw,
name: raw.name || symbol.toUpperCase()
};
}
exports.mapIntradayApiResponse = mapIntradayApiResponse;
function mapChartingToIntradayData(chart, symbol) {
var _a;
const upper = symbol.toUpperCase();
const points = (_a = chart.data) !== null && _a !== void 0 ? _a : [];
const grapthData = points.map((point) => [
point.time,
point.close,
'NM'
]);
const closePrice = points.length ? points[points.length - 1].close : 0;
return {
identifier: `${upper}EQN`,
name: upper,
grapthData,
closePrice
};
}
exports.mapChartingToIntradayData = mapChartingToIntradayData;
function isRetryableEquityEndpointError(error) {
if (!(error instanceof Error))
return false;
return /status code (401|403|404|502|503)/.test(error.message);
}
exports.isRetryableEquityEndpointError = isRetryableEquityEndpointError;
//# sourceMappingURL=equity-mappers.js.map