Resource icon

thinkScript Conditions: if, then, else statement

An if-then condition statement is employed when you want an indicator to act differently in specific situations. In ThinkorSwim, the if-then statement allows for advanced behavior and give your thinkScript code the flexibility to make decisions.


def pattern = if condition then 1 else 0;


This lower study will plot 1 for every red candle.

declare lower;

def red_bar = close < open;
plot spike = if red_bar then 1 else 0;

The example above is more so of an if-expression.

Here is another example where we use the if statement. When you have multiple conditions in your script, you can deploy the if - then - else statement multiple times.

The script below highlights bullish and bearish Engulfing patterns on your chart.
  • If the Bullish condition returns true, then the code will highlight your candle in green.
  • If the Bearish condition returns true, then the code highlights your candle in red.
  • For any candles without the Engulfing pattern, the script assigns the color white to each candle.
# TD Ameritrade IP Company, Inc. (c) 2011-2020

input length = 20;
input trendSetup = 3;

def BodyMax = Max(open, close);
def BodyMin = Min(open, close);
def IsEngulfing = BodyMax > BodyMax[1] and
    BodyMin < BodyMin[1];
def IsWhite = open < close;
def IsBlack = open > close;
def IsPrevDoji = IsDoji(length)[1];

def Bearish = IsAscending(close, trendSetup)[1] and
    (IsWhite[1] or IsPrevDoji) and
    IsBlack and

def Bullish = IsDescending(close, trendSetup)[1] and
    (IsBlack[1] or IsPrevDoji) and
    IsWhite and

AssignPriceColor(if Bullish then else if Bearish then else color.white);

Additional scripts related to if, then, else

First release
Last update
0.00 star(s) 0 ratings

More resources from BenTen