How To Script If Then Else Conditional Statements In ThinkOrSwim

Thebtrader

Member
VIP
If I want to say the following: if A=true AND B=true then X else Y. How do I handle double conditionality of if-then statement in thinkscript?
 
@MoneyMagnet so you want to convert the CompoundValue call to use the BarNumber technique?

Post the full, working, code, and I might be able to help. From the above, I think it would be something like

Code:
def bn=BarNumber();
def XR;
#def XR = CompoundValue(1, if AbsValue(low - XR[1]) > AbsValue(high - XR[1]) then low else high, high);

if (bn==1) then {
XR = high;
} else {
if AbsValue(low - XR[1]) > AbsValue(high - XR[1]) then XR=low else XR=high
}
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

@korygill: Thanks for taking a look for me:)

This is the full working code - using CompoundValue():

Code:
def XR = CompoundValue(1, if AbsValue(low - XR[1]) > AbsValue(high - XR[1]) then low else high, high);
plot ZIGGY = XR;

It's merely intended to plot a line between highs and lows, each point based on which (high or low) is farthest from the previous bar's point.

Below is my code that attempts to do the same thing, but using BarNumber() to initialize XR (copied from the first post):

Code:
def XR;
def highdiff;
def lowdiff;

if BarNumber() == 1
    {XR = hl2;
    highdiff = 0;
    lowdiff = 0;
    }
else
    {highdiff = AbsValue(high - XR[1]);
    lowdiff = AbsValue(low - XR[1]);
    if lowdiff < highdiff
        {XR = low;}
    else
        {XR = high;}
    }

plot XRI = XR;

But here the plot stays always at the high; regardless of the result of the condition (lowdiff < highdiff), it always executes the "else" code, and never the "then" code.

Based on the code you posted, I created this version, which omits the unneeded variables for lowdiff and highdiff and adds a variable for bn... but the result is the same:

Code:
def bn = BarNumber();
def XR;

if bn == 1
    {XR = high;}
else
    {if AbsValue(low - XR[1]) > AbsValue(high - XR[1])
        {XR = low;}
    else
        {XR = high;}
    }
plot XRI = XR;

If you can help me figure out why this concept works when XR is initialized using CompoundValue() but acts incorrectly when XR is initialized using BarNumber(), I would be eternally grateful. For my immediate purposes, using CompoundValue() is sufficient, but it would be great to know what's going wrong when I try to use BarNumber() because
  1. Sometimes I want to assign values to an initialized series variable using more complex code - such as multiple statements or structured statements. I don't think you can do that within the second argument of a CompoundValue() function.
  2. As you (@korygill) stated in your other post, CompoundValue() may not always work if used more than once in a single code.
  3. As a student of thinkScript, I'd like to understand the BarNumber() function, and clearly there is something I'm missing...
 
+ @MoneyMagnet

This is totally messed up, and there is a serious bug in thinkscript. But it appears if you follow the (well my) best practice of always using variables for high/low/etc to reduce calls to the server, it works as expected.

+ @BenTen --> you might want to take note of always using the "v" variables I typically use like:
def vClose = close;

Use this study and you can see the bug and see it working by changing 2 lines. You can also see how I used AddChartBubble to debug this. I used a 6 period daily chart. I also made the c1 variable just to confirm the > operator was working as expected....

Code below with a comment to show you how to turn the bug on/off. (the code below is the working code)

Code:
declare lower;
declare once_per_bar;

def bn = BarNumber();
def vlow = low;
def vhigh = high;


def XR_C = CompoundValue(1, if AbsValue(low - XR_C[1]) > AbsValue(high - XR_C[1]) then low else high, high);

def XR;
def lowdiff;
def highdiff;
def c1; # condition 1

if (bn == 1) then {
    lowdiff = high-low;
    highdiff = 0;
    XR = high;
    c1 = 0;
} else {
    lowdiff = AbsValue(low - XR[1]);
    highdiff = AbsValue(high - XR[1]);
    c1 = lowdiff > highdiff;

    # strange BUG in thinkscript!
    # if you use low/high below, XR is always HIGH
    # using vlow and vhigh, works as expected!
    if c1==1 then {
        XR = vlow;       
    } else {
        XR = vhigh;
    }
}

plot ZIGGY = XR;
plot ZIGGY_C = XR_C;

AddChartBubble(
    yes,
    XR,
    "c1:"+c1+"\nld:"+lowdiff+"\nhd:"+highdiff+"\nxr:"+XR+"\nxr_c:"+XR_C+"\nh:"+high+"\nl:"+low,
    color.Gray,
    yes);
 
Hi everyone! This is probably an easy question. I'm trying to figure out how to do a multiple condition if statement. If you look at the following, I'm trying to do something like this:

Code:
if cond1 > 0 && cond2 > 0 && cond3 > 0 && cond4 > 0 && cond5 > 0 {
    # plot green arrow on chart 
} else {}

How would I do this?
 
Hi everyone! This is probably an easy question. I'm trying to figure out how to do a multiple condition if statement. If you look at the following, I'm trying to do something like this:

Code:
if cond1 > 0 && cond2 > 0 && cond3 > 0 && cond4 > 0 && cond5 > 0 {
    # plot green arrow on chart
} else {}

How would I do this?
something like this:
Code:
plot buy = if condition_1 > 0 AND condition_2 >= 0 and condition_3 > 0 then LOW else double.nan;

BUT

ToS works better, in my experience, with breaking it up into smaller code chunks:
Code:
def a = if condition_1 > 0 then 1 else 0;
def b = if condition_2 > 0 then 1 else 0;
def c = if condition_3 > 0 then 1 else 0;
plot buy = if a + b + c == 3 then LOW else double.nan;

it's also cleaner when debugging to separate the arguments. I also stay away from && and the rest of all that as it reminds me too much of java and since thinkscript allows me to use niceties like "AND" I use it.

-mashume
 
Hi Guys,
I am trying to code following
diff.AssignValueColor(if a and b and c then Color.Green else color.gray);
diff.AssignValueColor(if d and e and f then Color.RED else color.gray);

ultimately i want something like
diff.AssignValueColor(if a and b and c
then Color.Green
else color.gray
else d and e and f
then Color.RED
else color.gray);

But this code has error, not sure how i can fix this code.
Thanks in advance.
 
I want to set up a scan study so that if a plot "k" is within -10 or +10 of another plot "k" it will return those stocks

ie
if k1 >=(k2-10) or k1 <=(K2+10), True, otherwise false

Any help is appreciated.
 
Hello,

I am trying to paste this script in TOS, but I am getting syntax error


Code:
# Define the MACD
def macd = MACD(close, 12, 26, 9);
def macdSignal = macd.MACDSignal;
def macdHist = macd.MACDHist;

# Define the current bar
def currentBar = barNumber();

# Define the previous bar
def prevBar = currentBar - 1;

# Define the current and previous highs
def currentHigh = high[currentBar];
def prevHigh = high[prevBar];

# Define the current and previous closes
def currentClose = close[currentBar];
def prevClose = close[prevBar];

# Check if the MACD is bullish and the current high is above the previous high
if (macdHist > 0 and currentHigh > prevHigh) {
  # Check if the current close is above the previous high
  if (currentClose > prevHigh) {
    # Plot an upward arrow and set the text to "BUY"
    plotArrowUp(high + 1);
    label.new(bar_index, high + 2, "BUY", color = color.green);
  }
}
# Check if the MACD is bearish and the current high is below the previous high
else if (macdHist < 0 and currentHigh < prevHigh) {
  # Check if the current close is below the previous high
  if (currentClose < prevHigh) {
    # Plot a downward arrow and set the text to "SELL"
    plotArrowDown(high - 1);
    label.new(bar_index, high - 2, "SELL", color = color.red);
  }
}


Error Says

Code:
Syntax error: An 'else' block expected at 23:3
Syntax error: Semicolon expected at 21:1
Invalid statement: } at 36:3


Thank you for your help.
 
Without getting into the specifics of your code, there is a problem in the structure of your if else blocks at the end. The structure needs to be like this:

if a then b
else if c then d
[else if ... then ...]
else z;

the else if statements are optional, the if and else are not.
You have a strange mishmash of if, else if, and no else statements.

-mashume
 
Hello,

I am trying to paste this script in TOS, but I am getting syntax error


Code:
# Define the MACD
def macd = MACD(close, 12, 26, 9);
def macdSignal = macd.MACDSignal;
def macdHist = macd.MACDHist;

# Define the current bar
def currentBar = barNumber();

# Define the previous bar
def prevBar = currentBar - 1;

# Define the current and previous highs
def currentHigh = high[currentBar];
def prevHigh = high[prevBar];

# Define the current and previous closes
def currentClose = close[currentBar];
def prevClose = close[prevBar];

# Check if the MACD is bullish and the current high is above the previous high
if (macdHist > 0 and currentHigh > prevHigh) {
  # Check if the current close is above the previous high
  if (currentClose > prevHigh) {
    # Plot an upward arrow and set the text to "BUY"
    plotArrowUp(high + 1);
    label.new(bar_index, high + 2, "BUY", color = color.green);
  }
}
# Check if the MACD is bearish and the current high is below the previous high
else if (macdHist < 0 and currentHigh < prevHigh) {
  # Check if the current close is below the previous high
  if (currentClose < prevHigh) {
    # Plot a downward arrow and set the text to "SELL"
    plotArrowDown(high - 1);
    label.new(bar_index, high - 2, "SELL", color = color.red);
  }
}


Error Says

Code:
Syntax error: An 'else' block expected at 23:3
Syntax error: Semicolon expected at 21:1
Invalid statement: } at 36:3


Thank you for your help.

edit - updated code


@krsheath
where are you trying to use this?
did you write it?

just about everything in this study is wrong.
but, this is ok, trying is how you learn.

you should be looking up functions in the manual, to verify how to use them.


thinkscript doesn't highlight all the errors at once. it will find some and skip others.
when the highlighted errors are fixed, other errors will become highlighted red.
and on, and on,... until all the errors are fixed.
if you were to disable each red line, by commenting it with a # at the beginning of the code line, you will find that another one will pop up as red, until you have most of your code disabled.


i will add comments to a corrected copy of it, explainging what is wrong.


https://tlc.thinkorswim.com/center/reference/Tech-Indicators/studies-library/M-N/MACD

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddChartBubble

https://tlc.thinkorswim.com/center/reference/thinkScript/Constants/PaintingStrategy

https://tlc.thinkorswim.com/center/...nced/Chapter-10---Referencing-Historical-Data

Code:
# macd_errors_01

#https://usethinkscript.com/threads/syntax-error.13851/
#Syntax Error
# krsheath  Start dateYesterday at 9:57 PM

#I am trying to paste this script in TOS, but I am getting syntax error


# Define the MACD

#---------------------

def na = double.nan;
def bn = barnumber();

# def macd = MACD(close, 12, 26, 9);
# def macdSignal = macd.macdSignal;
# def macdHist = macd.macdHist;

# macd doesn't have a price parameter , close is invalid
# better to set up inputs, if you want to pass parameters to a study
# functions and studies need () after the name , macd()
# referencing a function without the plot name will read the first plot from that study. if you want to read other plots, you need to append the plot name to the end of the study.
# underline is the only special character that can be used in variable names. i like to use it to separate words, because i think it makes it easier to read.
# if you want to read a different plot from a study, you have to supply the parameters again, to make sure you are getting the correct output.


input fast_length = 12;
input slow_length = 26;
input length = 9;

#  2 plot values aren't used, so i commented them out
#def macd_value = MACD(fast_length, slow_length, length).value;
#def macd_avg = MACD(fast_length, slow_length, length).avg;
def macd_hist = MACD(fast_length, slow_length, length).diff;


#---------------------


# Define the current bar
def currentBar = BarNumber();

# Define the previous bar
def prevBar = currentBar - 1;


#---------------------

# your offsets are wrong
# when a number is appended to a variable, in brackets, it is a relative offset to another value at another bar.
#  offsets are relative, not absolute.
#   abc[1] does not read from bar #1, it means go 1 bar back in time, to the previous bar and read the value.
#   abc[-1]  means look at the next future bar and read a value.
# an offset of 0 isn't needed, but i used it to stay consistant.


# Define the current and previous highs
#def currentHigh = high[currentBar];
#def prevHigh = high[prevBar];
# Define the current and previous closes
#def currentClose = close[currentBar];
#def prevClose = close[prevBar];


def currentHigh = high[0];
def prevHigh = high[1];
def currentClose = close[0];
def prevClose = close[1];


#---------------------

# can only assign a number or generate a true/false within an if then.
#   can't create any outputs within an if then.
#   can't draw shapes, or lines, or bubbles, or labels,..

# invalid functions ,  plotArrowUp()  label.new() ,
# it looks like you are trying to use several conditions to draw a bubble and an arrow.

# since you want 2 things to happen when all the conditions are true, i would set up a variable to be equal to a formula containing the conditions. then use the variable in a plot formula and as a time parameter in a bubble.
# if a formula will be true or false, a boolean, it doesn't need to use an if then to define a value. true = 1 and false will be = to 0.  i like to wrap it in parenthesis.
# can't display text on an arrow. have to use a bubble

#-------------------------

## Check if the MACD is bullish and the current high is above the previous high
#if (macdHist > 0 and currentHigh > prevHigh) {
#  # Check if the current close is above the previous high
#    if (currentClose > prevHigh) {
#    # Plot an upward arrow and set the text to "BUY"
#        plotArrowUp(high + 1);
#        label.new(bar_index, high + 2, "BUY", color = Color.GREEN);
#    }
#}

input show_arrows = yes;
input show_bubbles = yes;

# create a true/false formula
def up = (macd_hist > 0 and currentHigh > prevHigh and currentClose > prevHigh);

# plot an up arrow below the candle
# use a formula with a price level or nan value
# i tend to add z to a variable i am plotting.

plot zup = if show_arrows and up then (low*0.999) else na;
zup.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
zup.SetDefaultColor(Color.green);
# can pick a weight size , 1 to 5
zup.setlineweight(3);
# stop a price bubble from showing up on y axis
zup.hidebubble();


addchartbubble(show_bubbles and up, (low*0.996),
"BUY"
, color.green, no);


#-------------------------

## Check if the MACD is bearish and the current high is below the previous high
#else if (macdHist < 0 and currentHigh < prevHigh) {
#  # Check if the current close is below the previous high
#  if (currentClose < prevHigh) {
#    # Plot a downward arrow and set the text to "SELL"
#    plotArrowDown(high - 1);
#        label.new(bar_index, high - 2, "SELL", color = Color.RED);
#    }
#}


def dwn = (macd_hist < 0 and currentHigh < prevHigh and currentClose < prevHigh);

plot zdwn = if show_arrows and dwn then (high*1.001) else na;
zdwn.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
zdwn.SetDefaultColor(Color.red);
zdwn.setlineweight(3);
zdwn.hidebubble();

addchartbubble(show_bubbles and dwn, (high*1.004),
"SELL"
, color.red, yes);


#-------------------------
#

F 15min chart
RC2JTPC.jpg
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
452 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top