On this page
One endpoint returns price history: TPSeries. This guide takes you from "I know the name of a stock" to a clean OHLCV series at whatever interval you want, and is honest about the two places the API will not help you.
Two limits shape everything below, and neither is a matter of opinion:
- There is no interval parameter. TPSeries takes a start time and an end time and nothing else. The API specification publishes no way to ask for 5-minute or daily candles. You aggregate them yourself, and the code to do it is below.
- There is no end-of-day endpoint. No daily bars, no adjusted closes, no corporate-action history. TPSeries is the whole of the historical surface.
The whole flow
Four steps, and only the last two need credentials.
- Download the symbol masterA public ZIP per segment, no token required. Instruments & the symbol master covers every file and its column layout.
- Find the contract and take its TokenTPSeries is addressed by numeric token, not by trading symbol.
RELIANCE-EQis token2885;NIFTY INDEXis26000. - Convert your date range to Unix seconds
standetare seconds since 1 January 1970. Indian markets run on IST, which is UTC+5:30, and getting that offset wrong is the most common reason an empty array comes back. - Call TPSeries and merge the candlesNewest first, as strings, in a JSON array on success and a JSON object on failure.
| Step | Needs a token? | What you get |
|---|---|---|
1. Download <SEG>_symbols.txt.zip | no | Every contract on that segment, with its numeric Token. |
2. Look up your contract by TradingSymbol | no | The Token and the Exchange that owns it. |
| 3. Convert your dates to Unix seconds | no | st and et, in IST. |
4. POST to TPSeries | yes | Candles, newest first, as strings. |
| 5. Aggregate to the interval you want | no | 5m, 15m, 30m, 1h or daily bars. |
What TPSeries takes
| Field | Value | Notes | |
|---|---|---|---|
uid | required | IN001 | The logged-in user ID. |
exch | required | NSE | The segment the token belongs to. A token queried against the wrong segment returns nothing, not an error. |
token | required | 2885 | The numeric contract token from the symbol master. Not the trading symbol. |
st | optional | 1759722300 | Start time, Unix seconds. Interpret your dates as IST. |
et | optional | 1759744800 | End time, Unix seconds. |
| interval | does not exist | - | Documentation information not available. No candle-interval parameter is published, and none is documented as a default. The published sample shows one-minute candles. |
Both exchanges below work the same way. The segment goes in exch and must be the segment the token belongs to - an NSE token with exch: "NFO" returns nothing rather than an error.
| Market | exch | Symbol master | Trading hours (IST) |
|---|---|---|---|
| NSE cash and indices | NSE | NSE_symbols.txt.zip | 09:15 – 15:30 |
| NSE equity derivatives | NFO | NFO_symbols.txt.zip | 09:15 – 15:30 |
| NSE currency | CDS | CDS_symbols.txt.zip | 09:00 – 17:00 |
| NSE commodity | NCOM | NCOM_symbols.txt.zip | 09:00 – 23:30 |
| BSE cash | BSE | BSE_symbols.txt.zip | 09:15 – 15:30 |
| BSE equity derivatives | BFO | BFO_symbols.txt.zip | 09:15 – 15:30 |
| MCX commodity | MCX | MCX_symbols.txt.zip | 09:00 – 23:30 |
Converting a date range to st and et
This is where most of the mistakes happen. The exchange day is IST; your server is probably UTC.
from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9+
IST = ZoneInfo("Asia/Kolkata")
def epoch(date_str, time_str="09:15:00"):
"""'2026-10-06', '09:15:00' -> Unix seconds, read as IST.
Naive datetimes are interpreted by Python as LOCAL time, which on a
UTC server is 5 hours 30 minutes adrift -- enough to return the
previous session, or nothing at all.
"""
stamp = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M:%S")
return int(stamp.replace(tzinfo=IST).timestamp())
# A single session: 09:15 to 15:30 IST.
start = epoch("2026-10-06", "09:15:00")
end = epoch("2026-10-06", "15:30:00")
print(start, end) # 1759722300 1759744800NSE and BSE equities trade 09:15 to 15:30 IST. MCX runs 09:00 to 23:30 IST (23:55 when US daylight saving is in effect). A range entirely outside those hours returns an empty array, not an error - which looks exactly like a broken request.
Complete worked example
Get 5-minute candles for RELIANCE-EQ on NSE, from 2026-10-06 09:15 to 15:30 IST.
RELIANCE-EQ is token 2885, verified against NSE_symbols.txt. The API has no 5-minute mode, so this asks for the full session and aggregates.
"""Fetch a session of candles from Infinn and resample them.
python historical.py
Needs INFINN_ACCESS_TOKEN in the environment. Get one from
/getting-started/authentication/.
"""
import json
import os
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import requests
URL = "https://api.infinn.in/NorenWClientAPI/TPSeries"
IST = ZoneInfo("Asia/Kolkata")
ACCESS_TOKEN = os.environ["INFINN_ACCESS_TOKEN"]
USER_ID = os.environ.get("INFINN_USER_ID", "IN001")
def epoch(date_str, time_str):
stamp = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M:%S")
return int(stamp.replace(tzinfo=IST).timestamp())
def fetch(exch, token, start, end):
"""Returns candles oldest-first, or raises with a readable reason."""
payload = {
"uid": USER_ID,
"exch": exch,
"token": str(token),
"st": str(start),
"et": str(end),
}
response = requests.post(
URL,
headers={
"Authorization": f"Bearer {ACCESS_TOKEN}",
"Content-Type": "text/plain",
},
data="jData=" + json.dumps(payload),
timeout=30,
)
# Layer 1. A rejected token gives 401 with an EMPTY body, so this has
# to happen before any attempt to parse.
if response.status_code != 200:
raise RuntimeError(
f"HTTP {response.status_code}. If 403: check the token, and "
f"that this machine's public IP is registered on your profile."
)
if not response.text.strip():
raise RuntimeError("empty body with HTTP 200")
data = response.json()
# Layer 2. Success is an ARRAY; failure is an OBJECT with stat/emsg.
if isinstance(data, dict):
raise RuntimeError(data.get("emsg", "Not_Ok with no emsg"))
if not data:
raise RuntimeError(
"no candles. Check the range is inside market hours, that the "
"token belongs to this exch, and that the day was a trading day."
)
candles = []
for row in data:
# Every row carries its own stat. A partial failure is possible.
if row.get("stat") != "Ok":
continue
candles.append({
"time": datetime.strptime(row["time"], "%d-%m-%Y %H:%M:%S")
.replace(tzinfo=IST),
"open": float(row["into"]),
"high": float(row["inth"]),
"low": float(row["intl"]),
"close": float(row["intc"]),
"volume": int(row["intv"]),
"vwap": float(row["intvwap"]),
"oi": int(row["oi"]) if row.get("oi") else None,
})
# The API returns newest first. Nobody wants that.
candles.sort(key=lambda c: c["time"])
return candles
def resample(candles, minutes):
"""Aggregates 1-minute candles into `minutes`-minute candles.
OHLCV aggregation is not elementwise: open is the FIRST open, close
the LAST close, high the max, low the min, volume the sum. Getting
this wrong by averaging is a classic and silent error.
"""
if not candles:
return []
buckets = {}
for c in candles:
# Floor to the bucket start.
minute = (c["time"].hour * 60 + c["time"].minute) // minutes * minutes
key = c["time"].replace(hour=minute // 60, minute=minute % 60,
second=0, microsecond=0)
buckets.setdefault(key, []).append(c)
out = []
for key in sorted(buckets):
group = buckets[key]
out.append({
"time": key,
"open": group[0]["open"],
"high": max(g["high"] for g in group),
"low": min(g["low"] for g in group),
"close": group[-1]["close"],
"volume": sum(g["volume"] for g in group),
})
return out
if __name__ == "__main__":
start = epoch("2026-10-06", "09:15:00")
end = epoch("2026-10-06", "15:30:00")
try:
raw = fetch("NSE", 2885, start, end)
except RuntimeError as err:
raise SystemExit(f"TPSeries failed: {err}")
print(f"{len(raw)} raw candles")
for size in (5, 15, 30, 60):
bars = resample(raw, size)
print(f"{size:>3}m -> {len(bars):>4} bars")
for bar in resample(raw, 5)[:3]:
print(bar["time"].strftime("%Y-%m-%d %H:%M"),
bar["open"], bar["high"], bar["low"], bar["close"],
bar["volume"])// historical.js -- fetch one session of 1-minute candles with TPSeries (Node 18+)
// infinn.js -- shared helper used by the guide scripts (Node 18+, no packages)
const BASE = process.env.INFINN_BASE || 'https://api.infinn.in';
const ACCESS_TOKEN = process.env.INFINN_ACCESS_TOKEN || 'YOUR_ACCESS_TOKEN';
const UID = process.env.INFINN_USER_ID || 'IN001';
class InfinnError extends Error {
constructor(message, status, payload) { super(message); this.status = status; this.payload = payload; }
}
// Parses a numeric string, tolerating inf / -nan / NULL.
function num(value, fallback = 0) {
if (value === null || value === undefined) return fallback;
const text = String(value).trim().toLowerCase();
if (['', 'nan', '-nan', 'inf', '-inf', 'null', 'none'].includes(text)) return fallback;
const n = Number(text);
return Number.isFinite(n) ? n : fallback;
}
// One call, checking BOTH error layers.
async function call(path, payload) {
const res = await fetch(BASE + path, {
method: 'POST',
headers: { Authorization: `Bearer ${ACCESS_TOKEN}`, 'Content-Type': 'text/plain' },
body: 'jData=' + JSON.stringify(payload),
signal: AbortSignal.timeout(15000),
});
// Layer 1: HTTP. Error responses have an empty body, so check before parsing.
if (res.status !== 200) {
throw new InfinnError(`HTTP ${res.status} -- check the token and that this machine's IP is whitelisted`, res.status);
}
const text = await res.text();
if (!text.trim()) throw new InfinnError('Empty body with HTTP 200', 200);
const data = JSON.parse(text);
// Layer 2: application. Lists are successes; objects carry stat.
if (!Array.isArray(data) && data.stat && data.stat !== 'Ok') {
throw new InfinnError(data.emsg || 'Not_Ok with no emsg', 200, data);
}
return data;
}
// INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... node historical.js
// History covers roughly the last 10 months.
// 'YYYY-MM-DD', 'HH:MM:SS' read as IST (+05:30) -> Unix seconds.
function epoch(date, time) {
return Math.floor(Date.parse(`${date}T${time}+05:30`) / 1000);
}
async function fetchCandles(exch, token, start, end) {
const data = await call('/NorenWClientAPI/TPSeries', {
uid: UID, exch, token: String(token), st: String(start), et: String(end),
});
if (!Array.isArray(data) || data.length === 0) throw new Error('No candles in that range');
// Newest first on the wire; return oldest first, with numbers parsed.
// Each row carries its own stat; skip partial failures. Time is 'dd-mm-yyyy HH:MM:SS' (IST).
const key = (t) => t.replace(/^(\d\d)-(\d\d)-(\d{4}) /, '$3-$2-$1 ');
return data.filter((c) => c.stat === 'Ok').map((c) => ({
time: c.time, open: num(c.into), high: num(c.inth), low: num(c.intl),
close: num(c.intc), volume: num(c.intv),
})).sort((a, b) => key(a.time).localeCompare(key(b.time)));
}
async function main() {
const start = epoch('2026-10-06', '09:15:00');
const end = epoch('2026-10-06', '15:30:00');
const candles = await fetchCandles('NSE', '2885', start, end); // RELIANCE-EQ
console.log(`${candles.length} candles; first ${candles[0].time}, last ${candles[candles.length - 1].time}`);
const day = {
open: candles[0].open,
high: Math.max(...candles.map((c) => c.high)),
low: Math.min(...candles.filter((c) => c.low > 0).map((c) => c.low)),
close: candles[candles.length - 1].close,
volume: candles.reduce((s, c) => s + c.volume, 0),
};
console.log('session:', day);
}
main().catch((err) => { console.error(err.message); process.exit(1); });TPSeries needs a Bearer token, and the account's registered IP must match the machine making the call. The code above was run as part of this site's test suite and reached the API; without credentials it returns HTTP 401 with an empty body, which is exactly the path its first error branch handles.
The response shown below is therefore the documented example response, reproduced in the exact shape the API specifies. It is not output captured from a live authenticated call, and this page does not pretend otherwise.
The response
An array, newest candle first, every value a string.
[
{
"stat": "Ok",
"time": "02-06-2020 15:46:23",
"into": "0.00",
"inth": "0.00",
"intl": "0.00",
"intc": "0.00",
"intvwap": "0.00",
"intv": "0",
"intoi": "0",
"v": "980515",
"oi": "128702"
},
{
"stat": "Ok",
"time": "02-06-2020 15:43:23",
"into": "1287.00",
"inth": "1287.00",
"intl": "0.00",
"intc": "1287.00",
"intvwap": "128702.00",
"intv": "4",
"intoi": "128702",
"v": "980515",
"oi": "128702"
}
]| Field | Meaning | In the sample |
|---|---|---|
stat | Per-candle status. Check it per row, not just once - a partial failure is possible. | "Ok" |
time | Candle timestamp, dd-mm-yyyy HH:MM:SS, IST. Day first. | "02-06-2020 15:46:23" |
into | Open of the interval. | "1287.00" |
inth | High of the interval. | "1287.00" |
intl | Low of the interval. | "0.00" |
intc | Close of the interval. | "1287.00" |
intv | Volume traded in the interval. | "4" |
intvwap | Volume-weighted average price for the interval. | "128702.00" |
intoi | Change in open interest over the interval. Derivatives only. | "128702" |
v | Cumulative volume for the day so far - not the interval's volume. | "980515" |
oi | Open interest outstanding at the end of the interval. | "128702" |
- It is newest-first. The sample descends: 15:46, then 15:43. Sort by
timerather than assuming order. - Every number is a string.
"1287.00", not1287.0. Convert explicitly. - Zeros are real. The first candle in the sample has
into,inth,intlandintcall"0.00"withintv: "0"- a minute in which nothing traded. Do not plot those as a price crash; skip zero-volume candles or carry the previous close. - Failure changes the type. Success is an array, failure is an object.
data[0]on a failure gives you a dictionary key, not a candle.
The timestamp format
"02-06-2020 15:46:23" is dd-mm-yyyy HH:MM:SS in IST - day first, not month first. Parsing it as %m-%d-%Y succeeds silently for the first twelve days of any month and then throws, which is the worst possible failure mode.
from datetime import datetime
from zoneinfo import ZoneInfo
stamp = datetime.strptime("02-06-2020 15:46:23", "%d-%m-%Y %H:%M:%S")
stamp = stamp.replace(tzinfo=ZoneInfo("Asia/Kolkata"))
# 2020-06-02 15:46:23+05:30 -- the 2nd of June, not the 6th of FebruaryGetting 5-minute, 15-minute and daily candles
The API has no interval parameter, so the answer is to aggregate. The resample function above does it; this is the rule it implements, because OHLCV does not aggregate elementwise:
| Output field | How it is derived from the minutes in the bucket |
|---|---|
| Open | The first minute's open. Not an average. |
| High | The maximum of the minutes' highs. |
| Low | The minimum of the minutes' lows - excluding zero-volume minutes, whose low is 0.00. |
| Close | The last minute's close. Not an average. |
| Volume | The sum of intv. Never sum v, which is already cumulative. |
| VWAP | Recompute as ∑(price × volume) / ∑volume. Averaging the per-minute VWAPs is wrong unless every minute had equal volume. |
The single most common error in home-made resampling. A 5-minute candle's open is the first minute's open and its close is the last minute's close. Averaging them produces a chart that looks plausible, smooths away every gap, and is wrong everywhere.
Daily candles
Same function, one bucket per session - but request one day at a time rather than a wide range, and key the bucket by date:
from datetime import date, timedelta
def daily(exch, token, first, last):
"""One bar per trading day between two dates, inclusive."""
bars = []
day = first
while day <= last:
start = epoch(day.isoformat(), "00:00:00")
end = epoch(day.isoformat(), "23:59:59")
try:
candles = fetch(exch, token, start, end)
except RuntimeError:
# Weekend, holiday, or a day before the contract listed.
day += timedelta(days=1)
continue
bars.append({
"date": day,
"open": candles[0]["open"],
"high": max(c["high"] for c in candles),
"low": min(c["low"] for c in candles if c["low"] > 0),
"close": candles[-1]["close"],
"volume": sum(c["volume"] for c in candles),
})
day += timedelta(days=1)
return bars
# Mind the rate limit: 20 orders per second and 200 orders per minute. One call per day
# means a year of history is roughly 250 calls -- well inside the minute
# budget if you pace it, and instantly over if you do not.Without it, a single zero-volume minute drags the day's low to 0.00. The same trap applies to any aggregation over a period that might contain an untraded minute.
What is not available
| What you might want | What there is instead | |
|---|---|---|
| A candle-interval parameter | not available | Request the range and aggregate the result yourself. |
| An end-of-day / daily-bar endpoint | not available | One TPSeries call per session, bucketed by date. |
| Split- and dividend-adjusted history | not available | Nothing. Infinn publishes no corporate-action endpoint. |
| A documented maximum range per call | not available | Documentation information not available. No limit is published; assume one exists and page by day. |
| A documented history depth | not available | Documentation information not available. How far back TPSeries goes is not stated. |
| Tick-by-tick history | not available | The WebSocket gives live ticks only. Record them yourself if you need them. |