Tradingview: Ternary Conditional Operators ?:

For myself, coming from a Python background, reading the syntax on a Tradingview script can sometimes feel a little alien. The ternary conditional operators are one such example. Most scripts on Tradingview contain them and they can even be stacked together to provide the switch-like statement (or the equivalent of if elif and else in Python ).

For others, just the term ternary conditional operator sounds intimidating. If you didn’t study maths or science at university there is a chance you will be completely unfamiliar with it. However, as acedemic as it sounds, it is actually pretty straightforward. It essentially refers to something that consists of three or has three variables.

http://www.dictionary.com/browse/ternary

And with that definition lies the heart of the operator. We are taking three variables, looking at one and then assigning either of the remaining two depending on the outcome of the first one. For example in the following statement:

x = variable_one ? variable_two : variable_three

We assign variable two to X if variable one is True, else we assign variable three to x.

Going back to the Python parallel, it converts to:

Simple Example

Let’s start with a simple example. This script will simply change the bar color of Friday’s to blue.

Let’s break it down:

  • x: Is the variable that will hold our series of true / false data.
  • dayofweek: Is a built-in variable that returns 1-6 depending on which day of the week it is.
  •  x = dayofweek == 5: Performs a check every single bar to test whether the dayofweek equals 5. If so, it stores a true value, if not it stores false.
  • barcolor(): A built-in function to change the color of a bar on the chart.
  • barcolor(x ? blue:gray): Checks to see if x is true, if so, blue will be assigned, if false gray is assigned.

We can actually write the whole study as barcolor(dayofweek == 5 ? blue:gray). However, I think it is easier understand the logic if we break it down into mini steps as above.

If you run the script above, it will look like this on the charts:

Conditional operator simple example

Switch-Like Operator

Next, we can add some more complexity to the operator by stacking them up. Let’s continue with the example above and give each day of the week a different color.

Here we have added a new variable y and are assigning a color to it depending on the value of x.  If x equals 1 we assign black to the y variable. If it is 2 we assign white and so on. When adding additional conditions, we replace the 3rd variable with the new test. It essentially means the test returns false, do another test. This continues on until the last test where we add the final value if none of the tests return true. In this case, our final value is yellow.

Finally, running the script should look like this on the charts:

And that is all there is to it! Let me know in the comments if anything is unclear.