Calculating the number of bars since a lower low (or higher high)

TNTrader5159

Active member
How would I calculate the number of bars since a lower low vs the present bar? I take it to subtract the bar number of that most recent occurrence of a lower low from the current bar number to determine the range. I do not know how to write that, and the official tutorials are not indicative enough to my somewhat untrained eye.

Then I would also want to calculate the number of bars since both the highest and lowest prices within that range (assuming it is big enough to be worth counting, which I already know how to qualify). I believe HighestAll would be in order, but again I am unsure of the parameters of that function.

The objective is to find low and high pivot points and measure the number of bars higher/lower on each side AND find the relative locations of the highest and lowest prices within each of those ranges going back until the most recent occurrence of a lower/higher price that would truncate the range.

Please enlighten me with my advance thanks!

Matt
 
Solution
How would I calculate the number of bars since a lower low vs the present bar? I take it to subtract the bar number of that most recent occurrence of a lower low from the current bar number to determine the range. I do not know how to write that, and the official tutorials are not indicative enough to my somewhat untrained eye.

Then I would also want to calculate the number of bars since both the highest and lowest prices within that range (assuming it is big enough to be worth counting, which I already know how to qualify). I believe HighestAll would be in order, but again I am unsure of the parameters of that function.

The objective is to find low and high pivot points and measure the number of bars higher/lower on each side...
How would I calculate the number of bars since a lower low vs the present bar? I take it to subtract the bar number of that most recent occurrence of a lower low from the current bar number to determine the range. I do not know how to write that, and the official tutorials are not indicative enough to my somewhat untrained eye.

Then I would also want to calculate the number of bars since both the highest and lowest prices within that range (assuming it is big enough to be worth counting, which I already know how to qualify). I believe HighestAll would be in order, but again I am unsure of the parameters of that function.

The objective is to find low and high pivot points and measure the number of bars higher/lower on each side AND find the relative locations of the highest and lowest prices within each of those ranges going back until the most recent occurrence of a lower/higher price that would truncate the range.

EDIT 9-26
fix formula for peak , def peak = high > highest(high[1], ....
add an input to turn bubbles on/off

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

this will find how many bars back to the recent peak or valley.
i'm not sure what you mean in the last sentence.

Code:
# bars_since_low_0

def na = double.nan;
def bn = BarNumber();
def lastbn = highestall(if isnan(close) then 0 else bn);
def lastcls = if lastbn then close else lastcls[1];
#def lastbar = (!isnan(close) and isnan(close[-1]));

input show_peak_valley_arrows = yes;
def spva = show_peak_valley_arrows;

input len = 4;

#input length = 10;
#def bn = BarNumber();
#def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
def offset = Min(len - 1, lastbn - bn);
#def swingLow = low < Lowest(low[1], len - 1) and low == GetValue(Lowest(low, len), -offset);


#--------------------------
#valley section
#def Valley = low < Lowest(low[1], len) and low < Lowest(low[-len], len);
def valley = low < Lowest(low[1], len - 1) and low == GetValue(Lowest(low, len), -offset);

plot ArrowUP = if spva then Valley else na;
ArrowUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
ArrowUP.SetDefaultColor(Color.WHITE);
ArrowUP.SetLineWeight(2);

#---------------------------
#peak section
#def Peak = high > highest(high[1], len) and high > highest(high[-len], len);
def peak = high > highest(high[1], len - 1) and high == GetValue(highest(high, len), -offset);

plot ArrowDN = if spva then Peak else na;
ArrowDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
ArrowDN.SetDefaultColor(Color.WHITE);
ArrowDN.SetLineWeight(2);

# -------------------------

def lolo = if bn == 1 then 9999 else if valley and low < lolo[1] then low else lolo[1];
def lolobn = if bn == 1 then 0 else if lolo[1] != lolo then bn else lolobn[1];

def hihi = if bn == 1 then 0 else if peak and high > hihi[1] then high else hihi[1];
def hihibn = if bn == 1 then 0 else if hihi[1] != hihi then bn else hihibn[1];

def valleybars = if bn == 1 then 0 else if lastbn then bn - lolobn else valleybars[1];
def peakbars = if bn == 1 then 0 else if lastbn then bn - hihibn else peakbars[1];

def new_low = (valley and low < lolo[1]);
def new_high = (peak and high > hihi[1]);

addlabel(1, "bars since valley " + valleybars, color.yellow);
addlabel(1, "bars since peak " + peakbars, color.yellow);

input test1_bubbles = no;
addchartbubble(test1_bubbles , low*0.99,
bn + "\n" +
lastbn + "\n" +
hihi + " hh\n" +
hihibn + " hhbn\n" +
lolo + " ll\n" +
lolobn + " llbn\n"
, (if new_high then color.green else if new_low then color.red else color.gray), no);
#
#
 
Last edited:
Solution

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

this will find how many bars back to the recent peak or valley.
i'm not sure what you mean in the last sentence.

Code:
# bars_since_low_0

def na = double.nan;
def bn = BarNumber();
def lastbn = highestall(if isnan(close) then 0 else bn);
def lastcls = if lastbn then close else lastcls[1];
#def lastbar = (!isnan(close) and isnan(close[-1]));

input show_peak_valley_arrows = yes;
def spva = show_peak_valley_arrows;

input len = 4;

#input length = 10;
#def bn = BarNumber();
#def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
def offset = Min(len - 1, lastbn - bn);
#def swingLow = low < Lowest(low[1], len - 1) and low == GetValue(Lowest(low, len), -offset);


#--------------------------
#valley section
#def Valley = low < Lowest(low[1], len) and low < Lowest(low[-len], len);
def valley = low < Lowest(low[1], len - 1) and low == GetValue(Lowest(low, len), -offset);

plot ArrowUP = if spva then Valley else na;
ArrowUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
ArrowUP.SetDefaultColor(Color.WHITE);
ArrowUP.SetLineWeight(2);

#---------------------------
#peak section
#def Peak = high > highest(high[1], len) and high > highest(high[-len], len);
def peak = high < highest(high[1], len - 1) and high == GetValue(highest(high, len), -offset);

plot ArrowDN = if spva then Peak else na;
ArrowDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
ArrowDN.SetDefaultColor(Color.WHITE);
ArrowDN.SetLineWeight(2);

# -------------------------

def lolo = if bn == 1 then 9999 else if valley and low < lolo[1] then low else lolo[1];
def lolobn = if bn == 1 then 0 else if lolo[1] != lolo then bn else lolobn[1];

def hihi = if bn == 1 then 0 else if peak and high > hihi[1] then high else hihi[1];
def hihibn = if bn == 1 then 0 else if hihi[1] != hihi then bn else hihibn[1];

def valleybars = if bn == 1 then 0 else if lastbn then bn - lolobn else valleybars[1];
def peakbars = if bn == 1 then 0 else if lastbn then bn - hihibn else peakbars[1];

def new_low = (valley and low < lolo[1]);
def new_high = (peak and high > hihi[1]);

addlabel(1, "bars since valley " + valleybars, color.yellow);
addlabel(1, "bars since peak " + peakbars, color.yellow);


addchartbubble(1, low*0.99,
bn + "\n" +
lastbn + "\n" +
hihi + " hh\n" +
hihibn + " hhbn\n" +
lolo + " ll\n" +
lolobn + " llbn\n"
, (if new_high then color.green else if new_low then color.red else color.gray), no);

#
Wow, thank you so much halcyon guy! I'm not well and my thinker is fogged up, so this is a great blessing for me. I meant to find the total number of bars behind and ahead of, for example, a valley low that have lows higher than that valley low until a bar is reached on both sides with a low less than the valley low.
Then I would see how far back or forward as the case may be within those ranges on either side that the highest prices occurred before or after which a low less than the valley low occurs.
Then I would take the lesser side of the two as measured in bars as the strength of the pivot.
This would then be compared with the size of the triggered pattern to determine if the Impedance Factor (support or resistance) is greater than the pattern (Thrust Factor). (I won't go into the pattern definition rules here.)

If so, exit the trade at 89% of the way to that Impedance Point (in this case the valley low) with a profit.
If the pattern (Thrust Factor) is stronger than the Impedance Factor just described, then the market will likely penetrate the Impedance Point (in this case the valley low) and continue favorable downward movement.
This system works like a charm and has taken me a total of 53 years to develop. I am now having a lot of health issues with extreme fibromyalgia pain and brain fog, and thinking in terms of code is way harder than it otherwise would be.

If you have any other questions just ask. I do not mind sharing this strategy with anyone. With a quadrillion dollar pie, someone besides me needs to make some money LOL. People are so overwhelmed with modern sensory input and thus jaded that few if any would even pay attention here. Thank you so much again!
 
Wow, thank you so much halcyon guy! I'm not well and my thinker is fogged up, so this is a great blessing for me. I meant to find the total number of bars behind and ahead of, for example, a valley low that have lows higher than that valley low until a bar is reached on both sides with a low less than the valley low.
Then I would see how far back or forward as the case may be within those ranges on either side that the highest prices occurred before or after which a low less than the valley low occurs.
Then I would take the lesser side of the two as measured in bars as the strength of the pivot.
This would then be compared with the size of the triggered pattern to determine if the Impedance Factor (support or resistance) is greater than the pattern (Thrust Factor). (I won't go into the pattern definition rules here.)

If so, exit the trade at 89% of the way to that Impedance Point (in this case the valley low) with a profit.
If the pattern (Thrust Factor) is stronger than the Impedance Factor just described, then the market will likely penetrate the Impedance Point (in this case the valley low) and continue favorable downward movement.
This system works like a charm and has taken me a total of 53 years to develop. I am now having a lot of health issues with extreme fibromyalgia pain and brain fog, and thinking in terms of code is way harder than it otherwise would be.

If you have any other questions just ask. I do not mind sharing this strategy with anyone. With a quadrillion dollar pie, someone besides me needs to make some money LOL. People are so overwhelmed with modern sensory input and thus jaded that few if any would even pay attention here. Thank you so much again!
sorry about your medical condition.
thanks for describing your process some more. it's still a little confusing, i will have to read that a few times and make some sketches.
 
Wow, thank you so much halcyon guy! I'm not well and my thinker is fogged up, so this is a great blessing for me. I meant...

am i close?
i copied the rules in post3 and tried to interpret them.
bn is barnumber

1. I meant to find the total number of bars behind and ahead of, for example, a valley low that have lows higher than that valley low until a bar is reached on both sides with a low less than the valley low.

find a valley,
(a valley implies that nearby lows will be higher)
...look at past bars, until a low that is lower than the valley. get barnumber
...look at future bars, until a low that is lower than the valley. get barnumber



2. Then I would see how far back or forward as the case may be within those ranges on either side that the highest prices occurred before or after which a low less than the valley low occurs.

look for the highest price in,
...the past bars, to #1 past lower low. get bn
...the future bars, to #1 future lower low. get bn



3. Then I would take the lesser side of the two as measured in bars as the strength of the pivot.

?? 2 what?
the high $ or the lower lows?

compare the quantity of bars, from current valley, to the 2 highs , before and after.
x = min( #2 past highprice bn, #2 future high price bn )



4. This would then be compared with the size of the triggered pattern to determine if the Impedance Factor (support or resistance) is greater than the pattern (Thrust Factor). (I won't go into the pattern definition rules here.)

? no idea on what these terms are
Impedance Point (valley low)



5. If so, exit the trade at 89% of the way to that Impedance Point (in this case the valley low) with a profit.

89% of some range, from the top?
is the range from a near high to the lowest low?



6. If the pattern (Thrust Factor) is stronger than the Impedance Factor just described, then the market will likely penetrate the Impedance Point (in this case the valley low) and continue favorable downward movement.

?


 
sorry about your medical condition.
thanks for describing your process some more. it's still a little confusing, i will have to read that a few times and make some sketches.
As I am able, I will send you some illustrations of these concepts in annotated screenshots. I have been so long imbibed in this that it's simpler to me than any attempted explanation to someone unfamiliar with it. It expounds on the double top/double bottom and the three-line break pattern used by some candlestick traders. It rides the coattails of the smart money that creates these timeless patterns in all major markets in numerous timeframes that are like the key to a bank vault when grasped, quantified, coded, and applied. Someone in Germany named Mike Semlitsch (www.perfecttrendsystems.com) developed a similar concept I found last year that helped solidify my understanding of how/why this works. It's only for MetaTrader and ForEx however.
I have spent all the time and energy I could spare on tweaking and hopefully coding this ABCD pattern into workable form. Finding and working with developers has been very frustrating.
I have part of it plugged into TOS now that will yield preliminary signals without the Impedance qualifications. I can eyeball that enough to make a trade if I happen to catch one. Thing is it's hard for me to watch and jump on the alerts when they do come before the window of opportunity closes. With 23-hour markets, so many opportunities are available that only a computer can catch and act upon while I sleep or eat or whatever.
 
As I am able, I will send you some illustrations of these concepts in annotated screenshots. I have been so long imbibed in this that it's simpler to me than any attempted explanation to someone unfamiliar with it. It expounds on the double top/double bottom and the three-line break pattern used by some candlestick traders. It rides the coattails of the smart money that creates these timeless patterns in all major markets in numerous timeframes that are like the key to a bank vault when grasped, quantified, coded, and applied. Someone in Germany named Mike Semlitsch (www.perfecttrendsystems.com) developed a similar concept I found last year that helped solidify my understanding of how/why this works. It's only for MetaTrader and ForEx however.
I have spent all the time and energy I could spare on tweaking and hopefully coding this ABCD pattern into workable form. Finding and working with developers has been very frustrating.
I have part of it plugged into TOS now that will yield preliminary signals without the Impedance qualifications. I can eyeball that enough to make a trade if I happen to catch one. Thing is it's hard for me to watch and jump on the alerts when they do come before the window of opportunity closes. With 23-hour markets, so many opportunities are available that only a computer can catch and act upon while I sleep or eat or whatever.
The Pivot function in EasyLanguage does this well. I have not seen an equivalent in ThinkScript though I know it can be done in other ways I have yet to master. I like TD Ameritrade better overall than TradeStation, and I want to trade there if automation can be achieved.

https://markplex.com/free-tutorials/tutorial-21-tradestations-pivot-function/
 
The Pivot function in EasyLanguage does this well. I have not seen an equivalent in ThinkScript though I know it can be done in other ways I have yet to master. I like TD Ameritrade better overall than TradeStation, and I want to trade there if automation can be achieved.

https://markplex.com/free-tutorials/tutorial-21-tradestations-pivot-function/

The Pivot function in EasyLanguage does this well. I have not seen an equivalent in ThinkScript though I know it can be done in other ways I have yet to master. I like TD Ameritrade better overall than TradeStation, and I want to trade there if automation can be achieved.

https://markplex.com/free-tutorials/tutorial-21-tradestations-pivot-function/

am i close?
i copied the rules in post3 and tried to interpret them.
bn is barnumber

1. I meant to find the total number of bars behind and ahead of, for example, a valley low that have lows higher than that valley low until a bar is reached on both sides with a low less than the valley low.


find a valley,
(a valley implies that nearby lows will be higher)
...look at past bars, until a low that is lower than the valley. get barnumber
...look at future bars, until a low that is lower than the valley. get barnumber



2. Then I would see how far back or forward as the case may be within those ranges on either side that the highest prices occurred before or after which a low less than the valley low occurs.


look for the highest price in,
...the past bars, to #1 past lower low. get bn
...the future bars, to #1 future lower low. get bn



3. Then I would take the lesser side of the two as measured in bars as the strength of the pivot.


?? 2 what?
the high $ or the lower lows?

compare the quantity of bars, from current valley, to the 2 highs , before and after.
x = min( #2 past highprice bn, #2 future high price bn )



4. This would then be compared with the size of the triggered pattern to determine if the Impedance Factor (support or resistance) is greater than the pattern (Thrust Factor). (I won't go into the pattern definition rules here.)


? no idea on what these terms are
Impedance Point (valley low)



5. If so, exit the trade at 89% of the way to that Impedance Point (in this case the valley low) with a profit.


89% of some range, from the top?
is the range from a near high to the lowest low?



6. If the pattern (Thrust Factor) is stronger than the Impedance Factor just described, then the market will likely penetrate the Impedance Point (in this case the valley low) and continue favorable downward movement.


?
I'll go back and answer these questions shortly. HERE is an illustration of a good trade in Gold basis 30m timeframe that happened this morning. You see my little indicator at the bottom that said the conditions for a Long pattern completion had been fulfilled and returned a 1. To find many patterns like this both short and long, simply monitor many timeframes at once to find these patterns and ratios without having to change the formula!
 
I'll go back and answer these questions shortly. HERE is an illustration of a good trade in Gold basis 30m timeframe that happened this morning. You see my little indicator at the bottom that said the conditions for a Long pattern completion had been fulfilled and returned a 1. To find many patterns like this both short and long, simply monitor many timeframes at once to find these patterns and ratios without having to change the formula!
And HERE is another illustration of the Impedance Factor calculation basis the Impedance Point at the valley low. It is former support penetrated to convert it to resistance at a value half the Primary Impedance value in bars. A peak would be Primary Impedance for a Long trade and a valley Secondary Impedance. The lesser side in bars back to the highest points on either side short of the first penetration of the IP (valley low) determines the strength. As you see, it is 9.5 in this case, and the TF was 5. That tells you to exit the trade in deference to the larger value. "Tie goes to the pitcher" in the event of equal values for the IF and TF, in that it's better to get out of a profitable position too soon than too late.
 
The Pivot function in EasyLanguage does this well. I have not seen an equivalent in ThinkScript though I know it can be done in other ways I have yet to master. I like TD Ameritrade better overall than TradeStation, and I want to trade there if automation can be achieved.

https://markplex.com/free-tutorials/tutorial-21-tradestations-pivot-function/

i don't think there is a pivot function...
you can look at post2 and see the code i used to find pivots.
someday, i could make a routine that replicates the easycode function
 
I'll go back and answer these questions shortly. HERE is an illustration of a good trade in Gold basis 30m timeframe that happened this morning. You see my little indicator at the bottom that said the conditions for a Long pattern completion had been fulfilled and returned a 1. To find many patterns like this both short and long, simply monitor many timeframes at once to find these patterns and ratios without having to change the formula!
i can see your images. that helps explain things.
this site Isn't set up for posting images. you have to go to a 3rd party site , imgur.com and post your picture there, and then grab a shortcut and paste the shortcut here.
 
I'll go back and answer these questions shortly. HERE is an illustration of a good trade in Gold basis 30m timeframe that happened this morning. You see my little indicator at the bottom that said the conditions for a Long pattern completion had been fulfilled and returned a 1. To find many patterns like this both short and long, simply monitor many timeframes at once to find these patterns and ratios without having to change the formula!
I'll go back and answer these questions shortly. HERE is an illustration of a good trade in Gold basis 30m timeframe that happened this morning. You see my little indicator at the bottom that said the conditions for a Long pattern completion had been fulfilled and returned a 1. To find many patterns like this both short and long, simply monitor many timeframes at once to find these patterns and ratios without having to change the formula!
ANSWERS INTERSPERSED:

am i close?

Getting there yes

i copied the rules in post3 and tried to interpret them.
bn is barnumber

1. I meant to find the total number of bars behind and ahead of, for example, a valley low that have lows higher than that valley low until a bar is reached on both sides with a low less than the valley low.


find a valley,
(a valley implies that nearby lows will be higher)
...look at past bars, until a low that is lower than the valley. get barnumber
...look at future bars, until a low that is lower than the valley. get barnumber

Yes. Then find the FIRST highest bar past and future of that calculated range from the valley low and differentiate them from the valley low. (Ties always defer to the most recent for past bars or first to occur for future bars, ie how long did it take to get there?) Take the lesser of those two numbers (left and right side strength) and divide by 2. For Primary Impedance there is no division, and in this case, the IP or valley low is Secondary Impedance.

Hope that's clear. I try to be redundant to convey a better understanding. I could make a Glossary if it would help.



2. Then I would see how far back or forward as the case may be within those ranges on either side that the highest prices occurred before or after which a low less than the valley low occurs.


look for the highest price in,
...the past bars, to #1 past lower low. get bn
...the future bars, to #1 future lower low. get bn

EXACTLY!

3. Then I would take the lesser side of the two as measured in bars as the strength of the pivot.

YES!

?? 2 what?
the high $ or the lower lows?

Back/forward to the high $. Inside bars behind or ahead of the determined High-Low range are ignored.
compare the quantity of bars, from current valley, to the 2 highs , before and after.
x = min( #2 past highprice bn, #2 future high price bn )

You got it! And for Secondary, divide it by 2. Eg x = minSecondary( #2 past highprice bn, #2 future high price bn ) / 2;

4. This would then be compared with the size of the triggered pattern to determine if the Impedance Factor (support or resistance) is greater than the pattern (Thrust Factor). (I won't go into the pattern definition rules here.)

Right!

? no idea on what these terms are
Impedance Point (valley low)

They are synonymous.

5. If so, exit the trade at 89% of the way to that Impedance Point (in this case the valley low) with a profit.

Right. And the number 89% is not set in stone. It could be optimized later on, but for now let's use it. It's a good general point to take profits before the obvious high or low where other traders would want to get out. And it's a Fib number ;). Take a little less, up your winning percentage, and save time. Sometimes markets will stop short of obvious points where the majority looks to exit. Get the jump on them! It's a modification of Joe Ross' "trader's trick." Markets that stop like this usually reverse big-time, but that's another matter.

89% of some range, from the top?
is the range from a near high to the lowest low?

From in this case the lowest price of the pattern on the current bar to the IP or valley low.

6. If the pattern (Thrust Factor) is stronger than the Impedance Factor just described, then the market will likely penetrate the Impedance Point (in this case the valley low) and continue favorable downward movement.


?

Yes, and in this case the IF was stronger. If the TF is stronger, stay with the trade and look for the next IP that is strong enough to impede the move and exit accordingly. You will know your profit objective when entering every trade.
 
i can see your images. that helps explain things.
this site Isn't set up for posting images. you have to go to a 3rd party site , imgur.com and post your picture there, and then grab a shortcut and paste the shortcut here.

I uploaded the 2 images to my OneDrive, and it generated the links I sent you.

I have to call it a day today. Much pain and need rest. Have at this and see what you can do with my heartfelt thanks. Will check in tomorrow.
 
I uploaded the 2 images to my OneDrive, and it generated the links I sent you.

I have to call it a day today. Much pain and need rest. Have at this and see what you can do with my heartfelt thanks. Will check in tomorrow.
Here is my code for the base pattern Long and Short. It does NOT include the feature of determining the highest and lowest bars engulfed and going back only that far in measuring the strength of the pattern or Thrust Factor. Bars behind those that include only the highest and lowest prices engulfed should NOT be counted as inside the range of said high and low.
declare lower;

input BarsEngulfed = 3;
# Number of bars engulfed as a MINIMUM 3/1 ratio. To find more trades, simply take this pattern and apply it to numerous timeframes at once to find these pattern requirements and minimum ratio much more often than in looking on single timeframes. Ideally it would not depend upon bars but TIME proper in whatever frame it takes place, as long as the trade is big enough to be worthwhile.

# These patterns take place more on shorter timeframes where the players work their magic within the longer term charts and trends more indicative of supply and demand and news. That's why they're the SMART money. All we do is seek to find their indicative markers and harness these timeless patterns to ride their coattails to riches. I pay no mind to news or fundamentals or the Fed's latest sneeze, as the market knows them all before we do and has them already for the most part baked into the cake.

def CondVol = if volume >= volume[1] * 1.618034 then 1 else 0;
# Trigger bar must take place on a significant increase in volume vs the previous bar to ensure "smart money" participation

### BEGIN LONG PATTERN ###

def MinPatternPointsLong = ExpAverage(Max(Max(high - low, high - close[1]), close[1] - low), 987);

def ALong = Lowest(low, BarsEngulfed)[1];
def BLong = Highest(high, BarsEngulfed)[1];
def CLong = low;
def DLong = BLong;

def Cond1Long = if open < BLong then 1 else 0;
# Open must be lower than the highest price of the previous <BarsEngulfed> bars

def Cond2Long = if low < ALong then 1 else 0;
# Low must be lower than the lowest price of the previous <BarsEngulfed> bars

def Cond3Long = if high > BLong then 1 else 0;
# High must be greater than or equal to the highest price of the previous <BarsEngulfed> bars (this is the trigger point)

def Cond4Long = if close > open then 1 else 0;
# Close must be higher than the lowest price of the previous <BarsEngulfed> bars

def Cond5Long = if low >= ALong - (BLong - ALong) then 1 else 0;
# Low must be no lower than the first valley at ALong minus the difference between the highest price of the previous <BarsEngulfed> bars and the lowest price of the previous <BarsEngulfed> bars

def Cond6Long = if BLong - ALong >= MinPatternPointsLong then 1 else 0;

plot LongPattern = if Cond1Long + Cond2Long + Cond3Long + Cond4Long + Cond5Long + Cond6Long + CondVol == 7 then 1 else 0;
# If all conditions are satisfied at once, alert me to a possible trade.

LongPattern.SetDefaultColor(CreateColor(0, 255, 0));

### END OF LONG PATTERN ###

#***********************************************************

### BEGIN SHORT PATTERN ###

def MinPatternPointsShort = ExpAverage(Max(Max(high - low, high - close[1]), close[1] - low), 987);

def AShort = Highest(high, BarsEngulfed)[1];
def BShort = Lowest(low, BarsEngulfed)[1];
def CShort = high;
def DShort = BShort;

def Cond1Short = if open > BShort then 1 else 0;
# Open must be higher than the lowest price of the previous <BarsEngulfed> bars

def Cond2Short = if high > AShort then 1 else 0;
# High must be higher than the highest price of the previous <BarsEngulfed> bars

def Cond3Short = if low < BShort then 1 else 0;
# Low must be less than or equal to the lowest price of the previous <BarsEngulfed> bars (this is the trigger point)

def Cond4Short = if close < open then 1 else 0;
# Close must be lower than the highest prices of the previous <BarsEngulfed> bars

def Cond5Short = if high <= AShort + (AShort – BShort) then 1 else 0;
# High must be no higher than the first peak at AShort plus the difference between the highest price of the previous <BarsEngulfed> bars minus the lowest price of the previous <BarsEngulfed> bars

def Cond6Short = if AShort - BShort >= MinPatternPointsLong then 1 else 0;

plot ShortPattern = if Cond1Short + Cond2Short + Cond3Short + Cond4Short + Cond5Short + Cond6Short + CondVol == 7 then -1 else 0;

ShortPattern.SetDefaultColor(CreateColor(255, 0, 0));

# If all conditions are satisfied at once, plot a -1 and sound/email alert me to a possible trade.

plot ZeroLine = 0;
ZeroLine.SetDefaultColor(CreateColor(0, 255, 0));
 
this will find how many bars back to the recent peak or valley.
i'm not sure what you mean in the last sentence.

Code:
# bars_since_low_0

def na = double.nan;
def bn = BarNumber();
def lastbn = highestall(if isnan(close) then 0 else bn);
def lastcls = if lastbn then close else lastcls[1];
#def lastbar = (!isnan(close) and isnan(close[-1]));

input show_peak_valley_arrows = yes;
def spva = show_peak_valley_arrows;

input len = 4;

#input length = 10;
#def bn = BarNumber();
#def lastBar = HighestAll(if IsNaN(close) then 0 else bn);
def offset = Min(len - 1, lastbn - bn);
#def swingLow = low < Lowest(low[1], len - 1) and low == GetValue(Lowest(low, len), -offset);


#--------------------------
#valley section
#def Valley = low < Lowest(low[1], len) and low < Lowest(low[-len], len);
def valley = low < Lowest(low[1], len - 1) and low == GetValue(Lowest(low, len), -offset);

plot ArrowUP = if spva then Valley else na;
ArrowUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
ArrowUP.SetDefaultColor(Color.WHITE);
ArrowUP.SetLineWeight(2);

#---------------------------
#peak section
#def Peak = high > highest(high[1], len) and high > highest(high[-len], len);
def peak = high < highest(high[1], len - 1) and high == GetValue(highest(high, len), -offset);

plot ArrowDN = if spva then Peak else na;
ArrowDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
ArrowDN.SetDefaultColor(Color.WHITE);
ArrowDN.SetLineWeight(2);

# -------------------------

def lolo = if bn == 1 then 9999 else if valley and low < lolo[1] then low else lolo[1];
def lolobn = if bn == 1 then 0 else if lolo[1] != lolo then bn else lolobn[1];

def hihi = if bn == 1 then 0 else if peak and high > hihi[1] then high else hihi[1];
def hihibn = if bn == 1 then 0 else if hihi[1] != hihi then bn else hihibn[1];

def valleybars = if bn == 1 then 0 else if lastbn then bn - lolobn else valleybars[1];
def peakbars = if bn == 1 then 0 else if lastbn then bn - hihibn else peakbars[1];

def new_low = (valley and low < lolo[1]);
def new_high = (peak and high > hihi[1]);

addlabel(1, "bars since valley " + valleybars, color.yellow);
addlabel(1, "bars since peak " + peakbars, color.yellow);


addchartbubble(1, low*0.99,
bn + "\n" +
lastbn + "\n" +
hihi + " hh\n" +
hihibn + " hhbn\n" +
lolo + " ll\n" +
lolobn + " llbn\n"
, (if new_high then color.green else if new_low then color.red else color.gray), no);

#
great . When seeing this indication in action, I noticed that the arrows vanish even after the candle closes. Is it possible to prevent repainting of this stock indicator? Many thanks

@halcyonguy @TNTrader5159 My early observations show that the downarrow repaints whereas the uparrow does not. When the stock is on an uptrend, uparrow typically provides precise signals. I need a notification when the uparrow appears. I therefore inserted this line ( Alert(Valley, "Long", Alert.BAR, Sound.ring); )to the code, but unfortunately the alert does not function despite the fact that the code is right (i.e no ring sound when the arrow appears). Please, could you assist me. Many Thanks


The alert code functions with all of my stock indicators. but not for this study (the alert initially activates when I open the stock and the up arrow shows) (i.e I hear the sound and the alert appears in the messages box, but not afterwards). Could someone please help me? I desperately need the notifications because I can't keep watching the screen all the time. Thank you very much
 
Last edited by a moderator:
ZigZags, Swings, Waves, Reversals, and Pivots are all repainting indicators.
No, repainting indicators can not be rewritten to not repaint.

Both arrows will repaint.

You will see more up arrow repainting when the instrument has a strong bearish trend. As it makes new lows the previous up arrows will be erased.
You will see more down arrow repainting when the instrument has a bullish trend. As it makes new highs the previous down arrows will be erased.

They are written specifically to repaint.
A stock makes a low, the study provides a signal. The stock goes lower. The study erases the signal and paints a new one.
That is the function of these indicators. And it is important in particular with support & resistance such as the study in this thread.

Repainters are the FASTEST way to find and be alerted to tops and bottoms which make them the preferred indicators for shorter timeframes..
But because repainters are such prolific liars, these studies should ONLY be used to make entry by traders proficient in using them in correlation with price action and candlestick patterns. These types of chart setups can be significantly profitable for disciplined traders.


The alert code functions with all of my stock indicators. but not for this study (the alert initially activates when I open the stock and the up arrow shows) (i.e I hear the sound and the alert appears in the messages box, but not afterwards). Could someone please help me? I desperately need the notifications because I can't keep watching the screen all the time. Thank you very much
Repainters go back and repaint the signals. So it is not possible to get an alert on the current bar.
You can change your alert code to alert "within 10 bars" which will tell you if it has repainted any of the last 10 bars.
 
ZigZags, Swings, Waves, Reversals, and Pivots are all repainting indicators.
No, repainting indicators can not be rewritten to not repaint.

Both arrows will repaint.

You will see more up arrow repainting when the instrument has a strong bearish trend. As it makes new lows the previous up arrows will be erased.
You will see more down arrow repainting when the instrument has a bullish trend. As it makes new highs the previous down arrows will be erased.

They are written specifically to repaint.
A stock makes a low, the study provides a signal. The stock goes lower. The study erases the signal and paints a new one.
That is the function of these indicators. And it is important in particular with support & resistance such as the study in this thread.

Repainters are the FASTEST way to find and be alerted to tops and bottoms which make them the preferred indicators for shorter timeframes..
But because repainters are such prolific liars, these studies should ONLY be used to make entry by traders proficient in using them in correlation with price action and candlestick patterns. These types of chart setups can be significantly profitable for disciplined traders.



Repainters go back and repaint the signals. So it is not possible to get an alert on the current bar.
You can change your alert code to alert "within 10 bars" which will tell you if it has repainted any of the last 10 bars.
I appreciate your response and the resolution. I've been watching this etf (Labu) nonstop for the last 30 minutes. When the up arrow appears (
at least during the time I was watching, the up arrow didn't get repainted)., the alert occasionally works and occasionally doesn't.
 
ANSWERS INTERSPERSED:

am i close?

Getting there yes

i copied the rules in post3 and tried to interpret them.
bn is barnumber

1. I meant to find the total number of bars behind and ahead of, for example, a valley low that have lows higher than that valley low until a bar is reached on both sides with a low less than the valley low.


find a valley,
(a valley implies that nearby lows will be higher)
...look at past bars, until a low that is lower than the valley. get barnumber
...look at future bars, until a low that is lower than the valley. get barnumber

Yes. Then find the FIRST highest bar past and future of that calculated range from the valley low and differentiate them from the valley low. (Ties always defer to the most recent for past bars or first to occur for future bars, ie how long did it take to get there?) Take the lesser of those two numbers (left and right side strength) and divide by 2. For Primary Impedance there is no division, and in this case, the IP or valley low is Secondary Impedance.

Hope that's clear. I try to be redundant to convey a better understanding. I could make a Glossary if it would help.



2. Then I would see how far back or forward as the case may be within those ranges on either side that the highest prices occurred before or after which a low less than the valley low occurs.


look for the highest price in,
...the past bars, to #1 past lower low. get bn
...the future bars, to #1 future lower low. get bn

EXACTLY!

3. Then I would take the lesser side of the two as measured in bars as the strength of the pivot.

YES!

?? 2 what?
the high $ or the lower lows?

Back/forward to the high $. Inside bars behind or ahead of the determined High-Low range are ignored.
compare the quantity of bars, from current valley, to the 2 highs , before and after.
x = min( #2 past highprice bn, #2 future high price bn )

You got it! And for Secondary, divide it by 2. Eg x = minSecondary( #2 past highprice bn, #2 future high price bn ) / 2;

4. This would then be compared with the size of the triggered pattern to determine if the Impedance Factor (support or resistance) is greater than the pattern (Thrust Factor). (I won't go into the pattern definition rules here.)

Right!

? no idea on what these terms are
Impedance Point (valley low)

They are synonymous.

5. If so, exit the trade at 89% of the way to that Impedance Point (in this case the valley low) with a profit.

Right. And the number 89% is not set in stone. It could be optimized later on, but for now let's use it. It's a good general point to take profits before the obvious high or low where other traders would want to get out. And it's a Fib number ;). Take a little less, up your winning percentage, and save time. Sometimes markets will stop short of obvious points where the majority looks to exit. Get the jump on them! It's a modification of Joe Ross' "trader's trick." Markets that stop like this usually reverse big-time, but that's another matter.

89% of some range, from the top?
is the range from a near high to the lowest low?

From in this case the lowest price of the pattern on the current bar to the IP or valley low.

6. If the pattern (Thrust Factor) is stronger than the Impedance Factor just described, then the market will likely penetrate the Impedance Point (in this case the valley low) and continue favorable downward movement.


?

Yes, and in this case the IF was stronger. If the TF is stronger, stay with the trade and look for the next IP that is strong enough to impede the move and exit accordingly. You will know your profit objective when entering every trade.

just wanted to let you know i haven't forgotten about this thread. i am in the middle of a couple of house projects, so i haven't had a couple of uninterupted hours to devout to it.
 
just wanted to let you know i haven't forgotten about this thread. i am in the middle of a couple of house projects, so i haven't had a couple of uninterupted hours to devout to it.

Actually I have sorta forgotten it. Been through some unkind sickness and personal traumas this month. Now slowly getting reoriented to finish this task and walk my talk. I thought I should become a VIP Member to support the whole cause that is this site. Don't want to be freeloading here. Too good of a site to take lightly. Thanks for the reminder, and no worries. I think you gave me much to go on that I have not had the opportunity to incorporate into my TS knowledge base that's been painfully slow to grow. Help along this last leg of my quest is always VERY appreciated. Thank you.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
463 Online
Create Post

Similar threads

Similar threads

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