Search code examples
pine-scriptpine-script-v5

Rounding values in PineScript in a table


I'm new to coding generally, but cobbling together parts from other indicator examples.

I have the following code for displaying average volume for a stock in a table:

// Average volume
volAvg = ta.ema(volume, 20)

// Table
var table infoDisplay = table.new(position.bottom_right, 1, 2, bgcolor = color.rgb(38, 166, 154), border_color = color.white, border_width = 1)
if barstate.islast
    table.cell(infoDisplay, 0, 0, 'ADR\n' + str.tostring(ADR, "0.00") + '%', text_size = size.small)
    table.cell(infoDisplay, 0, 1, 'Avg D Vol\n' + str.tostring(volAvg), text_size = size.small)

This works, but the volume can be very long

ideally this would be simplified to "K, M, B" using something like:

volAvgSimp = if (volAvg > 1000000000)
    str.tostring(volAvg/1000000000, "0.00") + "B"
else if (volAvg < 1000000000 and volAvg > 1000000)
    str.tostring(volAvg/1000000, "0.00") + "M"
else if (volAvg < 1000000)
    str.tostring(volAvg/1000, "0.00") + "K"

However this is giving the error: Error at 27:9 Mismatched input 'str' expecting 'end of line without line continuation'

====

Looks like there's "format.volume" which automatically does this, but I think it applies to the whole script, doesn't seem to work in the table?


Solution

  • Instead of manually constructing the volAvgSimp string, you can directly format the volAvg value using the format.volume argument of str.tostring() function.

    format (series string) Format string. Accepts these format.* constants: format.mintick, format.percent, format.volume. Optional. The default value is '#.##########'.

    https://www.tradingview.com/pine-script-reference/v5/#fun_str%7Bdot%7Dtostring

    table.cell(infoDisplay, 0, 1, 'Avg D Vol\n' + str.tostring(volAvg, format.volume), text_size = size.small)
    

    enter image description here