Data Functions
Everything your script can pull in: quick data helpers, live ticks, minute bars, option Greeks, bid/ask and market depth, historical OHLC and tick data, the option chain, and market-wide analytics and corporate financials.
Quick Data Helpers
Clean, named, numeric data - no positional arrays, no strings to convert, no records check
Each helper is available both as TD.<name> and as a plain global - history(...) is the same as TD.history(...). If your script declares its own variable named history, notify, optionChain and so on, yours takes precedence.
Unlike the raw TD.* calls, which reply with { error }, helpers throw an Error on failure. Wrap them in try/catch, or an uncaught error stops the script.
history(symbol?, timeframe = "5m", count? | { count, session, exchange }) { time, open, high, low, close, volume }[], oldest first, loaded exactly as the chart loads them.optionChain(symbol?, { expiry?, greeks?, exchange? }) { symbol, expiry, exchange, expiries, strikes[{ strike, ce, pe }], atm, pcr, maxPain, totalCallOI, totalPutOI, support, resistance, at(strike) }expiryList(symbol?, { exchange? }) "YYYY-MM-DD"[], nearest first.topGainers(index = "NIFTY 50", top = 10)topLosers(...) { symbol, ltp, prevClose, change, changePct }[]marketGainers(segment = "NSEEQ", top = 10)marketLosers(...)volumeGainers(...) The fields above plus exchange, series, open, high, low, volume, turnover.mostActive(by = "volume" | "turnover", index = "NIFTY 50", top = 10) Mover fields plus series, time, volume, turnover, bid, bidQty, ask, askQty.oiGainers(series = "XX" | "CE" | "PE", top = 10)oiLosers(...) { symbol, expiry, strike, ltp, oi, prevOI, oiChange, oiChangePct }[]financialResults(symbol?, { period, nature, count = 4 }) { period, endDate, id, revenue, profit, margin, eps, statement }[], newest first (? crore).isMarketOpen(segment = "NSE_EQ") true / false / null.try { const bars = await history("NIFTY 50", "15m", 200); const chain = await optionChain("NIFTY"); console.log("Close", bars.at(-1).close, "| ATM", chain.atm, "PCR", chain.pcr?.toFixed(2), "Max pain", chain.maxPain); const atm = chain.at(chain.atm); console.log("ATM straddle:", atm.ce.ltp + atm.pe.ltp); console.table(await topGainers("NIFTY BANK", 5)); console.table(await financialResults("TCS")); if (await isMarketOpen("NSE_FO")) console.log("F&O is trading"); } catch (err) { console.warn(err.message); }
history() detailsTimeframes: 1m, 2m, 3m, 5m, 15m, 30m, 1h, 1D, 1W, 1M (also 5min, 60min, EOD, daily, weekly, monthly). session is "chart" (default; follows your chart), "RTH" or "ETH". With no count, it returns every bar loaded, up to your plan's bar limit. The symbol defaults to the chart's.
notify, chartLink and link are also plain globals - the same as TD.UI.notify, TD.UI.chartLink and TD.UI.link (see Logging, Alerts & Storage).
Live Market Data
TD.Feed and TD.on - subscribe to symbols and listen for ticks, 1- and 5-minute bars, option Greeks, bid/ask, market depth and heartbeats
TD.onChartBar does not subscribe the chart's symbol to tick events. To receive data for any symbol - including the chart's own - subscribe yourself.
TD.onStart = async () => { await TD.Feed.addSymbols(["RELIANCE", "HDFCBANK", "NIFTY-I", TD.Chart.getSymbol()]); }; TD.onStop = async () => { await TD.Feed.removeSymbols(["RELIANCE", "HDFCBANK", "NIFTY-I", TD.Chart.getSymbol()]); };
All subscriptions are also released automatically when the script stops.
Option symbol format. Write option symbols as underlying + expiry (YYMMDD) + strike + CE/PE, for example "NIFTY26100622600CE" (NIFTY, 06-10-2026, strike 22600, call). Any other format won't match a subscription, so no events arrive.
One listener receives events for all your subscribed symbols, so always check data.symbol.
TD.on("tick", (data) => { if (data.symbol === "RELIANCE" && data.ltp > 3000) { TD.log("RELIANCE above 3000: " + data.ltp); } });
"tick" Each trade update for a subscribed symbol. Also fires when Greeks or bid/ask change for the symbol. symbol, ltp, ltq, atp, volume, open, high, low, prevClose, oi, prevOi, turnover, bid, bidQty, ask, askQty, timestamp. Options also include iv, delta, theta, gamma, vega, rho."bar1min" When a 1-minute bar completes. symbol, timestamp, open, high, low, close, volume, oi."bar5min" When a 5-minute bar completes. Same fields as "bar1min"."greeks" When an option's Greeks update. Option symbols only. symbol, iv, delta, gamma, theta, vega, rho."bidAsk" When the top of book changes (NSE and MCX). symbol, bid, bidQty, ask, askQty."bidAskL2" When the 5-level market depth changes (BSE). symbol, depth, where depth is { totalBidQty, totalAskQty, bids[], asks[] } and each level is { orders, qty, price }, best price first."heartbeat" Periodically while connected. Carries a connection status payload (timestamp).A tick can contain only the fields that changed, so check a value before using it - if (data.ltp) .... Listeners also keep the script running until you click Stop.
"tick", "greeks", "bidAsk" and "bidAskL2" can fire many times a second. Keep listeners light, and throttle any logging or drawing (for example, at most once every 5 seconds per symbol). Events only arrive for symbols you have subscribed to with TD.Feed.addSymbols. See Example 6 for a complete script using every event.
Historical Data
TD.Historical - every function returns a Promise resolving to { status, records }, or { error } on failure
For plain bars, the history() helper is simpler: it returns named numeric fields and throws on failure. Use TD.Historical for ticks, whole-segment snapshots and top movers, or when you prefer { error } replies.
const res = await TD.Historical.getLastNBars({ symbol: "RELIANCE", nbars: 5, interval: "5min" }); if (res.error) { TD.log("Failed: " + res.error); return; } console.table(res.records);
getBars { symbol, from, to, interval }getLastNBars { symbol, nbars, interval }getTicks { symbol, from, to, bidask? }getLastNTicks { symbol, nticks, bidask? }getAllBars { timestamp, segment, interval } - all symbols in a segment at one timegetTopNGainersgetTopNLosersgetTopNVolumeGainers { segment, topn }, for example { segment:"NSEEQ", topn: 10 }Dates: "2026-09-15 09:15:00" in local time. Intervals: "1min", "5min", "15min", "30min", "60min", "EOD".
TD.onStart = async () => { const res = await TD.Historical.getBars({ symbol: "TCS", from: "2026-09-15 09:15:00", to: "2026-09-15 15:30:00", interval: "15min" }); TD.log("Bars received: " + (res.records ? res.records.length : 0)); };
Historical Data and Gainers & Losers are included in some plans only - see Plan Access.
Option Chain
TD.OptionChain - all parameters are optional, and the chain defaults to the chart's symbol and the nearest expiry
For ready-made totals - ATM, PCR, max pain, support and resistance - use the optionChain() helper. The raw calls below return rows you read through columns.
const chain = await TD.OptionChain.getOptionChain(); // chain.resolved -> { symbol:"NIFTY", expiry:"25-09-2026", exchange:"NSE" } // chain.records -> array of rows (each row is an array) // chain.columns -> which position in a row holds each field // chain.expiries -> list of available expiries
Read record fields through columns, never by hard-coded number. Column positions differ between BSE chains and the Greeks chain, and columns already accounts for that.
const c = chain.columns; for (const row of chain.records) { TD.log(row[c.strike], "CE OI", row[c.callOI], "PE OI", row[c.putOI]); }
getOptionChain(params?) symbol (e.g. "NIFTY" or "auto"), expiry ("28-04-2026", "2026-04-28", or a number where 0 is nearest and 1 is next), exchange ("NSE", "BSE", "MCX")getOptionChainWithGreeks(params?) Same parameters as getOptionChain.getExpiryList(params?) symbol, exchange. Returns records as ["2026-09-25", ...], nearest first.symbol, expiry, strike, callLTP, callVolume, callOI, callPrevOI, callBid, callBidQty, callAsk, callAskQty, callTimestamp, putLTP, putVolume, putOI, putPrevOI, putBid, putBidQty, putAsk, putAskQty, putTimestampcallPrevClose, putPrevClose, callDelta, callTheta, callVega, callGamma, callRho, callIV, and the same six Greeks for puts (put…).// Next week's BANKNIFTY chain, whatever the chart shows const bn = await TD.OptionChain.getOptionChain({ symbol: "BANKNIFTY", expiry: 1 });
Analytics
TD.Analytics - market-wide screens
getOIGainers / getOILosers { series:"CE"|"PE"|"XX", top }getIndexGainers / getIndexLosers { indexName:"NIFTY 50", segment:"EQ"|"FUT", top }getIndustryGainers / getIndustryLosers { industry:"Healthcare", segment, top }getMostActiveByTurnover / getMostActiveByVolume { indexName, segment, top }const g = await TD.Analytics.getIndexGainers({ indexName: "NIFTY 50", segment: "EQ", top: 5 }); console.table(g.records);
The helpers topGainers, topLosers, marketGainers, marketLosers, volumeGainers, mostActive, oiGainers and oiLosers return the same screens as clean named arrays - see Quick Data Helpers.
Corporate Data
TD.Corporate - per-company financials, in two steps
First find the record id with getAllResults, then fetch the statement.
const list = await TD.Corporate.getAllResults({ symbol: "TCS", nature: "consolidated", period: "quarterly", type: "pl" }); console.table(list.records); // find the id of the result you want const pnl = await TD.Corporate.getPnL({ id: "<record id>", cumulative: false }); console.log("Revenue:", pnl.records.Income.Operating.RevenueFromOperations, "cr");
records holdsgetAllResults An array of filings: { id, ReportingQuarter, ReportingStartDt, ReportingEndDt, Nature, Audited }.getPnL The statement object (not an array): records.Income.Operating.RevenueFromOperations, records.Profit.PnLForPeriod, records.EPS.BasicEPS.getBalancesheet The statement object: records.Assets.TotalAssets, records.EquityAndLiabilities.Equity.TotalEquity.getCashflow The statement object: records.CashFlowSummary.CashFlowOperating.getPnL, getBalancesheet and getCashflow all take { id, cumulative } and resolve to { status, records }. Figures are in ? crore.
Balance sheets and cash flows aren't filed every quarter. A filing without one has its figures as 0 or "".
The financialResults() helper joins these steps for you and returns { period, endDate, id, revenue, profit, margin, eps, statement }[] - see Quick Data Helpers.
Market Status
TD.getMarketStatus() answers from the live feed
records is an object with one entry per segment, which reads "OPEN" while that segment is trading.
const ms = await TD.getMarketStatus(); if (!ms.error && ms.records.NSE_EQ === "OPEN") console.log("NSE equity is open"); // or, as a plain yes/no if (await isMarketOpen("NSE_FO")) console.log("F&O is trading");
If the feed disconnects, the last status it reported is returned. If it has never reported one, the reply is { error: "Market status is not available -- the live feed is not connected." }.
Plan Access for Data APIs
Data APIs a script calls are gated by your plan, the same as the panels that show that data
TD.Historical.getTicks, getBars, getAllBars, getLastNTicks, getLastNBars; history()TD.Historical.getTopN*; all of TD.Analytics; topGainers, topLosers, marketGainers, marketLosers, volumeGainers, mostActive, oiGainers, oiLosersTD.OptionChain; optionChain, expiryListTD.Corporate; financialResults{ error: "<Feature> API access is not included in your plan. Upgrade your plan to use it from scripts." }. A helper throws the same message.history() and TD.Indicators.subscribe also refuse symbols outside your plan's segments: "X is not included in your plan's segments."history() returns at most your plan's bar limit.Historical, option-chain, analytics and corporate calls are one-shot requests - fetch once at the top of your script or in TD.onStart, or on a timer of a minute or more. Never call them from inside a "tick" listener.