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
January 07, 2017 07:33AM
Sara, I refer you to the think script manual page that discusses aggregation periods. The times listed on that page are the only ones available to work with. [tlc.thinkorswim.com]

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
January 09, 2017 01:30PM
Ive been using a code to paint inside bars. It paints new bars also until it goes outside the previous bar. Is there a way to modify this code where it will only flag/paint the candle after it closes? Also is there a way to make it into a pre-defined watchlist? Thanks

plot Data = close;
def insideBar = if
(High[0] < High[1] && Low[0] > Low[1])

then
yes else no;

input price = close;

plot insideBarFlag = double.nan;

insideBarFlag.DefineColor("insidebarcolor", color.blue);

AssignPriceColor(if insideBar then insideBarFlag.color("insidebarcolor"winking smiley else
color.current);

# // End of script

A link is posted of pictures for explanation.

[www.forexfactory.com]
Re: Fun with ThinkScript
January 09, 2017 09:09PM
Hey Robert -

Maybe you can help me with an issue I'm having.

I need a way to count down how many 5 minute bars are left to complete an hour.

For example - if it is 5:35, I need to have a returned value of 5, meaning there are 5 bars left till the top of the hour (5:35, 5:40, 5:45, 5:50, and 5:55 bars).

Is there an easy way to get this countdown, so to speak?
Re: Fun with ThinkScript
January 09, 2017 10:01PM
Never mind.... Figured it out. smiling smiley
Previous days different color bars..
January 10, 2017 08:04PM
is there a script that can color the previous days bars differently than today's? this makes it super easy to see Todays price movement..
Re: Fun with ThinkScript
January 11, 2017 05:11PM
I'm still fairly new to ThinkScript so bare with me. Is there of way of showing the price when criteria is met. For example, if the EMA(10) crosses the SMA(20) and the volume increases by 20% from the previous bar I currently have it showing a green arrow but is it possible to show the price too (preferable below the arrow)? Also, this criteria gives my multiple green arrows, is it possible to only show the first time the criteria is met?
Thank you for your help.
ttm_scalper alert color bars
January 12, 2017 01:08AM
Hi.. how can i get a chart that changes bar color to red when the TTM_SCALPERALERT has down arrow and colors the bars as green when the "pivotlow" is reached ?
Re: Fun with ThinkScript
January 12, 2017 01:43PM
For some reason the begin_time and end_time functions and how to code them correctly are the trickiest things for me to do correctly.

I want to get the highest high during pre-market trading which I want to begin at time = 0000 and end at time = 0830. Then, after the markets open if the high of the current bar is greater than that pre-market high....do this. I am central time US.

This is what I have:

input begin_time = 0000;

input end_time = 0830;

def begin = secondstilltime(begin_time);

def end = secondstilltime(end_time);

def prehigh = high; # the pre-market highest high between 0000 and 0830

def marhigh = high; # the high after the market opens for regular trading hours

def cond1 = if end_time > 0830 and marhigh > prehigh; # THIS IS INCORRECT but is what I need

Just can't get these time functions and the logic correct. Most other things I am okay with....

Thanks
Re: Fun with ThinkScript
January 12, 2017 02:09PM
Palmer - this will get you started with your Pre-Market high.....
Not sure what you're trying to do beyond that.



input RangeBegin = 0000;
input RangeEnd = 0929;
input MarketOpen = 0930;
input ShowTodayOnly = { "No", default "Yes"};


def s = ShowTodayOnly;

Def IsRangeActive = if secondstilltime(RangeEnd) > 0 && secondsfromtime(RangeBegin) >= 0 then 1 else 0;
def today = if s == 0 OR getday() == getlastday() && secondsfromtime(RangeBegin) >= 0 then 1 else 0;

Rec RangeHigh = if RangeHigh[1] == 0 or IsRangeActive[1] == 0 && IsRangeActive == 1 then high else if IsRangeActive && high > RangeHigh[1] then high else RangeHigh[1];

plot PreH = RangeHigh;
Re: Fun with ThinkScript
January 12, 2017 04:54PM
dd6:

The plot works great! Thanks!

Question....I am central time zone US and my charts are set for the same time zone. I need to change the input RangeEnd = to 0829 and MarketOpen to 0830 I believe.

Ok, so I need to define a condition where once the market opens, if the high during the regular trading hours (00830 through about noon) is greater than the pre-market high then do this...

By do this I will create a label or an alert. I can take care of that part but it is the defining the condition that is throwing me off.

I 'think' the RangeHigh is the pre-market high as you have defined it...I think...???

So when the market opens for the regular trading day it can be as simple as:

def cond1 = high > RangeHigh;.....but not sure if that is correct.

When I am away from my main trading station I have once 19" screen to trade with. I trade the open up to a few hours after that and I need to see information fast and in an organized way to my watchlist and chart labels have visual cues such as red, green, or white, to instead of trying to read a chart I can read the data in the watchlist or labels in the chart to let me 'see the chart by just looking at the data' if you know what I mean. When the regular trading hours (up until about noon) high opens or breaks above the pre-market high that is a cue for me to 'get ready'.

Thanks again....it's the condition for the regular trading hours high (up until about noon) to be greater than the pre-mark high for what I need...

I came up with this and based on where the high is now vs. the pre-market high it seems to work. It simply adds a 1 with a green border in the upper left of the chart if the high > RangeHigh or a 0 with a red border if the high < RangeHigh.

def cond1 = high > RangeHigh;

AddLabel(yes, + Round(cond1,1), if high > RangeHigh then color.green else if high < RangeHigh then color.red else color.white);


It seems to work, just want to make sure.

It's from another label indicator. The Round is there to round that indy number to one decimal. Don't need it here but there is a parenthesis or comma that needs to be left out. It's not critical to have it only work through noon. As long as it automatically 'restarts' for the next trading day it's all good.
Re: Fun with ThinkScript
January 12, 2017 09:55PM
Hi All,

Need help coding a strategy to look for a pullback then buy if it bounces and breaks above previous 10 min high.

Example: Price runs higher then pulls back to below the EMA(8 period). If the price closes below the 8 period EMA then buy if it breaks out above the previous run's high within 10 minutes.

Tried the below code but I'm having trouble with figuring out the aggregation.

def avg3 = MovAvgExponential(close, 8, 0);
plot pullback = price crosses below avg3 within 10 bars and price > highest(price,[10]) ;
Re: Fun with ThinkScript
January 13, 2017 01:34PM
Hey Robert,

I'm hoping you'd be willing to help my with a problem I'm having..I have the following code I use as a trailing stop loss:

#ATR Stoploss
input Length = 20;
input ATRFactor = 3;
input AverageType = AverageType.WILDERS;

def HiLo = Min(high - low, 1.5 * Average(high - low, Length));
def HRef = if low <= High[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def TrueRange;
    TrueRange = Max(HiLo, Max(HRef, LRef));

def ATR = ATRFactor*MovingAverage(AverageType, TrueRange, Length);

def trail;
    if (close()[1] > trail[1]) {
    trail = Max(trail[1], close - ATR);
    } else {
    trail = Min(trail[1], close - ATR);
    }

plot TrailingStop = trail;

When I build a conditional sell order in the Study Order Condition screen, I set it up as the following:

close crosses below ATRTrailingStop_UPTREND_v2()

My problem is, seemingly at random, I'll get an error message stating "rec usage is not allowed in this context". Twice now, I've built this study from scratch, testing to see if the order will pass with each change and it'll work, but then it seems as if it just decides it doesn't want to work anymore.

For example, I set the order up last night and it executed perfectly this morning. When I tied to setup my next order, I get the error message. This has happened twice this week. What am I dong wrong? I'm stumped...HALP
Strategy to Buy on Breakout after Pullback
January 12, 2017 09:49PM
Need help coding a strategy to look for a pullback then buy if it bounces and breaks above previous 10 min high.

Example: Price runs higher then pulls back to below the EMA(8 period). If the price closes below the 8 period EMA then buy if it breaks out above the previous run's high within 10 minutes.

Tried the below code but I'm having trouble with figuring out the aggregation.

def avg3 = MovAvgExponential(close, 8, 0);
plot pullback = price crosses below avg3 within 10 bars and price > highest(price,[10]) ;
Re: Fun with ThinkScript
January 15, 2017 07:52AM
Thank you Robert ,

I just want to Ask you : Is it possible to combine value chart with Bollinger Bands?
From strategy to scan
January 15, 2017 04:52PM
Been having a hard time trying to turn a strategy into a form of a buy sigal scan. Ive been getting error messages like one plot expected. I think it has something to do with the offesetings int the strategy like [-1], [2], and [3]. If I remove those offsettings I get couple scans but its not exactly what related to the original strategy. Im new to think scrpit coding, and ive been working on this on/off for a while and I'm pretty much stumped myself ont this one. Im okay with coming up with strategies buy not the best at trying to scan for my strategies. I'm all for shareing knowledge, im not a finacial advisor, not resposible for any losses, blah blah legal jargon blah. Anyway this is the full strategy code (you can ignore the # notes, its just for my reference, im not a programer):

input signalOffsetFactor = 0.20;

def signalOffset = Average(TrueRange(high, close, low), 9) * signalOffsetFactor;
#plot Data = hlc3;

def triggerSell = If(If(close[-1] < high, 1, 0) and (hlc3[-2] < close[-1] or hlc3[-3] < close[-1]), 1, 0);
#close offest [-1] true 1, false 0;

def triggerBuy = If(If(close[-1] > low, 1, 0) and (hlc3[-2] > close[-1] or hlc3[-3] > close[-1]), 1, 0);
#hlc3 stands for High Low Close average

rec buySellSwitch = If(triggerSell, 1, If(triggerBuy, 0, buySellSwitch[1]));

def thirdBarClosed = If(IsNaN(hlc3[-3]), 0.0, 1.0);

plot DotSignal = If(triggerSell and thirdBarClosed and !buySellSwitch[1], high + signalOffset, If(triggerBuy and thirdBarClosed and buySellSwitch[1], low - signalOffset, Double.NaN));

DotSignal.SetStyle(Curve.FIRM);
DotSignal.SetPaintingStrategy(PaintingStrategy.LINE_VS_POINTS);
DotSignal.SetLineWeight(1);

DotSignal.AssignValueColor(if triggerSell then
if thirdBarClosed then
#UpPos
CreateColor(255, 0, 0) else
#UpNeg
CreateColor(255, 0, 0)
else if triggerBuy then
#DnPos
CreateColor(0, 255, 0) else
#DnNeg
CreateColor(0, 255, 0));
#END of Script

And for the buy signals I came up with this, according a youtube video it should be this simple;

"def triggerBuy = If(If(close[-1] > low, 1, 0) and (hlc3[-2] > close[-1] or hlc3[-3] > close[-1]), 1, 0);
plot scan = triggerBuy;"

But that one above gets an error mesaage, "one plot expected." So with some adjustments I changed it to;

"def triggerBuy = If(If(close> low, 1, 0) and (hlc3 > close or hlc3 > close), 1, 0);
plot scan = triggerBuy;"

In which I get couple hits but obivioulsy its not related to the original strategy. Anyone have any idea on converting into a buy signal scan? Should the whole thing be rewritten in a simplifed version to then covert into a scan? Any advice is appreicated, and please excuse my grammer.
Re: Fun with ThinkScript
January 17, 2017 04:12AM
I'm wondering if this type of scanner is possible with tos.

1) has average daily volume greater than x.
2) the time to look back is y (days or weeks or months).
3) the current price range is between a and b.
4) the current price has retraced z% from high

I'm trying to create a scanner that will allow me to look back a customizable time frame(let's say 20 days, 3 months, 1 year, etc) and return a list of stocks that has retraced a certain %(50%, 61.8%, 78%, etc)? has anyone done this? guidance appreciated. thanks in advance.



Edited 1 time(s). Last edit at 01/17/2017 04:16AM by JamesBond.
Re: Fun with ThinkScript
January 20, 2017 08:16PM
Robert -

I'm having an issue, or possibly a brain fart, in coming up with the best way to do something.
Wondering if maybe you can help me get started.

I want to join two daily levels when they're within each other's "confluence zone" with a cloud, but only if they're within that range.
If they're within the tolerance, then the plot line would automatically hide, and a cloud would be formed instead of the two lines.

If not within the tolerance of any of the other levels, they would just be a solid line plot.

Any help on this would be appreciated.
Re: Fun with ThinkScript
January 21, 2017 07:20AM
SARA Wrote:
-------------------------------------------------------
> Thank you Robert ,
>
> I just want to Ask you : Is it possible to combine
> value chart with Bollinger Bands?


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

I got it, thanks
Thinkorswim candles
January 20, 2017 05:58AM
I have finally got all my charts the way I want them on ThinkorSwim, but I still cant figure out how to get the candles to sit on top of the upper indicators vs behind them. It makes it much harder to see some of the doji's and patterns, does anyone even know if its possible to get them to sit on top of the indicators vs behind them?
Re: Thinkorswim candles
January 20, 2017 09:26AM
Unfortunately, I don't believe it is possible. At least, I've not found a way.

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Thinkorswim candles
January 21, 2017 02:29AM
BLAHHHH,
Yea I think I have exhausted all options I don't think its possible either. Thanks for the reply.
Re: Fun with ThinkScript
January 21, 2017 09:17PM
Hi Robert,
I have question on how to get the value of the peak before the valley if valley is true
if valley[5] == 1 then close else double.NaN
I want to know is the above is true then what was the peak right before it?

Thanks

robert Wrote:
-------------------------------------------------------
> I wrote this for myself a while ago and was
> recently asked in a PM about something similar, so
> I may as well throw this out there for anyone who
> may find it useful.
>
> This will mark reversal areas.
>
> From the study preferences panel, adjust the
> "magnitude" value to suit your needs. If you want
> to plot minor reversals, use a small value (maybe
> 2 or 3). If you want more significant reversals,
> set a higher value.
>
> [i.imgur.com]
>
> [i.imgur.com]
>
>
> # Plot areas of potential support / resistance
> based on major peaks and valleys.
> # 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 high must be
> greater than the 2 candles
> # before and after it to be considered a peak.
> Likewise for the lows to be a valley.
> #
> # Robert Payne
>
>
> input magnitude = 5;
>
> # define and plot the most recent peak
> def peak = high >= Highest(high[1], magnitude) and
> high >= Highest(high[-magnitude], magnitude);
> def peakvalue = if BarNumber() < magnitude then
> Double.NaN else if peak then high else
> peakvalue[1];
> plot peakline = peakvalue;
>
> peakline.SetPaintingStrategy(PaintingStrategy.HORI
> ZONTAL);
> 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.HORIZ
> ONTAL);
> 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.D
> ASHES);
> oldpeakline.SetDefaultColor(Color.GREEN);
>
> # define and plot the most recent valley
> def valley = low <= Lowest(low[1], magnitude) and
> low <= Lowest(low[-magnitude], magnitude);
> def valleyValue = if BarNumber() < magnitude then
> Double.NaN else if valley then low else
> valleyValue[1];
> plot valleyline = valleyValue;
>
> valleyline.SetPaintingStrategy(PaintingStrategy.HO
> RIZONTAL);
> 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.HOR
> IZONTAL);
> 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);
>



Edited 1 time(s). Last edit at 01/21/2017 09:18PM by strategynode.
Re: Fun with ThinkScript
January 23, 2017 10:40PM
Harmonic trading patterns, including the Gartley, are now available for the first time on ThinkorSwim



- robert


Professional ThinkorSwim indicators for the average Joe



Edited 1 time(s). Last edit at 01/24/2017 03:07PM by robert.
Re: Fun with ThinkScript
January 25, 2017 06:33PM
Hello,

I tried to tweak Robert's Opening Range indicator posted on page 11 so that it plots the high/low of midnight ET to 9 am ET. However, I'm not a programmer and I could not get it to work. Help anyone?
Re: Fun with ThinkScript
January 26, 2017 12:13AM
max range for last x number of days ?
Re: Fun with ThinkScript
January 26, 2017 08:03AM
does anyone know how to make teh ichimoku cloud more translucent?
Re: Fun with ThinkScript
January 26, 2017 01:09PM
Robert or anyone,

I'm at a loss at how to code to calculate the 20 days average (daily in nature) of a RTH opening price (intraday data)? Any suggestion?

Thanks
Chef



Edited 2 time(s). Last edit at 01/26/2017 01:32PM by SkyChef.
Issue with local alerts.
January 27, 2017 09:44AM
Good fellow thinkscript brainiacs! I am hoping someone can guide me to what I am doing wrong. I am trying to modify the LBR 3/10 oscillator on TOS so that it gives me directional arrows as well as local sound alerts (with the chart actively loaded), when the histogram crosses from negative to positive and vice versa. After modifying the code like below, I get everything exactly as intended, but the alerts to not make an audible sound. I have checked everything, even computer volume, and it's just silent when the arrow fires, even though a sound is written in the code?
Thanks!


declare lower;

input price = close;
input calculationMode = {default Normal, Alternate};

plot FastLine;
switch (calculationMode) {
case Normal:
FastLine = Average(price, 3) - Average(price, 10);
case Alternate:
FastLine = Average(price - Average(price[3], 3), 2);
}
plot SlowLine = Average(FastLine, 16);
plot Hist = FastLine;
plot ZeroLine = 0;

plot Arrowup = Crosses(Hist,0,CrossingDirection.ABOVE);
plot Arrowdown = Crosses(Hist,0,CrossingDirection.BELOW);

FastLine.SetDefaultColor(GetColor(1));
SlowLine.SetDefaultColor(GetColor(8));
Hist.DefineColor("Positive", Color.UPTICK);
Hist.DefineColor("Negative", Color.DOWNTICK);
Hist.AssignValueColor(if Hist >= 0 then Hist.color("Positive"winking smiley else Hist.color("Negative"winking smiley);
Hist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
Hist.HideTitle();
ZeroLine.SetDefaultColor(GetColor(7));

ArrowUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

ArrowDown.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

Alert(Hist> 0 ,"Buy",Alert.ONCE,sound.ding);
Alert(Hist< 0 ,"Sell",Alert.ONCE,sound.ring);
Re: Issue with local alerts.
January 27, 2017 12:43PM
DrugDoc

Alert(Hist crosses above 0 , "Buy", Alert.ONCE, Sound.Ding);
Alert(Hist crosses below 0 , "Sell", Alert.ONCE, Sound.Ring);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
January 29, 2017 08:08AM
how do i make the cloud more translucent???

input tenkan_period = 9;
input kijun_period = 26;

plot Tenkan = (Highest(high, tenkan_period) + Lowest(low, tenkan_period)) / 2;
plot Kijun = (Highest(high, kijun_period) + Lowest(low, kijun_period)) / 2;
plot "Span A" = (Tenkan[kijun_period] + Kijun[kijun_period]) / 2;
plot "Span B" = (Highest(high[kijun_period], 2 * kijun_period) + Lowest(low[kijun_period], 2 * kijun_period)) / 2;
plot Chikou = close[-kijun_period];

Tenkan.SetDefaultColor(Color.ORANGE);
Kijun.SetDefaultColor(Color.BLUE);
"Span A".SetDefaultColor(Color.GREEN);
"Span B".SetDefaultColor(Color.RED);
Chikou.SetDefaultColor(Color.LIGHT_GRAY);

DefineGlobalColor("Bullish", Color.GREEN);
DefineGlobalColor("Bearish", Color.RED);
AddCloud("Span A", "Span B", globalColor("Bullish"winking smiley, globalColor("Bearish"winking smiley);

def Long = close > "Span B" AND "Span A" > "Span B";
def Short = close < "Span A" AND "Span A" < "Span B";

def crossUpper = (close crosses above Kijun) OR (Tenkan crosses above Kijun);
def crossLower = (close crosses below Kijun) OR (Tenkan crosses below Kijun);

def Bull_trading_signal = Long is true and crossUpper is true;
def Bear_trading_signal = Short is true and crossLower is true;

alert(Bull_trading_signal or Bear_trading_signal, if Bull_trading_signal then "Bullish Signal"
else "Bearish Signal", alert.BAR, sound.RING);

AddLabel(if Bull_trading_signal is true then yes else no, "Bullish Ichimoku signal", CreateColor(51, 204, 0));
AddLabel(if Bear_trading_signal is true then yes else no, "Bearish Ichimoku signal", color.RED);
Sorry, only registered users may post in this forum.

Click here to login