New features in Pine Script: str.format() and array.from()

May 21, 2021

This update of the Pine Script language adds functions for working with strings and arrays.

The str.format() function allows you to convert the arguments passed to it into a string with a specified format:

str.format(formatString, arg0, arg1, ...) -> string

The formatString includes an N subscript in parentheses “{}” to substitute the corresponding formatted arguments (arg0, arg1..argN, which are strings or numbers), and some of the patterns discussed below.

So, for parsing strings, you no longer need to use a construction using the str.replace_all() function:

txt := "Time to {0} some {1}!"

txt := str.replace_all(txt, "{0}", close > open ? "buy" : "sell")

txt := str.replace_all(txt, "{1}", syminfo.ticker)

but you can do it in a new, more convenient, and shorter way:

txt = str.format("Time to {0} some {1}!", close > open ? "buy" : "sell", syminfo.ticker)

The subscripts {0} and {1} enclosed in brackets are replaced with the corresponding ordinal arguments: {0} – the result of the ternary operator execution, the string “buy” or “sell”, is returned depending on the inequality of prices close and open, {1} – syminfo.ticker, the current symbol on the chart:

Using the number template, the number converted to a string can be converted to a different representation, for example, to limit the number of decimal places

str.format("{0,number,#.#}", 1.34) // returns: 1.3

Discard the fractional part of the number:

str.format("{0,number,integer}", 1.34) // returns: 1

Get financial information:

str.format("The cash turnover amounted to {0,number,currency}", 1340000) 

// “The cash turnover amounted to $1,340,000.00”.

Get percentages:

str.format("Expected return is {0,number,percent} - {1,number,percent}", 0.1, 0.2)  

// returns: Expected return is 10% - 20%. 

The str.format() function supports the date template for formatting date/time.

This script displays the number of months, weeks, and days:

//@version=4
study("str_format_date")

//formatting string with date pattern
txt = str.format("Current bar date: {0,date, y-MM-d'.' \n M 'months \n' F 'weeks \n' D 'days \n' }", timenow)

//printing label
var l1 = label.new(na, na, color = #FFFFFF00)
label.set_x(l1, bar_index)
label.set_yloc(l1, yloc.belowbar)
label.set_text(l1, txt)

plot(close)

Only one variable timenow is passed to the str.format() function, which contains the UNIX time representation: the current date, time and time zone for the exchange of a symbol on the chart. The string is formatted using the characters yM, D, F (year, month, day of the year, week of the month), the \n special character for line breaks, and single quotes ‘’ to insert text between characters.

This script outputs formatted strings to the label and the corresponding result of the str.format() function with various characters:

//@version=4
study("str_format_date_time")

// creating date-time variable: 2021.05.04. 14:30:59
t = timestamp("GMT+0", 2021, 05, 04, 14, 30, 59)

// function for left side of the label
f_print_left(_text)  => var _label = label.new(bar_index, na, _text, xloc.bar_index, yloc.price, color(na), label.style_label_right, color.green, size.large, text.align_right), label.set_xy(_label, bar_index, 0), label.set_text(_label, _text)

// function for right side of the label
f_print_right(_text) => var _label = label.new(bar_index, na, _text, xloc.bar_index, yloc.price, color(na), label.style_label_left, color.red, size.large, text.align_left), label.set_xy(_label, bar_index, 0), label.set_text(_label, _text)

var string format = 
  "{0,date,y.MM.dd hh:mm:ss}\n" +
  "{1,date,short}\n" +
  "{2,date,medium}\n" +
  "{3,date,long}\n" +
  "{4,date,full}\n" +
  "{5,date,h a z (zzzz)}\n" +
  "{6,time,short}\n" +
  "{7,time,medium}\n" +
  "{8,time,long}\n" +
  "{9,time,full}\n" + 
  "{10,time,hh:mm:ss}\n" +
  "{11,time,HH:mm:ss}\n"

// printing format string 
f_print_left(format)
//printing formatted string
f_print_right(str.format(format, t, t, t, t, t, t, t, t, t, t, t, t))

The left column of the label contains the characters enclosed in {}, the right is the result of the str.format function:

The t variable is passed to the str.format() function, which contains the UNIX time representation: the current date, time and timezone.

The next innovation is the array.from() function, which takes a variable number of input arguments of one of the following types: float, int, bool, string, label, line, color and returns an array of the corresponding type. The function allows you to declare an array, assign initial values to it and assign the result to any variable in just one line of code.

Previously, to create an array and fill it with initial values, you had to use the array.new() function and the array.push() or array.set() functions:

color[] plotColors = array.new_color(size=0)
array.push(plotColors, color.red)
array.push(plotColors, color.green)
array.push(plotColors, #0000FF)

Now, to create an array that will contain the colors of the charts, you can get by with just one line:

plotColors = array.from(color.red, color.green, #0000FF)

The function will automatically cast the plotColors array to the color[] type based on the received arguments:

//@version=4
study(title="array_from")

f_arr (series1, series2, color1, color2) =>
    [ array.from(series1, series2), array.from(color1, color2) ]

[lines, colors] = f_arr(close, open, color.red, color.green)    

plot ( array.get(lines, 0), color = array.get(colors, 0))
plot ( array.get(lines, 1), color = array.get(colors, 1))

Information about these str.format() and array.from() functions is always available in our reference manual.

If you would like to know about Pine Script updates, check out the Release notes section. The PineCoders account also broadcasts updates on its Squawk Box Telegram channel, Twitter and the Pine Script public chat on TradingView.

We hope you find these improvements useful, and please do continue to share your opinion with us. We’re building TradingView for our users, and we love hearing what you think about our innovations.

Look first Then leap

TradingView is built for you, so make sure you're getting the most of our awesome features
Launch Chart