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
February 07, 2015 04:52PM
Quote
StrategyNode
do you have a example code which shows how to count thinks in thinkscript?

You can count things by using the SUM function.

Start by defining what you want to count. In this example, the goal is to count the number of UP candles.

def GreenCandle = Open > Close;

Once defined in this manner, GreenCandle will have a value of 1 on an UP candle (open > close) and a value of 0 on a DOWN candle (open < close). Now, if you wanted to know how many of the last 10 candles were UP candles, you just use the SUM function.

def GreenCount = SUM(GreenCandle, 10);
Re: Fun with ThinkScript
February 07, 2015 05:28PM
Thanks For the info I am going try this today.
Re: Fun with ThinkScript
February 07, 2015 08:52PM
Ok this what I came up with it looks promising to me but not sure yet since I have to use my eyes to analyze it. to get around the aggregation problem of not being able to show it as a study on a daily chart I creates a column in the watchlist and added the code as a label makesure to select 5 min also I have unchecked the extended hour data.

def GreenCandle = Close>Open;
def RedCandle = Close<Open;
def GreenCount = SUM(GreenCandle, 78);
def RedCount = SUM(RedCandle, 78);

Plot SignalUP = GreenCount[1]>RedCount[1];

signalUP.AssignvalueColor(IF signalUP THEN COLOR.GREEN ELSE Color.Red);

AssignbackgroundColor(IF signalUP THEN COLOR.dark_GREEN ELSE Color.Red);

Now have another question... is there a way to add all the volume from a green candle seperatly from a red candle? so say there are 10 green bars and 13 red bars in a 5 min chart but when you add the volume from a green bars its greater than red and that may show that buyers were more than the sellers. -- any help will be much appreciated ...

StrategyNode
Re: Fun with ThinkScript
February 07, 2015 10:43PM
Quote
StrategyNode
Now I have another question... is there a way to add all the volume from a green candle seperatly from a red candle?

def UpVolume = if GreenCandle then Volume else double.nan;
def GreenVolume = SUM(UpVolume, 78);

def DownVolume = if RedCandle then Volume else double.nan;
def RedVolume = SUM(DownVolume, 78);
Re: Fun with ThinkScript
February 08, 2015 01:30PM
robert Wrote:
-------------------------------------------------------
> > Now I have another question... is there a way to
> add all the volume from a green candle seperatly
> from a red candle?
>
>
>
> def UpVolume = if GreenCandle then Volume else
> double.nan;
> def GreenVolume = SUM(UpVolume, 78);
>
> def DownVolume = if RedCandle then Volume else
> double.nan;
> def RedVolume = SUM(DownVolume, 78);
>

This dosen't seem to work I am inserting it as a column code in a watchlist I have chossen the 5 min time frame without extended hour ... I dont see anything wrong with the code but it only says NAN in all rows instead of red or green like it should.

def GreenCandle = Close>Open;
def RedCandle = Close<Open;
def UpVolume = if GreenCandle then Volume else double.nan;
def GreenVolume = SUM(UpVolume, 78);
def DownVolume = if RedCandle then Volume else double.nan;
def RedVolume = SUM(DownVolume, 78);

Plot SignalUP = GreenVolume[0]>RedVolume[0];

signalUP.AssignvalueColor(IF signalUP THEN COLOR.GREEN ELSE Color.Red);

AssignbackgroundColor(IF signalUP THEN COLOR.dark_GREEN ELSE Color.Red);
Re: Fun with ThinkScript
February 08, 2015 02:17PM
Quote
StrategyNode
I dont see anything wrong with the code but it only says NAN in all rows instead of red or green like it should.

I should have set the false value to 0 instead of double.nan.

def UpVolume = if GreenCandle then Volume else 0;
Re: Fun with ThinkScript
February 08, 2015 02:29PM
Perfect! that worked thank Robert
az
Re: Fun with ThinkScript
February 09, 2015 08:18PM
Hi,

I have a graph of AAPL and would like to add several labels with the following criteria:

1. Display current price of $DJI, the symbol and the Net Change in green or red
2. Display current price of SPX, the symbol and the Net Change in green or red
3. Display current price of COMP, the symbol and the Net Change in green or red

Can you help?

Much appreciated.



Edited 1 time(s). Last edit at 02/09/2015 08:22PM by az.
Re: Fun with ThinkScript
February 09, 2015 10:06PM
Quote
az
Hi,

I have a graph of AAPL and would like to add several labels with the following criteria:

1. Display current price of $DJI, the symbol and the Net Change in green or red
2. Display current price of SPX, the symbol and the Net Change in green or red
3. Display current price of COMP, the symbol and the Net Change in green or red

Can you help?

Much appreciated.

You will need to know how to access data from another symbol (another example here).

You'll also want to use the AddLabel function which I've described in detail here.

Finally, here is the code that I use to display the DJI on my own charts. It should be easy for you to modify it to suit your own needs.
az
Re: Fun with ThinkScript
February 09, 2015 11:07PM
Robert,

This is absolutely perfect. Thank you very much!
Re: Fun with ThinkScript
February 20, 2015 01:32PM
Good evening Robert and other really technically sharp folks,

Is it possible to create an alert that will notify me audibly or by text message when the first bullish candle closes above the 8MA- after coming out of oversold conditions (Stochastic 20 or below)? I would love to have the same happen on the other side..... alert when the first bearish candles closes below the 8MA after coming out of overbought conditions (Stochastic 80 or above). I greatly appreciate it.

R30
Re: Fun with ThinkScript
February 20, 2015 03:08PM
Hello R30,

Hope your trading is going well. Try this code:

input price = close;
input length = 8;
input displace = 0;
input StochLong = 20;
input StochShort = 80;

# return %k for going long or short on stochastics
def Stoch = StochasticFull(80,20,14,3,High,Low,Close,3, "SMA" ).FullK;
def longFilter = Stoch < StochLong;
def shortFilter = Stoch > StochShort;

plot AvgExp = ExpAverage(price[=displace], length);
AvgExp.SetDefaultColor(GetColor(5));

plot SignalBuy = if close > AvgExp and longFilter then low else double.nan;
plot SignalSell = if close < AvgExp and shortFilter then high else double.nan;

# show arrows for buy or sell signal
SignalBuy.SetPaintingStrategy(PaintingStrategy.arrow_up);
SignalBuy.AssignValueColor(color.GREEN);
SignalSell.SetPaintingStrategy(PaintingStrategy.arrow_down);
SignalSell.AssignValueColor(color.RED);

# show alert and make sound
alert(SignalBuy, "Time to go long", alert.Bar, sound.Ring);
alert(SignalSell, "Time to go short", alert.Bar, sound.Ring);

You can change StochLong to 30 or 40 and StochShort to 70 or 60 to get more signals. Play around with these values to get best signals.

In my trading experience, I have found that the T-line (8 EMA) is amazing for day trading. Nowadays I enter when price retraces to 8 EMA or 21 EMA after a breakout and exit when bar closes on the other side of 8 EMA.

Best regards and good luck smiling smiley
Scan for hammer bars
February 20, 2015 03:56PM
Hi,
I am trying to generate a scan that will pull up candlesticks with hammer or shooting stars.The tail should be 3 times longer than the body and also there can be small wicks too. Is there a way to do this with a study in thinkscript?

Thanks
steve
Re: Fun with ThinkScript
February 20, 2015 04:02PM
tanman,

Thank you very much. I will try that code a little later tonight. I am having my ups and downs with trading since switching to big charts. I will tell you something that has worked extremely well. This is going to sound crazy, but again it has worked for me.

Get this, about 4 of 10 trades tend to reverse on me. I typically lose between 10-15% on the position. I clearly know when to exit a loser. The 6 trades that work are usually big winners. My trades average about 70% gains on my winners and 10-15% losses on my losers. I really hate trading like this, but honestly at the end of the month, my account say, "It works for me". This code will help me a lot. I want to narrow my losers down to about 2 or 3 of 10. I guess when I am really good, I will string 20-30 consecutive winners, but right now, I am making really good money, but I am getting my cracked over the skull a few times in the process. Thanks again for your help.

R30
Re: Fun with ThinkScript
February 20, 2015 04:04PM
Let me rephrase something. I stated, "I really hate trading like this". My point is, I really hate trading against those kind of odds (4 of 10 losers). I love trading big charts. I am being challenged like never before.
Re: Fun with ThinkScript
February 20, 2015 05:17PM
Quote
stefonk
Hi,
I am trying to generate a scan that will pull up candlesticks with hammer or shooting stars.The tail should be 3 times longer than the body and also there can be small wicks too. Is there a way to do this with a study in thinkscript?

Thanks
steve

This should get you started.

# Calculate the length of the candle's wicks
def UpperWick = high - Max(open, close);
def LowerWick = Min(open, close) - low;

# Calculate the length of the candle's body
def CandleBody = AbsValue(open - close);

# Compare the wicks to the body to ensure that one wick is 3x longer than the body
# also compare the other wick to ensure that it is a "small" wick
def Hammer = (UpperWick / CandleBody >= 3) and (LowerWick / CandleBody <= 0.5);
def Star = (LowerWick / CandleBody >= 3) and (UpperWick / CandleBody <= 0.5);

# A scan should define one (and only one) plot for output. This plot will signal on
# either a hammer or a star;
plot data = Hammer or Star;



If you look at the def hammer and def star statements, the first half (before the AND) verifies that one wick is at least 3x longer than the body. The portion after the AND looks for a "small" wick. In this case, it's looking for a wick that is half the size of the candle body (<= 0.5) or less. You may want to tweak that value to suit your needs. Maybe you are willing for the "small" wick to be the same size (or smaller) as the body (<= 1.0); maybe you want it to only be a quarter of the body (<= 0.25). Whatever floats your boat.
Re: Fun with ThinkScript
February 20, 2015 06:17PM
Thank you so much Robert, you are the best
ZigZag Scan
February 20, 2015 07:09PM
Thanks for all the help but I need one more scan if this can be done. This is a built in study from TOS that I am trying to use but always get this error message that, its too complex to produce a realtime data. Actually I am scanning EOD data. I just cant get this to work properly. Its the ZigZag Pattern. I plot either the Upstep or Downstep but still having problems. If you can help with this scan, I would greatly appreciate it.

# TD Ameritrade IP Company, Inc. (c) 2013-2015
#

input priceH = high;
input priceL = low;
input percentageReversal = 5.0;
input absoluteReversal = 0.0;
input atrLength = 5;
input atrReversal = 1.5;

def zigZag = reference ZigZagHighLow(priceH, priceL, percentageReversal, absoluteReversal, atrLength, atrReversal).ZZ;

def step1 = open[1] >= open and open >= close[1] and open[1] > close[1];
def step2 = open[1] <= open and open <= close[1] and open[1] < close[1];

def upStep1 = step1 and close > open[1];
def upStep2 = step2 and close > close[1];
def downStep1 = step1 and close < close[1];
def downStep2 = step2 and close < open[1];

plot UpStep = (upStep1 or upStep1[-1] or upStep2 or upStep2[-1]) and zigZag == low;
plot DownStep = (downStep1 or downStep1[-1] or downStep2 or downStep2[-1]) and zigZag == high;

#End

Thanks
Steve
Re: ZigZag Scan
February 20, 2015 08:05PM
Scripts used as part of the scan function have more limitations than the charting scripts.

For instance, code written for a charting indicator has the luxury of seeing all the candles in a range; whereas the code for the scan can only look at the current candle and those before it.

plot UpStep = (upStep1 or upStep1[-1] or upStep2 or upStep2[-1]) and zigZag == low;

That line of code tries to get data from the current candle and the one following it.

1) this candle -- upStep1, upStep2, and ZigZag
2) the candle after this one -- upStep[-1], upStep2[-1]

That logic works fine on a charting indicator because the indicator starts from the oldest candle, then works its way to the right until it reaches the current candle.

The scan, however, can only look at the current candle and those behind it. So, using the line of code above, it would first look at the current candle (upStep) which is ok. Then it would try to get data from the following candle (upStep[-1]) which is no longer ok because the scan can't look into the future.

To further clarify, when defining something in ThinkScript such as "def Value = close" it is assumed that close is really close[0].

close[0] means the current candle.

If you want to reference the previous close, you can use close[1]; the close from five candles before would be close[5]; etc. If you want to reference the close for the candle after the current candle, you would use close[-1]; close[-5] for five candles after the current candle etc. Scans cannot use negative values in references [-1] because scans are always run on the current candle.

I haven't loaded this into TOS to verify, but you might try shifting everything back by one so that there are no future references being called out.

change:

plot UpStep = (upStep1 or upStep1[-1] or upStep2 or upStep2[-1]) and zigZag == low;

to:

plot UpStep = (upStep1[1] or upStep1 or upStep2[1] or upStep2) and zigZag[1] == low;

That may or may not work for you. Best of luck.



Edited 2 time(s). Last edit at 02/20/2015 08:19PM by robert.
Re: ZigZag Scan
February 21, 2015 02:32PM
I have been asked to convert the "The Edge" script for use as custom watch list columns. If anyone else wants to do the same, here is the modified code.



The first three columns---1D, 1H, and 15---represent the Daily, Hourly, and 15 min trends. They all use the same code. You just have to change the Aggregation Period in the drop down menu to match the desired time.

plot trendup = close > ExpAverage(close, 8);
trendup.AssignValueColor(if trendup then Color.UPTICK else Color.DOWNTICK);
AssignBackgroundColor(if trendup then Color.UPTICK else Color.DOWNTICK);



NS (net signal) uses this code:

plot NetSignal = close > close(period = "day" )[1];
AssignBackgroundColor(if NetSignal then Color.UPTICK else Color.DOWNTICK);
NetSignal.AssignValueColor(if NetSignal then Color.UPTICK else Color.DOWNTICK);

OS (open signal) uses this code:

plot OpenSignal = close - open(period = "day" );
AssignBackgroundColor(if OpenSignal > 0 then Color.UPTICK else Color.DOWNTICK);
OpenSignal.AssignValueColor(if OpenSignal > 0 then Color.UPTICK else Color.DOWNTICK);

HL (high / low) uses this code:

def Higher = close > high(period = "day" )[1];
def Lower = close < low(period = "day" )[1];
plot data = 1;
data.AssignValueColor(if Higher then Color.UPTICK else if Lower then Color.DOWNTICK else Color.GRAY);
AssignBackgroundColor(if Higher then Color.UPTICK else if Lower then Color.DOWNTICK else Color.GRAY);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
February 21, 2015 04:49PM
Hello All,

I am new to this forum and am excited to find a vibrant community actively discussing trading, thinkscript and TOS. Although I've only scratched the surface when it comes to the substantial repository of thinkscripts contained herein, I want to thank Robert in advance for his time, efforts and invaluable contributions to this community's knowledgebase...

On that note, I hope Robert or another member of the community might be able to help me with an issue I'm having. I am running into a little difficulty trying to incorporate the Volume Box study into my charts. More specifically, when I add the study to a 5 min chart, the candles get compacted making the chart impossible to analyze...

Below is a screen capture of what it looks like with the Volume Box study applied:



Below is a screen capture of what it looks like with the Volume Box study disabled/removed:





Edited 1 time(s). Last edit at 02/21/2015 05:04PM by netarchitech.
Re: Fun with ThinkScript
February 21, 2015 04:58PM
You are plotting somthing (the white line at the bottom of the first screen). Disable that from displaying and you should be ok
NMR
Re: Fun with ThinkScript
February 21, 2015 04:58PM
Robert- you have this great code for IN BAND and OUTSIDE BANDS:
input length = 21;
input MinDaysInband = 5;
def sDev = StDev(data = close, length = length);
def Avg = Average(close, length);
def UpperBand = Avg + 2 * sDev;
def LowerBand = Avg - 2 * sDev;
def inband = if close < UpperBand and close > LowerBand then inband[1] + 1 else 0;
def outband = if inband[1] >= MinDaysInband and close > UpperBand or close < LowerBand then outband[1] + 1 else 0;

AddLabel(inband >= MinDaysInband, "In BB: " + inband, Color.BLACK);
AddLabel(outband, "Out BB: " + outband, Color.WHITE);
AddLabel(inband < MinDaysInband and !outband, " ", Color.CURRENT);
AssignBackgroundColor(if inband >= MinDaysInband then Color.DARK_ORANGE else if outband then Color.RED else Color.CURRENT);

Is it possible for you to quickly modify the code so that all that displays is a "Color.Dark_Orange" if it is outside of the Band- all else it is just BLACK? I am asking for this because I feel that the most important thing to know is weather the candle is IN BAND or OUT of BAND- and that is it- no numbers- and no 'min days in band' I use this to quickly scan my WS and see if there is an "OOB" play on the W, D or 233 charts (I have these columns set up on my watch list) and I essentially play a "SLING SHOT" on these.

I'd be more than happy to start another thread on this and explain more what I'm looking for and how they work.

Thank you in advance.
Re: Fun with ThinkScript
February 21, 2015 05:29PM
Quote
NMR
Is it possible for you to quickly modify the code so that all that displays is a "Color.Dark_Orange" if it is outside of the Band- all else it is just BLACK? I am asking for this because I feel that the most important thing to know is weather the candle is IN BAND or OUT of BAND- and that is it- no numbers- and no 'min days in band' I use this to quickly scan my WS and see if there is an "OOB" play on the W, D or 233 charts (I have these columns set up on my watch list) and I essentially play a "SLING SHOT" on these.

def length = 21; 
def sDev = StDev(data = close, length = length); 
def Avg = Average(close, length); 
def UpperBand = Avg + 2 * sDev; 
def LowerBand = Avg - 2 * sDev; 
plot OutBand = close > UpperBand or close < LowerBand;
Outband.AssignValueColor(if OutBand then color.dark_orange else color.black);
AssignBackgroundColor(if OutBand then color.dark_orange else color.black);
Re: Fun with ThinkScript
February 21, 2015 05:50PM
Quote
netarchitech
I am running into a little difficulty trying to incorporate the Volume Box study into my charts. More specifically, when I add the study to a 5 min chart, the candles get compacted making the chart impossible to analyze...

What MTUT said is correct. You've got something extra plotting down around the zero mark that is causing everything else to be compressed. I can't duplicate exactly what you are seeing since I don't know what all the scripts you are running are. However, you mentioned having trouble, specifically, with the v-box code. I pulled up the same 5-min chart of UGAZ that you show and added only the v-box script that you linked to and this is what I'm seeing.



If you can't figure out which line of code is causing you trouble, you can always adjust the scaling of your chart so that the candles take priority by following the directions below.

Re: Fun with ThinkScript
February 21, 2015 09:40PM
Thanks for the swift replies and tips, mtut and robert...

Based on your suggestions, I feel confident I'll be able to find the source of the issue...

Thanks again! I really appreciate it...
Re: Fun with ThinkScript
February 21, 2015 10:55PM
Well, it appears the difficulty I was having with the Volume Box study was not with the study, but with the "Fit Studies" chart scaling option, as suggested by Robert...





Thanks again to Robert and MTUT for their time, efforts and assistance. It is most definitely appreciated smiling smiley
Re: Fun with ThinkScript
February 22, 2015 08:54AM
Robert,

Being a fledgling, aspiring Thinkscript programmer, I have taken the liberty of slightly modifying your Volume Box code to incorporate vertical lines delineating the starting times of the Three Trading Blocks. I just appended the following new code (borrowed and modified from another script) to the bottom of the existing Volume Box code...

# Plot Vertical Lines for Three Trading Blocks
AddVerticalLine(SecondsFromTime(0930) >= 0 and SecondsFromTime(0930) < 60, "09:30", Color.WHITE);
AddVerticalLine(SecondsFromTime(1100) >= 0 and SecondsFromTime(1100) < 60, "11:00", Color.LIME);
AddVerticalLine(SecondsFromTime(1400) >= 0 and SecondsFromTime(1400) < 60, "14:00", Color.PINK);

I hope this modification is acceptable. In the spirit of "paying it forward", I further hope it proves useful / helpful to someone along the way...
Re: ZigZag Scan
February 22, 2015 11:14AM
Hi Robert,

Thanks very much but apparently it didn't work.

input priceH = high;
input priceL = low;
input percentageReversal = 5.0;
input absoluteReversal = 0.0;
input atrLength = 5;
input atrReversal = 1.5;

def zigZag = reference ZigZagHighLow(priceH, priceL, percentageReversal, absoluteReversal, atrLength, atrReversal).ZZ;

def step1 = open[1] >= open and open >= close[1] and open[1] > close[1];
def step2 = open[1] <= open and open <= close[1] and open[1] < close[1];

def upStep1 = step1 and close > open[1];
def upStep2 = step2 and close > close[1];

plot UpStep = (upStep1[1] or upStep1 or upStep2[1] or upStep2) and zigZag[1] == low;This is the error I get.

com.devexperts.tos.thinkscript.runtime.TooComplexException: The complexity of the expression suggests that it may not be reliable with real-time data.
Re: ZigZag Scan
February 22, 2015 11:57AM
Quote
netarchitech
Being a fledgling, aspiring Thinkscript programmer, I have taken the liberty of slightly modifying your Volume Box code to incorporate vertical lines delineating the starting times of the Three Trading Blocks. ...I hope this modification is acceptable.

By all means. Tweak to your heart's content. Modify stuff so that it works best for you.
Sorry, only registered users may post in this forum.

Click here to login