Repaints ZigZag High Low Stats for ThinkorSwim

Repaints
Hi. Im new to this site and new to trading. I didn't have an arrow up or down. I just went thru this post and copy paste this code and added to the script . Now I have arrow.

Code:
plot HighArrow = swingHigh;
HighArrow.SetLineWeight(5);
HighArrow.SetDefaultColor(Color.RED);
HighArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

plot LowArrow = swingLow;
LowArrow.SetLineWeight(5);
LowArrow.SetDefaultColor(Color.GREEN);
LowArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
 
Extracted idea from RDMercer's post #369 of a variant of a massive Zig Zag High Low Supply Demand study that comprises many different components

https://usethinkscript.com/threads/...-signals-for-thinkorswim.183/page-19#post-369
I heavily modified, cleaned up and extracted some interesting Zig Zag statistical information resulting in this study called Zig Zag High Low Stats. It displays the following information represented via bubbles at each of the Zig zag turning points

Label for Confirmed/Unconfirmed Status of Current Zigzag
Price Change between Zigzags
Price at Zigzag High/Low
Bar Count between Zigzags
Volume at Zigzag Reversals

Here's the study - you might like to load this study on a Daily chart of AAPL, AMZN or your favorite ticker
You can turn off any information you don't want via the user interface

Code:
# ZigZag High Low Stats
# tomsk
# 11.16.2019

# V1.0 - 11.16.2019 - tomsk - Initial release of ZigZag High Low Stats

# Extracted idea from RDMercer's post #369 of a variant of a massive
# Zig Zag High Low Supply Demand study that comprises many different
# components
#
# https://usethinkscript.com/threads/trend-reversal-indicator-with-signals-for-thinkorswim.183/page-19#post-369
#
# I heavily modified, cleaned up and extracted some interesting Zig Zag statistical information resulting in this study called Zig Zag High
# Low Stats. It displays the following information represented via bubbles at each of the Zig zag turning points
#
# Label for Confirmed/Unconfirmed Status of Current Zigzag
# Price Change between Zigzags
# Price at Zigzag High/Low
# Bar Count between Zigzags
# Volume at Zigzag Reversals

input showBubblesChange = no;   # Price Change between Zigzags
input showBubblesPrice = no;    # Price at Zigzag High/Low
input showBubblesBarCount = no; # Bar Count between Zigzags
input showBubblesVolume = no;   # Volume at Zigzag Reversals

input BubbleOffset = .0005;
input PercentAmount = .01;
input RevAmount = .05;
input ATRreversal = 3.0;
input ATRlength = 5;

def zz = ZigZagHighLow("price h" = high, "price l" = low, "percentage reversal" = PercentAmount,
"absolute reversal" = RevAmount, "atr length" = ATRlength, "atr reversal" = ATRreversal);

def ReversalAmount = if (close * PercentAmount / 100) > Max(RevAmount < ATRreversal * reference ATR(ATRlength), RevAmount)
                     then (close * PercentAmount / 100)
                     else if RevAmount < ATRreversal * reference ATR(ATRlength)
                          then ATRreversal * reference ATR(ATRlength)
                          else RevAmount;
# Zig Zag Specific Data

def zzSave = if !IsNaN(zz) then zz else GetValue(zzSave, 1);
def chg = (if zzSave == high then high else low) - GetValue(zzSave, 1);
def isUp = chg >= 0;
def isConf = AbsValue(chg) >= ReversalAmount or (IsNaN(GetValue(zz, 1)) and GetValue(isConf, 1));

# Price Change Specific Data

def xxHigh = if zzSave == high then high else xxHigh[1];
def chgHigh = high - xxHigh[1];
def xxLow = if zzSave == low then low else xxLow[1];
def chgLow = low - xxLow[1];

# Bar Count Specific Data

def zzCount = if zzSave[1] != zzSave then 1 else if zzSave[1] == zzSave then zzCount[1] + 1 else 0;
def zzCountHiLo = if zzCountHiLo[1] == 0 and (zzSave == high or zzSave == low) then 1
                  else if zzSave == high or zzSave == low then zzCountHiLo[1] + 1
                  else zzCountHiLo[1];
def zzHiLo = if zzSave == high or zzSave == low then zzCountHiLo else zzCountHiLo + 1;
def zzCountHigh = if zzSave == high then zzCount[1] else Double.NaN;
def zzCountLow  = if zzSave == low then zzCount[1] else Double.NaN;

# Volume Specific Data

def vol = if BarNumber() == 0 then 0 else volume + vol[1];
def vol1 = if BarNumber() == 1 then volume else vol1[1];
def xxVol = if zzSave == high or zzSave == low then TotalSum(volume) else xxVol[1];
def chgVol =  if xxvol - xxVol[1] + vol1 == vol then vol else xxVol - xxVol[1];

# Zigzag Status Label

AddLabel(BarNumber() != 1, (if isConf then "Confirmed " else "Unconfirmed ") + "ZigZag: " + chg + "  ATRrev " + Round(reference ATR(ATRlength) * ATRreversal, 2) + "  RevAmt " + Round(ReversalAmount, 2), if !isConf then Color.Dark_Orange else if isUp then Color.Green else Color.Red);

# Zig Zag Plot

plot zzp = if isUp <= 1 then zz else Double.NaN;
zzp.AssignValueColor(if isUp then Color.Green else if !isUp then Color.Red else Color.Dark_Orange);
zzp.SetStyle(Curve.FIRM);
zzp.EnableApproximation();
zzp.HideBubble();

# Bubbles

# Price Change between Zigzags

AddChartBubble(showBubblesChange and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + BubbleOffset) else low * (1 - BubbleOffset), "$" + Round(chg, 2), if isUp and chgHigh > 0 then Color.Green else if isUp and chgHigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chgLow > 0 then Color.Green else if !isUp and chgLow < 0 then Color.Red else Color.Yellow, isUp);

# Price at Zigzag High/Low

AddChartBubble(showBubblesPrice and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + BubbleOffset) else low * (1 - BubbleOffset), if isUp then "$" + high else "$" + low, if isUp and chgHigh > 0 then Color.Green else if isUp and chgHigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chgLow > 0 then Color.Green else if !isUp and chgLow < 0 then Color.Red else Color.Yellow, isUp);

# Bar Count between Zigzags

AddChartBubble(showBubblesBarCount and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + BubbleOffset) else low * (1 - BubbleOffset), if zzSave == high then zzCountHigh else zzCountLow, if isUp and chgHigh > 0 then Color.Green else if isUp and chgHigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chgLow > 0 then Color.Green else if !isUp and chgLow < 0 then Color.Red else Color.Yellow, if isUp then yes else no);

# Volume at Zigzag Reversals

AddChartBubble(showBubblesVolume and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + bubbleoffset) else low * (1 - bubbleoffset), chgVol, if isUp and chghigh > 0 then Color.Green else if isUp and chghigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chglow > 0 then Color.Green else if !isUp and chglow < 0 then Color.Red else Color.Yellow, if isUp then yes else no);

# End ZigZag High Low Stats
I really like this study. Great work. Does it repaint? or would you wait until candle closes for confirmation.
Thanks.
 
Here is my chart/This is my gun/FullMetalJacket......it is as clean as I can keep it,....I have many indicators in the studies, most are necessary labels. Savage was kept because I like the bit of assistance close to turns as well as Hi_Low. I draw trendlines by hand, but thought the IronrodSMI was an enhancement,...lines up well with the repainted reversal arrow......but is for a price reader,.. a candle lover, tea leaves,...they tell you all you need to know. I like simple/ KISS
https://tos.mx/ztmJu7z
 
@Thomas
I enjoy this forum because contributors like you share their setups.

You use this ZigZag, Trend Reversal, and Swing High/Low. They are possibly the three most viewed indicators on the forum. They are all repainting indicators.

I am trying to understand how people use repainting indicators. A trader using repainting Hurst Bands told me they only use the current timeframe and therefore it doesn't matter that the history repaints. But the current candle repaints also.

ZigZag, Trend Reversal, and Swing High/Low all are designed to find a stock's lowest point thus signaling a good entry point but then the stock drops lower and it erases all those signals and says "oops didn't mean it." Not so good for you if you just bought in and the stock drops like a rock.

I am not being critical. I want to understand. You have been trading for many years, could you tell us how you feel these indicators can be used reliably?
 
@Thomas
I enjoy this forum because contributors like you share their setups.

You use this ZigZag, Trend Reversal, and Swing High/Low. They are possibly the three most viewed indicators on the forum. They are all repainting indicators.

I am trying to understand how people use repainting indicators. A trader using repainting Hurst Bands told me they only use the current timeframe and therefore it doesn't matter that the history repaints. But the current candle repaints also.

ZigZag, Trend Reversal, and Swing High/Low all are designed to find a stock's lowest point thus signaling a good entry point but then the stock drops lower and it erases all those signals and says "oops didn't mean it." Not so good for you if you just bought in and the stock drops like a rock.

I am not being critical. I want to understand. You have been trading for many years, could you tell us how you feel these indicators can be used reliably?
I try to reduce clutter, indicators of any kind and rely on price and candles. It doesn't take long to learn to read price and maybe one trusted Indicator for assistance. No grails, I searched, except the one you wrote, understanding it and grow your account size. Several years ago, a public YouTube video became my "ah ha," moment, brought me to tears, I was struggling and saw how simple it can be, I said "yes," that's it. I watched the videos, joined the site for my education. This Iron Rod with Hi_Low indicates gives a confident picture of a reverse, if you want to overlay the zig-zag, fine but the Hi_Low is a simpler signal, incorporated price candles, manually drawn trendlines, I never trusted any indicator signal unless I wrote it in a way it was growing my account. The repainting arrows do a good job of indicating entry, maybe I have entered slightly sooner, but for nothing else, study the entry arrow position and candle formation to understand the pattern for a future entry. I'm asking myself questions of some recent information I learned, how can I accelerate, to speed growth of account. A serious athlete wants to improve quickly, difficult, what's needed is to find a way to accelerate improvement without injuries, time is one answer and chart studies. I recommend shortcuts in learning to speed up portfolio growth. Many observations led me to write notes on charts, during live markets, I papertrade different symbols other than what I personally hold, to test alternative trades. I don't journal, or deviate with useless distractions, looking at charts that don't work, creating Holy-Grails, everything else except reading candles, understanding what is happening with price. I turn off news noise, read a few trusted opinions for confirming beliefs and attack market as early as possible.
Heard this from Oliver Velez, Traders want instant success, without putting in the time, you wouldn't want a doctor operating on you without putting in the time, traders complicate, instead of making it simple enough to explain to a child. One thing I find very important are scans, the selections from which to choose from,...that's something to focus on, most here are trading weak stocks.....
 
Last edited by a moderator:
@Thomas
I am obsessed w/ studying charts.
  • I agree w/ you, I haven't found a script that can compete w/ manually drawn trendlines.
  • For lows, the BTP (Buy the Dip) indicator doesn't repaint.
  • I agree w/ you: IronRod was my first indicator and whether I am using a tick chart, a 2min, or an hourly; it is a mainstay. Stochastic provides so much information and there are so many ways of displaying that but for me, the IronRod is clean and easy to read at a glance.
  • Support&Resistance for me are invaluable as they keep me out of trades not going anywhere thus increasing my ROI.
  • Multi-TimeFrame Analysis. Looking across timeframes especially for trends and ROI.
AND I LOVE labels. Like you, they help keep charts clean. I will be adding some of yours to my repertoire. Thanks again for sharing. This forum is a great place to continue to learn.
 
Last edited:
@Thomas Good write-up... It's easy to get overwhelmed with indicators to the point where you can't see the forest for the trees... I like testing and writing new indicators but also keep in mind that some indicators are great at spelling things out after-the-fact... However, few show real-time or accurately predict the future... As you alluded to, the fewer "good" indicators the better...

@MerryDay I'm really starting to like the IronRod SMI... (y)

And lest I deviate too far off-topic, I've been a fan of ZigZag indicators for quite some time...
 
Extracted idea from RDMercer's post #369 of a variant of a massive Zig Zag High Low Supply Demand study that comprises many different components

https://usethinkscript.com/threads/...-signals-for-thinkorswim.183/page-19#post-369
I heavily modified, cleaned up and extracted some interesting Zig Zag statistical information resulting in this study called Zig Zag High Low Stats. It displays the following information represented via bubbles at each of the Zig zag turning points

Label for Confirmed/Unconfirmed Status of Current Zigzag
Price Change between Zigzags
Price at Zigzag High/Low
Bar Count between Zigzags
Volume at Zigzag Reversals

Here's the study - you might like to load this study on a Daily chart of AAPL, AMZN or your favorite ticker
You can turn off any information you don't want via the user interface

Code:
# ZigZag High Low Stats
# tomsk
# 11.16.2019

# V1.0 - 11.16.2019 - tomsk - Initial release of ZigZag High Low Stats

# Extracted idea from RDMercer's post #369 of a variant of a massive
# Zig Zag High Low Supply Demand study that comprises many different
# components
#
# https://usethinkscript.com/threads/trend-reversal-indicator-with-signals-for-thinkorswim.183/page-19#post-369
#
# I heavily modified, cleaned up and extracted some interesting Zig Zag statistical information resulting in this study called Zig Zag High
# Low Stats. It displays the following information represented via bubbles at each of the Zig zag turning points
#
# Label for Confirmed/Unconfirmed Status of Current Zigzag
# Price Change between Zigzags
# Price at Zigzag High/Low
# Bar Count between Zigzags
# Volume at Zigzag Reversals

input showBubblesChange = no;   # Price Change between Zigzags
input showBubblesPrice = no;    # Price at Zigzag High/Low
input showBubblesBarCount = no; # Bar Count between Zigzags
input showBubblesVolume = no;   # Volume at Zigzag Reversals

input BubbleOffset = .0005;
input PercentAmount = .01;
input RevAmount = .05;
input ATRreversal = 3.0;
input ATRlength = 5;

def zz = ZigZagHighLow("price h" = high, "price l" = low, "percentage reversal" = PercentAmount,
"absolute reversal" = RevAmount, "atr length" = ATRlength, "atr reversal" = ATRreversal);

def ReversalAmount = if (close * PercentAmount / 100) > Max(RevAmount < ATRreversal * reference ATR(ATRlength), RevAmount)
                     then (close * PercentAmount / 100)
                     else if RevAmount < ATRreversal * reference ATR(ATRlength)
                          then ATRreversal * reference ATR(ATRlength)
                          else RevAmount;
# Zig Zag Specific Data

def zzSave = if !IsNaN(zz) then zz else GetValue(zzSave, 1);
def chg = (if zzSave == high then high else low) - GetValue(zzSave, 1);
def isUp = chg >= 0;
def isConf = AbsValue(chg) >= ReversalAmount or (IsNaN(GetValue(zz, 1)) and GetValue(isConf, 1));

# Price Change Specific Data

def xxHigh = if zzSave == high then high else xxHigh[1];
def chgHigh = high - xxHigh[1];
def xxLow = if zzSave == low then low else xxLow[1];
def chgLow = low - xxLow[1];

# Bar Count Specific Data

def zzCount = if zzSave[1] != zzSave then 1 else if zzSave[1] == zzSave then zzCount[1] + 1 else 0;
def zzCountHiLo = if zzCountHiLo[1] == 0 and (zzSave == high or zzSave == low) then 1
                  else if zzSave == high or zzSave == low then zzCountHiLo[1] + 1
                  else zzCountHiLo[1];
def zzHiLo = if zzSave == high or zzSave == low then zzCountHiLo else zzCountHiLo + 1;
def zzCountHigh = if zzSave == high then zzCount[1] else Double.NaN;
def zzCountLow  = if zzSave == low then zzCount[1] else Double.NaN;

# Volume Specific Data

def vol = if BarNumber() == 0 then 0 else volume + vol[1];
def vol1 = if BarNumber() == 1 then volume else vol1[1];
def xxVol = if zzSave == high or zzSave == low then TotalSum(volume) else xxVol[1];
def chgVol =  if xxvol - xxVol[1] + vol1 == vol then vol else xxVol - xxVol[1];

# Zigzag Status Label

AddLabel(BarNumber() != 1, (if isConf then "Confirmed " else "Unconfirmed ") + "ZigZag: " + chg + "  ATRrev " + Round(reference ATR(ATRlength) * ATRreversal, 2) + "  RevAmt " + Round(ReversalAmount, 2), if !isConf then Color.Dark_Orange else if isUp then Color.Green else Color.Red);

# Zig Zag Plot

plot zzp = if isUp <= 1 then zz else Double.NaN;
zzp.AssignValueColor(if isUp then Color.Green else if !isUp then Color.Red else Color.Dark_Orange);
zzp.SetStyle(Curve.FIRM);
zzp.EnableApproximation();
zzp.HideBubble();

# Bubbles

# Price Change between Zigzags

AddChartBubble(showBubblesChange and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + BubbleOffset) else low * (1 - BubbleOffset), "$" + Round(chg, 2), if isUp and chgHigh > 0 then Color.Green else if isUp and chgHigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chgLow > 0 then Color.Green else if !isUp and chgLow < 0 then Color.Red else Color.Yellow, isUp);

# Price at Zigzag High/Low

AddChartBubble(showBubblesPrice and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + BubbleOffset) else low * (1 - BubbleOffset), if isUp then "$" + high else "$" + low, if isUp and chgHigh > 0 then Color.Green else if isUp and chgHigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chgLow > 0 then Color.Green else if !isUp and chgLow < 0 then Color.Red else Color.Yellow, isUp);

# Bar Count between Zigzags

AddChartBubble(showBubblesBarCount and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + BubbleOffset) else low * (1 - BubbleOffset), if zzSave == high then zzCountHigh else zzCountLow, if isUp and chgHigh > 0 then Color.Green else if isUp and chgHigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chgLow > 0 then Color.Green else if !isUp and chgLow < 0 then Color.Red else Color.Yellow, if isUp then yes else no);

# Volume at Zigzag Reversals

AddChartBubble(showBubblesVolume and !IsNaN(zz) and BarNumber() != 1, if isUp then high * (1 + bubbleoffset) else low * (1 - bubbleoffset), chgVol, if isUp and chghigh > 0 then Color.Green else if isUp and chghigh < 0 then Color.Red else if isUp then Color.Yellow else if !isUp and chglow > 0 then Color.Green else if !isUp and chglow < 0 then Color.Red else Color.Yellow, if isUp then yes else no);

# End ZigZag High Low Stats
Is there a way to make this accessible for tos mobile?
 
Hello how are you?

Is there an indicator in TOS where you can count the bars in the form of a zig zag? For example, mark a swing if it contains 7 bars or more.

Thanks
 
Hello how are you?

Is there an indicator in TOS where you can count the bars in the form of a zig zag? For example, mark a swing if it contains 7 bars or more.

Thanks
If there isn't one listed anywhere here in this topic then it most likely doesn't exist...
 
Last edited by a moderator:
Hello All,
I came across this code for options trading which has been very helpful and profitable. Please I will be very grateful if anyone can create a scanner for the indicator. Thanks in advance. See link to indicator below

Code:
## START CODE
## ZigZagSign TOMO modification, v0.2 written by Linus @Thinkscripter Lounge adapted from Thinkorswim ZigZagSign Script

input price             = close;
input priceH            = high;    # swing high
input priceL            = low;     # swing low
input ATRreversalfactor = 3.2;
def ATR                 = reference ATR(length = 5);
def reversalAmount      = ATRreversalfactor * ATR;
input showlines         = yes;
input displace          = 1;
input showBubbleschange = yes;


def barNumber = BarNumber();
def barCount = HighestAll(If(IsNaN(price), 0, barNumber));

rec state = {default init, undefined, uptrend, downtrend};
rec minMaxPrice;

if (GetValue(state, 1) == GetValue(state.init, 0)) {
    minMaxPrice = price;
    state = state.undefined;
} else if (GetValue(state, 1) == GetValue(state.undefined, 0)) {
    if (price <= GetValue(minMaxPrice, 1) - reversalAmount) {
        state = state.downtrend;
        minMaxPrice = priceL;
    } else if (price >= GetValue(minMaxPrice, 1) + reversalAmount) {
        state = state.uptrend;
        minMaxPrice = priceH;
    } else {
        state = state.undefined;
        minMaxPrice = GetValue(minMaxPrice, 1);
    }
} else if (GetValue(state, 1) == GetValue(state.uptrend, 0)) {
    if (price <= GetValue(minMaxPrice, 1) - reversalAmount) {
        state = state.downtrend;
        minMaxPrice = priceL;
    } else {
        state = state.uptrend;
        minMaxPrice = Max(priceH, GetValue(minMaxPrice, 1));
    }
} else {
    if (price >= GetValue(minMaxPrice, 1) + reversalAmount) {
        state = state.uptrend;
        minMaxPrice = priceH;
    } else {
        state = state.downtrend;
        minMaxPrice = Min(priceL, GetValue(minMaxPrice, 1));
    }
}

def isCalculated = GetValue(state, 0) != GetValue(state, 1) and barNumber >= 1;
def futureDepth =  barCount - barNumber;
def tmpLastPeriodBar;
if (isCalculated) {
    if (futureDepth >= 1 and GetValue(state, 0) == GetValue(state, -1)) {
        tmpLastPeriodBar = fold lastPeriodBarI = 2 to futureDepth + 1 with lastPeriodBarAcc = 1
            while lastPeriodBarAcc > 0
            do if (GetValue(state, 0) != GetValue(state, -lastPeriodBarI))
                then -lastPeriodBarAcc
                else lastPeriodBarAcc + 1;
    } else {
        tmpLastPeriodBar = 0;
    }
} else {
    tmpLastPeriodBar = Double.NaN;
}

def lastPeriodBar = if (!IsNaN(tmpLastPeriodBar)) then -AbsValue(tmpLastPeriodBar) else -futureDepth;

rec currentPriceLevel;
rec currentPoints;
if (state == state.uptrend and isCalculated) {
    currentPriceLevel =
        fold barWithMaxOnPeriodI = lastPeriodBar to 1 with barWithMaxOnPeriodAcc = minMaxPrice
            do Max(barWithMaxOnPeriodAcc, GetValue(minMaxPrice, barWithMaxOnPeriodI));
    currentPoints =
        fold maxPointOnPeriodI = lastPeriodBar to 1 with maxPointOnPeriodAcc = Double.NaN
            while IsNaN(maxPointOnPeriodAcc)
            do if (GetValue(priceH, maxPointOnPeriodI) == currentPriceLevel)
                then maxPointOnPeriodI
                else maxPointOnPeriodAcc;
} else if (state == state.downtrend and isCalculated) {
    currentPriceLevel =
        fold barWithMinOnPeriodI = lastPeriodBar to 1 with barWithMinOnPeriodAcc = minMaxPrice
            do Min(barWithMinOnPeriodAcc, GetValue(minMaxPrice, barWithMinOnPeriodI));
    currentPoints =
        fold minPointOnPeriodI = lastPeriodBar to 1 with minPointOnPeriodAcc = Double.NaN
            while IsNaN(minPointOnPeriodAcc)
            do if (GetValue(priceL, minPointOnPeriodI) == currentPriceLevel)
                then minPointOnPeriodI
                else minPointOnPeriodAcc;
} else if (!isCalculated and (state == state.uptrend or state == state.downtrend)) {
    currentPriceLevel = GetValue(currentPriceLevel, 1);
    currentPoints = GetValue(currentPoints, 1) + 1;
} else {
    currentPoints = 1;
    currentPriceLevel = GetValue(price, currentPoints);
}

plot "ZZ$" = if (barNumber == barCount or barNumber == 1) then if state == state.uptrend then priceH else priceL else if (currentPoints == 0) then currentPriceLevel else Double.NaN;

rec zzSave =  if !IsNaN("ZZ$" ) then if (barNumber == barCount or barNumber == 1) then if IsNaN(barNumber[-1]) and  state == state.uptrend then priceH else priceL else currentPriceLevel else GetValue(zzSave, 1);

def chg = (if barNumber == barCount and currentPoints < 0 then priceH else if barNumber == barCount and currentPoints > 0 then priceL else currentPriceLevel) - GetValue(zzSave, 1);

def isUp = chg >= 0;

#Higher/Lower/Equal High, Higher/Lower/Equal Low
def xxhigh = if zzSave == priceH then Round(high, 2) else Round(xxhigh[1], 2);
def chghigh = Round(Round(high, 2) - Round(xxhigh[1], 2), 2);
def xxlow = if zzSave == priceL then Round(low, 2) else Round(xxlow[1], 2);
def chglow = Round(Round(low, 2) - Round(xxlow[1], 2), 2);


rec isConf = AbsValue(chg) >= reversalAmount or (IsNaN(GetValue("ZZ$", 1)) and GetValue(isConf, 1));

"ZZ$".EnableApproximation();
"ZZ$".DefineColor("Up Trend", Color.UPTICK);
"ZZ$".DefineColor("Down Trend", Color.DOWNTICK);
"ZZ$".DefineColor("Undefined", Color.WHITE);
"ZZ$".AssignValueColor(if !isConf then "ZZ$".Color("Undefined" ) else if isUp then "ZZ$".Color("Up Trend" ) else "ZZ$".Color("Down Trend" ));

DefineGlobalColor("Unconfirmed", Color.WHITE);
DefineGlobalColor("Up", Color.UPTICK);
DefineGlobalColor("Down", Color.DOWNTICK);

AddChartBubble(showBubbleschange and !IsNaN("ZZ$" ) and barNumber != 1, if isUp then high else low , Round(chg, 2) , if barCount == barNumber or !isConf then GlobalColor("Unconfirmed" ) else if isUp then GlobalColor("Up" ) else GlobalColor("Down" ), isUp);

## END CODE

https://tos.mx/Zy7sWOu
 
Last edited:
Hi All, Does anyone have a modified TOS Zig Zag script that will count the number of highs and number of lows while also adding up the price/percentage total. Or maybe can point me in the right directions. Thanks.

Code:
# TD Ameritrade IP Company, Inc. (c) 2011-2021

#



input price = close;

input reversalAmount = 8.0;

input showBubbles = no;

input showLabel = no;



assert(reversalAmount > 0, "'reversal amount' should be positive: " + reversalAmount);



plot "ZZ%" = reference ZigZagHighLow(price, price, reversalAmount, 0, 1, 0);



def zzSave = if !IsNaN("ZZ%") then price else getValue(zzSave, 1);

def chg = (price / getValue(zzSave, 1) - 1) * 100;

def isUp = chg >= 0;

def isConf = AbsValue(chg) >= reversalAmount or (IsNaN(getValue("ZZ%", 1)) and getValue(isConf, 1));



"ZZ%".EnableApproximation();

"ZZ%".DefineColor("Up Trend", Color.UPTICK);

"ZZ%".DefineColor("Down Trend", Color.DOWNTICK);

"ZZ%".DefineColor("Undefined", Color.DARK_ORANGE);

"ZZ%".AssignValueColor(if !isConf then "ZZ%".color("Undefined") else if isUp then "ZZ%".color("Up Trend") else "ZZ%".color("Down Trend"));



DefineGlobalColor("Unconfirmed", Color.DARK_ORANGE);

DefineGlobalColor("Up", Color.UPTICK);

DefineGlobalColor("Down", Color.DOWNTICK);



def barNumber = barNumber();



AddChartBubble(showBubbles and !IsNaN("ZZ%") and barNumber != 1, price, round(chg) + "%", if !isConf then globalColor("Unconfirmed") else if isUp then globalColor("Up") else globalColor("Down"), isUp);

AddLabel(showLabel and barNumber != 1, (if isConf then "Confirmed " else "Unconfirmed ") + "ZigZag: " + round(chg) + "%", if !isConf then globalColor("Unconfirmed") else if isUp then globalColor("Up") else globalColor("Down"));

#
 
Last edited:
@Madison I think you would find that there would be inaccuracies, and perhaps gross inaccuracies, due to the fact that the ZigZagHighLow indicator repaints...
 
rad14733 brings up a good point, be sure you understand the data you are working with.


edited below ------

to count how many times a variable x is equal to 1. create an if then to,
..test for x = to 1
....if it is, then read the value of x in the previous candle , by using x[1], and add 1.
....if x is not = to 1, then just read the value of x in the previous candle.
Code:
def xcnt = if (x == 1) then xcbt[1] + 1 else xcbt[1] ;

to help with debugging and see the values in xcnt, add a bubble to display them, below each candle.
Code:
addchartbubble(yes, low, xcnt, color.cyan, no);

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Look---Feel/AddChartBubble


this method may have issues, because on bar #1, a previous bar doesn't exist. so using x[1] may cause invalid data.

here are examples using compoundvalue( ). it is a way of executing different formulas, depending on the current bar number.
...if the bar # is greater than the 1st parameter, execute the 2nd parameter.
...otherwise use the 3rd parameter.
compoundvalue( 1st, 2nd, 3rd ).

https://usethinkscript.com/threads/...-bars-on-entire-chart-or-specified-time.5496/

https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Others/CompoundValue

if the variable values are 1 or 0, you could use totalsum(x) to add up all the values, which would be the same as counting the 1's.
https://tlc.thinkorswim.com/center/reference/thinkScript/Functions/Math---Trig/TotalSum


============
EDIT:
i don't use compoundvalue().
i add a check to the if-then , to check if the barnumber is 1. if it is, then set the value to some initial value, usually 0.

Code:
# counting the times x = 1
def init = 0;
def y = if barnumber() == 1 then init
  else if x == 1 then x[1] + 1
  else x[1];

this assumes only 1 offset of [1] will be used in the following if-then formula. if x[1] and x[2] will be used then the first line would be

def y = if barnumber() <= 2 then init
else.....
 
Last edited:
@Madison If you haven't already done this, here is one way to use code to count the number of Highs and Lows displayed on the chart.

Capture.jpg
Code:
# TD Ameritrade IP Company, Inc. (c) 2011-2021

#



input price = close;

input reversalAmount = 8.0;

input showBubbles = no;

input showLabel = no;



Assert(reversalAmount > 0, "'reversal amount' should be positive: " + reversalAmount);



plot "ZZ%" = reference ZigZagHighLow(price, price, reversalAmount, 0, 1, 0);



def zzSave = if !IsNaN("ZZ%") then price else GetValue(zzSave, 1);

def chg = (price / GetValue(zzSave, 1) - 1) * 100;

def isUp = chg >= 0;

def isConf = AbsValue(chg) >= reversalAmount or (IsNaN(GetValue("ZZ%", 1)) and GetValue(isConf, 1));



"ZZ%".EnableApproximation();

"ZZ%".DefineColor("Up Trend", Color.UPTICK);

"ZZ%".DefineColor("Down Trend", Color.DOWNTICK);

"ZZ%".DefineColor("Undefined", Color.DARK_ORANGE);

"ZZ%".AssignValueColor(if !isConf then "ZZ%".Color("Undefined") else if isUp then "ZZ%".Color("Up Trend") else "ZZ%".Color("Down Trend"));



DefineGlobalColor("Unconfirmed", Color.DARK_ORANGE);

DefineGlobalColor("Up", Color.UPTICK);

DefineGlobalColor("Down", Color.DOWNTICK);



def barNumber = BarNumber();



AddChartBubble(showBubbles and !IsNaN("ZZ%") and barNumber != 1, price, Round(chg) + "%", if !isConf then GlobalColor("Unconfirmed") else if isUp then GlobalColor("Up") else GlobalColor("Down"), isUp);

AddLabel(showLabel and barNumber != 1, (if isConf then "Confirmed " else "Unconfirmed ") + "ZigZag: " + Round(chg) + "%", if !isConf then GlobalColor("Unconfirmed") else if isUp then GlobalColor("Up") else GlobalColor("Down"));

input show_stats_labels = yes;
def xh = CompoundValue(1, if isUp and !IsNaN("ZZ%") then xh[1] + 1 else xh[1], 0);
AddLabel(show_stats_labels, "#Highs: " + xh, Color.GREEN);
def xl = CompoundValue(1, if !isUp and !IsNaN("ZZ%") then xl[1] + 1 else xl[1], 0);
AddLabel(show_stats_labels, "#Lows: " + xl, Color.RED);

input showbubbles_stats = yes;
AddChartBubble(showbubbles_stats and !IsNaN("ZZ%") and barNumber != 1 and isUp, price, "H: " + xh, Color.GREEN, isUp);
AddChartBubble(showbubbles_stats and !IsNaN("ZZ%") and barNumber != 1 and !isUp, price, "L: " + xl, Color.RED, isUp);
#
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
398 Online
Create Post

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top