How can I plot repeating price levels in pinescript?

I'm trying to plot price levels that I want to easily see as essentially a grid in Pinescript. From what I have seen I can't use hline in a loop, any ideas how I could achieve this in a different way?

Example: plot a horizontal line every $1000 on the chart.


Solution 1:

This should do it.

//@version=5
indicator('Lines', max_lines_count=500, overlay=true)

var float   minPrice    = input.float(0,  'Price : From', 0, inline='price')
var float   maxPrice    = input.float(50, 'To',           0, inline='price')
var float   interval    = input.float(5,  'Step',         0, inline='price')
var bool    betweenHiLo = input.bool(false, 'Only show lines between highest and lowest price of the ticker')
var int     timeFirst   = na
var float   atl         = 1e20
var float   ath         = 0

if barstate.isfirst
    timeFirst := time
    
if betweenHiLo
    atl := math.min(atl, low)
    ath := math.max(ath, high)
    
if barstate.islast
    atl := math.floor(atl / interval) * interval
    ath := math.ceil(ath / interval) * interval

    fromY = betweenHiLo ? atl : minPrice
    toY   = betweenHiLo ? ath : maxPrice

    for i = fromY to toY by interval
        line.new(timeFirst, i, timeFirst+1, i, xloc.bar_time, extend.right)