Spencer Burgess
Spencer Burgess

Reputation: 1

A way to have multiple price points in an array and then have a for loop go over the array and create a horizontal line at each price point

I made an array containing all of the price points that i had, and then I ran a for loop after that with a statement to create a horizontal line with each of the price points. This is my first night learning pine editor, i have no clue how to find/use their terminal or where the error messages pop out.

float[] priceList = array.from(138.73, 140.47, 139.59, 141.25, 138.9)
for i = 0 to array.size(priceList) - 1
    hline([i], title = "Price Line", color = color.red, linestyle = hline.style_solid, linewidth = 2)

Upvotes: -1

Views: 1348

Answers (1)

mr_statler
mr_statler

Reputation: 2161

The code won't compile, since hline function requires input form type. Use the newer, more flexible, line function:

float[] priceList = array.from(138.73, 140.47, 139.59, 141.25, 138.9)

for i = 0 to array.size(priceList) - 1
    line.new(0, array.get(priceList, i), bar_index, array.get(priceList, i), extend = extend.both, color = color.red)

Some side notes -

  1. If you want to loop through an array, you can use for...in loop.
  2. Pine script runs on each bar, and currently we are creating all those lines on each bar without deleting them. You can specify the script to run only once on the very last bar to optimize this.
float[] priceList = array.from(138.73, 140.47, 139.59, 141.25, 138.9)

if barstate.islast
    for [index, price] in priceList
        line.new(0, array.get(priceList, index), bar_index, array.get(priceList, index), extend = extend.both, color = color.red)

EDIT:

If you do want to create new lines and delete them later using an array, you can use another array which will be an array of lines, and then delete the lines if a condition is met:

float[] priceList = array.from(open, high, low, close)

line[] lineList = array.new_line(array.size(priceList))
                                
if yourCondition
    for [index, line] in lineList
        line.delete(array.get(lineList, index))
        newPrice = array.get(priceList, index)
        array.set(lineList, index, line.new(0, newPrice, bar_index, newPrice, extend = extend.both))

Upvotes: 1

Related Questions