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
June 20, 2014 11:56AM
Robert, Thank you for the modifications. The opening range works fine now smiling smiley

I see your point about entry after close above white line but that causes a problem. The stop loss and target1 is calculated based on white line but if you enter after a candle closes above white line then depending on how far above it closes, the stop loss and target1 will be erroneous and might cause excessive loss (because now stop loss is greater than 2 x ATR) or early profit target exit (because now the target1 is closer than 2 X ATR). Stop loss and target1 should be calculated from entry price and not the white line in that case. If you continue to do that then I will suggest 2 x ATR stop loss from white line and 3 x ATR for target1 from white line, to compensate for that.

I was not using extended hours before but then I noticed something strange. SPY would be going sideways but 60 min ADX or 5 min ADX reading was high which was causing erroneous entries and losses when I should have stayed out. Then I checked ADX with extended hours showing, and viola it corrected the ADX to more accurately reflect the market price action. For example look at SPY today. At 10:50 EST SPY was clearly sideways but with extended hours off, 5 min ADX was 24 which does not make any sense, and could cause a wrong entry in a stock. Then if you switch to extended hours showing, presto the 5 min ADX was 15 at that time, which more accurately reflects the market price action, and you would stay out of trading. Same thing with 60 min ADX, it was lower with extended hours showing, than with extended hours off.

The reason for this is that SPY was trending up yesterday which caused high ADX readings towards the end of day and if you switch off extended hours, the software is suddenly confronted with sideways action immediately after a steep ascent and ADX takes time to come down which gives false readings. If the extended hours are showing, then based on sideways trading from 4 pm to 8 pm yesterday and from 4 am to 9:30 am today the ADX has had time to adjust so when market opens at 9:30 it gives accurate low readings.

This can also affect trading the other way around. If SPY was going sideways during market hours, the ADX would be low and then if it started going up after hours and continued to go up next day during market hours, then with extended hours switched off ADX would be low soon after market open when market is trending up and you will stay out when you need to jump in, but with extended hours showing, the ADX would be high soon after market open because it had time to adjust during after hours trading, which would be more accurate and you won't miss the trades in that case.
Re: Fun with ThinkScript
June 20, 2014 06:40PM
Hi Robert, been following this thread and want to say I appreciate your generosity.
I wonder if I could to call upon your expertise.
I am having some difficulty creating a thinkscript of a simple moving average that will show exclusively on my daily charts.
For example when I click on my daily chart the SMA will automatically display the 30, 50, and 100 day moving average lines, when I go back to say a 5 minute chart those moving average lines are no longer displayed.
Re: Fun with ThinkScript
June 20, 2014 08:02PM
Quote
mark1234
Hi Robert, been following this thread and want to say I appreciate your generosity.

My pleasure.

Quote
mark1234
I wonder if I could to call upon your expertise.
I am having some difficulty creating a thinkscript of a simple moving average that will show exclusively on my daily charts.
For example when I click on my daily chart the SMA will automatically display the 30, 50, and 100 day moving average lines, when I go back to say a 5 minute chart those moving average lines are no longer displayed.

Piece of cake. Add this line to the top of your script.

declare hide_on_intraday;
Re: Fun with ThinkScript
June 20, 2014 08:33PM
Excellent, thank you so much

here is the script for those that are interested,

declare hide_on_intraday;

input price = close;
input length = 30;
input displace = 0;

plot SMA = Average(price[-displace], length);
SMA.SetDefaultColor(GetColor(1));



Edited 1 time(s). Last edit at 06/20/2014 08:42PM by mark1234.
Re: Fun with ThinkScript
June 21, 2014 11:04PM
I recently started watching the Time & Sales but it goes pretty fast. What I'm looking for is a way to take the average trade size and plot it on my chart by coloring the candlesticks based on that. A way to identify high average size and low average size. Average high and low can be different for everyone I guess so maybe that can be user defined? Or I guess maybe a cutoff between high and low? Not sure. Maybe I need to think thru this more. Anyways, don't even know if this is possible. I know nothing about code.

Thanks for looking at this.

Gaterz

PS. Ok, I've thought about this some more...I'm trading futures which are traded in contracts. I'm thinking if the average # of contracts is X or higher, the bar is painted one color. If the average # of contracts is Y or lower, the bar is painted another color. Everything else in between is painted a neutral color. Now I'm not sure what number of contracts would constitute high and low so I guess it could be user controlled?



Edited 1 time(s). Last edit at 06/21/2014 11:37PM by Gaterz.
Re: Fun with ThinkScript
June 22, 2014 04:48PM
Quote
Gaterz
Ok, I've thought about this some more...I'm trading futures which are traded in contracts. I'm thinking if the average # of contracts is X or higher, the bar is painted one color. If the average # of contracts is Y or lower, the bar is painted another color. Everything else in between is painted a neutral color.

Changing the candle color based on user-defined criteria isn't that difficult. That said, I'm not sure thinkscript is able to access number of contracts traded. Take a look at the thinkscript help page and go through all the functions listed on the left-hand menu. If you can find a function that will report the data you need, I'll try to write up the code for you.

[tlc.thinkorswim.com]
Re: Fun with ThinkScript
June 24, 2014 12:00PM
hey, robert: here's a nice little inside-day, narrow-range-4 script that i've taken from an old post on the Lawyer Trader blog and wondered if you might be able to do a few things to it for me:

i'm soley interested in those times when the yellow dot (NR4) and the violet dot (low volatility) line up right together. Is there a way to:

1/ put a big fat arrow on the screen whenever this happens, above the bar in question?
1b/ make it sound an alarm?
2/ write a scan for the condition?



(never mind the arrows here, it's the double dots i'm interested in ....)

here's the code:


# ID/NR4 Bars
#
def range = high – low;
def na=double.nan;

def plotter=high+range*0.3;

def longvol = volatilityStdDev(100);
def shortvol = volatilityStdDev(6);

def volratio = shortvol/longvol;

def isnr4 = (range <= range[1] and range <= range[2] and range <= range[3] and range and high<high[1] and low>low[1]);

plot lowvol = if volratio<.5 and isnr4 then low-.0005 else double.nan;

lowvol.SetDefaultColor(color.violet);
lowvol.setstyle(curve.points);
lowvol.setlineWeight(3);

plot nr4 = if isnr4 then plotter else na;

nr4.SetDefaultColor(Color.yellow);
nr4.setstyle(curve.points);
nr4.setlineWeight(3);
Re: Fun with ThinkScript
June 24, 2014 06:28PM
Quote
linter
hey, robert: here's a nice little inside-day, narrow-range-4 script that i've taken from an old post on the Lawyer Trader blog and wondered if you might be able to do a few things to it for me:

i'm soley interested in those times when the yellow dot (NR4) and the violet dot (low volatility) line up right together. Is there a way to:

1/ put a big fat arrow on the screen whenever this happens, above the bar in question?
1b/ make it sound an alarm?
2/ write a scan for the condition?

Here you go. Arrow only plots when both yellow and violet dots are present.



I'm not sure how much good an alarm will do on a daily plot, but I included it per your request.

If you'd like to run this as a scan, just include the first five lines (def and plot statements) and delete the last four lines (plot settings and alert).

def lowVol = (VolatilityStdDev(6) / VolatilityStdDev(100)) < 0.5;
def insideDay = high < high[1] and low > low[1];
def range = high - low;
def NR4 = range < Lowest(range[1], 3);
plot signal = lowVol and insideDay and NR4;
     signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
     signal.SetDefaultColor(Color.MAGENTA);
     signal.SetLineWeight(5);
Alert(signal, getsymbol() + " inside & narrow range day.", alert.bar, sound.ring);
Re: Fun with ThinkScript
June 25, 2014 08:58AM
oh man that's great.
thanks a bunch.
have some other thoughts about this but will give you a break ... for the moment!



Edited 1 time(s). Last edit at 06/25/2014 10:12AM by linter.
Re: Fun with ThinkScript
June 25, 2014 11:01AM
robert Wrote:
-------------------------------------------------------
> > could you cobble together a scan for the
> following? i should be able to do it myself but
> the heat in RI is making me denser than usual.
>
>
[i.imgur.com]
>
> When writing a script for use in the stock
> screening tool, that script must return a yes or
> no answer to just one question. In your case,
> that question seems to be, ....

I was wondering if someone could help me as my question is more complex and I'd like to have some sort of text output for my watchlist.

It's a two part watchlist - maybe they need to be seperate or I would prefer if they could be combined into one.

A. For a close inside of the Bollinger Bands, calculate the number of days of consecutive closes inside the bands and display it like "In: n" where n is the number of days. Only display this when n > 15, say else display blank.

B. For a close outside of the Bollinger Bands, I'm looking to calculate the number of consecutive days outside of the bands only if the close was immediately inside of the bollinger bands (see A above) for a minimum mumber of days, say 19 and display it lilke "Ex: m" where m is the number of days outside of the bollinger bands. For eg. the stock is inside of the bollinger bands for 22 days and then it's outside for 4 days - "Ex: 4". else display blank.
Re: Fun with ThinkScript
June 25, 2014 09:13PM
Can I get a script for the previous week's High and low? Plotted on "today's" chart

Do you have Paypal or something for donations?
Re: Fun with ThinkScript
June 25, 2014 09:49PM
Man, you will not believe my pc had crash and I couldn't find this site for about a week or 2. sad smiley

I just started to use the RSI EMA and wondered if a alarm could be made that would change the background color and a bell ring when EMA touches the OverSold and OverBought lines. Then when the level goes back within the range the background goes back to normal?

So glad I found this post again. lmbo smh
Re: Fun with ThinkScript
June 26, 2014 07:50AM
Quote
eurekaaa
I was wondering if someone could help me as my question is more complex and I'd like to have some sort of text output for my watchlist.

It's a two part watchlist - maybe they need to be seperate or I would prefer if they could be combined into one.

A. For a close inside of the Bollinger Bands, calculate the number of days of consecutive closes inside the bands and display it like "In: n" where n is the number of days. Only display this when n > 15, say else display blank.

B. For a close outside of the Bollinger Bands, I'm looking to calculate the number of consecutive days outside of the bands only if the close was immediately inside of the bollinger bands (see A above) for a minimum mumber of days, say 19 and display it lilke "Ex: m" where m is the number of days outside of the bollinger bands. For eg. the stock is inside of the bollinger bands for 22 days and then it's outside for 4 days - "Ex: 4". else display blank.

Fortuitous timing on your part. I was thinking just a couple days ago about writing something along these lines for myself. I'll probably work on this sometime over the next few days when I have the time.
Re: Fun with ThinkScript
June 26, 2014 08:10AM
Quote
Gaterz
Can I get a script for the previous week's High and low? Plotted on "today's" chart

Change colors and whether you want to plot last week's high / low only today or every day from within the script settings window.



input ShowTodayOnly = yes;

def today = if !ShowTodayOnly then 1 else GetDay() == GetLastDay();
plot HighLW = if !today then Double.NaN else high(period = "week" )[1];
     HighLW.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
plot LowLW = if !today then Double.NaN else low(period = "week" )[1];
     LowLW.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 26, 2014 08:17AM
Quote
wiineedmore
I just started to use the RSI EMA and wondered if a alarm could be made that would change the background color and a bell ring when EMA touches the OverSold and OverBought lines. Then when the level goes back within the range the background goes back to normal?

declare lower;

input length = 14;
input over_bought = 70;
input over_sold = 30;
input price = close;

def NetChgAvg = ExpAverage(price - price[1], length);
def TotChgAvg = ExpAverage(AbsValue(price - price[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;

plot RSI_EMA = 50 * (ChgRatio + 1);
plot OverSold = over_sold;
plot OverBought = over_bought;

RSI_EMA.SetDefaultColor(GetColor(8));
OverBought.SetDefaultColor(GetColor(5));
OverSold.SetDefaultColor(GetColor(5));

AssignBackgroundColor(if RSI_EMA >= OverBought then Color.PINK else if RSI_EMA <= OverSold then Color.LIGHT_GREEN else Color.CURRENT);
def soundAlert = (RSI_EMA crosses above OverBought) or (RSI_EMA crosses below OverSold);
Alert(soundAlert, "", Alert.BAR, Sound.Ring);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 26, 2014 03:32PM
I have this:

AddLabel(yes, if close > Average(close, 20) then "Uptrend" else "Downtrend"winking smiley;

but I can't get the color to change depending if it's Uptrend or Downtrend. It's always red. I've tried different things with no luck.

Help?

Thx for the code above. Yo'ure awesome!

Gaterz
Re: Fun with ThinkScript
June 26, 2014 03:53PM
Hi Gaterz,

Try this:

def UpTrend = close > Average(close, 20);
AddLabel(UpTrend, " UpTrend ", Color.UPTICK);
AddLabel(!UpTrend, " DownTrend ", Color.DOWNTICK);

The Label will be green in uptrend (defined as price close above 20 SMA), and red in downtrend (price close below 20 SMA).

Hope that helps,

Tan
Re: Fun with ThinkScript
June 26, 2014 11:48PM
I really appreciate everyones hard work in this forum. That is the reason I decided to join. This is a community of friends with a common goal.

I was wondering if anyone happen to know a way to quickly seach for the following.

Scan for for stocks that have the following.
1) Look at the past earnings (Choose how many earnings you go back, minimum of three earnings.
2) Look for stocks that were always going up PRIOR to earnings for at least a 10% difference from the day before earnings.
3) Look for stocks that were always going down PRIOR to earnings for at least a 10% difference from the day before earnings.
4) Look for stocks that were always going down AFTER to earnings for at least a 10% difference from the day after earnings.
5) Look for stocks that were always going up AFTER to earnings for at least a 10% difference from the day after earnings.

The reason I mention the day before or after is because if you include the earnings date within the mathmatical equation it would be scewed due to to gap ups and downs that earnings produces.

Alternative to this search method would be some sort of color, arrow, etc.. that indicates the direction the trend is going as long as the following is true.
1) There is a 10% difference from the first candlestick to the candlestick right before earnings or after earnings.

Any ideas?

Thanks so much!!!
Re: Fun with ThinkScript
June 27, 2014 07:08AM
Quote
eurekaaa
I was wondering if someone could help me as my question is more complex and I'd like to have some sort of text output for my watchlist.

It's a two part watchlist - maybe they need to be seperate or I would prefer if they could be combined into one.

A. For a close inside of the Bollinger Bands, calculate the number of days of consecutive closes inside the bands and display it like "In: n" where n is the number of days. Only display this when n > 15, say else display blank.

B. For a close outside of the Bollinger Bands, I'm looking to calculate the number of consecutive days outside of the bands only if the close was immediately inside of the bollinger bands (see A above) for a minimum mumber of days, say 19 and display it lilke "Ex: m" where m is the number of days outside of the bollinger bands. For eg. the stock is inside of the bollinger bands for 22 days and then it's outside for 4 days - "Ex: 4". else display blank.

As a chart label.



input length = 21;
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 close > UpperBand or close < LowerBand then outband[1] + 1 else 0;

AddLabel(inband, "In BB: " + inband, Color.YELLOW);
AddLabel(outband, "Out BB: " + outband, Color.WHITE);



As a watchlist column.



input length = 21;
input MinDaysInband = 15;
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.PLUM else Color.CURRENT);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 27, 2014 11:10AM
robert: okay, i know you're bored and waiting for another li'l assignment, so in the spirit of helping you out and getting you busy, here's another in my ongoing long line of recent requests, for which i am sorry, but OCD has a grip on me and what can i do? anyway ...

how about a custom sortable column that would take the high of the 30-minute opening range and tell me how far off, in % terms, the current prices in my watchlist are from that high-water mark. my concern here is that the updating of the column lags behind too much for the numbers to be useful. hmmm. i don't know. what do you think?
Re: Fun with ThinkScript
June 27, 2014 11:24AM
Quote
linter
my concern here is that the updating of the column lags behind too much for the numbers to be useful. hmmm. i don't know. what do you think?


LInter, I can write the code for what you ask, however, I am not a fan of custom watchlist columns which are dependent on intraday data being updated in real-time because they always seem to be delayed by 20 minutes or more. As a matter of fact, I put the DOW on my charts so that I can see how it is moving in real-time when the market first opens.

As an experiment for yourself, run this script which will put the net change in the DOW in a label on your charts. Then, compare it to what the net change is being reported as on the watchlist. Finally, compare it to the net change being reported by a different real-time service such as your brokerage account. When I compare the value printed in the label on my charts with the value reported by OptionsXpress, they match in real-time whereas the value reported by the watchlist is ALWAYS 15-20 minutes behind for me.

input sym = "$DJI";
def Net = Round(close(sym) - close(sym, period = "day" )[1], 1);
AddLabel(Net >= 20, "DJI:  " + Net, Color.GREEN);
AddLabel(Net <= -20, "DJI:  " + Net, Color.PINK);
AddLabel(Net between -19.9 and 19.9, "DJI:  " + Net, Color.LIGHT_GRAY);

Unfortunately, it has been my experience that custom watchlist columns are always delayed in the same manner (or even longer).

That being said, stock and option prices seem to be updated in real-time on the watchlist.



Edited 1 time(s). Last edit at 06/27/2014 11:27AM by robert.
Re: Fun with ThinkScript
June 27, 2014 11:48AM
Robert,

Do you have Level II quotes in Realtime? Are you doing this on the Paper side or Live side? If the account is not funded (doesn't have to be) then there will in fact be a delay. Most things on the Live side are Realtime, but not everything is. I'd call and asked them to check and ensure that everything is "Realtime" especially on the Paper side. Funding the account does NOT automatically switch all the Paper side stuff to Realtime. If you have not funded the account, you could shoot them 50 bucks to fund the account, and that money will just sit there forever or until you remove it. That way you can have them turn ALL your stuff to "Realtime"

And that's just my 2 cents:-) Meow!
Re: Fun with ThinkScript
June 27, 2014 12:00PM
As a follow up to my last post regarding custom watchlists, this is what I am seeing right now when I run the simplest of watchlist columns.

plot NetChg = close - close[1];

This will calculate the net change in price and it should match the built-in Net Chng column, but it doesn't. The values are mostly off, or they don't even calculate as indicated by the rows which display "loading".



It gets even worse when trying to use a more complex formula in the custom columns. That's why, for myself, I have abandoned them altogether.
Re: Fun with ThinkScript
June 27, 2014 12:04PM
Quote
RichieRick
Robert,

Do you have Level II quotes in Realtime? Are you doing this on the Paper side or Live side?

Thanks for the feedback, Rick. I'm using the live login and this is what my settings show.



I don't trade futures so I don't care if they are delayed.
Re: Fun with ThinkScript
June 27, 2014 12:12PM
I was just asked this question in a PM and thought I would repost here in case anyone else was unaware that this feature was recently added to TOS. It's quite useful.

Quote

I also have a question..... If I draw trend lines using the tools available through TOS, can you create a formula that would give me an alert, notifying me when a candle closes above or below that line?

Funny you should ask. grinning smiley TOS just added that functionality in last month's update. Simply right-click on the trendline then choose "create alert from drawing."

Re: Fun with ThinkScript
June 27, 2014 12:53PM
robert Wrote:
-------------------------------------------------------
> > Robert,
>
> Do you have Level II quotes in Realtime? Are you
> doing this on the Paper side or Live side?
>
>
> Thanks for the feedback, Rick. I'm using the live
> login and this is what my settings show.
>
> I don't trade futures so I don't care if they are
> delayed.


Yeah I don't mess with the Futures stuff either:-) It may be the "Other" category that has you tripped up. I'm not sure what "Other" covers but it's possible it has something to do with scans, and watchlists... possibly.
Re: Fun with ThinkScript
June 27, 2014 01:44PM
Thank you so much for this thread. I really appreciate your generosity to share.

Also, i was wondering if it's possible to do column script that changes colors when price is above or below the daily VWAP.

Thanks.
Re: Fun with ThinkScript
June 27, 2014 03:13PM
okay, robert, i believe you. funny you should mention "create alert from drawing." what i could do is go through my watchlist and draw a price line just beneath the opening range high and put an alert on it and then open the stocks all up on a new page like i've seen you do. that might work.

seems to me, though, that you once wrote a bit of code that plotted the opening range and also plotted lines just beneath the OR high and just above the low. can't remember if alerts were part of the study. i'll have to go back through this thread and see if anything rings a bell. does this sound familiar?

thanks again.
Re: Fun with ThinkScript
June 27, 2014 03:58PM
Quote
linter
seems to me, though, that you once wrote a bit of code that plotted the opening range and also plotted lines just beneath the OR high and just above the low. can't remember if alerts were part of the study. i'll have to go back through this thread and see if anything rings a bell. does this sound familiar?

I believe you are referring to this.



Yellow dashed is 5 min opening range; solid yellow is 30 min opening range. I'm not an alert-sounding-kind-of-guy, but I'll add them for you since you asked so nicely.

# 5 min opening range
# Robert Payne

def OpenRangeMinutes = 5;
def MarketOpenTime = 0930;
input ShowTodayOnly = yes;

def Today = if GetDay() == GetLastDay() then 1 else 0;
def FirstMinute = if SecondsFromTime(MarketOpenTime) < 60 then 1 else 0;
def OpenRangeTime = if SecondsFromTime(MarketOpenTime) < 60 * OpenRangeMinutes then 1 else 0;

def ORHigh =  if FirstMinute then high else if OpenRangeTime and high > ORHigh[1] then high else ORHigh[1];
def ORLow = if FirstMinute then low else if OpenRangeTime and low < ORLow[1] then low else ORLow[1];

plot OpenRangeHigh = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORHigh else Double.NaN;
plot OpenRangeLow = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORLow else Double.NaN;

OpenRangeHigh.SetStyle(Curve.SHORT_DASH);
OpenRangeHigh.SetDefaultColor(Color.YELLOW);
OpenRangeHigh.SetLineWeight(1);
OpenRangeLow.SetStyle(Curve.SHORT_DASH);
OpenRangeLow.SetDefaultColor(Color.YELLOW);
OpenRangeLow.SetLineWeight(1);

# Plot 5 min entry line
def first30 = if SecondsFromTime(0930) >= 0 and SecondsTillTime(1000) > 0 then 1 else 0;
def dailyRange = high(period="day" )[1] - low(period="day" )[1];
def range = average(dailyrange,10);

plot entryLine1 = if first30 then openrangehigh + (range * 0.03) else double.nan;
entryline1.setdefaultcolor(color.green); 
entryline1.setpaintingStrategy(paintingStrategy.HORIZONTAL);

plot entryLine2 = if first30 then openrangelow - (range * 0.03) else double.nan;
entryline2.setdefaultcolor(color.green); 
entryline2.setpaintingStrategy(paintingStrategy.HORIZONTAL);

def SoundAlert = high crosses above entryLine1 or low crosses below entryLine2;
Alert(SoundAlert, "Something exciting just happened with " + GetSymbol(), Alert.BAR, Sound.Ring);

# 30 min opening range
# Robert Payne

def OpenRangeMinutes = 30;
def MarketOpenTime = 0930;
input ShowTodayOnly = yes;

def Today = if GetDay() == GetLastDay() then 1 else 0;
def FirstMinute = if SecondsFromTime(MarketOpenTime) < 60 then 1 else 0;
def OpenRangeTime = if SecondsFromTime(MarketOpenTime) < 60 * OpenRangeMinutes then 1 else 0;

def ORHigh =  if FirstMinute then high else if OpenRangeTime and high > ORHigh[1] then high else ORHigh[1];
def ORLow = if FirstMinute then low else if OpenRangeTime and low < ORLow[1] then low else ORLow[1];

plot OpenRangeHigh = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORHigh else Double.NaN;
plot OpenRangeLow = if ShowTodayOnly and !Today then Double.NaN else if !OpenRangeTime then ORLow else Double.NaN;

OpenRangeHigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OpenRangeHigh.SetDefaultColor(Color.YELLOW);
OpenRangeHigh.SetLineWeight(2);
OpenRangeLow.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
OpenRangeLow.SetDefaultColor(Color.YELLOW);
OpenRangeLow.SetLineWeight(2);

DefineGlobalColor("cloud", CreateColor(161, 182, 158));
AddCloud(OpenRangeHigh, OpenRangeLow, GlobalColor("cloud" ));

def dailyRange = high(period = "day" )[1] - low(period = "day" )[1];
def range = Average(dailyRange, 10);

plot entryLine1 = OpenRangeHigh + (range * 0.06);
entryLine1.SetDefaultColor(Color.GREEN);

plot entryLine2 = OpenRangeLow - (range * 0.06);
entryLine2.SetDefaultColor(Color.GREEN);

def SoundAlert = high crosses above entryLine1 or low crosses below entryLine2;
Alert(SoundAlert, "Something exciting just happened with " + GetSymbol(), Alert.BAR, Sound.Ring);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 27, 2014 04:09PM
robert Wrote:
-------------------------------------------------------
> As a chart label.
>
>
> input length = 21;
> 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 close > UpperBand or close <
> LowerBand then outband[1] + 1 else 0;
>
> AddLabel(inband, "In BB: " + inband,
> Color.YELLOW);
> AddLabel(outband, "Out BB: " + outband,
> Color.WHITE);
>
> As a watchlist column.
>
> input length = 21;
> input MinDaysInband = 15;
> 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.PLUM else Color.CURRENT);
>

Robert:

After taking about 60 min to realize that the reason why I wasn't seeing any outbands was because all my background was set to the same color, white.

Then I was able to realize that his is an excellent start to my question:

First thing def outband = if inband[1] >= MinDaysInband and close > UpperBand or close < LowerBand then outband[1] + 1 else 0; needs parenthsis around (close > UpperBand or close < LowerBand).

Next it's not necessarily the 1st bar back that inband needs to be >= MinDaysInband , it could be one, two, three or more bars back depending on how many days the stock closed outside of the Bollinger bands.

so I tried this:

def inband = if close < UpperBand and close > LowerBand then inband[1] + 1 else 0; #no change here
def daysoutband = if close > UpperBand or close < LowerBand then daysoutband[1] + 1 else 0;
def outband = if daysoutband != 0 and inband[daysoutband+1] >= MinDaysInband then daysoutband else 0;

However it appears that I can't use daysoutband in square brackets. TOS doesn't like the last line.

Any ideas?

Eric



Edited 2 time(s). Last edit at 06/27/2014 04:12PM by eurekaaaa.
Sorry, only registered users may post in this forum.

Click here to login