Tutorial

Pine Script ta.change: Detect a New Day, Week or Session

Use ta.change and timeframe.change to detect a new day, week or session in Pine Script v6, and reset your running values on the right bar.

•11 min read

You add a line to an intraday script that is supposed to reset every morning. A running high, a day-open reference, a counter of how many bars have printed today. On the first day everything looks right. Then you scroll back a few weeks and the reset has fired in the middle of a session, or not at all on Mondays, or on every single bar of the daily chart. The logic you wrote was one line long, which makes the bug feel unfair.

Almost every one of those scripts depends on the same small idea: knowing the exact bar where a higher time frame ticks over. Pine Script gives you two good ways to ask the question, ta.change applied to a time value and the built-in timeframe.change. This guide covers both, shows where each one behaves differently, and walks through the mistakes that make a reset fire at the wrong moment. Every example is complete Pine Script v6 that you can paste into TradingView's Pine Editor.

What ta.change actually computes

ta.change(source) returns the current value of the source minus its value on the previous bar. With a length argument, ta.change(source, length) subtracts the value from that many bars back instead. For a price series that is a one-bar difference, which is why you often see it used for momentum. For a series that normally stays flat and occasionally jumps, the result is zero almost everywhere and nonzero exactly where the jump happens.

That second behavior is the useful one for time frame detection. Take a series that holds the same number for a whole day and a different number on the next day. Subtract yesterday's bar value from today's and you get zero on every bar except the first bar of the new day. The nonzero result is your marker. Nothing about it is specific to days. It works for any series that is constant within a period and moves between periods.

Two details matter before you build on it. First, the very first bar of the chart has no previous bar, so ta.change returns na there. In v6 a comparison with na, such as na != 0, evaluates to false rather than carrying the na forward, so a test like ta.change(x) != 0 quietly does the right thing on bar one. Second, the function keeps its own history, which means it has to be evaluated on every bar. That second point comes back later, because it is the source of the most common reset bug.

Detecting a new day with ta.change(time("D"))

The time function with a timeframe argument returns the opening timestamp, in milliseconds, of the higher time frame bar that contains the current chart bar. Every bar inside the same day reports the same timestamp. When the day changes, the timestamp jumps. Putting the two ideas together gives the classic new-day test.

pine
//@version=6
indicator("New day marker", overlay = true)

// time("D") holds the same value for every bar inside one day.
// It jumps on the first bar of the next day, so the change is nonzero there.
bool newDay = ta.change(time("D")) != 0

bgcolor(newDay ? color.new(color.blue, 88) : na, title = "New day")
plotshape(newDay, "Day start", shape.triangleup, location.bottom, color.blue, size = size.tiny)

Add that to an intraday chart and a faint blue band appears on the first bar of each day. If the band shows up on the wrong bar, the explanation is almost always the time zone. The day boundary follows the exchange time zone of the symbol on your chart, not your computer's time zone and not the time zone you picked in the chart's lower corner. A crypto pair and a stock listed in New York each get their own midnight. When a reset looks one bar or several hours off, check which time zone the symbol uses before you suspect the code. The free Pine Script session and time zone tool on the PineScripter site, at /tools/pine-script-session-timezone-tool, is useful for checking where a session boundary falls.

The same pattern extends to longer periods by changing the string. time("W") gives the opening time of the week, time("M") the month. ta.change(time("W")) != 0 is true on the first bar of each new week, and which weekday counts as the first depends on the exchange. For markets that trade through the weekend, the week boundary can land on a different weekday than you expect, so look at one on the chart instead of assuming.

timeframe.change, the shorter way to say the same thing

Pine Script v6 has a built-in for exactly this question. timeframe.change(timeframe) returns true on the first bar of a new bar of the higher time frame you name, and false otherwise. It is a bool already, so there is no subtraction and no comparison.

pine
//@version=6
indicator("Distance from day open", overlay = false)

bool newDay = timeframe.change("D")

// var keeps the value between bars; it is reassigned only when a new day starts.
var float dayOpen = na
if newDay
    dayOpen := open

float pctFromOpen = (close - dayOpen) / dayOpen * 100

plot(pctFromOpen, "Change from day open (%)", style = plot.style_columns, color = pctFromOpen >= 0 ? color.teal : color.red)
hline(0)

The result is a column chart that measures how far each bar is from the open of its own day, and snaps back to measuring from the new open the moment the day changes. The reset lives in four lines. Everything else is presentation.

For most scripts timeframe.change is the better default, because it states what you mean. ta.change(time("D")) != 0 works and is worth understanding, since it explains why the built-in works, but a reader of your script has to decode it. The built-in also accepts any timeframe string, so timeframe.change("W"), timeframe.change("M"), and timeframe.change("240") for a four-hour block all read the same way. The ta.change form earns its place when you want the size of the jump rather than a yes or no, or when you are working with a series that is not a timeframe at all.

There is one guard worth writing. A daily reset only makes sense when the chart is finer than a day. On a daily chart every bar is its own day, so a "new day" is true every time and your running state resets on every bar. If the script is meant for intraday use, say so by checking timeframe.isintraday and, if you like, raising an error with runtime.error when it is false. A clear message beats a mysteriously flat indicator.

Resetting state with var

Detecting the change is half the work. The other half is what you do with it, and that nearly always means a variable that survives from bar to bar and is cleared at the change. In Pine Script a variable declared with var keeps its value across bars, which is exactly what a running total or a running extreme needs. The var and varip guide explains the initialization rules in detail. For resets the pattern is always the same: seed the value on the change bar, update it on every other bar.

pine
//@version=6
indicator("Daily running high and low", overlay = true)

bool newDay = timeframe.change("D")

var float dayHigh = na
var float dayLow  = na

if newDay
    dayHigh := high
    dayLow  := low
else
    dayHigh := math.max(dayHigh, high)
    dayLow  := math.min(dayLow, low)

// Break the lines at each reset so the new day does not join the old one.
plot(newDay ? na : dayHigh, "Day high", color.green, 1, plot.style_linebr)
plot(newDay ? na : dayLow,  "Day low",  color.red,   1, plot.style_linebr)

Two choices in that script are deliberate. The first is the else branch. On the change bar you want to start from this bar's high and low, not compare them with yesterday's extremes. If you used math.max on every bar without the branch, the "daily" high would just be the highest price since the chart began. The second is plot.style_linebr, which breaks the line wherever the plotted value is na. Without it, the plot draws a near-vertical stroke from yesterday's final level to today's first level, which looks like price movement and is not.

Notice also that dayHigh is na on every bar before the first reset. A chart that begins mid-day has a partial first day with no change bar to seed it, so nothing plots until the next day begins. That is correct behavior. If you would rather see something on the first day, seed the variable with na(dayHigh) ? high : dayHigh logic, knowing that the first day then covers fewer bars than the others. The guide to na values covers how na moves through arithmetic and why math.max returns na when one argument is na.

Using ta.change on values that are not time

Nothing about ta.change requires a timestamp. Any series that holds steady and then moves works. A frequent use is detecting a flip in a state you computed yourself, for instance whether price is above or below a moving average. Encode the state as a number, and the change tells you when the state flipped.

pine
//@version=6
indicator("Trend flip marker", overlay = true)

length = input.int(50, "Average length", minval = 2)
float ma = ta.sma(close, length)

// 1 when price is above the average, -1 when below.
int state = close > ma ? 1 : -1

// +2 on a flip up, -2 on a flip down, 0 otherwise. na on the first bar.
float flip = ta.change(state)

plot(ma, "Average", color.gray)
plotshape(flip == 2,  "Flip up",   shape.triangleup,   location.belowbar, color.teal, size = size.tiny)
plotshape(flip == -2, "Flip down", shape.triangledown, location.abovebar, color.red,  size = size.tiny)

The arithmetic is the point. A change from -1 to 1 is +2 and a change from 1 to -1 is -2, so a single call tells you both whether the state moved and which way. Compare that with the alternative, state != state[1], which finds the flip but needs a second test to find the direction. If you only need to know that a flip happened, ta.change(state) != 0 and state != state[1] are equivalent. Use whichever your future self will read faster.

For crossings between two lines, ta.crossover and ta.crossunder are the better tools, and the crossover guide explains how they treat equal values. ta.change is the right choice when the thing that changes is a state, a counter, or a timestamp rather than two lines passing through each other.

The mistake that makes resets fire at the wrong time

The most expensive bug in this area is calling ta.change inside a condition. Functions that keep a history of their own, including ta.change, ta.sma, and most of the ta namespace, need to run on every bar to see every value. When you place the call inside an if block, a ternary branch, or the right side of and or or, it runs only on the bars where that branch executes. Its internal previous value then comes from a bar several bars earlier, and the difference it reports is wrong.

pine
//@version=6
indicator("Safe change detection", overlay = true)

bool sessionOpen = hour >= 9 and hour < 17

// Risky: the call only runs while sessionOpen is true, so its
// "previous bar" can be many bars old.
// float badDelta = sessionOpen ? ta.change(close) : na

// Safe: evaluate on every bar first, then use the result.
float delta = ta.change(close)
float usedDelta = sessionOpen ? delta : na

plot(usedDelta, "Change inside the window", style = plot.style_histogram)

The rule is simple: call it on its own line, at the top level of the script, then combine the stored result with your conditions. The and and or operators in v6 also stop evaluating early, which can skip a call in the same way, and the lazy evaluation article shows how that surprises people who inline these tests.

Intraday sessions are a different question

A new calendar day and the start of a trading session are not always the same moment. Equities have an opening bell, a pre-market and a post-market, and the first bar of the regular session is not the first bar of the exchange day. Futures can start a session in the evening of the previous calendar day. If your reset is meant to follow the session, not the day, use session.isfirstbar or session.isfirstbar_regular, which are true on the first bar of the session defined for the symbol. timeframe.change("D") is a calendar test. session.isfirstbar is a trading hours test. The session and time filter guide goes through the session string format if you need a custom window.

The distinction matters for anchored calculations. A volume-weighted average anchored to the session starts when the session starts. One anchored with a calendar test starts at midnight. The anchored VWAP guide uses ta.change(time("D")) for its day anchor and shows what that does to the running totals, and the VWAP guide uses timeframe.change("1D") to anchor ta.vwap. They are the same idea written the two ways described above.

Testing a reset before you trust it

A reset bug is a bug about one bar, and that bar is easy to miss in a month of data. Before relying on a reset, check three things. Find the first bar of a week you know began on a particular weekday and confirm the marker is on it. Look at a holiday or a gap and confirm that the marker fires on the first bar that exists, not on a bar that is missing. And switch to a few different chart timeframes, because the same code can behave differently on a 5 minute chart and a 4 hour chart when the day boundary falls inside a bar.

Stepping through the chart one bar at a time makes this much faster than scrolling. PineScripter's replay view steps a chart run one bar at a time, so you can stop on the exact bar where your marker should fire and see what the script did there. The chart view runs your script on its crypto spot market data before you paste it into TradingView, which is a quick way to watch a reset across many days.

From a reset idea to working code

Most readers of this topic arrive with a sentence, not a snippet: reset my running volume at the start of each session, or only count the first hour of each day. You can describe that in plain English to the PineScripter AI editor, which writes Pine Script v6 and checks it for compile errors. If you already have a script that ignores the day boundary, ask for the new condition to be wired in. The editor changes only the lines that need to change and shows them in a line-by-line Code Changes view, so you can review the new var and the new condition before you keep them. The result is code you own and can read, which matters here, because a reset is only trustworthy if you understand the one line that decides it.

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.

Frequently asked questions

What does ta.change do in Pine Script?

It returns the current value of a series minus its value on the previous bar. With a length argument it subtracts the value from that many bars back. On the first bar of the chart it returns na.

What is the difference between ta.change(time("D")) and timeframe.change("D")?

Both mark the first bar of a new day. timeframe.change is a built-in that returns a bool directly and reads more clearly. ta.change(time("D")) != 0 does the same job by subtracting timestamps, and is useful when you want the size of the jump.

Why does my daily reset fire on every bar?

On a daily or higher chart every bar is its own day, so a daily change is true on every bar. Check timeframe.isintraday and stop the script with a clear message if the chart is too coarse.

Why is my new day marker on the wrong bar?

The day boundary follows the exchange time zone of the symbol, not your computer or chart display time zone. Check which time zone the symbol uses before changing the code.

Can I call ta.change inside an if block?

You should not. It needs to run on every bar to track its history. Call it on its own line at the top level, store the result, and use the variable in your conditions.

Should I use timeframe.change or session.isfirstbar?

Use timeframe.change for calendar boundaries and session.isfirstbar when the reset should follow the trading session defined for the symbol.

Describe your indicator in plain English and get Pine Script that compiles →


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.