Topics like health, travel, finance, home, living, education and careers | Media Search Home

How do we make a string of text from a TradingView number?

We often work with numbers in TradingView Pine. But at some point we may need to use them where only a string (meaning, text) is allowed. Let"s see how we can turn numbers into text, and the formatting options we have.

IN THIS ARTICLE:

  • Turn TradingView numbers into text with tostring()
  • Examples: turn numbers into TradingView text
    • Turn an input option into a time frame string with tostring()
    • Include numbers in the strategy"s order comments
  • Limitations of TradingView"s tostring() function
  • Summary
tostring()""># Turn TradingView numbers into text with tostring()

Much of the operations we perform in our TradingView scripts have to do with numbers. But occasionally we need to use a function that accepts a string of text, and cannot work with numbers. Luckily there"s one helper function that makes text from numbers.

The tostring() function converts a numerical value into a string of text (TradingView, n.d.). We can use this function in indicator (study) and strategy scripts.

There are two ways to use tostring() (TradingView, n.d.):

tostring(value) tostring(value, format)

These two arguments mean the following:

  • value: a required argument with the number that tostring() should turn into text.
  • format: an optional format string that specifies how the number should be turned into text. This argument has a default value of #.##########, which formats a number to a string with 10 non-zero values. (Each # sign represents one number.) Should we use #.## as the format string, then tostring() turns a value of 1.42345 into the "1.42" string.

Let"s explore the situations in which we can use the tostring() function.

# Examples: turn numbers into TradingView text

To my knowledge there are at this time just two ways to use tostring():

  • The resolution argument of the security() function requires a text value that specifies which time frame of data the function should load. We can use the tostring() function there to turn a number into a time frame string.
  • The comment argument of the strategy.entry(), strategy.exit(), and strategy.order() functions specifies a descriptive name for the order. We can use the tostring() function there to include a numerical value in that order comment.

Let"s look at an example of these ways to use tostring().

tostring()""># Turn an input option into a time frame string with tostring()

The first application of tostring() is with the security() function. Let"s say we want to plot the highest high and lowest low of the last n days. An easy way to configure such a script is with a numerical input option that specifies how many days of data the script should plot.

But there"s a problem with that: our script can load higher time frame data with security(), but that function requires a string that specifies the time frame (in this case, daily). security() won"t accept the number from our input option. Luckily we can have tostring() turn that number into text, and then use that text with security().

Here"s how the code of such an example indicator looks like:

//@version=3 study(title="tostring() example indicator", overlay=true) // Make input option resValue = input(title="Higher time frame days", type=integer, defval=1) // Get the previous days' higher time frame ('htf') high and low htfHigh = security(tickerid, tostring(resValue, "#D"), high)[1] htfLow = security(tickerid, tostring(resValue) + "D", low)[1] // Plot values plot(series=htfHigh, color=green, linewidth=2) plot(series=htfLow, color=red, linewidth=2)

Let"s step through the code. First we define indicator properties with the study() function. Then we make an input option:

// Make input option resValue = input(title="Higher time frame days", type=integer, defval=1)

We make this input with the input() function. The type of input we make is a whole number (type=integer), and we give it a default value of 1 (defval=1). We store the current setting of this option in the resValue variable for use later.

Then we load daily price data with security():

// Get the previous days' higher time frame ('htf') high and low htfHigh = security(tickerid, tostring(resValue, "#D"), high)[1] htfLow = security(tickerid, tostring(resValue) + "D", low)[1]

We call security() here with three arguments. The first is tickerid, a variable that returns the exchange and symbol for the current instrument on the chart. This way we load data for the exact same instrument as the script currently runs on.

Next we specify the time frame of the data to load. For this second argument security() expects a string. Our input option – whose value we stored in resValue – is an integer, however. To make that value into a string we use tostring():

  • The first security() line uses tostring(resValue, "#D"). This turns the value of resValue into a string as a whole number, followed with the letter ‘D’. (This ‘D’ signals security() that we want to load daily data.)
  • The second security() statement uses tostring(resValue) + "D". This converts our input option into text, using the default formatting of tostring(). Then we add (+) the letter ‘D’ to make it a daily time frame string.

While both code expressions are a little bit different, their outcome is the same. When our input option has a value of 1, both expressions create the "1D" string. Should our input be 3, tostring() helps to make it into the "3D" text.

The third and last argument of security() is the data to load. Here we use high and low to retrieve daily high and low data. Note that behind both security() function calls we place the history referencing operator ([]) with a value of 1. This way we don"t load data for the current day, but for the previous day.

Then we use the plot() function to plot the daily data on the chart:

// Plot values plot(series=htfHigh, color=green, linewidth=2) plot(series=htfLow, color=red, linewidth=2)

We show the highs from the higher time frame (htfHigh) in green while the lows (htfLow) display in the red colour. With the linewidth argument set to 2 both line plots appear a bit thicker than their default size.

When we add this indicator to the chart the input option uses a default of 1. That makes the script plot the high and low from the previous day:

Example chart: plotting the high and low from yesterday in TradingViewExample chart: plotting the high and low from yesterday in TradingView

If we change that input setting to 3, then the indicator script shows the high and low from the previous 3 days:

TradingView chart that shows high and low from 3 daysTradingView chart that shows high and low from 3 days# Include numbers in the strategy"s order comments

Another way to use tostring() is with TradingView"s order functions: strategy.entry(), strategy.exit(), and strategy.order(). Each of those functions has a comment argument that gives the order a description. That text then appears on the chart and in the ‘List of Trades’ in the ‘Strategy Tester’ window.

Now we could use a simple static text as the order comment, like ‘Enter long order’ or ‘RSI buy signal’. But with tostring() we can also include numbers, such as the strategy"s parameters.

Here"s how we can code that into a TradingView strategy:

//@version=2 strategy(title="tostring() example strategy", overlay=true) // Input options maLenLong = input(title="MA Length Long", type=integer, defval=20) maLenShort = input(title="MA Length Short", type=integer, defval=10) // Trading conditions enterLong = (open > high[1]) and (close > ema(close, maLenLong)) enterShort = (open < low[1]) and (close < ema(close, maLenShort)) // Submit orders strategy.entry(id="long", long=true, when=enterLong, comment="EL with MA len " + tostring(maLenLong)) strategy.entry(id="short", long=false, when=enterShort, comment="ES with MA len " + tostring(maLenShort))

Let"s see what goes on here. First we define strategy settings with the strategy() function. Then we make two input options:

// Input options maLenLong = input(title="MA Length Long", type=integer, defval=20) maLenShort = input(title="MA Length Short", type=integer, defval=10)

To make these settings we execute the input() function. They"re both integers (type=integer) and have default values (defval) of 20 and 10. We store their value in the maLenLong and maLenShort variables for use later.

Then we code two basic trading conditions:

// Trading conditions enterLong = (open > high[1]) and (close > ema(close, maLenLong)) enterShort = (open < low[1]) and (close < ema(close, maLenShort))

The long condition(enterLong) that we make here looks for two things. First, whether the bar"s open is greater than (>) the previous high (high[1]). Second, if the bar"s close is above the 20-bar moving average (ema(close, maLenLong)). Since we combine these two requirements with the and logical operator, both have to be true before our enterLong variable becomes true as well. (When one or both are false, enterLong is false too.)

The other condition we code here, enterShort, specifies when the strategy should go short. There are two requirements for that. First the bar"s open has to be less than (<) the previous low (low[1]). Then we want the closing price to be below a 10-bar moving average (close < ema(close, maLenShort). When these two things happen, enterShort is true (and false otherwise).

The last bit of strategy code submits the orders:

// Submit orders strategy.entry(id="long", long=true, when=enterLong, comment="EL with MA len " + tostring(maLenLong)) strategy.entry(id="short", long=false, when=enterShort, comment="ES with MA len " + tostring(maLenShort))

We send the orders with the strategy.entry() function. The first function call opens a long trade (long=true) named ‘long’ (id="long"). We send this order whenever enterLong is true (when=enterLong). With the function"s comment argument we give the order a description. Here that text reads "EL with MA len " added with (+) the maLenLong input variable converted to a string. We do that latter with TradingView"s tostring() function.

The second strategy.entry() line is much like the first. Here we send a short order (long=false) whenever enterShort is true. The order comment says "ES with MA len " combined with (+) the maLenShort input variable turned into text with the tostring() function.

When we add this example strategy to the chart, we see the current settings of the input options appear in the order comments:

Example of order comments on the TradingView chartExample of order comments on the TradingView chart

The same text that we made with the tostring() function also shows in the ‘List of Trades’ tab of the ‘Strategy Tester’ window:

Overview of trades in TradingViewOverview of trades in TradingView

When we use the tostring() function to include a number into an order comment, that value better stay the same during the entire backtest. Should the value change (like a moving average or closing price value does), then only the first order of our backtest has a correct order comment. All the other orders will simply repeat the first order comment, and thus have an incorrect and outdated value.

Since the parameter settings of a strategy remain the same during a backtest, we can include those in order comments. This ‘feature’ is unfortunately a big limitation in how useful tostring() is with order comments. (I hope this limit is soon removed, but it has been in TradingView Pine since at least October 2017.)

Speaking of limitations, there are a few more disadvantages that tostring() has. Let"s look at those now.

tostring() function""># Limitations of TradingView"s tostring() function

In theory, the tostring() function would make it possible to plot numbers and script values on the chart. And generate alert messages with price and script data.

But in practice most TradingView functions that do have a string argument do not accept dynamic string values. So if we use a static text like "New higher high" the function does work. But if we use text with a changing value, like "New high @ " + tostring(high), the function generates an error message.

So unfortunately there are plenty of code situations in which we cannot use the tostring() function. These are TradingView functions that don"t work with tostring():

  • alertcondition() (title and message argument)
    • Test code: alertcondition(condition=close > ema(close, 20), message="Price " + tostring(close))
    • Works?* No, gives the ‘Cannot call alertcondition with arguments…"* error message.
  • plotchar() (text argument)
    • Test code: plotchar(series=close > ema(close, 10), text="close @ " + tostring(close))
    • Works? No, triggers the ‘argument “text” accepts only constant string values’ error message.
  • plotshape() (text argument)
    • Test code: plotshape(series=close > ema(close, 20), text="Close @" + tostring(close))
    • Works? No, triggers the ‘argument “text” accepts only constant string values’ error message.
  • strategy.entry() (id argument)
    • Test code: strategy.entry(id="long at " + tostring(close), long=true, when=open > high[1])
    • Works?* No, gives the ‘Cannot call strategy.entry with arguments…"* error message.
  • strategy.exit() (id argument)
    • Test code: strategy.exit(id="order at bar #" + tostring(n))
    • Works? No, triggers the ‘Cannot call strategy.exit() with arguments…" error message.
  • strategy.order() (id argument)
    • Test code: strategy.order(id="@ " + tostring(close), long=true, when=close > sma(close, 10))
    • Works?* No, triggers the ‘Cannot call strategy.order() with arguments…"* error message.

I originally collected these limitations in November 2017 and checked them again in October 2018. When TradingView Pine makes it possible to use tostring() with the above functions, I"ll update this article.

# Summary

We turn numbers into text with TradingView"s tostring() function. There are two ways to execute that function. We can call tostring() with a single argument (so tostring(close)). That converts the specified numerical value into a string with up to 10 non-zero values after the decimal point.

Or we execute tostring() with a format string. That specifies how the number should be turned into a string. With #.##, for instance, tostring() converts a value of 1.25345 into "1.25".

There are currently two ways to use tostring(). We can use the function with security() to specify a time frame. Or we use it with the strategy.entry(), strategy.exit(), or strategy.order() function to create an order comment. There are a lot more situations in which tostring() can be useful, but current TradingView Pine limitations prevent those.

References

TradingView (n.d.). Pine Script Language Reference Manual. Retrieved on October 18, 2018, from https://www.tradingview.com/study-script-reference/

Last updated on February 24, 2021 (published October 22, 2018).
# Related TradingView tutorials
  • How to truncate numbers in TradingView"s Pine Script?

    Truncation throws away a number"s fractional value. TradingView does so with the int() function. With a custom function we truncate a number of decimals.

  • Three ways to round numbers in TradingView Pine Scripts

    TradingView has three rounding functions. round() rounds to the nearest full integer, with .5 rounding up. ceil() rounds up and floor() rounds down.

« All TradingView types & values articles


Email: contact@about.com.vn - Phone: 818.333.007 - Website: Media Search Home
Copyright © 2007 - Noos. All rights reserved