Peaks Valleys Bar Questions

TNTrader5159

Active member
How would I call the BarNumber of a condition in its most recent occurrence prior to either the current bar or counting from x number of bars back? All I saw in the tutorial is that BarNumber() calls up the current bar. I do not understand what that means.

Let's say I want to call up the most recent occurrence of the Low being less than a defined reference in number of bars back, eg Low < Lowest(Low, 34)[1]. Thanks!
 
i am sorry for what you have gone through in life. i remember reading an earlier post where you mentioned some of this.
i am near your age and know about helping parents.
hang in there, keep asking questions and learning. this place will help you get there.

i hope you haven't read any negativity in any of my posts. sometimes i ask questions bluntly, trying to get someone to provide more information.

you made a recent post about some peak and valley formulas.
https://usethinkscript.com/threads/...peaks-and-valleys-crash-the-tos-editor.12979/
i will see about making a working version of it.
I will see about clarifying the PDI as you had asked a few questions about my annotated image. We have the engulfed bars and Thrust Factor already determined. I think those are understood as measuring the strength of the pattern (call it the ABCD pattern) where a market breaks into new ground, often slowly, then moves decisively the other way. This is what I call the "launch" of a move, and the thrust of that launch (Thrust Factor) is measured by the price range of the number of bars engulfed in that manner.
<p>
Support and resistance I generically label "impedance," from which I get the Impedance Factor.
<p>
I measure it in 3 ways: Peaks (Primary and Secondary), Valleys (Primary and Secondary), and congestion as measured by the Price Density Index or PDI for short. The formula actually does not need parentheses for order of operations, but it would be expressed in using them as (bar matches / total bars) * bar matches. A bar match is any past bar that includes within its range any price matching a given level relevant to a trade. Some bars in a series may not have a match and are excluded from the matches part but included in total bars.
<p>
If you're long Gold, you want to know the PDI at every price above your entry level tick by tick using all loaded data on the chart, though a script would need only display any PDI greater than the Thrust Factor of the pattern that launched the trade. Any relevant Peak, Valley, or PDI too close to the entry level would negate taking the trade at all. This happens quite a bit. We can determine just how close later. Suffice it to say no trade should be taken that is not worth the commission and slippage it would entail. This can vary according to time-frame and symbol.
<p>
The green line is just a random level I chose for illustration of the method in the image from before.
 

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

I will see about clarifying the PDI as you had asked a few questions about my annotated image. We have the engulfed bars and Thrust Factor already determined. I think those are understood as measuring the strength of the pattern (call it the ABCD pattern) where a market breaks into new ground, often slowly, then moves decisively the other way. This is what I call the "launch" of a move, and the thrust of that launch (Thrust Factor) is measured by the price range of the number of bars engulfed in that manner.
<p>
Support and resistance I generically label "impedance," from which I get the Impedance Factor.
<p>
I measure it in 3 ways: Peaks (Primary and Secondary), Valleys (Primary and Secondary), and congestion as measured by the Price Density Index or PDI for short. The formula actually does not need parentheses for order of operations, but it would be expressed in using them as (bar matches / total bars) * bar matches. A bar match is any past bar that includes within its range any price matching a given level relevant to a trade. Some bars in a series may not have a match and are excluded from the matches part but included in total bars.
<p>
If you're long Gold, you want to know the PDI at every price above your entry level tick by tick using all loaded data on the chart, though a script would need only display any PDI greater than the Thrust Factor of the pattern that launched the trade. Any relevant Peak, Valley, or PDI too close to the entry level would negate taking the trade at all. This happens quite a bit. We can determine just how close later. Suffice it to say no trade should be taken that is not worth the commission and slippage it would entail. This can vary according to time-frame and symbol.
<p>
The green line is just a random level I chose for illustration of the method in the image from before.
On the Peaks and Valleys as parts of the Impedance Factor, it works just like the Thrust Factor in taking the lesser of the two sides, as measured in the case of a Valley as the number of bars backward and forward to the highest price on either side out of all bars that stay equal to or above the Valley low until that Valley low is penetrated.
<p>
A Peak or Valley is considered Primary when it is untouched as with no penetration since its formation. If and when it is first penetrated, a Valley's support value begins to diminish at the rate of 0.5 * the number of bars fully below it (or 0.5 for every bar of the Valley's lesser side) until its value is cut in half and its support value is gone. For example, a Valley with a lesser side value of 5 would be "eaten up" as viable support at a rate of 0.5 bars at a time down to a minimum value of 2.5 that would then act as resistance should the market approach it and be "eaten up" potentially down to zero 0.5 bars at a time as it was when it acted as support. Any bars straddling the Valley level in either direction would count off as the percentage of the bar below the Valley * 0.5. So the Peak and Valley values are potentially dynamic until eliminated as both support and resistance once their original value is determined.
<p>
I am worn out for this evening, so if anyone has questions or would like illustrations of the above examples, I'll be happy to furnish them next time I get back to my computer.
 
declare lower;

def EngulfedHigh = Highest(high, fold ihigh = 3 to 1380
with counthigh = 3 while GetValue(high, -counthigh) < high do counthigh + 1);
# Number or prior highs less than the current high up to a maximum of 1380 (a day's session length in minutes)

def EngulfedLow = Lowest(low, fold ilow = 3 to 1380 with countlow = 3 while GetValue(low, -countlow) > low do countlow + 1);
# Number of prior lows greater than the current low up to a maximum of 1380 (a day's session length in minutes)

def EngulfedRange = if EngulfedHigh - EngulfedLow > ExpAverage(high - low, 987) then 1 else 0;
# Confirms the range of bars engulfed by the current bar is big enough to be worth trading as compared with the expressed average range of a single bar

plot Engulfed3 = if EngulfedHigh >= 3 && EngulfedLow >= 3 then 1 else 0;
# Confirms the current bar engulfs at least 3 bars and returns 1 if so

just rereading this post...
there will be several problems with it

trying to loop to 1380, on every bar , may be too many iterations, and may result in an error.

Do you want to confine your looping and checking to be within the same day or is it OK to look back 23 hours always.
You don't have any checks for start and stop of a day. so if it was an hour into the day and you're looking back 1380 bars, you're looking at yesterday's data.

I'm not sure about futures but with stocks the time period and pre market are not guaranteed to have price action and candles. so the candle count during premarket will be different every day. and during Normal hours something could happen where trading has stopped or doesn't happen and there will be less candles.
With stocks there is 6.5 hours of normal hours of trading, which is 390 minutes.
premarket may have one candle or may have 50. So Looping a set number to count them won't work with stocks.

it may be better to limit when loops are used. have formulas to find peaks and valleys. then if the bar is a peak or valley, then run the loops to count something.
i would reduce the 1380. maybe to 100, 200? how big of a number is useful? is a count of 500 more useful than 30? how often will 500 occur? 1 in 1000? not worth bogging down tos with excessive loops.
 
it's just a visual thing.
i don't like arrows and shapes touching candles. i want them separate. moving shapes away helps them to stick out and are easier for me to see.
Yeah I eventually figured that out when I plotted some things and saw the bubbles don't need to be too close to the bars as you said. Distance from them varies with the timeframe according to scale when it's .999 or .99 or .9.
 
just rereading this post...
there will be several problems with it

trying to loop to 1380, on every bar , may be too many iterations, and may result in an error.

Do you want to confine your looping and checking to be within the same day or is it OK to look back 23 hours always.
You don't have any checks for start and stop of a day. so if it was an hour into the day and you're looking back 1380 bars, you're looking at yesterday's data.

I'm not sure about futures but with stocks the time period and pre market are not guaranteed to have price action and candles. so the candle count during premarket will be different every day. and during Normal hours something could happen where trading has stopped or doesn't happen and there will be less candles.
With stocks there is 6.5 hours of normal hours of trading, which is 390 minutes.
premarket may have one candle or may have 50. So Looping a set number to count them won't work with stocks.

it may be better to limit when loops are used. have formulas to find peaks and valleys. then if the bar is a peak or valley, then run the loops to count something.
i would reduce the 1380. maybe to 100, 200? how big of a number is useful? is a count of 500 more useful than 30? how often will 500 occur? 1 in 1000? not worth bogging down tos with excessive loops.
Really all the bars that are needed in the lookback period for the measures of support/resistance would be enough to compare to the pattern strength (or Thrust Factor in my system). So yes, this number could be limited to say 144, if you go by Fibonacci numbers like I do. I'm especially partial to the number 144 anyway.
<p>
Since my account is too small to freely trade stocks or my favorite thing options due to the PDT rule, I am focusing only on the most liquid futures contracts with small tick increments like Gold, oil, and the Dow. Those can if needed be broken into the mini-contracts 1/10 the regular size.
<p>
Using a 1-minute chart for its own timeframe and from which to construct other ratios like 2:6, 3:9, 10:30 etc is the ideal for accuracy and maximizing opportunities. I would have to call upon secondary aggregates to bring support and resistance forward into my 1-minute chart that is necessarily limited in its scope.
<p>
If I use one bar engulfing 3 or more as a constant, then changing the timeframe and monitoring many timeframes at once would give the time scope that keeps the same minimum ratio to spot opportunities on all monitored aggregates. This would sacrifice some accuracy but likely is the best overall solution all things considered. The only caveat there is knowing which came first in the engulfment -- the high or low. It could be broken into 2 bars engulfing 6 or more as the constant base ratio and require the first bar to be the engulfing high (for a short trade setup) and second bar to be the engulfing low and thus trigger bar as it breaks below the range of bars engulfed. This can then be used to monitor charts of any number of different aggregates.
 
@TNTrader5159
Still working on this. Found a problem with the pivots. Had to go back and redefine the pivot flags.
Now each high pivot has a lower high on each side and a completely lower bar on each side.
Each low pivot has a higher low on each side and a completely higher bar on each side.
Also. have completed the bar count forwards and backwards of each pivot.

x4X2eju.png
 
@TNTrader5159
Still working on this. Found a problem with the pivots. Had to go back and redefine the pivot flags.
Now each high pivot has a lower high on each side and a completely lower bar on each side.
Each low pivot has a higher low on each side and a completely higher bar on each side.
Also. have completed the bar count forwards and backwards of each pivot.

x4X2eju.png
Looks good; nice work!
<p>
Now for high pivots (or peaks if you prefer), calculate the number of bars backward and forward to the lowest prices among all those lower bars on each side up until the high pivot (or peak) is first penetrated (if it is penetrated at all).
<p>
Likewise for low pivots (valleys if you prefer), calculate the number of bars backward and forward to the highest prices among all those higher bars on each side up until the low pivot (or valley) is first penetrated (if it is penetrated at all).
<p>
The LESSER of those two values is the base strength of the high or low pivot (peak or valley).
<p>
I will show you how to apply these as support and resistance once we have this much down pat.
<p>
Thank you!
 
Now for high pivots (or peaks if you prefer), calculate the number of bars backward and forward to the lowest prices among all those lower bars on each side up until the high pivot (or peak) is first penetrated (if it is penetrated at all).
<p>

you lost me on this.

lowest prices? prev lows?

penetrated?
you mean a price level is crossed by something? by what?
 
@TNTrader5159
Still working on this. Found a problem with the pivots. Had to go back and redefine the pivot flags.
Now each high pivot has a lower high on each side and a completely lower bar on each side.
Each low pivot has a higher low on each side and a completely higher bar on each side.
Also. have completed the bar count forwards and backwards of each pivot.

x4X2eju.png
Can you please share the code for the above chart/study?
 
you lost me on this.

lowest prices? prev lows?

penetrated?
you mean a price level is crossed by something? by what?
Lowest prices on either side of the high pivot (or peak) and the number of bars back to those lows. The high pivot (peak) being exceeded by any future trade price would constitute penetration.
you lost me on this.

lowest prices? prev lows?

penetrated?
you mean a price level is crossed by something? by what?
 
@majidg I will after I finish and clean it up, right now it's a mess of debug bubbles and vague variable names.
@TNTrader5159 yeah, got that working too.
k3Sw46Q.png
I'm working on the same basic thing, and you're way ahead of me with all the bubbles! It's at least good practice for me haha!
<p>
This is the first stage. Once this is down pat, we can get to how to figure the diminishing of the pivots' strength as they are penetrated by future price action above and below them to eventually render them no longer valid as support or resistance.
<p>
Then it will be time to learn to compare these pivots dynamically to the strength of any pattern launching a trade that would take place in order to determine entry and exit points. Stay tuned...
<p>
Goodnight gents!
 
@majidg I will after I finish and clean it up, right now it's a mess of debug bubbles and vague variable names.
@TNTrader5159 yeah, got that working too.
k3Sw46Q.png
Look at the bubbles again, it's already done.
Wow this is amazing! So you have included the depreciation factor that takes pivots from Initial Strength to End Strength?
<p>
The pivots that retain their Initial Strength value I call Primary Pivots. Once they begin to be depreciated, I call them Secondary Pivots.
<p>
I have a pivot depreciating by half a bar every time a bar crosses it for the first time. For example, a low pivot is crossed to the downside until up to half its value as support is lost. If the market goes up with only part of that value having been lost, it retains that remainder of its support value should the market turn back down.
<p>
I have tweaked this to add bars that straddle the pivot price as the percentage of the bar height below it * 0.5. Bars completely below the low pivot price are counted as 0.5 until the Initial Strength value is depreciated by half, at which time the pivot's support value is lost. From there it takes on half the Initial Strength value as resistance to any future upward price movement. If/when the original low pivot point is crossed to the upside, it depreciates from its remaining value again at the rate of half a bar for every bar above it, with bars straddling the original low pivot level counted as the percentage of the bar's height above that pivot level. The remainder of the pivot's resistance value is then depreciated until such time as the End Strength value is 0 and goes "off the board" forever.
<p>
So these pivots, once formed in their Initial Strength value, are dynamic and to be calculated as described above for reckoning as support or resistance for/to future price movement and trading activity.
<p>
I use the term "Impedance" to generically refer to either support or resistance and term the Initial Strength value on through such time as it goes "off the board" as a pivot's Impedance Factor.
<p>
I call the pivots Peaks and Valleys, and each of those are either Primary or Secondary. We are using a threshhold of 3 for minimum trade pattern strength, so really any pivot with a value less than 3 should be rendered as 0.
<p>
The whole idea behind this is that the degree to which a pivot turned price action one way or the other is its theoretical value in supporting or resisting future price movement that challenges it. The lesser side determines this value. If, for instance, a high pivot has 100 bars to the left and only 3 to the right, it's nearly a smooth line of declination so to speak that's only worth the 3 bars that interrupted what would have been a steady decline.
<p>
There is one more factor in valuing a pivot's strength expressed in bars, but ONLY as it relates to a pattern that launched a trade to challenge it. That would be factored into the trading rules that set exit points potentially based upon the locations and values of these pivots. I will go into that later.
<p>
The only other form of impedance (support/resistance) to consider in like manner aand along with these pivot values is what I call the Price Density Index or PDI for short. It measures the values within any price congestion zones that would stop a trade like a pivot would. It is actually simpler to calculate than the pivots and is not subject to depreciation as are pivots.
<p>
Blessings be upon you, Svanoy, for the great work you are doing, and do share your source code with us!
 
declare lower;
# Displays indicator in lower window

input countto = 144;
# Choose limit for bar counts

def bn = barnumber();
# Shorten barnumber()

def pivotcheck = if low < low[1] and low < low[-1] then bn else 0;
# If the low of a bar has at least 1 bar on each side with a higher low, return its bar number to indicate it is a valley, otherwise return 0

def pivotleftbars = if pivotcheck <> 0 then fold countleft = 1 to countto with a1 while low <= getvalue(low, countleft) do countleft + 1 else 0;
# Number of left side bars up to the maximum count of 144 having lows higher than the pivot

So far so good. Then I get confused. So at this point:

  • The bar number of any pivot as determined by <pivotcheck> is known.
  • The number of bars behind the pivot with lows greater than or equal to the pivot is known (pivotleftbars).
  • The current bar number is known.
<p>
So how would I follow to find the number of bars counting back from the pivot until the highest price of that known number behind the pivot having lows greater than or equal to the pivot?
 
@TNTrader5159 hoping to get time to work on this some tonight or tomorrow. Would like to clarify the "Impedence" reduction to make sure I am on the same page.

Referencing the high pivot circle in yellow, are the descriptions in the following red and green boxes correct?

tZOYRBa.png
 
declare lower;
# Displays indicator in lower window

input countto = 144;
# Choose limit for bar counts

def bn = barnumber();
# Shorten barnumber()

def pivotcheck = if low < low[1] and low < low[-1] then bn else 0;
# If the low of a bar has at least 1 bar on each side with a higher low, return its bar number to indicate it is a valley, otherwise return 0

def pivotleftbars = if pivotcheck <> 0 then fold countleft = 1 to countto with a1 while low <= getvalue(low, countleft) do countleft + 1 else 0;
# Number of left side bars up to the maximum count of 144 having lows higher than the pivot

So far so good. Then I get confused. So at this point:

  • The bar number of any pivot as determined by <pivotcheck> is known.
  • The number of bars behind the pivot with lows greater than or equal to the pivot is known (pivotleftbars).
  • The current bar number is known.
<p>
So how would I follow to find the number of bars counting back from the pivot until the highest price of that known number behind the pivot having lows greater than or equal to the pivot?

a code for post76,
looking back from a valley,
at the prev seq bars with higher lows,
find the highest high

i left the original code and words, and added to it.
there are yellow bubbles , that show below valleys, with several stats.
in between are gray bubbles with barnumber and high.

i'm guessing the next thing to do would be,
copy this code and modify it to look at future bars, after valleys.
then copy all of that and modify it to work on peaks, to look before and after a peak, for a lowest lows.

Ruby:
# look_at_prev_lows_find_highest_00

#https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/page-4#post-110277
# post78  10/14/22  TNTrader5159

input countto = 144;
# Choose limit for bar counts

def bn = BarNumber();
# Shorten barnumber()


#def pivotcheck =
#**** change variable name. pivot is vague. you will deal with peaks and valleys,  so use those words. replace check, vague. to check something, implies a true false possiblity, not an actual number.
#**** add a check if the first bar or last bar (offset error could cause a na to cascade through all values)

def valley_bn = if (bn == 1 or isnan(close[-1])) then 0
  else if (low < low[1] and low < low[-1]) then bn
  else 0;
# If the low of a bar has at least 1 bar on each side with a higher low, return its bar number to indicate it is a valley, otherwise return 0

def valley = (valley_bn > 0);

#def pivotleftbars = if pivotcheck <> 0 then fold countleft = 1 to countto with a1 while low <= GetValue(low, countleft) do countleft + 1 else 0;
#**** change name, to be more descriptive, use valley. replace bars with lows.
#**** change do variable , from countleft to a1.  you 'do' something to the temp variable spec'd by 'with'.  can't change the fold variable (shouldn't)
def valley_left_hilows = if valley_bn == 0 then 0
else fold countleft = 1 to countto
  with a1
  while (low <= GetValue(low, countleft))
  do a1 + 1 ;
# Number of left side bars up to the maximum count of 144 having lows higher than the pivot



#So far so good. Then I get confused. So at this point:

#The bar number of any pivot as determined by <pivotcheck> is known.
#**** valley_bn

#The number of bars behind the pivot with lows greater than or equal to the pivot is known (pivotleftbars).
#**** valley_left_hilows

#The current bar number is known.
#   bn


# added commas and separated your sentence and indented , to make it easier to read

# So how would I follow to,
#  find the number of bars counting back from the pivot,
#   until the highest price,
#    of that known number, behind the pivot, having lows greater than or equal to the pivot?


# rewritten

# So how would I find the number of bars counting back from the valley,
#   until the highest price,
#    that is within the  valley_left_hilows  quantity of bars?


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

# with another 2 loops

# look at  valley_left_hilows  quantity of bars before the valley,
#  and find which bar has the highest high,
#   and save the count (offset) back to it, from the valley

# need to +1 to the TO number , so it is included in the loop processing

#  looking at prev bar, not valley bar,   don't include the valley high.

# find highest prev hi
def v_prev_hi = if !valley then 0
  else fold i = 1 to valley_left_hilows + 1
  with j
  do (if GetValue(high, i) > j then GetValue(high, i) else j);

# find bn of highest prev hi
def v_prev_hioff = if !valley then 0
  else fold m = 1 to valley_left_hilows + 1
  with n
  do (if v_prev_hi == GetValue(high, m) then m else n);

def v_prev_hibn = if valley then (bn - v_prev_hioff) else 0;


input test1 = yes;
addchartbubble(test1 and valley, low*0.98,
bn + " bn\n" +
high + " high\n" +
valley_left_hilows + " left Lows\n" +
v_prev_hi + " prev hihi\n" +
v_prev_hioff + " hi off\n" +
v_prev_hibn + " hi bn"
, color.yellow, no);


addchartbubble(test1 and !valley, high*1.02,
bn + " bn\n" +
high + " hi\n"
, color.gray, yes);

#

WEsjXAO.jpg
 
Last edited:
@TNTrader5159 hoping to get time to work on this some tonight or tomorrow. Would like to clarify the "Impedence" reduction to make sure I am on the same page.

Referencing the high pivot circle in yellow, are the descriptions in the following red and green boxes correct?

No, though I think you have the right idea.
<p>
I made a note on a copy of this chart that says "Begin here and an arrow pointing to the bar that first penetrates the high pivot at 11,035. Note the strength of that pivot is only 3 since we are only dealing in number of bars and not factoring in the range, which is pretty enormous in the case of this one. Part of the bar I pointed to with the green arrow is above 11,035, so you take the percentage of that bar that is above that level and multiply it by 0.5 to begin depreciating the high pivot's resistance value. (Remember resistance is just one form of the generic term "impedance" I use to label support and resistance generically.) It is the single most important factor in determining when to pass on some trade signals and when to take profits on the trades that are taken.

The next bar (candle) has a tiny bit above 11,035 and then subsequent bars quickly depreciate the Initial Strength of the high pivot as resistance down to 1.5. There it will stand as support until it is eclipsed in the downward direction by net 3 bars, at which point it goes off the board never to be reckoned again. The range or height of a pivot matters, but we can factor that in later once this part is down pat.

https://netorgft9950864-my.sharepoi...JBq4SFrt-oFgkBZUK3NJ6UrnybY0fMB7svlQ?e=utbshD
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
254 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