You open an intraday chart, you want yesterday's high and low sitting on it as two clean lines, and you write the obvious thing: high[1]. It plots, but it is the high of the previous bar, not the previous day. So you reach for request.security, get a line, and then discover that it either jumps around while you replay the chart or quietly uses data it should not have had yet. Previous day high and low look like the simplest levels in Pine Script and they are surprisingly easy to get subtly wrong.
This guide builds them properly. You will see the one-line approach that works on any intraday timeframe, why it needs lookahead turned on even though that setting has a bad reputation, a second approach that needs no request.security at all, and a full version that draws lines, labels them, and exposes alert conditions. Along the way you will see where each approach differs, so you can pick the one that fits your script.
What "previous day" means to Pine Script
Before any code, settle what a day is. TradingView defines the daily bar by the exchange session of the symbol you are looking at. For a crypto spot market such as BTCUSDT, that is a UTC calendar day, midnight to midnight. For a stock it is the regular trading session, and extended hours may or may not be folded in depending on the chart's settings. The daily timeframe in Pine Script, "D", follows exactly that definition, so any approach that asks for daily data inherits it.
This matters because the levels you see on your chart must match the levels a daily candle shows. If you build your own day boundary from hour and dayofmonth, you take on the job of getting time zones, daylight saving shifts, and session breaks right. The two approaches below both lean on TradingView's own daily boundary, which is why they stay correct without extra work.
The second thing to settle is which values you want. The previous day high is the highest price reached between the previous day's open and close. The previous day low is the lowest. Many traders also keep the previous close, because the three together frame where the last session finished relative to its range. The code below plots high and low and notes where to add the close.
The shortest version: request.security with a one-bar shift
The standard way to ask for daily values from an intraday chart is request.security. It evaluates an expression on another timeframe and sends the result back to the chart you are on. If you have not used it much, the post on how request.security works in Pine Script explains the mechanics in depth. For this job you only need one pattern.
//@version=6
indicator("Previous Day High and Low", overlay = true)
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)
plot(pdh, "Previous day high", color = color.red, style = plot.style_stepline)
plot(pdl, "Previous day low", color = color.green, style = plot.style_stepline)Two details carry the whole thing. The expression [high[1], low[1]] is evaluated in the daily context, so high[1] there means the high of the previous daily bar, not the previous chart bar. And the tuple form fetches both values in one request, which matters because a script has a limit on how many request.* calls it can make. Using one call for both levels leaves room for the rest of your script.
The plot style plot.style_stepline draws the level as a flat step instead of a diagonal ramp between days. Without it, the line slopes from yesterday's value to today's across the first bar of the new day, which looks like a bug even though it is only how a plain line connects two points.
Why lookahead_on is correct here
If you have read anything about repainting, barmerge.lookahead_on makes you nervous, and that reputation is earned. The post on Pine Script lookahead covers how it lets a historical bar see data from its own future. So why use it here?
The answer is the [1]. Lookahead on a request for the current daily bar is dangerous, because on a historical 1 hour bar at 09:00 it would hand you the high of the whole day, including hours that had not happened yet. But the expression asks for the previous daily bar, which is complete and fixed from the first moment of the new day. There is nothing in it that can change later, so there is nothing to leak.
What lookahead changes is timing. With the default lookahead_off, a request for the higher timeframe returns a value only after that higher timeframe bar closes, and the value for the previous day then shows up late on historical bars in a way that does not match real time. With lookahead_on and the shift, yesterday's high is available from the first intraday bar of today, on history and in real time alike. The two behaviors agree, which is what non-repainting means. The rule to remember is that lookahead on is safe only when the requested expression is already shifted back by one bar.
If you remove the [1] and leave lookahead on, you have built the classic lying indicator, which draws today's final high on every bar of today. Keep the shift and the lookahead together or neither.
Doing it without request.security
The request.security route has a cost: it adds a data request, and on some symbols the daily series and the chart series can disagree about where a day starts, particularly around session boundaries. You can avoid both problems by tracking the day yourself on the chart's own bars, using timeframe.change. The post on detecting a new day, week or session with ta.change and timeframe.change goes deeper on that function.
//@version=6
indicator("Previous Day Levels, No Security Call", overlay = true)
var float dayHigh = na
var float dayLow = na
var float pdh = na
var float pdl = na
if timeframe.change("D")
pdh := dayHigh
pdl := dayLow
dayHigh := high
dayLow := low
else
dayHigh := math.max(dayHigh, high)
dayLow := math.min(dayLow, low)
plot(pdh, "Previous day high", color = color.red, style = plot.style_stepline)
plot(pdl, "Previous day low", color = color.green, style = plot.style_stepline)Read it as a small state machine. The var variables keep their values from bar to bar. While a day is running, dayHigh and dayLow stretch to cover every bar seen so far. The moment timeframe.change("D") reports a new day, the finished day's range is copied into pdh and pdl, and the running values restart from the first bar of the new day.
This version has no lookahead question at all, because it only ever uses bars that have already happened. It also works on any chart timeframe up to the daily, and on the daily chart itself it still returns the prior bar's high and low. The trade-off is that it only knows about bars loaded on your chart. If your chart history starts mid-day, the first "previous day" it reports is a partial day. The request.security version reads the real daily bar and does not have that problem, so for the first day on the chart it is the more accurate one.
For most scripts either approach is fine. Choose request.security when you want TradingView's daily bar as the single source of truth, and choose the manual version when you want to avoid a data request or need the day boundary to line up exactly with your chart bars.
Drawing lines that stop where they should
A plotted step line is simple, but it has two limits. It cannot extend to the right edge of the chart as a level you can project forward, and it draws a segment for every day with no label. When the levels are the point of the script, lines and labels read better. Drawing objects come with their own constraints, so it helps to have read Pine Script drawing objects and their limits first.
The approach is to draw one line per day and, when the next day starts, close it off so lines do not pile up to infinity.
//@version=6
indicator("Previous Day Levels With Lines", overlay = true, max_lines_count = 100, max_labels_count = 100)
var float dayHigh = na
var float dayLow = na
var float pdh = na
var float pdl = na
var line pdhLine = na
var line pdlLine = na
if timeframe.change("D")
if not na(pdhLine)
line.set_extend(pdhLine, extend.none)
line.set_x2(pdhLine, bar_index)
if not na(pdlLine)
line.set_extend(pdlLine, extend.none)
line.set_x2(pdlLine, bar_index)
pdh := dayHigh
pdl := dayLow
dayHigh := high
dayLow := low
if not na(pdh)
pdhLine := line.new(bar_index, pdh, bar_index + 1, pdh, extend = extend.right, color = color.red, width = 1)
pdlLine := line.new(bar_index, pdl, bar_index + 1, pdl, extend = extend.right, color = color.green, width = 1)
label.new(bar_index, pdh, "PDH", style = label.style_label_down, color = color.red, textcolor = color.white, size = size.small)
label.new(bar_index, pdl, "PDL", style = label.style_label_up, color = color.green, textcolor = color.white, size = size.small)
else
dayHigh := math.max(dayHigh, high)
dayLow := math.min(dayLow, low)Each new day creates two lines that extend to the right. When the next day starts, the script first fixes the old lines by turning off their extension and setting their right edge to the current bar, then creates the new pair. The result is a set of finite lines that each cover exactly the day they were relevant to, with the latest pair still reaching out to the right edge.
The guards with not na(pdhLine) are not decoration. On the very first day there is no previous line to close, and calling a line.set_* function on an na line stops the script with a runtime error. The same reasoning is behind if not na(pdh): until one full day has passed there is no level to draw. The max_lines_count and max_labels_count arguments raise the cap on how many drawings Pine keeps. Without them, Pine keeps only the most recent 50 lines and drops older ones, which is fine for a rolling view but surprising if you expected full history. If you hit the cap in a bigger script, the post on fixing the 500 object limit lists the options.
Mark it on the chart with the agent
Writing the code is one route. If what you want first is to see the two levels on a chart and decide whether they are worth coding, PineScripter's chart agent can mark them for you on PineScripter's own chart, which covers crypto spot markets. Here is a request you could type in the chat:
Mark the previous day's high and low on BTCUSDT 1h as horizontal lines.
The agent starts by reading the chart: the swing levels with their touch counts and any drawings that are already on it. It then draws with the drawing tools from the toolbar while you watch its cursor click the points on the chart. When it finishes, the batch of drawings it made can be undone in one step, so a marking you did not want costs you nothing.
The result is a starting point, and it is yours to check. Look at the touch counts the agent read for the nearby swing levels and see whether the lines sit near a level the market has already respected or in empty space. Switch the chart to 15 minutes and 4 hours and confirm the lines still sit on the same prices, because a previous day level should not move when you change timeframe. Then open replay and step through a few bars around midnight UTC, one bar at a time, to watch the lines hand over from one day to the next. If the level changes at a moment you did not expect, you have found something worth understanding before you trust it. The agent marks what you ask for and describes what is on the chart. It does not tell you which levels will matter, and a line on a chart is not a reason to act.
The next step is where code takes over: ask the AI editor to turn it into an indicator that plots the same two levels on every chart you open, and you get a script like the ones above, written in Pine Script v6 and checked for compile errors before you see it. If you want to learn how the agent treats clusters of levels, the guide to drawing support and resistance zones from swings walks through that task.
Turning the levels into alert conditions
Levels become more useful when your script can tell you something happened at them. A common starting point is knowing when price crosses yesterday's high or low. Add this to the end of the line-drawing script, or to the simpler step-line version, since it only needs pdh and pdl.
//@version=6
indicator("Previous Day Level Crosses", overlay = true)
var float dayHigh = na
var float dayLow = na
var float pdh = na
var float pdl = na
if timeframe.change("D")
pdh := dayHigh
pdl := dayLow
dayHigh := high
dayLow := low
else
dayHigh := math.max(dayHigh, high)
dayLow := math.min(dayLow, low)
plot(pdh, "Previous day high", color = color.red, style = plot.style_stepline)
plot(pdl, "Previous day low", color = color.green, style = plot.style_stepline)
crossAbove = ta.crossover(close, pdh)
crossBelow = ta.crossunder(close, pdl)
alertcondition(crossAbove, "Close above previous day high", "Price closed above the previous day high")
alertcondition(crossBelow, "Close below previous day low", "Price closed below the previous day low")Two behaviors are worth knowing. First, ta.crossover returns false whenever either side is na, so on the first day, before any level exists, no alert can fire. You do not need an extra guard. Second, the conditions are evaluated on the close of each bar. When you create the alert in TradingView, choose to trigger once per bar close. Triggering on every tick can fire the moment price touches the level and then fire again, and on a live bar the condition can come and go. The post on why alerts fire on the wrong bar covers exactly this, and building a repaint-free alert system shows the full pattern.
Notice that these alerts report that a condition occurred. They do not claim that price will continue in either direction, and nothing here suggests that a cross is a reason to take any position. It is a measurement, and what you do with it is your decision.
Common mistakes with previous day levels
The most frequent bug is using high[1] on the chart timeframe and calling it the previous day. It is only the previous bar. On a daily chart the two happen to be identical, which is why the mistake survives testing on a daily chart and then fails the moment you switch to 1 hour.
The second is dropping the shift but keeping lookahead on. The line then looks perfect on history because it shows the day's final high, which is exactly the information you would not have had at the time. If a level looks suspiciously well placed, check the shift first.
The third is forgetting that the previous day for a Monday on a stock chart is Friday, and that a crypto chart has no weekend gap at all. Any code that assumes "yesterday" is twenty-four hours back will break on a stock chart each Monday. Using the daily boundary from TradingView, as both approaches above do, handles this for you.
The fourth is plotting the level with a normal line style and then reading the diagonal segments between days as price action. They are only the line connecting two values. Use the step line style, or draw lines, so each day's level is flat.
Finally, if you extend the script to many symbols, remember the data request limit. A previous day level per symbol costs one request.security call each, so the manual timeframe.change approach is the one that scales when you only care about the chart you are on.
Checking your result before you rely on it
Whichever version you pick, verify it against a daily candle. Open the daily chart for the same symbol and read the high and low of yesterday's candle from the data window. Then open your intraday chart and check that the plotted levels match to the last decimal. Do this on at least two different days, including one that follows a weekend or holiday on a stock symbol, because that is where day boundary bugs show up.
You can also run the script on PineScripter's chart, which draws your script's plots on real market data for the 308 crypto spot markets before you paste anything into TradingView, and step through the midnight rollover with replay. If a script of yours misbehaves, you can describe the problem in plain English and the AI edits only the affected lines, with a line-by-line view of what changed. The pricing page lists the plans.
This article is educational content about writing code. PineScripter is a coding tool, not a financial advisor, and nothing here is a recommendation to buy or sell anything or a prediction of future prices.
Frequently asked questions
Why does high[1] not give me the previous day high?
On an intraday chart, high[1] is the high of the previous bar. To get the previous day, evaluate high[1] on the daily timeframe with request.security, or track the running day high yourself and store it when timeframe.change("D") reports a new day.
Is barmerge.lookahead_on safe for previous day levels?
Yes, when the requested expression is shifted back by one daily bar, as in [high[1], low[1]]. The previous day is already complete, so nothing can leak from the future. Without the shift, lookahead on makes history look better than real time.
Do I need request.security at all?
No. Tracking the day with var variables and timeframe.change works on the chart's own bars and needs no data request. The trade-off is that the first day on the chart can be partial if history starts mid-day.
How do I alert when price crosses the previous day high?
Compute ta.crossover(close, pdh) and pass it to alertcondition, then create the alert in TradingView with once per bar close. ta.crossover is false while either value is na, so no alert fires before the first level exists.
What counts as a day for crypto and for stocks?
TradingView follows the symbol's exchange session. For crypto spot markets that is a UTC calendar day. For stocks it is the regular session, and the previous day for a Monday is Friday.
Ask the agent to mark it on the chart, then turn it into Pine Script →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.