How to Draw Rectangle in Pine Script: Complete Guide for TradingView
Ever stared at your TradingView chart thinking "I really need to highlight this price zone" or "I wish I could mark where something important happened"? That's exactly what I felt when I first discovered Pine Script rectangles. They're honestly one of the most practical drawing tools you can learn, and way easier than most people think.
Drawing rectangles (or "boxes" as Pine Script calls them) lets you visually mark specific areas on your charts. Whether you're highlighting support and resistance levels, marking consolidation zones, or just trying to organize your analysis better, rectangles make everything clearer.
What Are Pine Script Rectangles?
Think of rectangles as invisible boxes you can draw on your chart to highlight specific price ranges and time periods. They're perfect for:
- Marking key support and resistance zones
- Highlighting price consolidation areas
- Showing important time periods (like news events)
- Creating visual boundaries for your analysis
- Building more organized, readable charts
The magic happens through Pine Script's box.new() function, which is surprisingly straightforward once you get the hang of it.
Understanding the box.new() Function
Here's the basic structure of how rectangles work in Pine Script:
box.new(left, top, right, bottom, border_color, border_width, border_style, extend, xloc, bgcolor)
Don't let all those parameters scare you - you'll mainly use just four of them:
- left/right: Where your rectangle starts and ends horizontally (time-wise)
- top/bottom: The price levels for the top and bottom of your rectangle
- border_color: What color you want the outline to be
- bgcolor: The fill color inside the rectangle
The rest are optional settings that give you more control, but you can ignore them when starting out.
Your First Rectangle: A Simple Example
Let's start with something basic. This code draws a rectangle showing the price range from 100 bars ago to 10 bars ago:
//@version=5
indicator("My First Rectangle", overlay=true)
// Create a rectangle from historical data
myBox = box.new(bar_index[100], highest(high, 50), bar_index[10], lowest(low, 50),
color.purple, 1, line.style_solid, extend.none, xloc.bar_index,
color.new(color.purple, 90))
// Clean up old rectangles to keep charts tidy
box.delete(myBox[1])
This example creates a purple rectangle that shows the high and low range over a specific time period. The box.delete() line is important - it removes the previous rectangle so you don't end up with hundreds of boxes cluttering your chart.
Practical Rectangle Examples That Actually Work
Creating Custom Price Zones
Sometimes you want to mark specific price levels that matter to your trading. Here's how to create a rectangle where you can set your own prices and times:
//@version=5
indicator("Custom Price Zone", overlay=true)
// Input settings you can adjust
startPrice = input.float(100, "Zone Bottom Price")
endPrice = input.float(200, "Zone Top Price")
startTime = input.time(timestamp("01 Jan 2023 00:00 +0000"), "Start Time")
endTime = input.time(timestamp("01 Jan 2024 00:00 +0000"), "End Time")
// Color customization
zoneColor = input.color(color.blue, "Zone Color")
fillColor = input.color(color.new(color.blue, 80), "Fill Color")
// Draw the rectangle on the last bar
if barstate.islast
box.new(startTime, startPrice, endTime, endPrice,
border_color=zoneColor, border_width=2, bgcolor=fillColor)
This creates a customizable rectangle that you can adjust through Pine Script's input settings. Super handy for marking specific support/resistance zones that matter to your strategy.
Highlighting Time-Based Events
Want to mark what happens at specific times? This is great for highlighting market opens, news events, or any time-based pattern:
//@version=5
indicator("Time Highlighter", overlay=true)
// Mark 9:30 AM EST (market open)
isMarketOpen = hour == 9 and minute == 30
// Draw a box around that specific candle
if isMarketOpen
box.new(bar_index-1, high, bar_index, low,
color.orange, 2, bgcolor=color.new(color.orange, 85))
This example highlights every candle that occurs at 9:30 AM with an orange rectangle. You can modify the time condition to mark any event that matters to your trading.
Solving Common Rectangle Problems
The Resolution Error That Drives Everyone Crazy
If you see an error message about "resolution argument is incompatible," here's the fix: remove any resolution= parameter from your indicator() function. Drawing tools like rectangles don't play nice with custom resolutions.
When Your Rectangle Shows Up in the Wrong Place
This usually happens because of coordinate confusion. Double-check:
- Are you using
bar_index[n]correctly? Remember,bar_index[1]is the previous bar,bar_index[10]is 10 bars ago - Are your left/right coordinates in the right order? Left should be smaller than right
- Are your price coordinates realistic for the current chart?
Performance Issues with Too Many Rectangles
If your chart starts running slowly, you're probably creating too many rectangles. Always use box.delete() to clean up old ones you don't need anymore.
Pro Tips for Better Rectangle Usage
Make Rectangles Semi-Transparent
Nobody wants rectangles that completely hide the price action. Use transparency to keep your charts readable:
bgcolor = color.new(color.red, 80) // 80% transparent red
Use Conditions to Control When Rectangles Appear
Don't draw rectangles on every bar. Use conditions to only create them when they're actually useful:
// Only draw rectangles during high volatility
if ta.atr(14) > ta.sma(ta.atr(14), 20)
box.new(bar_index-5, high, bar_index, low, color.yellow)
Clean Up Old Rectangles Automatically
Always include cleanup code to prevent chart clutter:
// Delete the rectangle from the previous bar
box.delete(myBox[1])
Real-World Trading Applications
Marking Dynamic Support and Resistance
Here's a practical example that automatically identifies and highlights recent support and resistance zones:
//@version=5
indicator("Auto Support/Resistance Zones", overlay=true)
// Calculate recent highs and lows
recentHigh = ta.highest(high, 50)
recentLow = ta.lowest(low, 50)
// Draw the zone on the last bar
if barstate.islast
box.new(bar_index-50, recentHigh, bar_index, recentLow,
color.red, 1, bgcolor=color.new(color.red, 90))
This creates a rectangle showing the 50-bar high/low range, giving you an instant visual of the recent trading range.
Session Range Tracker
Track and visualize daily trading ranges with this session-based rectangle:
//@version=5
indicator("Daily Range Tracker", overlay=true)
// Variables to track session highs and lows
var float sessionHigh = na
var float sessionLow = na
// Detect new trading day
newSession = ta.change(time("D"))
// Reset on new day
if newSession
sessionHigh := high
sessionLow := low
else
// Update throughout the day
sessionHigh := math.max(sessionHigh, high)
sessionLow := math.min(sessionLow, low)
// Draw the session range
if barstate.islast and not na(sessionHigh) and not na(sessionLow)
box.new(bar_index-20, sessionHigh, bar_index, sessionLow,
color.green, 1, bgcolor=color.new(color.green, 85))
This tracks the high and low of each trading session and displays it as a green rectangle, helping you visualize daily ranges at a glance.
Advanced Rectangle Techniques
Combining Rectangles with Other Indicators
Rectangles become even more powerful when combined with other Pine Script features. For instance, you can create rectangles that only appear when certain indicator conditions are met, or use different colors based on market conditions.
If you're new to Pine Script and want to learn more about combining different elements, check out our comprehensive Pine Script tutorial that covers everything from basic syntax to advanced strategies.
Using Rectangles in Trading Strategies
Rectangles aren't just for visual analysis - they can be part of your actual trading logic. You can use them to define entry and exit zones, or as part of breakout strategies. For more advanced strategy development, our guide on how to write a strategy in Pine Script shows you how to build complete trading systems.
Troubleshooting Rectangle Issues
Rectangle Not Showing Up?
- Make sure you have
overlay=truein your indicator declaration - Check that your coordinates are within the visible chart area
- Verify that your colors aren't set to transparent (100% transparency)
Colors Look Wrong?
- Double-check your color syntax:
color.red,color.new(color.blue, 50), etc. - Remember that transparency values range from 0 (opaque) to 100 (completely transparent)
Chart Running Slowly?
- You're probably creating too many rectangles
- Always use
box.delete()to clean up old rectangles - Consider using conditions to limit when rectangles are created
Rectangle Position Is Off?
- Verify your bar index calculations
- Make sure left coordinate is less than right coordinate
- Check that your price levels make sense for the current symbol
Getting Started with Pine Script Rectangles
If you're completely new to Pine Script, don't worry - rectangles are actually a great place to start learning. They're visual, immediately useful, and help you understand basic Pine Script concepts.
For beginners, I recommend starting with our beginner's guide to running Pine Script, which walks you through setting up your first script step by step.
Once you're comfortable with rectangles, you might want to explore other drawing tools like drawing lines with Pine Script, which opens up even more possibilities for chart analysis.
Wrapping Up
Drawing rectangles in Pine Script is one of those skills that seems complicated at first but becomes second nature once you get the hang of it. The key is to start simple, experiment with different parameters, and gradually build up to more complex applications.
Remember these essential points:
- Always use
overlay=truefor drawing tools - Clean up old rectangles with
box.delete()to maintain performance - Use transparency to keep your charts readable
- Start with simple examples before attempting complex logic
Whether you're marking support and resistance levels, highlighting important time periods, or building visual trading systems, rectangles are an incredibly versatile tool that can make your charts both more informative and easier to read.
The best part? Once you master rectangles, you'll have a solid foundation for understanding other Pine Script drawing tools and concepts. So fire up that Pine Editor, copy one of these examples, and start experimenting. Your charts will thank you for it!
