Search code examples
pine-scriptpine-script-v5

Add a $ dollar sign in front of the number printed by plotchar()


I am using pinescript v5 to print out a number num_size. The code looks something like this;

plotchar(num_size, title="num_size", char="", location=location.top, color=color.yellow)

I want to add a dollar sign in front of the number to be printed.

I don't mind answers that use alternative solution like label_new()


Solution

  • You cannot do that with plotchar() as the name suggests, it works with a char and not with a string.

    Since you mentioned you are open to alternative solutions, here are four ways to do it with a label.

    The first example uses str.format(). This will format the number and add the $ in front.

    The second example uses a hard-coded approach.

    The third example puts the currency of the symbol in front. It will not be a dollar sign but USD instead. You can convert the return value to currency signs if you need because this is the most reliable option in my opinion -which is option four.

    //@version=5
    indicator("My script", overlay=true)
    
    f_conver_currency_to_sign(p_currency) =>
        switch (p_currency)
            "EUR" => "€"
            "USD" => "$"
            "GBP" => "£"
            => p_currency
    
    if (barstate.islast)
        s = "Close 1: " + str.format("{0,number,currency}", close) + "\n"
        s := s + "Close 2: " + "$" + str.tostring(close, format.mintick) + "\n"
        s := s + "Close 3: " + syminfo.currency + str.tostring(close) + "\n"
        s := s + "Close 4: " + f_conver_currency_to_sign(syminfo.currency) + str.tostring(close)
        label.new(bar_index, high, s, textcolor=color.white)
    

    As you can see below, options 1 and 2 will fail on EURGBP:

    enter image description here

    EURUSD: enter image description here