Welcome! Log In Create A New Profile

Get Earnings and Seasonal Trends - Subscribe Today!

Advanced

Fun with ThinkScript

Posted by robert 
Re: Fun with ThinkScript
March 06, 2015 03:57AM
Quote
danyzuko
Just wondering, can you tweak it to draw lines based on the body of the candle instead of the absolute end of it?
Price lows and highs seem to be converging at the edge of the body of the candle and not so much the tail.

This version uses candle bodies rather than wicks.



# Plot areas of potential support / resistance based on major peaks and valleys.
# This version plots lines based on candle bodies rather than the wicks.
# Changing "magnitude" determines the granularity of detected peaks or valleys.
# A low magnitude value will plot minor price swings, while a high magnitude value
# will only plot major price swings.
# A magnitude value of 2 means that a bodytop must be greater than the 2 candles 
# before and after it to be considered a peak.  Likewise for the bodybottoms to be a valley.
# 
# Robert Payne


input magnitude = 5;

# define top and bottom of candle body
def bodytop = max(open, close);
def bodybottom = min(open, close);

# define and plot the most recent peak
def peak = bodytop >= Highest(bodytop[1], magnitude) and bodytop >= Highest(bodytop[-magnitude], magnitude);
def peakvalue = if BarNumber() < magnitude then Double.NaN else if peak then bodytop else peakvalue[1];
plot peakline = peakvalue;
     peakline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
     peakline.SetDefaultColor(Color.GREEN);

# extend the current peak line to the right edge of the chart
def countp = if IsNaN(peak) and !IsNaN(peak[1]) then 1 else countp[1] + 1;
plot peakext = if IsNaN(peak) then GetValue(peakline, countp) else Double.NaN;
     peakext.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
     peakext.SetDefaultColor(Color.GREEN);

# continue the previous peak as a dashed line
def oldpeak = if BarNumber() < magnitude then Double.NaN else if peak then peakvalue[1] else oldpeak[1];
plot oldpeakline = oldpeak;
     oldpeakline.SetPaintingStrategy(PaintingStrategy.DASHES);
     oldpeakline.SetDefaultColor(Color.GREEN);

# define and plot the most recent valley
def valley = bodybottom <= Lowest(bodybottom[1], magnitude) and bodybottom <= Lowest(bodybottom[-magnitude], magnitude);
def valleyValue = if BarNumber() < magnitude then Double.NaN else if valley then bodybottom else valleyValue[1];
plot valleyline = valleyValue;
     valleyline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
     valleyline.SetDefaultColor(Color.PINK);

# extend the current valley line to the right edge of the chart
def countt = if IsNaN(valley) and !IsNaN(valley[1]) then 1 else countt[1] + 1;
plot valleyext = if IsNaN(valley) then GetValue(valleyline, countt) else Double.NaN;
     valleyext.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
     valleyext.SetDefaultColor(Color.PINK);

# continue the previous valley as a dashed line
def oldvalley = if BarNumber() < magnitude then Double.NaN else if valley then valleyValue[1] else oldvalley[1];
plot oldvalleyline = oldvalley;
     oldvalleyline.SetPaintingStrategy(PaintingStrategy.DASHES);
     oldvalleyline.SetDefaultColor(Color.PINK);

- robert


Professional ThinkorSwim indicators for the average Joe



Edited 2 time(s). Last edit at 03/06/2015 09:19AM by robert.
az
Re: Fun with ThinkScript
March 08, 2015 01:33AM
Hi,

Is it possible to run a scan in TOS for the following combination:

- stocks with options expiring between 10 and 15 days from today and
- options having delta between -0.10 and -0.20 (for puts) and
- bid or mark price of $0.20 to $0.30

Just searching for options that have certain delta and certain price range.

Any help would be appreciated.

Thanks.
Re: Fun with ThinkScript
March 08, 2015 08:12AM
Hi

I would like to make from the following: 1) VIX (reverse) , 2) $ UVOL- $ DVOL , 3) $ TICK an indicator at the bottom,
meant ,3 lines to appear as an indicator

Tia


Isaac



Edited 1 time(s). Last edit at 03/08/2015 08:16AM by isaac.
Re: Fun with ThinkScript
March 09, 2015 08:09AM
Hi Robert ,
Could you please make TRIX indicator to give signals arrows UP and Down when crossing happens.
I want the signal to be with the candles (Upper Indicator)
and another one as a (Lower Indicator)

thanks for help ^_^

-------------------------------

TRIX Indicator

--------------------------------
declare lower;

input length = 7;
input colorNormLength = 14;
input price = close;
input signalLength = 3;

def tr = ExpAverage(ExpAverage(ExpAverage(Log(price), length), length), length);

plot TRIX = (tr - tr[1]) * 10000;
plot Signal = ExpAverage(TRIX, signalLength);
plot ZeroLine = 0;

TRIX.DefineColor("Highest", Color.YELLOW);
TRIX.DefineColor("Lowest", Color.LIGHT_RED);
TRIX.AssignNormGradientColor(colorNormLength, TRIX.color("Lowest"winking smiley, TRIX.color("Highest"winking smiley);
Signal.setDefaultColor(GetColor(3));
ZeroLine.SetDefaultColor(GetColor(5));
Re: Fun with ThinkScript
March 15, 2015 01:54AM
I'm having a problem with the AddLabel. This bit of code has the label always visible regardless if the conditions are met or not. Only want it showing if the Chop conditions are met. Can't find my error.

Help?


declare lower;

input length = 14;
input level_1 = 25.0;

plot ADX = ADhot smileylength);
plot Level1 = level_1;

def hiDiff = high - high[1];
def loDiff = low[1] - low;


def plusDM = if hiDiff > loDiff and hiDiff > 0 then hiDiff else 0;
def minusDM = if loDiff > hiDiff and loDiff > 0 then loDiff else 0;

def ATR = WildersAverage(TrueRange(high, close, low), length);
plot "DI+" = 100 * WildersAverage(plusDM, length) / ATR;
plot "DI-" = 100 * WildersAverage(minusDM, length) / ATR;

def DX = if ("DI+" + "DI-" > 0) then 100 * AbsValue("DI+" - "DI-"winking smiley / ("DI+" + "DI-"winking smiley else 0;

def chop = plusDM < level_1 and minusDM < level_1 and ADX < level_1;
AddLabel(chop, "CHOP!", color.yellow);
Re: Fun with ThinkScript
March 15, 2015 06:09AM
Quote
Gaterz
I'm having a problem with the AddLabel. This bit of code has the label always visible regardless if the conditions are met or not. Only want it showing if the Chop conditions are met. Can't find my error.

Help?

If you are meaning to define chop as when all three plotted lines are below the 25 level, then you might try this

def chop = "DI+" < level_1 and "DI-" < level_1 and ADX < level_1;

instead of

def chop = plusDM < level_1 and minusDM < level_1 and ADX < level_1;

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
March 19, 2015 07:37AM
Any one know if it is possible to create a signal based on the hi \ low bubbles on the chart?
Re: Fun with ThinkScript
March 19, 2015 11:32AM
Thank you Robert. That worked!! Sometimes it's staring me in the face and I can't see it. Thanks again.
Re: Fun with ThinkScript
March 19, 2015 12:22PM
Quote
mtut
Any one know if it is possible to create a signal based on the hi \ low bubbles on the chart?

I believe the high / low chart bubbles mark the highest / lowest point on the current charting time frame. So, you might play around with highestall(high) and lowestall(low) or, perhaps, highestall(high[1]) lowestall(low[1]) so that it doesn't count the most current bar.

I am just spit-balling here and don't have TOS opened, but maybe something along the lines of:

def alert = close > highestall(high[1]);
Re: Fun with ThinkScript
March 19, 2015 12:39PM
SARA,

See below code for buy and sell signal arrows.

##Begins

declare upper;

input length = 5; #changed to 5 to fit better.
input colorNormLength = 20; #changed to 20 to fit better.
input price = close;
input signalLength = 5; #changed to 5 to fit better.

def tr = ExpAverage(ExpAverage(ExpAverage(Log(price), length), length), length);

def TRIX = (tr - tr[1]) * 10000;
def Signal = ExpAverage(TRIX, signalLength);
def ZeroLine = 0;


Plot Buy = Trix crosses above Signal;
Plot Sell = Trix crosses below Signal;

BUY.setpaintingstrategy(paintingstrategy.BOOLEAN_ARROW_UP);
SELL.setpaintingstrategy(paintingstrategy.BOOLEAN_ARROW_DOWN);

##Ends



Edited 2 time(s). Last edit at 03/19/2015 02:09PM by anky7544.
Re: Fun with ThinkScript
March 19, 2015 08:55PM
Thanks, Robert, the bubbles are indeed plotted for the time frame of chart. Your were on the right track with you suggestion. I managed to get my answer from the TOS chat room from within the TOS platform. That may be a resource others should check out.

Thanks for your help
Re: Fun with ThinkScript
March 20, 2015 09:30AM
Is there a way to only display the last 20 bars on a 10-minute chart for an indicator?



Edited 1 time(s). Last edit at 03/20/2015 11:56AM by donmat.
Re: Fun with ThinkScript
March 20, 2015 01:06PM
Courtesy of Thinkscript Lounge:

input barstoshow = 20;
def lastBar = if isNaN(close[-1]) && !isNaN(close) then barnumber() else double.nan;
plot ema10=if barnumber()>=highestall(lastbar-barstoshow) then expaverage(close,10) else double.nan;
Re: Fun with ThinkScript
March 24, 2015 02:43PM
Quote
from a PM
Hi Robert,

Can you write a code that will mark the high and low of a stock with a option of setting the time period( 5,7,10 days prior )also,having the lines extend through the current trading day?

Based on user input, this script will mark the high and low from the previous X number of days. It will work for any charting time frame from 1 minute up to and including a daily chart.



From the settings panel, the user may choose the number of days to compare; whether to plot the high/low from the candle wicks or candle bodies; and whether or not to display the labels.





This script is available here.

- robert


Professional ThinkorSwim indicators for the average Joe



Edited 1 time(s). Last edit at 04/15/2015 11:45AM by robert.
Re: Fun with ThinkScript
March 24, 2015 09:06PM
Swing Hi and Lo Scan
December 10, 2014 10:12PM Registered: 3 months ago
Posts: 9
Is there a way that I can use this study as a scan to get symbols that

"close crosses above swing high or
"close crosses below swing low.

#Swing high Swing low study

input swing_back = 8;
input swing_forward = 2;
input maxbars = 30;
input showlevels = Yes;
def sb = swing_back;
def sf = swing_forward;
def na = double.nan;

def lfor = Lowest(low, sf)[-sf];
def lback = Lowest(low, sb)[1];
def swinglow = if low < lfor and low <= lback then 1 else 0;
plot sl = if swinglow then low else na;
def hfor = Highest(high, sf)[-sf];
def hback = Highest(high, sb)[1];
def swinghigh = if high > hfor and high >= hback then 1 else 0;
plot sh = if swinghigh then high else na;

rec lsl = if IsNaN(close[-sf]) then lsl[1] else if swinglow then low else
lsl[1];
rec lsh = if IsNaN(close[-sf]) then lsh[1] else if swinghigh then high else
lsh[1];

def bn = barNumber();
rec hcount = if swinghigh then 1 else hcount[1] + 1;
rec lcount = if swinglow then 1 else lcount[1] + 1;

plot lasthigh = if hcount<=maxbars AND IsNaN(close[-sf]) then lsh[1] else if
hcount > maxbars then na else if hcount < 2 then na else lsh;
plot lastlow = if lcount<=maxbars AND IsNaN(close[-sf]) then lsl[1] else if
lcount > maxbars then na else if lcount < 2 then na else lsl;
#########################################
Please Help
Steve
Re: Fun with ThinkScript
March 25, 2015 08:32PM
Quote
stefonk
Is there a way that I can use this study as a scan to get symbols that

"close crosses above swing high or
"close crosses below swing low.

The short answer is no.

Here's a bit more detail.

First you need to understand a little about ThinkScript notation.

1. The term close is understood to mean, "The closing price of this bar."

2. The term close[3] is understood to mean, "The closing price of the bar that is 3 bars before this one."
- The positive number inside the square brackets means "before" this bar.

3. The term close[-2] is understood to mean, "The closing price of the bar that is 2 bars after this one."
- The negative number inside the square brackets beans "after" this bar.

With that in mind, let's take a look at a portion of your script.

input swing_back = 8; 
input swing_forward = 2;

These first two lines allow the user to change the "swing back" and "swing forward" values to suit their needs from within the script settings panel.



def sb = swing_back; 
def sf = swing_forward;

These two lines are simply [def]ining "sb" and "sf" as abbreviations for "swing_back" and "swing_forward" so that the programmer doesn't have to type the full name throughout the rest of the script. So, "sb" would now equal "8" just like "swing_back" does and "sf" would equal "2" like "swing_forward" does.

def lfor = Lowest(low, sf)[-sf]; 
def lback = Lowest(low, sb)[1]; 
def swinglow = if low < lfor and low <= lback then 1 else 0;

This bit of code is defining what a "swing low" is. It's easier to understand what's going on if the actual numbers are substituted for the variable names. Recall that "sb" is "8" and "sf" is "2". So, rewriting the code would look like this:

def lfor = Lowest(low, 2)[-2];

Pay special attention to the [-2] above. Remember that a negative number inside the square brackets means "after" this bar. So, the above line is defining "lfor" as being the lowest value of the two bars after this bar.

def lback = Lowest(low, 8)[1];

This line of code is defining "lback" as the lowest value of the eight bars before this one.

def swinglow = if low < lfor and low <= lback then 1 else 0;

Finally, this line is actually defining what a "swing low" is. It says, if the low of this bar is lower than the two bars after this one AND the low of this bar is also lower than or equal to the lowest of the previous eight bars, then this bar is a swing low.

The code for determining a "swing high" is pretty much the same except that it is looking at high values rather than low values.

So, what that means is that in order to determine whether a point on the chart is either a swing high or a swing low, it must have eight bars before the bar in question, as well as, two bars after it.



Looking at the picture above, it can be seen that point "A" is a "swing high" because it is higher than the 8 bars before it AND it is higher than the 2 bars after it. Likewise, point "C" is a "swing low" because it is lower than the 8 bars before it AND it is lower than the 2 bars after it. (I know it's a line chart, not a bar chart. smiling smiley Just work with me here.)

What about points "B" and "D", though? Can we say that "B" is a swing low, or that "D" is a swing high? No. Both points do have at least 8 bars before them. However, neither has 2 bars after them to compare with. So we don't know whether "B" or "D" will be a swing high or low. We cannot see into the future.

The same holds true with the way the script calculates the values and plots them on the chart. Take a look at the screenshot below and notice that the gray swing high and orange swing low lines do not extend to the last two candles on the chart. That's because neither of those candles have at least two bars (candles) after them. The last red candle only has one after it, and the last green candle doesn't have any after it.



All of that, finally, brings us to the reason that you cannot run this script as a scan. When running a scan, the software is only interested in what is happening with the most recent candle (the last green candle on the chart above). So, in this case, if you are asking if the close of that last green candle has gone below the swing low point, the answer would be, "I don't know, it cannot be determined because in order to check the value of the swing low point, the candle in question must have two bars after it."

Since the scan cannot look into the future to see what the next two bars will be, it can never do what you have asked.

I hope that all makes sense.

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
March 26, 2015 02:27PM
Anyone that know how I can get the ATR in percent of the underlying price (last)? Just a simple ATR/LAST. I want it so I can sort my watchlist by biggest movers when there isnt any IV to go on.



Edited 1 time(s). Last edit at 03/26/2015 02:27PM by TraderJoe.
Re: Fun with ThinkScript
March 26, 2015 03:14PM
Quote
TraderJoe
Anyone that know how I can get the ATR in percent of the underlying price (last)? Just a simple ATR/LAST. I want it so I can sort my watchlist by biggest movers when there isnt any IV to go on.

plot data = 100 * atr(14).atr / close;

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
March 27, 2015 08:03AM
Thank you! Works like a charm
Re: Fun with ThinkScript
March 28, 2015 08:19AM
Robert I really commend you for the excellent work you submit to this forum. I want to know if it is possible to color the background just for crossover bar when one indicator crosses the other. (Ex. 50 SMA crosses 200 SMA). I have tried just about everything I can think of. I could get the vertical line by using something like

[ AddVerticalLine(SecondsFromTime(0930) >= 0 and SecondsFromTime(0930) < 60, "09:30", Color.BLUE);]

to show opening time but can not figure crossover.. Any help would be greatly appreciated. Thanks Gary



Edited 1 time(s). Last edit at 03/28/2015 08:25AM by GaryF.
Re: Fun with ThinkScript
March 28, 2015 10:08AM
Quote
GaryF
I want to know if it is possible to color the background just for crossover bar when one indicator crosses the other. (Ex. 50 SMA crosses 200 SMA). I have tried just about everything I can think of. ...but can not figure crossover.. Any help would be greatly appreciated. Thanks Gary

Let's take things one at a time. First, crossovers.

When I first started learning ThinkScript, I used complicated logic to figure crossovers (I'm sure some of the code at the beginning of this thread still uses this type of logic). For instance, if I wanted to know when the 10 SMA crossed above the 50 SMA, I would use something like this:

def sma10 = avarage(close, 10);
def sma50 = average(close, 50);
def SignalUP = if sma10[1] < sma50[1] and sma10 > sma50 then 1 else 0;

What that last line means is this: if the 10 SMA was below the 50 SMA on the previous bar, and now it is above the 50 SMA, then I know it must have crossed to the upside, so assign a value of 1 (which in computer terms means TRUE), otherwise assign a value of 0 (FALSE).

That logic works very well. However, it really can be much simpler than that. ThinkScript has a built-in crossover feature and it works like this:

1. _____ crosses above _____

2. _____ crosses below _____

3. _____ crosses _____

The first two are pretty self explanatory. The last one simply checks for any type of crossover regardless of the direction.

So, the example I started with above can be simplified to:

def SignalUP = sma10 crosses above sma50;

This, much easier to understand, line of code does exactly the same thing as the one before. If the 10 SMA crosses above the 50 SMA on this bar, then SignalUP is assigned a value of 1 (TRUE), otherwise, it gets a value of 0 (FALSE).

Now, changing background color.

The necessary function for doing this is " AssignBackgroundColor( <desired color> ); " So, if you wanted a blue background,

AssignBackgroundColor(Color.BLUE);

If you want to get fancy and change the background color based on meeting certain criteria, you can use an IF...THEN...ELSE statement inside the parenthesis.

def yHigh = high(period = "day" )[1];
def yLow = low(period = "day" )[1];

AssignBackgroundColor(if close > yHigh then Color.GREEN else if close < yLow then Color.RED else Color.CURRENT);

The above example sets the background color to green if the current price is above yesterday's high, sets it to red if the price is below yesterday's low, and leaves the background color alone (the default color) if the price is between yesterday's high and low.

The above examples should help you figure out what you are trying to accomplish. If not, feel free to ask more questions and I will try to steer you in the right direction.

- robert


Professional ThinkorSwim indicators for the average Joe
A TOS Squeeze WatchList
March 28, 2015 09:10PM
Firstly this is none of my effort and work , just available via google and the net

Some background , a stock may move from low volatility to high volatility and then back to low volatility , in what ever time frame you choose . One way to identify this is when the Bollinger bands move inside the Keltner channels , a "squeeze " or low volatility is identified .
I understand there are many other ways , but for the sack of this discussion , it will be when the BB moves inside the KC. To scan for this you can either use when the upper BB moves below the upper KC OR when the lower BB moves above the lower KC OR both

Again , I understand there can be many discussions about this , but I would like to keep it simple / easy , as this is the person I am .

So to display this in a TOS scan the attach image is such weekly daily hourly 30 min
and the list is the IBD 50 stocks

cheers
Michael bethel



PS how do I attach an image? thanks
mdtmn@optushome.com.au



Edited 4 time(s). Last edit at 03/29/2015 04:00AM by mdtmn8888.
Re: A TOS Squeeze WatchList
March 28, 2015 10:42PM
test



Edited 1 time(s). Last edit at 03/29/2015 04:03AM by mdtmn8888.
Re: A TOS Squeeze WatchList
March 28, 2015 10:52PM
But what can happen is this , which appears to be lack of data.

So , does anyone have comments or feed back to fix the problem.

Maybe re write the code etc etc thanks

Michael bethel





Edited 1 time(s). Last edit at 03/29/2015 04:06AM by mdtmn8888.
Re: A TOS Squeeze WatchList
March 28, 2015 11:50PM
Quote
mdtmn8888
PS how do I attach an image? thanks








- robert


Professional ThinkorSwim indicators for the average Joe



Edited 1 time(s). Last edit at 03/29/2015 12:42AM by robert.
Re: A TOS Squeeze WatchList
March 29, 2015 04:10AM
Hi Robert ,
Thanks for the above suggestion for attaching a picture. Sorry about the size of the image . I will have to work on that



I guess the above size is a more comfortable fit

cheers

Michael bethel
mdtmn@optushome.com.au



Edited 1 time(s). Last edit at 03/29/2015 04:12AM by mdtmn8888.
Re: A TOS Squeeze WatchList
March 29, 2015 04:31AM
Hello Robert and All ,
I would like to scan the NASDAQ and NYSE to end up with a list of stocks that I can see the 15min 30 min one hour daily and weekly time frames for a squeeze as per the attached

Re: Fun with ThinkScript
March 29, 2015 04:33AM
I think the above while huge is more readable than this

Re: Fun with ThinkScript
March 29, 2015 04:41AM
Hi Robert and All ,
Custom Expression Subscription Limit Exceeded

Has anyone ever seen this before?

Would anyone have any thourghts, comments , feedback , ideas , etc etc about how this can be worked around ?

If the code needs to be cut down or stream lined I would be unable to do this any suggestions about who could / can do this would be fantastic

Thanks for all and any feed back

Michael bethel

mdtmn@optushome.com.au

PS My Five Favourite Stratergies ( the Squeeze ) John Carter

[www.youtube.com]

0412274490



Edited 1 time(s). Last edit at 03/29/2015 04:46AM by mdtmn8888.
Re: Fun with ThinkScript
March 29, 2015 07:41AM
Thanks for the speedy reply. I guess I should have explained better that I want to paint a vertical line ( highlight zone) where the crossover takes place. and only at this point. This would make it very easy to see the results of the crossover. I wrote similar script for Trade Navigator Highlight zone as

Crosses Above(Daily50Ma of Daily,Daily200Ma of Daily)
I use it as a "highlight zone" that paints a vertical area where the crossover takes place. Light green for cross above and light red for cross below

I don't know if it is possible with think or swim? I see options to set painting strategy or paint vertical lines. Maybe it needs to be a cloud? Any help would be appreciated.



Edited 1 time(s). Last edit at 03/29/2015 07:44AM by GaryF.
Sorry, only registered users may post in this forum.

Click here to login