Nested IF THEN syntax in thinkscript?

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?
 

evanevans

Active member
Sorry if this has been asked before, but I couldn't get to the bottom of searching for this because the words "if" and "then".

How can you use an IF THEN statement to condition several lines of code?

Example:

Code:
def x=true;
If x then {
code line 1;
code line 2;
code line 3;
};
 

JebFrenko

New member
I'm trying to duplicate a snippet I have on another platform but and running into a brick wall. I am basically trying to color a line one way on the first occurrence of a condition and keep that color until the first occurrence of a different condition. I am breaking the if's into nested singles but the first one errors out "if MyUpFlag = False then {" telling me I need double equal sign. Elsewhere the algorithm is simple:

Code:
Var:
    vHi(0),
    vLo(0),
    MyUpFlag(False),
    MyDnFlag(False),
    thePlotter(0);

If C > vHi and MyUpFlag = False then
Begin
    MyUpFlag = True;
    MyDnFlag = False;
    thePlotter = Green;
End
Else If C < vLo and MyDnFlag = False then
Begin
    MyUpFlag = False;
    MyDnFlag = True;
    thePlotter = Red;
End;

Here I can't even get to first base. Can anyone help or point me to some examples that might help
 

MatthewA

Active member
Hello @JebFrenko I don't know what you want condition you wish to plug in but here is a lower that counts the number of bar between when some event happens and then another event happens. You would use the state of the events to turn different colors or arrows on or off...

Code:
# ConsecutiveBarCount
# Comment out unnecessary portions to preserve TOS memory and enhance speed
declare lower;
declare once_per_bar;
def nan = Double.NaN;
#### What is the Up Flag and What is the Down Flag??? Use whatever you like... RSI MACD whichever
#[B](You can give me an example case to plugin here!) I don't care what but I can't think of anything HigherHigh Lower Low??)[/B]
#Var:
#   vHi(0),
#    vLo(0),                 
#    MyUpFlag(False),
#    MyDnFlag(False),
#    thePlotter(0);

def zeroLine = 0;
plot pZeroLine = zeroLine;
pZeroLine.SetDefaultColor(Color.WHITE);

def barUpCount = CompoundValue(1, if MyDnFlag && !MyUpFlag then barUpCount[1] + 1 else 0, 0);
def AscendedProfile = CompoundValue(1, if barUpCount && !MyDnFlag[1] then 1 else if MyUpFlag or MyDnFlag then 0 else if !MyDnFlag && !MyUpFlag && AscendedProfile[1]>0 then  AscendedProfile[1]+1 else 0,0);
plot pBarUpCount = if AscendedProfile > 0 within 1 bar && !MyUpFlag then AscendedProfile else 0;
pBarUpCount.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
pBarUpCount.AssignValueColor(Color.GREEN);

def barDownCount = CompoundValue(1, if !MyDnFlag && MyUpFlag then barUpCount[1] + 1 else 0, 0);
def DescendedProfile = CompoundValue(1, if barDownCount && !MyUpFlag[1] then 1 else if MyUpFlag or MyDnFlag then 0 else if !MyDnFlag && !MyUpFlag && AscendedProfile[1]>0 then  AscendedProfile[1]+1 else 0,0);
plot pBarDownCount = if AscendedProfile > 0 within 1 bar && !MyDnFlag then DescendedProfile else 0;
pBarUpCount.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
pBarUpCount.AssignValueColor(Color.Red); [CODE]

We can plug in anything you want. I am glad I bumped into you because I don't think manuals explain translation to this detail...
Are you from TradingView???
 

JebFrenko

New member
Thank you for the info, it should keep me busy over the long weekend. I do have a TradingView but I only use it when I am out and about. I come from TradeStation land. The high and low is basically a channel I paint. I can eyeball things and I have it on TS but I wanted to even things up on TOS. As simple as if / thens usually are - it is the one thing (and variables) that kick my rear. For coding if I have something to actually do I can usually get something working, until this. I appreciate the help.
 

MatthewA

Active member
I come from TradeStation land. The high and low is basically a channel I paint.
I could also do a lower with the [Concat]command and those lines of codes stay open and keep counting until a condition is met...
But those use up a lot of resources compared to the [CompoundValue] line I gave you... IDK if tradestation easylanguage has an equivalent of that so you would need to nest a whole lot of loops to do that without hand entering Support & Resistance...
On Thinkscript the complaint I hear what you have to look out for is it hates math and Java only likes logic. That's kinda cool TradeView interprets your drawings into logic...

If you want to make up a condition for HIGH or LOW I will plug those in... If you become a VIP member they have some new indicators called BuyTheDip & TakeProfits which are basically a community tested vLow(0) & vHigh(0). I am glad I became a VIP https://usethinkscript.com/p/get-vip/
 
I need some help figuring out why my if-else statement is not working correctly.

The following code is supposed to create a line which jumps up and down from the low to the high of candles based on which is farther from the value plotted from the previous day, but it always plots the line on the high of each candle:

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;

In the line "if lowdiff < highdiff" should have XR set to the low in some cases and to the high in others, but it's always going to the 'else' code regardless.

In this almost identical code, I'm plotting the value of the condition "lowdiff < highdiff" directly - this is to verify that lowdiff and highdiff do in fact criss-cross above and below each other, and therefore the if-else statement does not always return false:

Code:
declare lower;
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 = lowdiff < highdiff;

Here's an image of the two plotted together:

Code-01.jpg


Can anyone help me figure out why the condition I'm using is working, but the if-else always goes to else? My brain's fried after grinding on this for two hours...
 
Last edited:

rad14733

Well-known member
VIP
While the "then" may be implicit it is never optional... In most programming languages the "else" can be optional, however...

So what you want, essentially, is a candle by candle ZigZag Study...???
 
While the "then" may be implicit it is never optional...

I'm not sure how you define optional, but I consider optional to mean you don't need to use it - you can build the statement with or without it. In this image from tlc.thinkorswim.com it clearly shows a conditional statement that does not include the word "then" anywhere in their example code:

2020-12-29-9-57-51.jpg


I've used this construction in other indicators (not typing the word "then") and it has worked just fine...
 
Last edited:

XeoNoX

Well-known member
VIP
@MoneyMagnet it can be represented with the short code as well as the worded code, its up to the coder, for learnings purposes its always friendlier to write it out worded so its easier to learn from for those that choose to learn.
 
@MoneyMagnet Your condition for barnumber() == 1 is never satisfied except for the beginning. Add addlabel(yes, barnumber()) to your script and you'll see what barnumber() is returning.

Interesting suggestion, @generic, but I'm not sure how AddLabel() helps me here. When I add it, what I get is a display of the value of BarNumber() based on the current bar - how does it tell me what BarNumber() was when it was calculating the first bar? On the chart I'm using, BarNumber() for the current bar is 253; surely the numbers of earlier bars were different, no?

In any case, the image I showed clearly establishes that at any given bar, the value of XR is the high of that bar (upper plot), whereas the result of the condition "lowdiff < highdiff" frequently changes (sometime true(1) and sometimes false(0)). Since the value of XR for each bar is set by the if-else statement based on that condition, the value of XR should be changing from high to low to high, etc.
 
To be more clear and focus on the question at hand:

2020-12-29-text.jpg


My understanding is that since the value of the condition changes, the result of the if-else statement should change, too. When the condition is true, the statement "XR = low;" should run, and when the condition is false, the statement "XR = high;" should run. Instead, it's always running the second statement.

Somehow, I'm doing something wrong (or expecting something I shouldn't expect) but for the life of me I don't see why it's acting this way. I'm hoping someone more knowledgeable and experienced than me can help fill in the gaps in my knowledge.
 

generic

Active member
@MoneyMagnet Ohh okay you're talking about the nested if-else statement. The problem is with your math absvalue(high - xr[1]) is always lower than absvalue(low - xr[1]). Xr[1] = high so (high - xr[1]) = 0 which is always lower than absvalue(low - xr[1]).
 
@generic:
'high' refers to the high of the current bar, whereas XR[1] refers to the value set during the calculation of the previous bar. Even if XR[1] had been set to the high of the previous bar, that high would most likely not be the same as the high of the current bar, so your statement that 'AbsValue(high - XR[1]) = 0' is not correct, most of the time.
 

rad14733

Well-known member
VIP
Bwahahahaha....

@MoneyMagnet You can have no "else" if there is no "If . . . then" from a programmers point of view... Might as well learn the correct semantics and syntax so you properly understand programming languages... As @XeoNoX was referring to you either use "if . . . then" OR you use "if . . . { implicit then by using braces } . . . else"... I've programmed in enough languages for enough years to know these things... I hope this clears things up so you can understand coding better... If this then that else the other thing... 💡
 

Similar threads

Top