Plotting multiple lines with a loop

Jompatan

New member
I don't get it. Is this a loop error in thinkscript? The first case should enter as true and add B = 1, then the rest of the cases should enter as false and add B = 10. But the graph only shows B = 10.

Code:
declare lower;
def A = 1 + A [1];
def b;
if A == 1 {
b = 1;
} else {
b = 10;
}
plot TotalB = b;
plot TotalA = A;
 
Last edited:
Hey guys I'm confused on how to implement a set of conditions that I want like an original while loop in Java or C because fold is acting like a for loop and I don't have a length for the fold <index>

Code:
def <result> = fold <index> = <start> to <end> [ with <variable> [ = <init> ] ] [ while <condition> ] do <expression>;

Because I want my condition to run until these conditions in the while are false. Appreciate any help received, Ty!

Code:
while (x == 1  and y == 1 and z == 1)
{
};
 
Last edited:
Hello, is there away to plot lines on the chart in a loop? For example, lets say I want to plot a line on the chart every 10 cents and then a thicker line ever 25 cents. I want to do this within a 5 dollar range up and down of the current price. Also, is there a way to automatically plot the option strike prices on a chart?
 
When creating a label using AddLabel, I want the color of label to depend on value of variable I'm showing in the label. I could do a series If, Else if, Else if, etc., for as many colors I want to choose from. So it would look something like this:

Code:
AddLabel(yes, "Label value is: " + myVar, (if myVar > 4 then Color.BLUE else if myVar > 3 then Color.Green else if myVar > 2 then Color.Yellow else if myVar > 1 then Color.Orange [and so on]));

This is clunky and for more than a few else if is super clunky and hard to read and edit down the road. And gets worse if I have multiple variables that I'm adding labels for, e.g., myVar1, myVar2, myVar3, etc.

So here's what I'm thinking and where I'm running into roadblocks:

1. can I rewrite this using Switch/Case? The cases would be potential values for myVar. For each case, I'd store the color as a variable string (I guess). How do I pass that variable string to
Code:
AddLabel(yes, myVar, Color.[need variable string to be understood as a color here])

Or perhaps it's easier to store the color as a numeric variable using the color codes and then pass that variable as the Color.colorVar argument for AddLabel?

2. if I have 1 label and 1 variable, I can place the Switch/Case just before AddLabel, and Switch will refer to myVar. But how do I efficiently extend this to multiple variables that I want to label? I could of course put a complete Switch/Case before each AddLabel. But since the cases will be the same for each variable, I'm guessing there is probably a more efficient and elegant way of doing this.
 
After some searching, I realize the title of this thread might lead to a misunderstanding. I'm not trying to use Switch to select among Cases involving multiple variables. Instead, I have multiple variables I want to run through Switch, and each variable has the same Cases, so I'm trying to reuse 1 Switch/Case statement for all the variables rather than copy/paste the entire Switch/Case statement multiple times when only thing that's changing between them is Switch is looking at a different variable. Hopefully that makes sense.

I'm imaging a Switch/Case subroutine that gets called and passed a different variable each time and that variable is part of the Switch, and Cases remain identical each time. The subroutine returns the value corresponding to the relevant case. That value gets used in AddLabel to specify color. Then subroutine is run again using a different variable. Rinse and repeat.
 
By 'structured', do you mean something other than the if then else example I used in first post?

Yes... To be honest, I find switch/case somewhat cumbersome in comparison as it's not as easy to implement as in other programming languages... And you might end up having to use if . . . then . . . else in the switch/case anyway...
 
Yes... To be honest, I find switch/case somewhat cumbersome in comparison as it's not as easy to implement as in other programming languages... And you might end up having to use if . . . then . . . else in the switch/case anyway...
I have done a little programming in other languages and have come to prefer Switch/Case when there are more than a few cases, as I find the if then else if to be unwieldy once it gets past a few else's. Too hard to read, and time consuming when you want to make changes. Switch/Case is so much easier to read and make changes.
 
I'm imaging a Switch/Case subroutine that gets called and passed a different variable each time and that variable is part of the Switch, and Cases remain identical each time. The subroutine returns the value corresponding to the relevant case. That value gets used in AddLabel to specify color. Then subroutine is run again using a different variable. Rinse and repeat.
Along these lines can I nest a Switch/Case statement inside a for loop? I see that thinkscript doesn't have for or while loops. Only loop is see is fold, which looks like an iterative loop that provides 1 result after looping is completed with interim results fed back into the loop. I'm trying to loop with a result generated each loop. Something like this:

Code:
for i = 1 to 3
    switch (i) {
        case 1
            switchVar = myVar1
        case 2
            switchVar = myVar2
        case 3
            switchVar = myVar3
    }
    switch (switchVar) {
        case switchVar > 4
            do something
        case switchVar > 3
            do something else
        case switchVar > 2
            do another thing
        case switchVar >1
            do yet another thing
    }

Is something like this possible in thinkscript? The code above is for 3 variables with 4 possible cases. For 10 variables with 10 possible cases, using if then else if seems daunting as I'd have 10 very long if statements.
 
I am new to coding, so correct me if I am wrong, if-else statement stops running when the first condition is true, right? How I would make it to a while-loop, so instead of stopping at the first condition when it is true, it will just keep stacking true statements by changing the color from gray to dark green to yellow to blue then lastly white, and it keeps repeating and repeating. Is it possible?

Code:
AddLabel (yes, " High: " + (High(period = AggregationPeriod.DAY)), (if

close is less than PH and close is greater than price and volume >= 50000 then Color.GRAY
#Above VWAP and below Prevhigh

else if close crosses price and close crosses PH and volume >= 50000 then Color.DARK_GREEN
#Crossed both VWAP and Prevhigh

else if close is greater than price and close crosses PH and volume >= 50000 then Color.DARK_GREEN
#Above VWAP and crossed Prevhigh

else if close is greater than price and close is less than high(period = AggregationPeriod.DAY) and volume >= 50000 then CreateColor(128, 128, 0)
#Above VWAP and below High, Yellow

else if close crosses DailySMA then CreateColor(128, 128, 0)
#Crosses DailySMA, Yellow

else if close >= (high(period = AggregationPeriod.DAY) * .9995) then CreateColor(0, 71, 179)
#Made new High, Blue

else color.white));
 
@Stoynks
if a statement is true, its either part of the statement is true or all of the statement is true... therefore it can be differentiated with AND / OR .

example in theory (not actual thinkscript code):

if study1 or study2 or study3 is true then color green, else if study4 or study5 is true then color hotpink else if study6 is true color blue else color white
 
Hey guys I'm confused on how to implement a set of conditions that I want like an original while loop in Java or C because fold is acting like a for loop and I don't have a length for the fold <index>

Code:
def <result> = fold <index> = <start> to <end> [ with <variable> [ = <init> ] ] [ while <condition> ] do <expression>;

Because I want my condition to run until these conditions in the while are false. Appreciate any help received, Ty!

Code:
while (x == 1  and y == 1 and z == 1)
{
};
@Tony Stark fold is used to count forward from starting point to a end point as long as the variable(study) is true then it will do (perform) the specified study(expression). That final "expression" can be a loop if you want it to, its up to you.

The code you defied is not well enough defined to assist you.
 
@Stoynks
if a statement is true, its either part of the statement is true or all of the statement is true... therefore it can be differentiated with AND / OR .

example in theory (not actual thinkscript code):

if study1 or study2 or study3 is true then color green, else if study4 or study5 is true then color hotpink else if study6 is true color blue else color white
Let's say, I have the first condition if close>price then color.dark_green is true, then after that happens while that one is true, I want, close>sma10 then color.blue is true. Will it stay dark.green since the first condition is still true, or will the second condition be run since it's also true? Can the second true statement override the first statement? reason being for me not wanting to use && or ll is because I want separate colors to differentiate each condition. Hopefully, I am making sense.
 
one of them will override.. ive never tried comparing different var with coloring, but normally i use same variable.

the order if comparing same viariable is.... first compared with higher value receives priority... this is how i personally have done it.

example (im not at a computer so this code doesnt work but here is the concept)
vol>100 color green, else if volume >75 color light green else if vol >50 color light red else color red.

since you are comparing different variables im not sure which is prioritized, you would have to trial and error.... i would suggest starting with no more than 3 possibilities ( & colors) to atleast get and idea.
 
I don't get it. Is this a loop error in thinkscript? The first case should enter as true and add B = 1, then the rest of the cases should enter as false and add B = 10. But the graph only shows B = 10.

Code:
declare lower;
def A = 1 + A [1];
def b;
if A == 1 {
b = 1;
} else {
b = 10;
}
plot TotalB = b;
plot TotalA = A;

i know it's been a year, but i figured if the op isn't around, someone else might learn from this .
that code had unexpected a values, because of
def A = 1 + A [1];
on bar 1 , A[1] looks to the previous bar, but there isn't one.
this will result in no plots or it may plot odd numbers. ( it starts at 4, on bar 1, on my chart)

i added a line that initializes A, with something like this, ( changed it for this example)
def A = compoundvalue(1, 2 + A[1], 4);

the first parameter, 1, means if the barnumber is <= 1 then assign the 3rd parameter , 4 to A
if the barnumber is > 1, the first parameter, then assign the middle expression to A

i added bubbles to display values. zoom in and to the left , to see the first 10 candles, to see the variable values.

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Others/CompoundValue

Python:
# ifelseerror
# https://usethinkscript.com/threads/plotting-multiple-lines-with-a-loop.3912/
declare lower;
#def A = 1 + A [1];
def A = compoundvalue(1, 1 + A[1], 1);
def b;
if A == 1 {
b = 1;
} else {
b = 10;
}
plot TotalB = b;
plot TotalA = A;

addchartbubble(yes,0, "bn " + barnumber() + "\na " + a + "\nb " + b, color.cyan, yes);
 
Hey guys I'm confused on how to implement a set of conditions that I want like an original while loop in Java or C because fold is acting like a for loop and I don't have a length for the fold <index>

Code:
def <result> = fold <index> = <start> to <end> [ with <variable> [ = <init> ] ] [ while <condition> ] do <expression>;

Because I want my condition to run until these conditions in the while are false. Appreciate any help received, Ty!

Code:
while (x == 1  and y == 1 and z == 1)
{
};
try setting the loop length to a big number, use while with a stop condition, and see if your stop condition is triggered.
experiment with different values for length.

fold will keep looping as long as the while statement is true, and the i counter is < length
i changed the trigger condition to use OR instead of AND, so all 3 variables will have to be false, for while to be false, and stop the fold.
i don't think getvalue() is needed in the while condition, but i included an example just in case.
i added an example of getvalue() , in the do expression , using the loop counter i. you will have to come up with your own do expression.

Python:
def b = ...
def x = ...
def y = ...
def z = ...
def length = 300;
def a = fold i = 1 to length
with p
while ( x == 1  or y == 1 or z == 1)
#while (getvalue(x, 0) == 1  or getvalue(y, 0) == 1 or getvalue(z, 0) == 1)
do p + (  getvalue( b , i ) .... );
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
295 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