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 07, 2014 08:49AM
Quote
linter
I'd like is a study that would sound an alarm and flip a label to a new color whenever two user-defined MAs get close to each other within a used-defined % difference. let's say the 240ma and the 21ma are coming together and are now 5% apart or 4% or whatever -- sound the alarum! flip to a new label color!

input Avg1 = 21;
input Avg2 = 240;
input Proximity = 5;

def ma1 = Average(close, Avg1);
def ma2 = Average(close, Avg2);
def BoundLow = ma2 * (1 - Proximity / 100);
def BoundHi = ma2 * (1 + Proximity / 100);

def CloseProximity = Between(ma1, BoundLow, BoundHi);
def Alarm = (ma1 crosses above BoundLow) or (ma1 crosses below BoundHi);

Alert(Alarm, GetSymbol() + ":  " + Avg1 + "MA is now within " + Round(100 * (ma1 / ma2 - 1), 1) + "% of the " + Avg2 + "MA.", Alert.BAR, Sound.Ring);
AddLabel(CloseProximity, Avg1 + "MA is " + Round(100 * (ma1 / ma2 - 1), 1) + "% away from the " + Avg2 + "MA.", Color.LIME);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 07, 2014 02:48PM
oh that's fantastic, robert. if i may ask for one additional thing. is there a way to make it so i have the option of triggering the alarm and label only when the shorter MA is approaching the longer MA going down from above?

oh, and is it possible to set it so i can use fractions of a %, instead of 1% and above? the time i tried it, with .50%, it just set itself to 0.

thanks!!



Edited 1 time(s). Last edit at 06/07/2014 02:49PM by linter.
Re: Fun with ThinkScript
June 07, 2014 04:01PM
Quote
linter
oh that's fantastic, robert. if i may ask for one additional thing. is there a way to make it so i have the option of triggering the alarm and label only when the shorter MA is approaching the longer MA going down from above?

oh, and is it possible to set it so i can use fractions of a %, instead of 1% and above? the time i tried it, with .50%, it just set itself to 0.

thanks!!

You're welcome.

input Avg1 = 21;
input Avg2 = 240;
input Proximity = 0.5;
input AlertUp = yes;
input AlertDown = yes;

def ma1 = Average(close, Avg1);
def ma2 = Average(close, Avg2);
def BoundLow = ma2 * (1 - Proximity / 100);
def BoundHi = ma2 * (1 + Proximity / 100);

def CloseProximity = Between(ma1, BoundLow, BoundHi);
def Alarm = (AlertUp and ma1 crosses above BoundLow) or (AlertDown and ma1 crosses below BoundHi);

Alert(Alarm, GetSymbol() + ":  " + Avg1 + "MA is now within " + Round(100 * (ma1 / ma2 - 1), 1) + "% of the " + Avg2 + "MA.", Alert.BAR, Sound.Ring);
AddLabel(CloseProximity, Avg1 + "MA is " + Round(100 * (ma1 / ma2 - 1), 1) + "% away from the " + Avg2 + "MA.", Color.LIME);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 07, 2014 04:14PM
what a great useful study, at least for me. thanks so much for its creation and for all that you do here. smiling smiley
Re: Fun with ThinkScript
June 11, 2014 01:12PM
hello, robert: sorry to once again come begging, but is it possible to have various vertical lines drawn when the bell rings every day and set where I want em to be set? right now i'm thinking i'd like top to bottom lines drawn at the 9:30 mark, the 9:40 mark, the 11:00 mark, the 2:30 mark and the 4:00 mark. this would tell me at a glance various things i want to know, among them when rookie30's "fat zone" is in effect (which is the time b/ 9:40 and 11am, I think). thanks!



Edited 1 time(s). Last edit at 06/11/2014 04:49PM by linter.
Re: Fun with ThinkScript
June 11, 2014 02:26PM
Quote
linter
hello, robert: sorry to once again come begging, but is it possible to have various vertical lines drawn when the bell rings every day and set where I want em to be set?

Easy, peasy. Use this line of script once for as many lines as you want and change the time for each one.

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


For example.

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(1325) >= 0 and SecondsFromTime(1325) < 60, "13:25", Color.PINK);



- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 11, 2014 03:26PM
oh man you are toooooo great. thanks!
Re: Fun with ThinkScript
June 12, 2014 02:18PM
quick question ...

is there a way to extend the length of time an alert message stays on the screen? often they come and go so fast i don't have a clue what was said. personally, i'd like em to stick around til i click to dismiss em, but that's probably too much to ask for, right?

also, while i'm on the topic, does this feature exist? a place where i can see all the past alert messages that have flickered by for a stock. doubtful, but maybe ...
Re: Fun with ThinkScript
June 12, 2014 03:37PM
You can click on "messages" on the top right hand of the TOS screen to see all the past alert messages. You can also detach that message window as a separate window and keep it open on the side. Maybe Robert can post a screen image showing where it is located!
Re: Fun with ThinkScript
June 12, 2014 04:49PM
oh wow, tanman, there they all are. thanks!
Re: Fun with ThinkScript
June 13, 2014 03:28PM
hello robert!

i took your hrfp/fp indicator, the ones with the dotted lines, and tried to add arrows to it, borrowing script from an earlier post in this thread. in the original, i think you had it with one arrow color for both fp up and hrfp up and another for the 2 downs. i wanted to separate them and have four different arrows but i guess you can't have two arrowup or two arrowdn in the same script. that being the case, and since i'm only interested in the up conditions, i got rid of the downers and attempted to use the arrowdn to show hrfp up and arrowup to show fp up. the arrowup works okay but i'm not getting an arrow from arrowdn. can you help me out? appended below is my (feeble) attempt.

# FP/HRFP Identifier
# Robert Payne

def CCr = Average(close,2);
def CCg = Average(close[3],3);
def C1 = if (CCr[0] > CCg[0] AND CCr[1] <= CCg[1]) then 1 else if (CCr[0] < CCg[0] AND CCr[1] >= CCg[1]) then -1 else 0;

def RSI = RSIWilder(length = 13).RSI;
def highestRSI = Highest(RSI, 21);
def lowestRSI = Lowest(RSI, 21);
def RSIS = (RSI - lowestRSI) / (highestRSI - lowestRSI);
def Kpd = Average(RSIS, 3);
def Dpd = Average(Kpd, 5);
def C2 = if (Kpd[0] > Dpd[0] AND Kpd[1] <= Dpd[1]) then 1 else if (Kpd[0] < Dpd[0] AND Kpd[1] >= Dpd[1]) then -1 else 0;

def MACDr = ExpAverage(close,8) - ExpAverage(close,13);
def MACDg = ExpAverage(MACDr,5);
def C3 = if (MACDr[0] > MACDg[0] AND MACDr[1] <= MACDg[1]) then 1 else if (MACDr[0] < MACDg[0] AND MACDr[1] >= MACDg[1]) then -1 else 0;

def DIr = DIPlus(5);
def DIg = DIMinus(5);
def C4 = if (DIr[0] > DIg[0] AND DIr[1] <= DIg[1]) then 1 else if (DIr[0] < DIg[0] AND DIr[1] >= DIg[1]) then -1 else 0;

def Count = C1 + C2 + C3 + C4;
def Hup = if Count == 4 then 1 else 0;
def Fup = if Count == 3 then 1 else 0;
def Hdn = if Count == -4 then 1 else 0;
def Fdn = if Count == -3 then 1 else 0;

AddVerticalLine(Fup,"FP",color.light_green);
AddVerticalLine(Hup,"HRFP",color.green);
AddVerticalLine(Fdn,"FP",color.pink);
AddVerticalLine(Hdn,"HRFP",color.red);

# ================================================================
# Define Alerts
plot AlertUp = if (Fup) then 1 else 0;
AlertUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
AlertUp.SetLineWeight(4);
AlertUp.SetDefaultColor(Color.UPTICK);

plot Alertdn = if (Hup) then 1 else 0;
AlertUp.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
AlertUp.SetLineWeight(4);
AlertUp.SetDefaultColor(Color.UPTICK);
Re: Fun with ThinkScript
June 13, 2014 05:51PM
Quote
linter
hello robert!

...can you help me out?

You've done a fantastic job of piecing together what you want. You're 95% there. Just make a small tweak and you'll be done.

Re: Fun with ThinkScript
June 14, 2014 07:35AM
Quote
optiontrader101
GM Robert ,,

Is there a way to make 4 separated indicators in one script with one signal ?

but I want the signal appears only when all these 4 indicators come together in the daily chart as shown in this Daily Chart :



I will put the 4 Indicators with their codes ( I have changed some values as I want it ) :


1) MacD_dots:

# MACD Dots on Price Chart
# Shows Primary Signals only. Once a BuyAlert is issued another BuyAlert cannot be issued until after a SellAlert has been issued, etc.
# Change Displace value below to adjust where Dots are placed on the Price Chart

input displace = 0.0;

input fastLength = 2;
input slowLength = 3;
input MACDLength = 2;
input AverageType = {default EMA};

def Value = MACD(fastLength, slowLength, MACDLength, AverageType).Value;
def Avg = MACD(fastLength, slowLength, MACDLength, AverageType).Avg;

def BuyAlert = Value > Avg;
def SellAlert = Value <= Avg;

rec count=if BuyAlert==1 and count[1]==0 then 1 else if SellAlert==0 and count[1]>=1 then count[1]+1 else 0;

rec count1=if SellAlert==1 and count1[1]==0 then 1 else if BuyAlert==0 and count1[1]>=1 then count1[1]+1 else 0;

def PrimaryBuyAlert = BuyAlert==1 and count==1;
def PrimarySellAlert = SellAlert==1 and count1==1;

plot DotUp = if PrimaryBuyAlert then Low * (1 - displace) else double.nan;
DotUp.SetPaintingStrategy(PaintingStrategy.POINTS);
DotUp.SetDefaultColor(Color.BLUE);
DotUp.SetLineWeight(5);
DotUp.HideBubble();
DotUp.HideTitle();

plot DotDn = if PrimarySellAlert then High * (1 + displace) else double.nan;
DotDn.SetPaintingStrategy(PaintingStrategy.POINTS);
DotDn.SetDefaultColor(Color.YELLOW);
DotDn.SetLineWeight(5);
DotDn.HideBubble();
DotDn.HideTitle();

_____________________________________

2) StochSlow:

# StochasticSlow Package - Signals
# Apr/11/2014
# jaimepinto@rogers.com

declare upper;

input over_bought = 80;
input over_sold = 30;
input KPeriod = 2;
input DPeriod = 2;
input priceH = close;
input priceL = close;
input priceC = close;
input smoothingType = {Default EMA};

def SlowD = reference StochasticFull(over_bought,over_sold,KPeriod,DPeriod,priceH,priceL,priceC,3,smoothingType).FullD;

plot buy = if SlowD crosses above over_sold then low else Double.Nan;
buy.SetPaintingStrategy( PaintingStrategy.ARROW_UP );
buy.SetDefaultColor( Color.MAGENTA );

plot sell = if SlowD crosses below over_bought then high else Double.Nan;
sell.SetPaintingStrategy( PaintingStrategy.ARROW_DOWN );
sell.SetDefaultColor( Color.CYAN );

_____________________________________

3) CCI :

def CCI = CCI(14);
plot signalUP = if CCI crosses above -100 then low * 1.09 else Double.NaN;
signalUP.SetStyle(Curve.POINTS);
signalUP.SetLineWeight(2);
signalUP.SetDefaultColor(Color.GREEN);
plot signalDN = if CCI crosses below 100 then high * 1.09 else Double.NaN;
signalDN.SetStyle(Curve.POINTS);
signalDN.SetLineWeight(2);
signalDN.SetDefaultColor(Color.RED);

_____________________________________
4) MFI crossover :



#wizard text: MFI crosses
#wizard input: crossingType
#wizard input: threshold
#wizard text: Inputs: length:
#wizard input: length

input length = 1;
input crossingType = {default above, below};
input threshold = 20;

plot signal = crosses(MoneyFlowIndex(length=length).MoneyFlowIndex, threshold, crossingType == CrossingType.above);

signal.DefineColor("Above", GetColor(4));
signal.DefineColor("Below", GetColor(5));
signal.AssignValueColor(if crossingType == CrossingType.above then signal.color("Above"winking smiley else signal.color("Below"winking smiley);
signal.SetPaintingStrategy(if crossingType == CrossingType.above
then PaintingStrategy.BOOLEAN_ARROW_UP
else PaintingStrategy.BOOLEAN_ARROW_DOWN);


_____________________________________

5) Fisher_Transformed_Signal:

# FisherTransformSignals
# [www.thinkscripter.com]
# thinkscripter@gmail.com
# Last Update 20 June 2010

input signalOffsetFactor = 1.0;
input length = 2;
input threshold = 0.0;

def signalOffset = AvgTrueRange(high, close, low, 10) * signalOffsetFactor;

def maxHigh = Highest(high, length);
def minLow = Lowest(low, length);

rec value = if maxHigh - minLow == 0 then 0 else 0.66 * ((close - minLow) / (maxHigh - minLow) - 0.5) + 0.67 * value[1];

def truncValue = if value > 0.99 then 0.999 else if value < -0.99 then -0.999 else value;

rec FT = 0.5 * (Log((1 + truncValue) / (1 - truncValue)) + FT[1]);

def trendDown = if FT < FT[1] and FT[1] > FT[2] and FT[1] >= threshold then 1 else 0;
def trendUp = if FT > FT[1] and FT[1] < FT[2] and FT[1] <= -threshold then 1 else 0;

def cSignal = if trendUp then low - signalOffset else if trendDown then high + signalOffset else Double.NaN;

plot signalHighlight = cSignal;
signalHighlight.AssignValueColor(if trendUp then Color.GREEN else Color.RED);
signalHighlight.SetLineWeight(1);
signalHighlight.SetStyle(Curve.POINTS);
signalHighlight.SetPaintingStrategy(PaintingStrategy.LINE_VS_TRIANGLES);

plot signal = cSignal;
signal.SetDefaultColor(Color.WHITE);
signal.SetLineWeight(4);
signal.SetStyle(Curve.POINTS);
signal.SetPaintingStrategy(PaintingStrategy.LINE_VS_SQUARES);

alert(trendup or trendDown, if trendUp then "Long" else "Short", Alert.bar, sound.bell);


_______________________________

If it is possible I will be really happy and appreciate your help so much , because so many indicators in the charts make a mess to me smiling smiley

I have tested theses indicators together and gave me a true signal and stocks move after 3 to 5 days , I hope you test too and give me your advice that I really look for ..

thanks for every thing smiling smiley

optiontrader,

Three times in your message you asked if I could combine four (4) different indicators. However, you posted five (5) indicators. Did you want all five combined, or only four of them?

I combined all five. Check this against what you are already using.

# MACD
def Value = MACD(2, 3, 2, "EMA" ).Value;
def Avg = MACD(2, 3, 2, "EMA" ).Avg;
def MACDup = Value > Avg;
def MACDdn = Value <= Avg;

# StochSlow
def SlowD = StochasticFull(80, 30, 2, 2, close, close, close, 3, "EMA" ).FullD;
def SlowDup = SlowD crosses above 30;
def SlowDdn = SlowD crosses below 80;

# CCI
def CCI = CCI(14);
def CCIup = CCI crosses above -100;
def CCIdn = CCI crosses below 100;

# MFI
def MFIup = MoneyFlowIndex(length = 1).MoneyFlowIndex crosses above 20;
def MFIdn = MoneyFlowIndex(length = 1).MoneyFlowIndex crosses below 80;

# Fish
def maxHigh = Highest(high, 2);
def minLow = Lowest(low, 2);
def fishValue = if maxHigh - minLow == 0 then 0 else 0.66 * ((close - minLow) / (maxHigh - minLow) - 0.5) + 0.67 * fishValue[1];
def truncValue = if fishValue > 0.99 then 0.999 else if fishValue < -0.99 then -0.999 else fishValue;
def FT = 0.5 * (Log((1 + truncValue) / (1 - truncValue)) + FT[1]);
def FTup = FT > FT[1] and FT[1] < FT[2] and FT[1] <= 0;
def FTdn = FT < FT[1] and FT[1] > FT[2] and FT[1] >= 0;

# Signals
plot signalUP = MACDup and SlowDup and CCIup and MFIup and FTup;
     signalUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
     signalUP.SetLineWeight(5);
     signalUP.SetDefaultColor(Color.LIGHT_GREEN);
plot signalDN = MACDdn and SlowDdn and CCIdn and MFIdn and FTdn;
     signalDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
     signalDN.SetLineWeight(5);
     signalDN.SetDefaultColor(Color.PINK);
Re: Fun with ThinkScript
June 14, 2014 10:59AM
Thank you very much Robert , That was really Great ..

I have changed some values and deleted the FISHER indicator :


# macd
def Value = MACD(2, 5, 2, "EMA" ).Value;
def Avg = MACD(2, 5, 2, "EMA" ).Avg;
def MACDup = Value > Avg;
def MACDdn = Value <= Avg;

# stochslow
def SlowD = StochasticFull(80, 30, 2, 2, hlc3, hlc3, hlc3, 3, "EMA" ).FullD;
def SlowDup = SlowD crosses above 30;
def SlowDdn = SlowD crosses below 80;

# CCI
def CCI = CCI(7);
def CCIup = CCI crosses above -100;
def CCIdn = CCI crosses below 100;

# MFI
def MFIup = MoneyFlowIndex(length = 1).MoneyFlowIndex crosses above 20;
def MFIdn = MoneyFlowIndex(length = 1).MoneyFlowIndex crosses below 80;


# Signals
plot signalUP = MACDup and SlowDup and CCIup and MFIup ;
signalUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signalUP.SetLineWeight(5);
signalUP.SetDefaultColor(Color.LIGHT_GREEN);
plot signalDN = MACDdn and SlowDdn and CCIdn and MFIdn ;
signalDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
signalDN.SetLineWeight(5);
signalDN.SetDefaultColor(Color.PINK);

I tried to add " RelativeMomentumIndex" indicator to that script instead of FISHER indicator with this value but I couldn't confused smiley :


# RelativeMomentumIndex_UpperChart
declare upper;
input length = 5;
input momentum = 5;
input levelOB = 75;
input levelOS = 25;
input offset = 50;
assert(momentum > 0, "'momentum' must be positive: " + momentum);
def emaInc = ExpAverage(Max(close - close[momentum], 0), length);
def emaDec = ExpAverage(Max(close[momentum] - close, 0), length);
def RMI = if emaDec == 0 then 0 else 100 - 100 / (1 + emaInc / emaDec);
plot OverBought = if RMI >= levelOB then high + offset * tickSize() else double.nan;
plot OverSold = if RMI <= levelOS then low - offset * tickSize() else double.nan;
OverBought.SetDefaultColor(GetColor(5));
OverBought.SetPaintingStrategy(PaintingStrategy.POINTS);
OverBought.SetLineWeight(2);
OverSold.SetDefaultColor(GetColor(6));
OverSold.SetPaintingStrategy(PaintingStrategy.POINTS);
OverSold.SetLineWeight(2);



Edited 3 time(s). Last edit at 06/14/2014 11:22AM by optiontrader101.
Re: Fun with ThinkScript
June 15, 2014 01:08AM
Quote
optiontrader101
I tried to add " RelativeMomentumIndex" indicator to that script instead of FISHER indicator with this value but I couldn't confused smiley

# macd
def Value = MACD(2, 5, 2, "EMA" ).Value;
def Avg = MACD(2, 5, 2, "EMA" ).Avg;
def MACDup = Value > Avg;
def MACDdn = Value <= Avg;

# stochslow
def SlowD = StochasticFull(80, 30, 2, 2, hlc3, hlc3, hlc3, 3, "EMA" ).FullD;
def SlowDup = SlowD crosses above 30;
def SlowDdn = SlowD crosses below 80;

# CCI
def CCI = CCI(7);
def CCIup = CCI crosses above -100;
def CCIdn = CCI crosses below 100;

# MFI
def MFIup = MoneyFlowIndex(length = 1).MoneyFlowIndex crosses above 20;
def MFIdn = MoneyFlowIndex(length = 1).MoneyFlowIndex crosses below 80;

# RMI
def emaInc = ExpAverage(Max(close - close[5], 0), 5);
def emaDec = ExpAverage(Max(close[5] - close, 0), 5);
def RMI = if emaDec == 0 then 0 else 100 - 100 / (1 + emaInc / emaDec);
def RMIob = RMI >= 75;
def RMIos = RMI <= 25;

# Signals
plot signalUP = MACDup and SlowDup and CCIup and MFIup and RMIos;
     signalUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
     signalUP.SetLineWeight(3);
     signalUP.SetDefaultColor(Color.LIGHT_GREEN);
plot signalDN = MACDdn and SlowDdn and CCIdn and MFIdn and RMIob;
     signalDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
     signalDN.SetLineWeight(3);
     signalDN.SetDefaultColor(Color.PINK);
Re: Fun with ThinkScript
June 15, 2014 11:04AM
Robert ,

You really deserve all the expressions of thanks and praise for all the effort that you do in this forum
All thanks to you,

I will try to make this signal more accurate with another indicators , thanks again smiling smiley




Re: Fun with ThinkScript
June 16, 2014 08:57AM
Auto Trend Line :



###############################
#### Trend Line Plot       ####
###############################
input TrendLineLength1 = 50;
input TrendLineLength2 = 30;
input TrendLineLength3 = 10;

def Inertia1 = InertiaAll(close, TrendLineLength1);
def Inertia2 = InertiaAll(close, TrendLineLength2);
def Inertia3 = InertiaAll(close, TrendLineLength3);

def TL_Bull1 = Inertia1 - (HighestAll(AbsValue(Inertia1 - close)) * 0.8);
def TL_Bear1 = Inertia1 + (HighestAll(AbsValue(Inertia1 - close)) * 0.8);
def slope1a = TL_Bull1 > TL_Bull1[1];
def slope1b = TL_Bear1 > TL_Bear1[1];

def TL_Bull2 = Inertia2 - (HighestAll(AbsValue(Inertia2 - close)) * 0.8);
def TL_Bear2 = Inertia2 + (HighestAll(AbsValue(Inertia2 - close)) * 0.8);
def slope2a = TL_Bull2 > TL_Bull2[1];
def slope2b = TL_Bear2 > TL_Bear2[1];

def TL_Bull3 = Inertia3 - (HighestAll(AbsValue(Inertia3 - close)) * 0.8);
def TL_Bear3 = Inertia3 + (HighestAll(AbsValue(Inertia3 - close)) * 0.8);
def slope3a = TL_Bull3 > TL_Bull3[1];
def slope3b = TL_Bear3 > TL_Bear3[1];

#### Long length ####
plot TrendLine1a = if slope1a > 0 then TL_Bull1 else TL_Bear1;
TrendLine1a.SetStyle(curve.long_dash);
TrendLine1a.SetLineWeight(1);
TrendLine1a.assignvaluecolor(if slope1a and IsAscending(close, 10) then color.BLACK else if slope1a then color.BLACK else if !IsAscending(close, 10)then color.BLACK else color.BLACK);

plot TrendLine1b = if slope1b > 0 then TL_Bear1 else TL_Bull1;
TrendLine1b.SetStyle(curve.long_dash);
TrendLine1b.SetLineWeight(1);
TrendLine1b.assignvaluecolor(if slope1b and IsAscending(close, 10) then color.BLACK else if slope1b then color.BLACK else if !IsAscending(close, 10)then color.BLACK else color.BLACK);

#### Medium length ####
plot TrendLine2a = if slope2a > 0 then TL_Bull2 else TL_Bear2;
TrendLine2a.SetStyle(curve.medium_dash);
TrendLine2a.SetLineWeight(2);
TrendLine2a.assignvaluecolor(if slope2a and IsAscending(close, 10) then color.LIGHT_GREEN else if slope2a then color.DARK_GREEN else if !IsAscending(close, 10)then color.LIGHT_RED else color.DARK_RED);

plot TrendLine2b = if slope2b > 0 then TL_Bear2 else TL_Bull2;
TrendLine2b.SetStyle(curve.medium_dash);
TrendLine2b.SetLineWeight(2);
TrendLine2b.assignvaluecolor(if slope2b and IsAscending(close, 10) then color.LIGHT_GREEN else if slope2b then color.DARK_GREEN else if !IsAscending(close, 10)then color.LIGHT_RED else color.DARK_RED);

#### Short length ####
plot TrendLine3a = if slope3a > 0 then TL_Bull3 else TL_Bear3;
TrendLine3a.SetStyle(curve.short_dash);
TrendLine3a.SetLineWeight(3);
TrendLine3a.assignvaluecolor(if slope3a and IsAscending(close, 10) then color.LIGHT_GREEN else if slope3a then color.DARK_GREEN else if !IsAscending(close, 10)then color.LIGHT_RED else color.DARK_RED);

plot TrendLine3b = if slope3b > 0 then TL_Bear3 else TL_Bull3;
TrendLine3b.SetStyle(curve.short_dash);
TrendLine3b.SetLineWeight(3);
TrendLine3b.assignvaluecolor(if slope3b and IsAscending(close, 10) then color.LIGHT_GREEN else if slope3b then color.DARK_GREEN else if !IsAscending(close, 10)then color.LIGHT_RED else color.DARK_RED);


Re: Fun with ThinkScript
June 16, 2014 10:13AM
Quote
optiontrader101
Auto Trend Line :

[code in post above]

optiontrader101,

That's a pretty slick bit of code. Thanks for sharing it. I may not use it on my charts, but if I can deconstruct it and figure out how it works, maybe I can pick up some new techniques for future projects.

If anyone is curious what it does, it looks like it's plotting short, medium, and long channels.

Re: Fun with ThinkScript
June 17, 2014 04:01AM
I've been trading intraday momentum / breakout moves for the past several months; so I really appreciated the very detailed post that tanman made the other day describing how he uses ATR as a filter to avoid false breakouts.

I recommend reading his post here.

I wrote the following script to go along with the breakout rules that he detailed. (I love rules grinning smiley)

This script will calculate and plot the stop loss and first profit target when the stock breaks out above the previous day's high or opening range high (whichever is higher) or vice versa to the low-side. This may be used with a 2 min chart as he described in his original post for a more aggressive entry point, or, as he recommended to me, on a 5 min chart for a more conservative entry point.



red -- stop loss
white -- entry point
green -- first profit target for scaling out
yellow -- opening range
orange -- ATR breakout confirmation level

[not shown in picture above]
cyan -- yesterday's high
pink -- yesterday's low

script OpenRange {
    input ORtime = 5;

    def FirstBar = GetDay() != GetDay()[1];
    def RangeTime = SecondsFromTime(0930) >= 0 and SecondsFromTime(0930) < 60 * ORtime;
    def Rhigh = if FirstBar then high else if RangeTime and high > Rhigh[1] then high else Rhigh[1];
    def Rlow = if FirstBar then low else if RangeTime and low < Rlow[1] then low else Rlow[1];

    plot h = if RangeTime then Double.NaN else Rhigh;
    plot l = if RangeTime then Double.NaN else Rlow;
}

def first30 = SecondsFromTime(0930) >= 0 and SecondsTillTime(1000) >= 0;
def today = GetLastDay() == GetDay();
def ATR = AvgTrueRange(high, close, low, 10);

plot yHigh = if !today then Double.NaN else high(period = "day" )[1];
     yHigh.SetDefaultColor(Color.CYAN);
plot yLow = if !today then Double.NaN else low(period = "day" )[1];
     yLow.SetDefaultColor(Color.PINK);

plot h5 = if !today then Double.NaN else if !first30 then Double.NaN else OpenRange(5).h;
     h5.SetDefaultColor(Color.YELLOW);
plot l5 = if !today then Double.NaN else if !first30 then Double.NaN else OpenRange(5).l;
     l5.SetDefaultColor(Color.YELLOW);
plot h30 = if !today then Double.NaN else OpenRange(30).h;
     h30.SetDefaultColor(Color.YELLOW);
plot l30 = if !today then Double.NaN else OpenRange(30).l;
     l30.SetDefaultColor(Color.YELLOW);

def lowConf = if first30 then Min(yLow, l5) - ATR else Min(yLow, l30) - ATR;
def highConf = if first30 then Max(yHigh, h5) + ATR else Max(yHigh, h30) + ATR;

plot lc1 = if first30 then lowConf else Double.NaN;
     lc1.SetDefaultColor(Color.ORANGE);
plot lc2 = if !first30 then lowConf else Double.NaN;
     lc2.SetDefaultColor(Color.ORANGE);
plot hc1 = if first30 then highConf else Double.NaN;
     hc1.SetDefaultColor(Color.ORANGE);
plot hc2 = if !first30 then highConf else Double.NaN;
     hc2.SetDefaultColor(Color.ORANGE);

def decisionL = if close > lowConf then Double.NaN else if close crosses below lowConf then low else decisionL[1];
def decisionH = if close < highConf then Double.NaN else if close crosses above highConf then high else decisionH[1];

plot dL = if !today then Double.NaN else decisionL;
     dL.SetDefaultColor(Color.WHITE);
plot dH = if !today then Double.NaN else decisionH;
     dH.SetDefaultColor(Color.WHITE);

def TL = CompoundValue(1, if IsNaN(dL) then Double.NaN else if !IsNaN(TL[1]) then TL[1] else if close crosses below dL then dL - 2 * ATR else Double.NaN, Double.NaN);
def SL = CompoundValue(1, if IsNaN(dL) then Double.NaN else if !IsNaN(SL[1]) then SL[1] else if close crosses below dL then dL + 2 * ATR else Double.NaN, Double.NaN);

plot Target1Low = if !today then Double.NaN else TL;
     Target1Low.SetDefaultColor(Color.GREEN);
     Target1Low.SetStyle(Curve.SHORT_DASH);
plot Stop1Low = if !today then Double.NaN else SL;
     Stop1Low.SetDefaultColor(Color.RED);
     Stop1Low.SetLineWeight(2);

AddChartBubble(IsNaN(TL[1]) and !IsNaN(TL), TL, "Target 1\n" + Round(TL, 2), Color.GREEN, no);
AddChartBubble(IsNaN(SL[1]) and !IsNaN(SL), SL, "Stop\n" + Round(SL, 2), Color.RED);

def TH = CompoundValue(1, if IsNaN(dH) then Double.NaN else if !IsNaN(TH[1]) then TH[1] else if close crosses above dH then dH + 2 * ATR else Double.NaN, Double.NaN);
def SH = CompoundValue(1, if IsNaN(dH) then Double.NaN else if !IsNaN(SH[1]) then SH[1] else if close crosses above dH then dH - 2 * ATR else Double.NaN, Double.NaN);

plot Target1High = if !today then Double.NaN else TH;
     Target1High.SetDefaultColor(Color.GREEN);
     Target1High.SetStyle(Curve.SHORT_DASH);
plot Stop1High = if !today then Double.NaN else SH;
     Stop1High.SetDefaultColor(Color.RED);
     Stop1High.SetLineWeight(2);

AddChartBubble(IsNaN(TH[1]) and !IsNaN(TH), TH, "Target 1\n" + Round(TH, 2), Color.GREEN);
AddChartBubble(IsNaN(SH[1]) and !IsNaN(SH), SH, "Stop\n" + Round(SH, 2), Color.RED, no);

- robert


Professional ThinkorSwim indicators for the average Joe
Re: Fun with ThinkScript
June 17, 2014 04:43AM
oh, wow, that's just great, and i bet tanman is going to love you for it.
one thing you might add is an alert message and alarm when the white-line buy is triggered.
and yet another edit for yet another suggestions ...
how about, in the stop loss bubble, in addition to the price level add the % decline number from entry price. that'd not only tell you the risk but also the potential reward going the other way.
thanks again!



Edited 3 time(s). Last edit at 06/17/2014 05:21AM by linter.
Re: Fun with ThinkScript
June 17, 2014 12:51PM
Robert, This is amazing. Thank you very much for this indicator, it visually plots everything I've been doing in my head so far smiling smiley A bubble to add might be the entry price next to the white line.

Linter, my suggestion is that the alert and alarm would be better when price closes beyond the ATR line or even beyond the range lines, because that will give you some time to check if other conditions are ok such as trend and direction of the broad market, trend of stock, price pattern etc. before you enter the trade at the white line. It can also give you time to place a buy stop order (for long) or sell stop order (for short) at the white line price, if the next candle opens before the white line, like in Robert's example price chart above. Otherwise if the alert is at the white line it might be a bit too late to confirm everything else and enter the trade at the right price. I personally prefer alert at a close beyond the range lines and before the ATR line because that gives me ample time to check other conditions and the stock price pattern, ascent etc. and then I watch and wait for the white line cross for the final pounce!

The percentage decline from entry price might not be that valuable because the actual risk percentage depends on how many shares you trade and your account equity. For example stop loss might be 50 cents which might be just 0.5% from entry price, but if you trade 2000 shares, the actual loss would be $1000 and if account equity is only $10,000 that would be a 10% loss! On the same 0.5% stop loss if you trade only 400 shares, the actual loss would be $200 which would be a 2% loss. So the 0.5% stop loss figure would be meaningless for the purpose of calculating trade risk.

Tan



Edited 3 time(s). Last edit at 06/17/2014 12:59PM by tanman.
Re: Fun with ThinkScript
June 18, 2014 07:50AM
tanman: you're pouncing suggestion makes perfect sense. yes, an alert of some kind should come a bit earlier. how about it, robert?

agreed on the % stuff too. thanks.
Re: Fun with ThinkScript
June 18, 2014 08:27AM
Linter and Tanman,

Add this to the bottom of the script and see how it works for you. The market is about to open, so I've not yet had a chance to test this. I'll revisit this thread later this afternoon to see if this worked for you or if you need it changed.

def alertup = close[1] crosses above hc1 or close[1] crosses above hc2;
def alertdn = close[1] crosses below lc1 or close[1] crosses below lc2;
alert(alertup, getsymbol() + " UP", alert.bar, sound.bell);
alert(alertdn, getsymbol() + " DOWN", alert.bar, sound.bell);



Edited 1 time(s). Last edit at 06/18/2014 08:50AM by robert.
Re: Fun with ThinkScript
June 18, 2014 10:31AM
thanks, i'll check it out.

meanwhile, just to keep you busy, because i know you aren't busy enough ;-), 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. anyway, the scan would be for the following:

stocks whose average prices -- (H+L)/2 + L -- for the past two (or possibly three) days are within a certain used-defined range (both % and $ would be nice) from each other. iow, let's say i wanted to find all stocks where yesterday's average price equaled the average price of the stock from the day before yesterday -- it would scan for that. or maybe it could scan for all stocks with average prices no more than, say, .5% (.005) from each other. am i making any sense?

let me see if i can find a picture of what i want ... will post it if i can.

edit: well, for some reason i can no longer find the print icon. i think it used to be in the upper right hand corner between Symbols and Reset. not there now, at least for me. where'd it go?



Edited 1 time(s). Last edit at 06/18/2014 10:43AM by linter.
Re: Fun with ThinkScript
June 18, 2014 08:24PM
Quote
linter
well, for some reason i can no longer find the print icon. i think it used to be in the upper right hand corner between Symbols and Reset. not there now, at least for me. where'd it go?

If you are trying to get a screenshot of your workspace, try one of the following:

1) on a Mac pressing [shift] + [command] + [3] will save a screenshot to your desktop.
2) on Windows then take a look at this tutorial. [www.wikihow.com]

Quote
linter
am i making any sense?

No. I'm not understanding what you mean. When you say, "stocks whose average prices -- (H+L)/2 + L -- for the past two (or possibly three) days are within a certain used-defined range (both % and $ would be nice) from each other." Do you mean that you want today's (H+L)/2 to be within x% of yesterday's low price?
Re: Fun with ThinkScript
June 19, 2014 09:17AM
okay, this ought to explain it. here's the code that i want to make a scan out of, per my ideas above:

#Plot pivot

plot Pivot = (high(period = "day" )[1] + low(period = "day" )[1]) / 2;
Pivot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
Pivot.SetDefaultColor(Color.ORANGE);
Pivot.SetLineWeight(2);

here are two pix of what the code produces





the yellow line at day two is from the plot Pivot formula above and uses the day 1 high and low
the yellow line at day three is from the plot Pivot formula above and uses the day 2 high and low.

the lines at days two and three appear on days two and three. in other words, the line at day 3 is calculated and shows up at the end of day two.

does this make things any clearer? and so what i'm looking to do is scan for days when, say, the lines at day 2 and day 3 are extremely close together. possible?
Re: Fun with ThinkScript
June 19, 2014 03:37PM
Quote
linter
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.



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, "Is today's Pivot 'close' to yesterday's Pivot?"

Step 1. What is a Pivot?

def Pivot = (high(period = "day" )[1] + low(period = "day" )) / 2;

Step 2. What does 'close' mean?

You stated that you want one Pivot to be within x% of the prior Pivot; or, as an alternative, within a dollar amount.

a) define 'close' to be today's Pivot falls within the range of yesterday's Pivot + / - x%

def Percent = 0.5;
def inRange = Pivot between (Pivot[1] * (1 - Percent / 100)) and (Pivot[1] * (1 + Percent / 100));

b) define 'close' to be today's Pivot falls within the range of yesterday's Pivot + / - x dollars

def DollarAmount = 0.75;
def inRange = Pivot between (Pivot[1] - DollarAmount) and (Pivot[1] + DollarAmount);

Step 3. Answer the question, "Is today's Pivot 'close' to yesterday's Pivot?"

The "question" is in the form of one defined plot which evaluates as either true (yes) or false (no).

plot signal = inRange;

The variable 'inRange' was previously defined to be true only when today's Pivot falls within the specified range of yesterday's Pivot. So, by setting 'signal' = to 'inRange' it will evaluate as either yes or no when the desired condition is met.

Putting it together:

If you want to scan when 'close' is defined using a given percentage, then use this code in your scan and replace "Percent = 0.5" with your desired percentage.
def Pivot = (high(period = "day" )[1] + low(period = "day" )) / 2;
def Percent = 0.5; 
def inRange = Pivot between (Pivot[1] * (1 - Percent / 100)) and (Pivot[1] * (1 + Percent / 100));
plot signal = inRange;

If you want to scan when 'close' is defined using a given dollar amount, then use this code in your scan and replace "DollarAmount = 0.75" with your desired value.
def Pivot = (high(period = "day" )[1] + low(period = "day" )) / 2;
def DollarAmount = 0.75;
def inRange = Pivot between (Pivot[1] - DollarAmount) and (Pivot[1] + DollarAmount);
plot signal = inRange;

Hope that helps.

edit: oops. In the final example, (Pivot + DollarAmount) should have been (Pivot[1] + DollarAmount). Sorry for the typing error. I've been up since 3 a.m. and my eyes are starting to cross. smiling smiley



Edited 4 time(s). Last edit at 08/28/2014 06:20AM by robert.
Re: Fun with ThinkScript
June 19, 2014 04:16PM
good golly you make it seem so easy. well, not really, at least not to my kind of brain. but at least now i see some of the logic behind it. maybe with time ...

thanks again!
Re: Fun with ThinkScript
June 19, 2014 06:21PM
Hi Robert,

The entry/stop loss/target1 script has a couple of problems.

1. It calculates and plots the open range not from market open but from the first candle after 4 am! So the open range lines are inaccurate. For example, run it on AAPL, BIDU and AMZN from today and see the open range plotted.

2. It starts plotting the stop loss line and target 1 line only after a candle closes beyond the white line and doesn't plot it when the candle pushes through the white line and then closes before it. The trade has to be entered as soon as the white line is hit, not when candle closes beyond white line. So the stop loss and target 1 should be plotted as soon as candle touches the white line, even if it retraces back after touching it, because trade has already been executed.

Tan

PS I just saw your post above after posting this. Wow you need to get some sleep. This can wait until the weekend. No hurry!



Edited 1 time(s). Last edit at 06/19/2014 06:23PM by tanman.
Re: Fun with ThinkScript
June 19, 2014 07:34PM
Quote
tanman
The entry/stop loss/target1 script has a couple of problems.

1. It calculates and plots the open range not from market open but from the first candle after 4 am! So the open range lines are inaccurate. For example, run it on AAPL, BIDU and AMZN from today and see the open range plotted.

It sounds like you have your charts set to show the extended sessions. I have them disabled so I've not run into that issue.

Replace the upper portion of the script with this:

script OpenRange {
    input ORtime = 5;

    def FirstBar = secondsfromtime(0930) >= 0 and secondsfromtime(0930) < 60;
    def RangeTime = SecondsFromTime(0930) >= 0 and SecondsFromTime(0930) < 60 * ORtime;
    def Rhigh = if FirstBar then high else if RangeTime and high > Rhigh[1] then high else Rhigh[1];
    def Rlow = if FirstBar then low else if RangeTime and low < Rlow[1] then low else Rlow[1];

    plot h = if RangeTime or secondstilltime(0930) > 0 then Double.NaN else Rhigh;
    plot l = if RangeTime or secondstilltime(0930) > 0then Double.NaN else Rlow;
}

Quote
tanman
2. It starts plotting the stop loss line and target 1 line only after a candle closes beyond the white line and doesn't plot it when the candle pushes through the white line and then closes before it.

I did that on purpose. I wanted confirmation of the breakout. I figured if it can't close above that white line, then I don't want to be in that trade. The target and stop loss values will be the same either way because they are based on the entry price (white line) +/- 2 * ATR. However, if you want them plotted sooner, then replace "def TL", "def SL", "def TH", and "def SH" with the appropriate values below.

def TL = CompoundValue(1, if IsNaN(dL) then Double.NaN else if !IsNaN(TL[1]) then TL[1] else if low crosses below dL then dL - 2 * ATR else Double.NaN, Double.NaN);
def SL = CompoundValue(1, if IsNaN(dL) then Double.NaN else if !IsNaN(SL[1]) then SL[1] else if low crosses below dL then dL + 2 * ATR else Double.NaN, Double.NaN);


def TH = CompoundValue(1, if IsNaN(dH) then Double.NaN else if !IsNaN(TH[1]) then TH[1] else if high crosses above dH then dH + 2 * ATR else Double.NaN, Double.NaN);
def SH = CompoundValue(1, if IsNaN(dH) then Double.NaN else if !IsNaN(SH[1]) then SH[1] else if high crosses above dH then dH - 2 * ATR else Double.NaN, Double.NaN);



Edited 1 time(s). Last edit at 06/19/2014 07:48PM by robert.
Sorry, only registered users may post in this forum.

Click here to login