Tutorial

Opening Range Breakout Pine Script: Build and Mark It

Code the opening range high and low in Pine Script v6, flag the first breakout of each day, and test it with fees and slippage in the Strategy Tester.

•13 min read

You have seen the picture a hundred times. A market opens, the first half hour prints a small box of highs and lows, and then price pushes out of one side of it and runs. The opening range breakout is the rule that turns that picture into something you can state exactly: take the high and low of a fixed window at the start of a session, wait for a bar to close beyond either edge, and treat that as the trigger. It is one of the simplest rules in technical analysis, similar in spirit to the Donchian channel breakout, which is exactly why it is a good first project for Pine Script. There is very little math, and almost all of the difficulty is in the details of time.

This guide builds the idea in three steps. First we define the opening range and the part most tutorials gloss over, which is what a "session" means on a market that never closes. Then we code an indicator that draws the range and marks the first breakout of each day, with an alert. Finally we turn it into a strategy with a stop, a target, fees, and slippage, so you can read the Strategy Tester honestly. In the middle there is a section on marking the same range by hand or with the chart agent, because it helps to see the range on a chart before you trust any code that computes it.

What the opening range actually is

The opening range is the highest high and the lowest low printed between the start of a session and a cutoff, commonly 15, 30, or 60 minutes later. Once the window closes, the two numbers are fixed for the rest of the day. A breakout is the first time price trades or closes beyond one of them. Nothing else about the idea is mandatory: the window length, the direction you allow, and the definition of "beyond" are all choices you make and then test.

Notice what the definition leaves out. It says nothing about what happens after the break, and it makes no claim that the break continues. Some days price leaves the range and keeps going. Many days it leaves, comes back, and closes the day inside the box. Anything you build on top of the range, a stop, a target, a filter, exists to deal with that second kind of day, and the quality of those choices is what the backtest will eventually measure. The range itself is only a measurement.

Defining a session on a 24 hour market

Equity markets have an obvious open, so the textbook version uses the first 30 minutes after 9:30 in New York. Crypto spot markets trade around the clock, so there is no natural opening bell. Traders substitute a convention, and the most common one is the UTC day boundary at 00:00, with the first 15, 30, or 60 minutes as the window. Others use the start of a regional session such as London or New York. All of these are legitimate, but you must pick one on purpose, because the range moves with it.

In Pine Script the tool for this is the time function with a session string and a time zone. A session string such as "0000-0030" describes a window, and time(timeframe.period, "0000-0030", "UTC") returns the bar's timestamp when the bar falls inside that window and na when it does not. That one expression is the whole definition of the range window. If you want the equity version, the same code with "0930-1000" and "America/New_York" works unchanged. The guide to session and time filters covers the other quirks of session strings, including windows that cross midnight.

One practical point about timeframes. The window has to be a whole number of bars, so a 30 minute window needs a chart of 30 minutes or lower. On a 15 minute chart the window is two bars, on a 5 minute chart it is six. On a 1 hour chart a window of "0000-0030" contains only the 00:00 bar, which silently turns your 30 minute range into a one hour range. The code below does not guard against that, so check that the window you typed matches the bars you see.

The indicator: draw the range and flag the first break

The indicator needs to do four things: detect when the window starts, accumulate the high and low while the window is open, hold them steady afterwards, and report the first close beyond either edge. Here is a complete version.

pine
//@version=6
indicator("Opening Range Breakout", overlay = true)

orSession = input.session("0000-0030", "Opening range window")
tz        = input.string("UTC", "Time zone")
showBreaks = input.bool(true, "Mark breakouts")

inRange  = not na(time(timeframe.period, orSession, tz))
newRange = inRange and not inRange[1]

var float orHigh = na
var float orLow  = na
var bool brokeUp = false
var bool brokeDn = false

if newRange
    orHigh := high
    orLow  := low
    brokeUp := false
    brokeDn := false
else if inRange
    orHigh := math.max(orHigh, high)
    orLow  := math.min(orLow, low)

rangeDone = not inRange and not na(orHigh)
longBreak  = rangeDone and not brokeUp and close > orHigh
shortBreak = rangeDone and not brokeDn and close < orLow

if longBreak
    brokeUp := true
if shortBreak
    brokeDn := true

plot(newRange ? na : orHigh, "Range high", color.new(color.green, 0), 2, plot.style_linebr)
plot(newRange ? na : orLow, "Range low", color.new(color.red, 0), 2, plot.style_linebr)

plotshape(showBreaks and longBreak, "Break up", shape.triangleup, location.belowbar, color.green, size = size.tiny)
plotshape(showBreaks and shortBreak, "Break down", shape.triangledown, location.abovebar, color.red, size = size.tiny)

alertcondition(longBreak, "Opening range break up", "Close above the opening range high")
alertcondition(shortBreak, "Opening range break down", "Close below the opening range low")

Walk through it from the top. inRange is true on every bar inside the window, and newRange is true only on the first of them, which is the moment to reset. The two var floats survive from bar to bar, so they hold the range after the window closes. Inside the window the code widens the range with math.max and math.min. After the window, rangeDone becomes true and the breakout conditions switch on.

The brokeUp and brokeDn flags are the part beginners tend to miss. Without them, every bar that closes above the high would fire, and a strong trend day would print a triangle on every candle. With them, each direction fires once per day. They reset on newRange, so the next day starts clean. The plots use newRange ? na : value together with plot.style_linebr so the line breaks at the start of each day instead of drawing a slanted connector from yesterday's range to today's.

Two decisions here are worth stating plainly because you may want to change them. The trigger uses the close, not the high or low, which filters out wicks that poke through the edge and snap back. Waiting for the close costs you a bar of delay and removes false pokes; using high > orHigh does the opposite. The alert conditions fire on the bar's close, but if you create an alert from them in TradingView, set the trigger to once per bar close so it does not fire intrabar and then disappear. The article on why alerts fire on the wrong bar explains why that setting matters.

Mark it on the chart with the agent

Before trusting the code, look at the range. This is where the chart agent in PineScripter is useful, because the question "what does the opening range look like over the last few days" is a drawing task. The agent works on PineScripter's own chart of crypto spot markets, not on your TradingView chart, and it marks what you ask for. It does not tell you which breakout will work.

The request you would type in the chat is plain English, for example: "Mark the high and low of the first 30 minutes of each UTC day on BTCUSDT 15m for the last week, and draw the two levels across the rest of each day."

The agent starts by reading the chart: the swing levels with their touch counts and any drawings already on it. Then it draws with the drawing tools from the toolbar while its cursor visibly clicks the points, so you can watch where each mark lands. If you also ask it to switch to another market or timeframe, it can do that as part of the same request. Every batch of drawings it makes can be undone, so a wrong guess costs you one click.

Then comes the part that matters, which is checking the result yourself. Do not accept the marks because they look tidy. Zoom to a single day and confirm the box covers exactly the first two 15 minute candles, that the high really is the highest wick among them, and that the lines extend only to the end of that day. Switch the timeframe to 5 minutes and confirm the same levels still sit on the same wicks. Then use bar replay to step through a day one bar at a time, which shows you the moment the range becomes final and the first bar that closes outside it. If the agent's marks and your reading disagree, trust the candles and ask again with a tighter request. The markup is a starting point you verify, never an answer.

The optional last step is the bridge to code: "Turn this into an indicator that draws the range every day and marks the first close outside it." The result should look like the script above. Because PineScripter lints its Pine Script the way TradingView does and fixes the errors it finds on its own, you are not the one copying error messages between tools. The hand-drawn lines to indicator workflow covers this handoff in more depth. Compare the result with the marks you drew by hand: if the indicator's lines land on the same wicks as your manual range, the session definition is right.

Turning it into a strategy

An indicator tells you when the range broke. A strategy has to say what you do about it, and that means an entry, a stop, and an exit. The version below enters on the first close beyond the range, places the stop at the opposite edge, sets a target as a multiple of the range, and closes anything still open when the next day's range begins. It also skips days where the range is very wide compared with recent volatility, since a stop at the far edge of a huge range is a huge stop.

pine
//@version=6
strategy("ORB Strategy", overlay = true,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
     commission_type = strategy.commission.percent, commission_value = 0.05,
     slippage = 2)

orSession = input.session("0000-0030", "Opening range window")
tz        = input.string("UTC", "Time zone")
rr        = input.float(1.5, "Target as multiple of range", minval = 0.5, step = 0.25)
maxRange  = input.float(1.5, "Skip if range wider than N x ATR", minval = 0.5, step = 0.25)

inRange  = not na(time(timeframe.period, orSession, tz))
newRange = inRange and not inRange[1]
atrValue = ta.atr(14)

var float orHigh = na
var float orLow  = na
var bool tradedToday = false

if newRange
    orHigh := high
    orLow  := low
    tradedToday := false
else if inRange
    orHigh := math.max(orHigh, high)
    orLow  := math.min(orLow, low)

rangeSize = orHigh - orLow
rangeDone = not inRange and not na(orHigh)
rangeOk   = rangeDone and rangeSize <= maxRange * atrValue

longBreak  = rangeOk and not tradedToday and close > orHigh
shortBreak = rangeOk and not tradedToday and close < orLow

if newRange
    strategy.close_all("New day")

if longBreak
    strategy.entry("Long", strategy.long)
    tradedToday := true
if shortBreak
    strategy.entry("Short", strategy.short)
    tradedToday := true

if strategy.position_size > 0
    strategy.exit("Long exit", "Long", stop = orLow, limit = orHigh + rangeSize * rr)
if strategy.position_size < 0
    strategy.exit("Short exit", "Short", stop = orHigh, limit = orLow - rangeSize * rr)

plot(newRange ? na : orHigh, "Range high", color.green, 2, plot.style_linebr)
plot(newRange ? na : orLow, "Range low", color.red, 2, plot.style_linebr)

Several lines deserve comment. The tradedToday flag allows one entry per day, so a stop-out followed by a break in the other direction does not turn into a stream of trades. If you want to allow a reversal, remove the flag and read the next section on what that does to your trade count. The exit prices use the range values that were fixed at entry time, and because strategy.exit is called every bar while the position is open, the orders stay in place until one fills. The strategy.close_all on newRange is a time stop: whatever is left at the next day's opening window is closed rather than carried.

The commission and slippage lines are the ones people leave out of first drafts. Here they are set to 0.05 percent per order and 2 ticks, which are placeholder numbers, not a claim about any exchange. Look up what your venue actually charges and set the values to match. The guide to commission and slippage settings explains each parameter, and the one on how slippage and commission eat returns shows how fast a high trade count magnifies the effect. An opening range strategy trades at most once a day, but on a 15 minute chart that is still a few hundred trades over a year, and small per-trade costs add up.

Reading the test honestly

Paste the strategy into TradingView and open the Strategy Tester. Resist the urge to look at net profit first. Start with the number of trades. A year of at most one trade per day gives about 365 on a market that never closes, which is a respectable sample. A test on only the last two months gives sixty, and nothing you conclude from sixty trades deserves much confidence. Then look at the maximum drawdown and the profit factor, and at the equity curve for long flat stretches. The articles on Strategy Tester metrics and on maximum drawdown explain what each of these means.

Then change one input at a time and watch how much the result moves. Try a 15 minute window, then 60 minutes. Try a target multiple of 1.0 and 2.0. Try a different time zone anchor. If a small change in the window flips the result from good to bad, the original result was probably a coincidence of that particular setting rather than something about the market. Results that stay roughly similar across a neighborhood of settings are the ones worth a second look. This is the same lesson as in any parameter search: the more settings you try, the more likely one of them looks good by chance, so keep a record of how many you tried.

Finally, check how the strategy behaves around the boundaries of the day. Open a handful of individual days in the chart view and confirm that entries happen after the range closes, that stops sit at the opposite edge, and that nothing is left open across the daily reset. Bugs in session logic show up as trades that start inside the window or exits that never fire, and they are far easier to catch by looking at five days by eye than by staring at a summary table.

Common mistakes

The first mistake is mixing time zones. The time function uses the zone you pass, but the chart's own axis may use another, so the range you see drawn may not match the window you think you typed. Always pass the zone explicitly and compare with a day you check by hand.

The second is using the high of a bar that is still forming. Real-time values of high and low change until the bar closes, which is why the breakout conditions here use close and a plain bar-by-bar comparison. If you rewrite them to use intrabar values, read the article on barstate.isconfirmed first, or your alerts will fire on bars that later do not qualify.

The third is forgetting the first bar. If you initialise the range with na and only widen it with math.max, the very first bar of the window never sets a value. The newRange branch assigns high and low directly for exactly that reason.

The fourth is treating the opening range as a prediction. It is a rule that defines an entry and nothing more. Whether it works on a given market, window, and period is an empirical question that the Strategy Tester can only answer about the past.

Where to go from here

Once the range code works, the useful extensions are small. Add a filter that skips days when the range is narrower than a fraction of ATR. Add a second window, such as the first hour of the New York session, and compare the two. Replace the fixed target with a trailing stop, using the trailing stops article as a guide. Each change is a short edit, and in PineScripter you can describe it in a sentence and have only the affected lines changed, with a Code Changes view showing exactly what moved.

If you would rather see the range first and code it second, the workflow above is the one to use: ask the agent to mark it, check the marks against the candles and in replay, then ask for the indicator. The drawing and the code should agree, and when they do not, the disagreement tells you which assumption about the session was wrong.

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 is an opening range breakout in Pine Script?

It is a rule that records the highest high and lowest low of a fixed window at the start of a session, then marks the first bar that closes beyond either edge. In Pine Script v6 the window is defined with the time function and a session string, and var variables hold the range after the window closes.

How do I define the opening range on a 24 hour crypto market?

Pick a convention on purpose. A common one is the first 15, 30, or 60 minutes after the 00:00 UTC day boundary, written as a session string such as 0000-0030 with the UTC time zone. Others use the start of a regional session. The range changes with the choice, so test more than one.

Which chart timeframe should I use?

The window must be a whole number of bars. A 30 minute window needs a chart of 30 minutes or lower. On a 1 hour chart a 0000-0030 window contains only the 00:00 bar, so the range silently becomes one hour wide.

Should the breakout use the close or the high and low?

The scripts here use the close, which ignores wicks that poke through the edge and snap back, at the cost of one bar of delay. Using high or low reacts sooner but triggers on those wicks. Test both on the same data.

Can the PineScripter chart agent find the best breakout?

No. It marks what you ask for, such as the first 30 minutes of each day on a crypto market, and you check the marks against the candles and in bar replay. It does not predict or pick trades.

Why include commission and slippage in the strategy?

Every entry and exit pays costs, and results without them look better than they are. Set the values to what your venue charges, then compare the Strategy Tester metrics with and without them.

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.