In Pine Script, the fill()
function is essential for creating shaded areas between two plots or horizontal lines. It adds a visual component to your script, aiding in data interpretation. Here, we’ll explore its usage in conjunction with plot()
and hline()
functions.
Using fill()
with plot()
Example 1: Shading between Sine and Cosine Waves
//@version=5 indicator("Example 1") sinHigh = plot(math.sin(high)) cosLow = plot(math.cos(low)) sinClose = plot(math.sin(close)) fill(sinHigh, sinClose, color.new(color.red, 90)) fill(cosLow, sinClose, color.new(color.blue, 90))
In this snippet:
sinHigh
,cosLow
, andsinClose
store IDs returned byplot()
.fill()
creates shaded areas between these plots.- We use sine and cosine functions for dynamic visualization.
Key Points:
fill()
requires IDs fromplot()
to create fills.- Math functions enhance visual representation.
Using fill()
with hline()
Example 2: Shading between Horizontal Lines
//@version=5 indicator("Example 2") horizLine1 = hline(0) horizLine2 = hline(1.0) horizLine3 = hline(0.5) horizLine4 = hline(1.5) fill(horizLine1, horizLine2, color.new(color.yellow, 90)) fill(horizLine3, horizLine4, color.new(color.lime, 90))
Here:
horizLine1
tohorizLine4
are horizontal lines at different levels.- Shaded areas are created between these lines.
Key Points:
hline()
creates horizontal reference lines.- Fills can visually distinguish different zones.
Combining plot()
and hline()
Example 3: Shading between Plot and Zero Line
//@version=5 indicator("Example 2") src = close ma = ta.sma(src, 10) osc = 100 * (ma - src) / ma oscPlotID = plot(osc) zeroPlotID = plot(0, "Zero", color.silver, 1, plot.style_circles) fill(oscPlotID, zeroPlotID, color.new(color.blue, 90))
In this example:
- We plot an oscillator and a zero line.
- Shading helps identify when the oscillator is above or below zero.
Key Points:
- Use
plot()
for dynamic lines like oscillators. hline()
is replaced withplot()
to enable fill.
Dynamic Color Shading
Example 4: Color Shading Based on Conditions
//@version=5 indicator("Example 3", "", true) line1 = ta.sma(close, 5) line2 = ta.sma(close, 20) p1PlotID = plot(line1) p2PlotID = plot(line2) fill(p1PlotID, p2PlotID, line1 > line2 ? color.new(color.green, 90) : color.new(color.red, 90))
Here:
- Shading color changes based on the condition (
line1 > line2
). - It’s a dynamic way to visualize crossovers of moving averages.
Key Points:
- Conditional colors add depth to analysis.
- Useful for highlighting trends or crossovers.
Conclusion and Takeaways
fill()
is versatile for shading between plots or lines in Pine Script.- It accepts IDs from
plot()
andhline()
. - Color and opacity can be dynamic, enhancing visual analysis.