Chapter 14. Concatenating Strings

In chapter 9, we've learned a lot about methods of outputting values beside plots. We considered the following example for AddLabel function:

AddLabel(yes, "Average: " + Average(close, 20));

This is where we first used string concatenation: we appended value of the average to the string using the “+” operator. In this last chapter we are going to find out other ways of concatenating strings and their peculiarities.

Beside the “+” operator, one can use the Concat function which was also briefly mentioned in chapter 9. Using both methods is beneficial when you need to pass resulting string to any of the following functions: AddLabel, AddVerticalLine, Alert, or AddChartBubble.

Note that the Concat function preliminarily converts values of different types to a string. For this reason you can use any numeric values as the function's parameters:

AddVerticalLine(getMonth() <> getMonth()[1], concat("Open: ", open));

This example draws a vertical line with the Open value for the beginning of each month. The same result will be obtained with concatenation operator “+”:

AddVerticalLine(getMonth() <> getMonth()[1], "Open: " + open);

The following example explains what should be done if you need to concatenate more than two values:

input price = close;
input threshold = 100;
alert(price > threshold, Concat("Current price ", Concat(price, Concat(" is greater than ", threshold))), Alert.TICK);

This example defines a local alert triggered once a new quotation arrives in case the current price is higher that the specified one. In order to concatenate more than two values, the example uses nested Concat function calls:

concat(value1, concat(value2, value3))

But we could, of course, make the script much simpler if we use the concatenation operator:

input price = close;
input threshold = 100;
alert(price > threshold, "Current price "+ price + " is greater than " + threshold, Alert.TICK);

But sometimes using the Concat function is unavoidable: it is the only way to convert a numerical value to string.

input isVerbose = yes;
AddLabel(yes, Concat(if isVerbose then "Close: " else "", close));

Let’s see what is going on here. This script adds a chart label which shows the Close price. If input isVerbose is set to yes, then the word “Close:” is prepended to the number. If it is set to no, only the number is displayed. As you can see from this example, in order to pass a numeric value as a string you need to preliminarily concatenate it with an empty string using the Concat function:

Concat(numerical_value, "")