Search code examples
pine-scriptpine-script-v5tradingview-api

Plot variable name instead of value


I'm trying to tabularize various ma values in descending order and i want to plot ma name instead of value

Here is my code

a = array.new_float(na)
    array.push(a,ma1[1])
    array.push(a,ma2[1])
    array.push(a,ma3[1])
    array.push(a,ma4[1])
    array.push(a,ma5[1])
    array.push(a,ma6[1])
    array.push(a,ma7[1])
    array.push(a,ma8[1])
    array.push(a,ma9[1])
    array.sort(a,order = order.descending)

    var table maDisplay = table.new(position.top_right, 10, 10)
    
    table.cell(maDisplay, 0, 1, str.tostring(array.get(a,0)))
    table.cell(maDisplay, 0, 2, str.tostring(array.get(a,1)))
    table.cell(maDisplay, 0, 3, str.tostring(array.get(a,2)))
    table.cell(maDisplay, 0, 4, str.tostring(array.get(a,3)))
    table.cell(maDisplay, 0, 5, str.tostring(array.get(a,4)))
    table.cell(maDisplay, 0, 6, str.tostring(array.get(a,5)))
    table.cell(maDisplay, 0, 7, str.tostring(array.get(a,6)))
    table.cell(maDisplay, 0, 8, str.tostring(array.get(a,7)))
    table.cell(maDisplay, 0, 9, str.tostring(array.get(a,8)))



and here is the plot ma plot

i want ma names to compare with current values visually

plot variable name instead of values


Solution

  • You should use the matrix type to record the value and the name of your ma.
    The problem with matrix is that the matrix cannot have float and string value.
    A workaround is to only use float value, and give the reference 1 to 9 to be able to show the ma name.

    NB : This work only in pinescript version 5

    // create a matrix : 
    // the column 0 will get the reference of the ma, the column 1 will get the value of the ma
    
    a = matrix.new<float>(9, 2, 0.0)
    
    // Add ma1[1] to the matrix
    // create an array to add the new row (reference, value)
    b = array.from(1, ma1[1])
    // add the array to the matrix
    matrix.add_row(a, 0, b)
    
    // Add ma2[1] to ma9[1] the same way
    b := array.from(2, ma2[1])
    matrix.add_row(a, 1, b)
    
    b := array.from(3, ma3[1])
    matrix.add_row(a, 2, b)
    
    ...
    
    b := array.from(9, ma9[1])
    matrix.add_row(a, 8, b)
    
    // Sort the matrix
    matrix.sort(a, 1, order.ascending ) // Sort the column with the ma values
    
    // Draw the table
    var table maDisplay = table.new(position.top_right, 2, 10)
        
    table.cell(maDisplay, 0, 0, "Name of ma")
    table.cell(maDisplay, 1, 0, "Value of ma")
    
    for row_matrix = 0 to 8
        table.cell(maDisplay, 0, 1+row_matrix, str.tostring(matrix.get(a, row_matrix, 0) )
        table.cell(maDisplay, 1, 1+row_matrix, str.tostring(matrix.get(a, row_matrix, 1) )