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 close to having a code for post78,
looking back from a valley,
at all prev seq bars with higher lows,
find the highest high
It works just like finding the Thrust Factor within the Bars Engulfed for the pattern development. You know how many bars it is and where and just looking for in this case the most recent (if there are two or more occurrences) high and the number of bars behind the low pivot it occurs.
 

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

Very dumb question perhaps, but how do you find the highest price of a series of bars starting one bar ago that is a VARIABLE number we will call x?

highest(high, x) will not work since the parameter here shown as x must be a CONSTANT. HighestAll returns the highest price in a series of bars, but how do you define that series of bars just mentioned to find it that way?

Let's say a formula counts 10 bars for the variable x. So starting one bar ago, how do you find the highest price among those 10 bars stored as x?

This seems so bloody simple, but I'm having a mental block and thus stymied.
 
Very dumb question perhaps, but how do you find the highest price of a series of bars starting one bar ago that is a VARIABLE number we will call x?

highest(high, x) will not work since the parameter here shown as x must be a CONSTANT. HighestAll returns the highest price in a series of bars, but how do you define that series of bars just mentioned to find it that way?

Let's say a formula counts 10 bars for the variable x. So starting one bar ago, how do you find the highest price among those 10 bars stored as x?

This seems so bloody simple, but I'm having a mental block and thus stymied.

morning,

Functions like highest() don't like having a variable as the length parameter.
sometimes you can use getvalue() with a variable for the offset.
other times you need to use a fold loop with getvalue() to read from a group of bars.

a variable can be used as the 'to' parameter in a fold loop.
a fold loop can read data and compare from many bars and come up with one number.


you have already asked this several times, in different ways.

here are 2 of my answers. not sure , but svanoy may have answered it too.

https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/
post15

https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/
post79
 
Last edited:
morning,

Functions like highest() don't like having a variable as the length parameter.
sometimes you can use getvalue() with a variable for the offset.
other times you need to use a fold loop with getvalue() to read from a group of bars.

a variable can be used as the 'to' parameter in a fold loop.
a fold loop can read data and compare from many bars and come up with one number.


you have already asked this several times, in different ways.

here are 2 of my answers. not sure , but svanoy may have answered it too.

https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/
post15

https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/
post79
Sorry -- I did not think a variable could be used in the TO of a fold.
 
@TNTrader5159
Is my understanding correct now?

8kWZLXf.png
 
@TNTrader5159
Is my understanding correct now?

8kWZLXf.png
Exactly correct! Bravo! You did not have a running total displayed, but I could see you let it go until it added up to each half of the pivot's initial strength of 3 as primary resistance then 1.5 as secondary support, at which point it went off the board to be disregarded.
<p>
This is an approximate representation of the concept of primary and secondary support/resistance (or impedance). I don't use volume as a factor, since it varies according to market participation that fluctuates throughout the trading sessions. People are paid on price not volume.
<p>
Now that we have this down, only the height of the pivot should be factored in to represent how much actual price change it represented. Take the lesser side in height of price movement it supports or resists as a multiplying factor for when a subsequent trade is taken and comparison drawn.
<p>
For instance, a completed pattern height in Gold of $5.00 would be compared to a pivot's height value basis its lesser side. If the pivot's height is $7.50, its strength in bars (call it the Initial Impedance Factor) would be multiplied by the pivot's height divided by the pattern height. So it's bar strength * (pivot height / pattern height).
<p>
The net result is you are factoring in volume in a sense as measured in bars (Initial Impedance Factor) and its height in price movement to produce what you can call the Final Impedance Factor or simply Impedance Factor (support/resistance) as a measure in determining trade exit points based on pivots (Peaks or Valleys).
<p>
When the lesser side IN HEIGHT is eaten up in absolute price movement above/below it in both directions, it no longer has any height premium or discount. It works the same way as finding the Thrust Factor of a pattern or bar value of a pivot. You want the maximum price movement it supports or resists until it has been penetrated in the other direction by that same amount in height.
<p>
And it would depreciate the same way as price moves to eat up the height a tick at a time.
<p>
If you need any visual examples, let me know, and I will make something to post.
<p>
PS: How do you put those charts inline with the text of your posts? I've been linking to images I upload to my One Drive, and it would be great to know how to do this.
<p>
THANK YOU!
 
@TNTrader5159 I use imgur.com and then just copy and paste the BBcode for images.

This is where we are now, found it easier to start the support and resistance strengths at half pivot strength and decrement each when appropriate. Can just add them together to get the full strength in bars.

8daUkxA.png


If you need any visual examples, let me know, and I will make something to post.
Yes.
 
@TNTrader5159 are you getting height in price movement from the 'high pivots' high to 'low pivots' low or 'high pivot' close to 'low pivot' close?
No idea what a 'completed pattern height' is.
It's measured from the low pivot backward and forward to the highest price that occurs until the low is penetrated. It's measured in height and bars, with the lesser side standing as the initial strength in both cases.
<p>
The height is only relevant when a trade is considered. The pattern that triggers a trade is one bar engulfing at least 3 bars or two engulfing 6 bars etc. The ratio of the number of bars engulfed to the engulfing bar(s) is the equivalent of the initial strength for a pivot. The number of bars that include the high AND low of the engulfed range is called the Thrust Factor, and it's compared to the Impedance Factor as in the strength of the pivots and the Price Density Index as a measure of congestion that also acts as support and resistance. It's actually simpler to code than the pivots.
<p>
The engulfing bar is called the trigger bar. If it exceeds the low of the engulfed range FIRST, then penetrates the high of the engulfed range, it signals a possible LONG trade. In the reverse order, it signals a possible SHORT trade.
<p>
The Thrust Factor in whichever way it signals a trade on whatever time-frame will be compared to the Impedance Factor as measured by prior pivot strengths and the PDI in the range of favorable movement, eg upward from the entry point in a LONG trade. This determines whether or not to take a trade based upon relative sizes of the pattern strength vs the PDI or pivot strengths.
<p>
The height of the pivots is factored in as it compares with the height of the pattern. The pattern height is in the case of a SHORT trade setup measured from the High of the trigger bar to the Low of the engulfed range. For a LONG setup, it's measured from the Low of the trigger bar to the High of the engulfed range. I call this the Standard Profit Projection or SPP for short as an easy term to remember. You divide the height strength of a pivot by the pattern height or SPP and multiply that factor by the pivot height to get its effective strength for impeding a trade. So again, the height is a relative measure vs a given pattern height.
<p>
If a trade is taken, you already know your exit point where you take your profit or occasionally take a small loss and reverse your position to usually recoup any loss and more by finding the first Impedance Point (pivot Low, pivot High, or PDI) that is equal to or greater than the Thrust Factor of the triggering pattern. You should get out with your profit at a predetermined percentage of the way from the trade entry point at the latter penetration of the engulfed range as described above to the first such Impedance Point.
<p>
Then smile and look for your next trade!
 
It's measured from the low pivot backward and forward to the highest price that occurs until the low is penetrated. It's measured in height and bars, with the lesser side standing as the initial strength in both cases.
Ok, got that part done.
pYjPazN.png


The height is only relevant when a trade is considered. The pattern that triggers a trade is one bar engulfing at least 3 bars or two engulfing 6 bars etc. The ratio of the number of bars engulfed to the engulfing bar(s) is the equivalent of the initial strength for a pivot. The number of bars that include the high AND low of the engulfed range is called the Thrust Factor, and it's compared to the Impedance Factor as in the strength of the pivots and the Price Density Index as a measure of congestion that also acts as support and resistance. It's actually simpler to code than the pivots.
Do you already have that code? If so, is it to be integrated in to this code?
 
Ok, got that part done.
pYjPazN.png



Do you already have that code? If so, is it to be integrated in to this code?
I have some code from halcyonguy for the pattern and Thrust Factor complete with bubbles yes. Do you have it as well?
<p>
I have been working on that some to get ready to integrate it with your project with the pivots and also the Price Density Index when it gets developed.
<p>
I hit a stumblingblock with finding the highest (or lowest) prices in a known engulfed range and have to go back to halcyonguy's code and notes to get that part down.
<p>
I've been pushing too hard and hit mental exhaustion a few days ago, so going easy for as long as it takes to get my brain's battery recharged and thus limiting my computer time. Thanks so much for stepping up to join this effort! Let me know whatever you need, and I'll check back in soon.
 
Ok, got that part done.
pYjPazN.png



Do you already have that code? If so, is it to be integrated in to this code?
Not exactly no. It's only been written for one bar engulfing 3 or more. It should be written to include 2 bars engulfing at least 6, 3 engulfing at least 9, 4 engulfing at least 12, etc on up to as high as you wanna go. It all boils down to a RATIO of at least 3:1 in bars engulfed by a trigger bar or bars. Ideally it would use a 1-minute aggregate chart for maximum number of trade opportunities and best accuracy in entry. The drawback there is the support/resistance (Impedance Factor) with the pivots and PDI can extend well back behind the scope of a 1-minute chart. This makes calling on secondary aggregates a must if we are to use a 1-minute chart for trade signals. I believe someone sent me a link on how to do this. Here it is: https://tlc.thinkorswim.com/center/...hapter-11---Referencing-Secondary-Aggregation. Please check it out...thanks!
<p>
One other good point is that with using 2 or more bars, it becomes easy to tell which end of the engulfed range was penetrated first and require the current bar to be the trigger bar that did NOT eclipse the other end. Say if using two bars engulfing 6 or more (regardless of whether or not the Thrust Factor is at least 6), the first of the two would, in the case of a SHORT setup, eclipse the range on the high side, and the second and current bar would eclipse the Low to trigger a trade. If the previous bar had eclipsed both the High and Low of the engulfed range in that order, it would signal a trade with the one bar engulfing 3 or more part of the script and render the current bar irrelevant.
 
Not exactly no. It's only been written for one bar engulfing 3 or more. It should be written to include 2 bars engulfing at least 6, 3 engulfing at least 9, 4 engulfing at least 12, etc on up to as high as you wanna go. It all boils down to a RATIO of at least 3:1 in bars engulfed by a trigger bar or bars. Ideally it would use a 1-minute aggregate chart for maximum number of trade opportunities and best accuracy in entry. The drawback there is the support/resistance (Impedance Factor) with the pivots and PDI can extend well back behind the scope of a 1-minute chart. This makes calling on secondary aggregates a must if we are to use a 1-minute chart for trade signals. I believe someone sent me a link on how to do this. Here it is: https://tlc.thinkorswim.com/center/...hapter-11---Referencing-Secondary-Aggregation. Please check it out...thanks!
<p>
One other good point is that with using 2 or more bars, it becomes easy to tell which end of the engulfed range was penetrated first and require the current bar to be the trigger bar that did NOT eclipse the other end. Say if using two bars engulfing 6 or more (regardless of whether or not the Thrust Factor is at least 6), the first of the two would, in the case of a SHORT setup, eclipse the range on the high side, and the second and current bar would eclipse the Low to trigger a trade. If the previous bar had eclipsed both the High and Low of the engulfed range in that order, it would signal a trade with the one bar engulfing 3 or more part of the script and render the current bar irrelevant.
Here's halcyonguy's code for the Thrust Factor. It's the strength of a completed pattern that breaks in either direction. You take this value and compare it to any Impedance values in the direction of favorable movement once both ends of the engulfed range have been eclipsed. The first Impedance Point reached, based upon the Pivots or the PDI as mentioned earlier that are >= the Thrust Factor determines your exit point. Take the pre-defined (as an input) percentage of the move from the entry point to that pivot-based Impedance Point as the price to exit MIT. In the case of the PDI stopping a trade, it is AT the first PDI reached that is >= The Thrust Factor.
<p>
The endless (we hope) battle of the irresistible force and the immovable object is always in play with this strategy. It's not omniscient or 100% accurate as far as the comparative values while actual market action theoretically takes into account other mundane factors such as volume and its variations, but I think it's close enough to perfect for me.
<p>
The Thrust Ratio in the following code is really not necessary, though it might be interesting to see how many times you have 3 or more bars engulfed without at least a 3 Thrust Factor. Hats off to halcyonguy for his knowledge and efforts here!...
<p>
# outsidebars_02b_engulf_cln

# mod with his rules
# rework engulf , # with thrust terms
# https://usethinkscript.com/threads/...thin-a-known-group-of-bars.12721/#post-108393
# post10 TNTrader5159
#------------------------------------

# engulfing pattern,
# find qty of engulf bars, display in a bubble
# draw lines to mother bar

def na = double.nan;
def bn = barnumber();

input minimum_engulfed_bars = 3;
input show_engulfed_count_bubbles = yes;
input show_horizontal_engulf_lines = yes;
def lookback = 48;
#def offset = lookback;
def barup = (close > open);

# find engulfing bar
# look backwards for an engulfing bar
# count how many previous bars are smaller than the current bar
#def lookback = 48;
def bigbarcnt1 = fold k = 1 to lookback
with p
while (high >= getvalue(high, k) and low <= getvalue(low, k))
do p + 1;

# disable engulfing bars with too few smaller bars
def bigbarcnt2 = if bigbarcnt1 >= minimum_engulfed_bars then bigbarcnt1 else 0;

# is the next future engulf bar, engulfing the current engulf bar?
# if yes , then disable current engulf bar
def bigbar_off2 = fold m = 1 to lookback
with q = 1
while getvalue(bigbarcnt2, -m) == 0
do q + 1;
def bigbarcnt3;
if isnan( getvalue(high, -bigbar_off2) ) then {
bigbarcnt3 = bigbarcnt2;
} else if (getvalue(high, -bigbar_off2) > high and getvalue(low, -bigbar_off2) < low) then {
bigbarcnt3 = 0;
} else {
bigbarcnt3 = bigbarcnt2;
}

def outbar = if (bigbarcnt3 >= minimum_engulfed_bars) then 1 else 0;

# bubble with qty of engulfed bars
addchartbubble(show_engulfed_count_bubbles and outbar,(low * 0.999), bigbarcnt3, if bigbarcnt3 == 0 then color.dark_gray else if barup then color.green else color.red, no);

# look ahead to find qty of bars to next mother bar
def engulf_off = fold n = 0 to lookback
with r
while getvalue(bigbarcnt3, -n) == 0
do r + 1;

def gulf_hi = if (show_horizontal_engulf_lines and getvalue(bigbarcnt3, -engulf_off) >= engulf_off) then getvalue(high, -engulf_off) else na;
def gulf_lo = if (show_horizontal_engulf_lines and getvalue(bigbarcnt3, -engulf_off) >= engulf_off) then getvalue(low, -engulf_off) else na;
plot zhi = gulf_hi;
plot zlo = gulf_lo;
zhi.SetDefaultColor(Color.cyan);
zhi.hidebubble();
zlo.SetDefaultColor(Color.cyan);
zlo.hidebubble();


def engulf_first = bn - bigbarcnt3;
input test_show_first_last_bns = yes;
addchartbubble(test_show_first_last_bns and outbar,(low * 0.999),
bn + " this bn\n" +
engulf_first + " first bn\n"
, color.gray, no);


# find the first bar in an engulfed line, which is the same as the engulfed group
def line_start = if (isnan(gulf_hi[1]) and !isnan(gulf_hi)) then 1 else 0;
def start_bn = if line_start then bn else start_bn[1];


input test_show_first_bn = yes;
addchartbubble(test_show_first_bn and line_start, gulf_hi,
start_bn + " start bn\n" +
engulf_off + " engulfed bars"
, color.yellow, yes);


#-----------------------------
# test stuff

input test1 = no;
addchartbubble(test1 , high,
engulf_off + "\n" +
line_start + "\n" +
start_bn
, (if line_start then color.yellow else color.gray), yes);

input test2 = no;
addchartbubble(test2, (low * 0.999),
bigbarcnt1 + " 1\n" +
bigbarcnt2 + " 2\n" +
bigbar_off2 + " off2\n" +
bigbarcnt3 + " 3\n"
# engulf_off
, color.cyan, no);


#input test_bubbles1 = no;
def test_bubbles1 = 0;
addchartbubble((test_bubbles1 and bigbarcnt1 > 0),(low * 0.999), bigbarcnt1 + " 1", if bigbarcnt1 == 0 then color.dark_gray else if barup then color.green else color.red, no);

addchartbubble((test_bubbles1 and bigbarcnt2 >= minimum_engulfed_bars),(low * 0.999), bigbarcnt2 + " 2", if bigbarcnt2 == 0 then color.dark_gray else if barup then color.green else color.red, no);

addchartbubble((test_bubbles1 and bigbarcnt3 >= minimum_engulfed_bars),(low * 0.999), bigbarcnt3 + " 3", if bigbarcnt3 == 0 then color.dark_gray else if barup then color.green else color.red, no);

# mod with his rules in post#10
# rework engulf , with thrust terms
# https://usethinkscript.com/threads/...thin-a-known-group-of-bars.12721/#post-108393
# post10 TNTrader5159
#------------------------------------
# make new vars, labels

# 1. Yes, first to see HOW MANY bars the current bar may engulf.
# recent engulf quantity
def engulf_bars = if outbar then bigbarcnt3 else engulf_bars[1];
addlabel(1, "recent engulf bars, quantity " + engulf_bars, color.yellow);


# 2. Then to find the relative positions of the highest and lowest prices within the engulfed range.

# loop , from line_start to outbar
# loop , 0 to engulf_off ( the qty of engulded bars )

def engulfed_hi;
def engulfed_lo;
def engulfed_hibn;
def engulfed_lobn;
def xbn;
if line_start then {
xbn = bn;
# start at the 1st bar of an engulfed period,
# look at future bars for the highest price
engulfed_hi = fold g1 = 0 to (engulf_off-0)
with g2
while !isnan(gulf_hi)
do (if getvalue(high, -g1) > g2 then getvalue(high, -g1) else g2);

# look at future bars for the lowest price
engulfed_lo = fold h1 = 0 to (engulf_off-0)
with h2 = 99999
while !isnan(gulf_hi)
do (if getvalue(low, -h1) < h2 then getvalue(low, -h1) else h2);


# look for the highest and lowest price , and read the bn
engulfed_hibn = fold g3 = 0 to (engulf_off - 0)
with g4
while !isnan(gulf_hi)
do (if engulfed_hi == getvalue(high, -g3) then (bn + g3) else g4);

engulfed_lobn = fold h3 = 0 to (engulf_off-0)
with h4
while !isnan(gulf_hi)
do (if engulfed_lo == getvalue(low, -h3) then (bn + h3) else h4);
} else {
engulfed_hi = engulfed_hi[1];
engulfed_lo = engulfed_lo[1];
engulfed_hibn = engulfed_hibn[1];
engulfed_lobn = engulfed_lobn[1];
xbn = xbn[1];
}


# plot points on highest and lowest prices, that are engulfed
input show_points_onhighest_lowest_in_engulfed_group = yes;
plot zenhi = if show_points_onhighest_lowest_in_engulfed_group and bn == engulfed_hibn then high else na;
zenhi.SetPaintingStrategy(PaintingStrategy.POINTS);
zenhi.SetDefaultColor(Color.white);
zenhi.setlineweight(2);
zenhi.hidebubble();

plot zenlo = if show_points_onhighest_lowest_in_engulfed_group and bn == engulfed_lobn then low else na;
#plot zenlo = if bn == xbn then low else na;
zenlo.SetPaintingStrategy(PaintingStrategy.POINTS);
zenlo.SetDefaultColor(Color.white);
zenlo.setlineweight(2);
zenlo.hidebubble();


input test_hi_lo_bns = yes;
addchartbubble(test_hi_lo_bns and line_start, gulf_lo*0.999,
"hi $" + engulfed_hi + " at bn: " + engulfed_hibn + "\n" +
"lo $" + engulfed_lo + " at bn: " + engulfed_lobn
, color.yellow, no);


# 3. Then to take the farther one back or lower bar number of those two prices, and subtract it from the current bar number.

def engulf_minbn = min( engulfed_hibn, engulfed_lobn);
def t = if line_start then ((bn + engulf_off) - engulf_minbn) else t[1];

# offset from first engulfed bar , to the first low/hi
def t_start_off = engulf_minbn - bn;


# 4. This returns the final value I call the Thrust Factor.
# The Thrust Factor measures the strength of the pattern once a breakout to either the upside or downside of the engulfed range occurs in real time.
# And of course which occurs first is the key to trade direction. That's another matter though.


# is the offset t pointing to the highest price in the group?
def isfirst_hi = if getvalue(high, -t_start_off) == engulfed_hi then 1 else 0;

# show a green or red bubble, on the first bar of engulfed group, that lists which comes first, a low or a high.
addchartbubble(line_start, gulf_lo*0.999,
getvalue(high, -t_start_off) + " t hi\n" +
#engulfed_hi + " ehi\n" +
(if isfirst_hi then "High" else "Low") + " is first"
, (if isfirst_hi then color.green else color.red), no);



# rule 4 questions
# you will have to define what a breakout is.
# there will be a highest price and a lowest price DURING a group of engulfed bars.
# but thos 2 points are within the engulfed price range. they didn't 'breakout'.

# there is only 1 breakout during a group of engulfed bars, on the bar after the last, big, engulfing bar.
# ( we could call the first bar, a breakin )


# 5. The Thrust Factor must be a minimum of 3 to qualify for a legit pattern per my definition. Otherwise it would be discarded from further qualifications for a trade, ie the Impedance Factor, which is irrelevant to the current discussion.

def t_min = 3;
def thrust_factor = if t < t_min then 0 else t;
def thrust_ratio = round(thrust_factor/ engulf_off,2);

addchartbubble(line_start, gulf_lo*0.999,
thrust_factor + " thrust_factor \n" +
#t + "\n" +
"out of\n" +
engulf_off + " engulfed bars\n" +
"is a ratio of\n" +
thrust_ratio + " : 1"
, (if isfirst_hi then color.green else color.red), no);


# 6. So for now, if I can determine the Thrust Factor, that part will be complete.

# 7 Your code shows the sizes of all engulfed ranges, which is good, and now only the highs and lows of those engulfed ranges need to be determined, with the bar number of the farther one back subtracted from the number of the engulfing bar to return the Thrust Factor.

# 8. It looks like the Thrust Factor of the first example on your chart with 21 total bars engulfed would be either 16 or 21, as it's hard to tell which of those two bars was higher. The second example with 7 total bars engulfed would be 6, with the high occurring on Bar 179 and the low on Bar 176 vs Bar 182 as the engulfing bar.

# 9. Both signals indicated taking Short positions.
 
Here's halcyonguy's code for the Thrust Factor. It's the strength of a completed pattern that breaks in either direction. You take this value and compare it to any Impedance values in the direction of favorable movement once both ends of the engulfed range have been eclipsed. The first Impedance Point reached, based upon the Pivots or the PDI as mentioned earlier that are >= the Thrust Factor determines your exit point. Take the pre-defined (as an input) percentage of the move from the entry point to that pivot-based Impedance Point as the price to exit MIT. In the case of the PDI stopping a trade, it is AT the first PDI reached that is >= The Thrust Factor.
<p>
The endless (we hope) battle of the irresistible force and the immovable object is always in play with this strategy. It's not omniscient or 100% accurate as far as the comparative values while actual market action theoretically takes into account other mundane factors such as volume and its variations, but I think it's close enough to perfect for me.
<p>
The Thrust Ratio in the following code is really not necessary, though it might be interesting to see how many times you have 3 or more bars engulfed without at least a 3 Thrust Factor. Hats off to halcyonguy for his knowledge and efforts here!...
<p>
# outsidebars_02b_engulf_cln

# mod with his rules
# rework engulf , # with thrust terms
# https://usethinkscript.com/threads/...thin-a-known-group-of-bars.12721/#post-108393
# post10 TNTrader5159
#------------------------------------

# engulfing pattern,
# find qty of engulf bars, display in a bubble
# draw lines to mother bar

def na = double.nan;
def bn = barnumber();

input minimum_engulfed_bars = 3;
input show_engulfed_count_bubbles = yes;
input show_horizontal_engulf_lines = yes;
def lookback = 48;
#def offset = lookback;
def barup = (close > open);

# find engulfing bar
# look backwards for an engulfing bar
# count how many previous bars are smaller than the current bar
#def lookback = 48;
def bigbarcnt1 = fold k = 1 to lookback
with p
while (high >= getvalue(high, k) and low <= getvalue(low, k))
do p + 1;

# disable engulfing bars with too few smaller bars
def bigbarcnt2 = if bigbarcnt1 >= minimum_engulfed_bars then bigbarcnt1 else 0;

# is the next future engulf bar, engulfing the current engulf bar?
# if yes , then disable current engulf bar
def bigbar_off2 = fold m = 1 to lookback
with q = 1
while getvalue(bigbarcnt2, -m) == 0
do q + 1;
def bigbarcnt3;
if isnan( getvalue(high, -bigbar_off2) ) then {
bigbarcnt3 = bigbarcnt2;
} else if (getvalue(high, -bigbar_off2) > high and getvalue(low, -bigbar_off2) < low) then {
bigbarcnt3 = 0;
} else {
bigbarcnt3 = bigbarcnt2;
}

def outbar = if (bigbarcnt3 >= minimum_engulfed_bars) then 1 else 0;

# bubble with qty of engulfed bars
addchartbubble(show_engulfed_count_bubbles and outbar,(low * 0.999), bigbarcnt3, if bigbarcnt3 == 0 then color.dark_gray else if barup then color.green else color.red, no);

# look ahead to find qty of bars to next mother bar
def engulf_off = fold n = 0 to lookback
with r
while getvalue(bigbarcnt3, -n) == 0
do r + 1;

def gulf_hi = if (show_horizontal_engulf_lines and getvalue(bigbarcnt3, -engulf_off) >= engulf_off) then getvalue(high, -engulf_off) else na;
def gulf_lo = if (show_horizontal_engulf_lines and getvalue(bigbarcnt3, -engulf_off) >= engulf_off) then getvalue(low, -engulf_off) else na;
plot zhi = gulf_hi;
plot zlo = gulf_lo;
zhi.SetDefaultColor(Color.cyan);
zhi.hidebubble();
zlo.SetDefaultColor(Color.cyan);
zlo.hidebubble();


def engulf_first = bn - bigbarcnt3;
input test_show_first_last_bns = yes;
addchartbubble(test_show_first_last_bns and outbar,(low * 0.999),
bn + " this bn\n" +
engulf_first + " first bn\n"
, color.gray, no);


# find the first bar in an engulfed line, which is the same as the engulfed group
def line_start = if (isnan(gulf_hi[1]) and !isnan(gulf_hi)) then 1 else 0;
def start_bn = if line_start then bn else start_bn[1];


input test_show_first_bn = yes;
addchartbubble(test_show_first_bn and line_start, gulf_hi,
start_bn + " start bn\n" +
engulf_off + " engulfed bars"
, color.yellow, yes);


#-----------------------------
# test stuff

input test1 = no;
addchartbubble(test1 , high,
engulf_off + "\n" +
line_start + "\n" +
start_bn
, (if line_start then color.yellow else color.gray), yes);

input test2 = no;
addchartbubble(test2, (low * 0.999),
bigbarcnt1 + " 1\n" +
bigbarcnt2 + " 2\n" +
bigbar_off2 + " off2\n" +
bigbarcnt3 + " 3\n"
# engulf_off
, color.cyan, no);


#input test_bubbles1 = no;
def test_bubbles1 = 0;
addchartbubble((test_bubbles1 and bigbarcnt1 > 0),(low * 0.999), bigbarcnt1 + " 1", if bigbarcnt1 == 0 then color.dark_gray else if barup then color.green else color.red, no);

addchartbubble((test_bubbles1 and bigbarcnt2 >= minimum_engulfed_bars),(low * 0.999), bigbarcnt2 + " 2", if bigbarcnt2 == 0 then color.dark_gray else if barup then color.green else color.red, no);

addchartbubble((test_bubbles1 and bigbarcnt3 >= minimum_engulfed_bars),(low * 0.999), bigbarcnt3 + " 3", if bigbarcnt3 == 0 then color.dark_gray else if barup then color.green else color.red, no);

# mod with his rules in post#10
# rework engulf , with thrust terms
# https://usethinkscript.com/threads/...thin-a-known-group-of-bars.12721/#post-108393
# post10 TNTrader5159
#------------------------------------
# make new vars, labels

# 1. Yes, first to see HOW MANY bars the current bar may engulf.
# recent engulf quantity
def engulf_bars = if outbar then bigbarcnt3 else engulf_bars[1];
addlabel(1, "recent engulf bars, quantity " + engulf_bars, color.yellow);


# 2. Then to find the relative positions of the highest and lowest prices within the engulfed range.

# loop , from line_start to outbar
# loop , 0 to engulf_off ( the qty of engulded bars )

def engulfed_hi;
def engulfed_lo;
def engulfed_hibn;
def engulfed_lobn;
def xbn;
if line_start then {
xbn = bn;
# start at the 1st bar of an engulfed period,
# look at future bars for the highest price
engulfed_hi = fold g1 = 0 to (engulf_off-0)
with g2
while !isnan(gulf_hi)
do (if getvalue(high, -g1) > g2 then getvalue(high, -g1) else g2);

# look at future bars for the lowest price
engulfed_lo = fold h1 = 0 to (engulf_off-0)
with h2 = 99999
while !isnan(gulf_hi)
do (if getvalue(low, -h1) < h2 then getvalue(low, -h1) else h2);


# look for the highest and lowest price , and read the bn
engulfed_hibn = fold g3 = 0 to (engulf_off - 0)
with g4
while !isnan(gulf_hi)
do (if engulfed_hi == getvalue(high, -g3) then (bn + g3) else g4);

engulfed_lobn = fold h3 = 0 to (engulf_off-0)
with h4
while !isnan(gulf_hi)
do (if engulfed_lo == getvalue(low, -h3) then (bn + h3) else h4);
} else {
engulfed_hi = engulfed_hi[1];
engulfed_lo = engulfed_lo[1];
engulfed_hibn = engulfed_hibn[1];
engulfed_lobn = engulfed_lobn[1];
xbn = xbn[1];
}


# plot points on highest and lowest prices, that are engulfed
input show_points_onhighest_lowest_in_engulfed_group = yes;
plot zenhi = if show_points_onhighest_lowest_in_engulfed_group and bn == engulfed_hibn then high else na;
zenhi.SetPaintingStrategy(PaintingStrategy.POINTS);
zenhi.SetDefaultColor(Color.white);
zenhi.setlineweight(2);
zenhi.hidebubble();

plot zenlo = if show_points_onhighest_lowest_in_engulfed_group and bn == engulfed_lobn then low else na;
#plot zenlo = if bn == xbn then low else na;
zenlo.SetPaintingStrategy(PaintingStrategy.POINTS);
zenlo.SetDefaultColor(Color.white);
zenlo.setlineweight(2);
zenlo.hidebubble();


input test_hi_lo_bns = yes;
addchartbubble(test_hi_lo_bns and line_start, gulf_lo*0.999,
"hi $" + engulfed_hi + " at bn: " + engulfed_hibn + "\n" +
"lo $" + engulfed_lo + " at bn: " + engulfed_lobn
, color.yellow, no);


# 3. Then to take the farther one back or lower bar number of those two prices, and subtract it from the current bar number.

def engulf_minbn = min( engulfed_hibn, engulfed_lobn);
def t = if line_start then ((bn + engulf_off) - engulf_minbn) else t[1];

# offset from first engulfed bar , to the first low/hi
def t_start_off = engulf_minbn - bn;


# 4. This returns the final value I call the Thrust Factor.
# The Thrust Factor measures the strength of the pattern once a breakout to either the upside or downside of the engulfed range occurs in real time.
# And of course which occurs first is the key to trade direction. That's another matter though.


# is the offset t pointing to the highest price in the group?
def isfirst_hi = if getvalue(high, -t_start_off) == engulfed_hi then 1 else 0;

# show a green or red bubble, on the first bar of engulfed group, that lists which comes first, a low or a high.
addchartbubble(line_start, gulf_lo*0.999,
getvalue(high, -t_start_off) + " t hi\n" +
#engulfed_hi + " ehi\n" +
(if isfirst_hi then "High" else "Low") + " is first"
, (if isfirst_hi then color.green else color.red), no);



# rule 4 questions
# you will have to define what a breakout is.
# there will be a highest price and a lowest price DURING a group of engulfed bars.
# but thos 2 points are within the engulfed price range. they didn't 'breakout'.

# there is only 1 breakout during a group of engulfed bars, on the bar after the last, big, engulfing bar.
# ( we could call the first bar, a breakin )


# 5. The Thrust Factor must be a minimum of 3 to qualify for a legit pattern per my definition. Otherwise it would be discarded from further qualifications for a trade, ie the Impedance Factor, which is irrelevant to the current discussion.

def t_min = 3;
def thrust_factor = if t < t_min then 0 else t;
def thrust_ratio = round(thrust_factor/ engulf_off,2);

addchartbubble(line_start, gulf_lo*0.999,
thrust_factor + " thrust_factor \n" +
#t + "\n" +
"out of\n" +
engulf_off + " engulfed bars\n" +
"is a ratio of\n" +
thrust_ratio + " : 1"
, (if isfirst_hi then color.green else color.red), no);


# 6. So for now, if I can determine the Thrust Factor, that part will be complete.

# 7 Your code shows the sizes of all engulfed ranges, which is good, and now only the highs and lows of those engulfed ranges need to be determined, with the bar number of the farther one back subtracted from the number of the engulfing bar to return the Thrust Factor.

# 8. It looks like the Thrust Factor of the first example on your chart with 21 total bars engulfed would be either 16 or 21, as it's hard to tell which of those two bars was higher. The second example with 7 total bars engulfed would be 6, with the high occurring on Bar 179 and the low on Bar 176 vs Bar 182 as the engulfing bar.

# 9. Both signals indicated taking Short positions.

code in post #94
https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/#post-108548
post15
# outsidebars_02b_engulf_cln

i can't find source of 2nd half.

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

@TNTrader5159
try to include links to original. i try to include a unique name in most of my codes. makes it easier to search for.

try to post code in a code window. it makes a post a lot easier to read.
in the header, look for </> icon. click it and a window pops open . paste code in it.
 
code in post #94
https://usethinkscript.com/threads/peaks-valleys-bar-questions.13012/#post-108548
post15
# outsidebars_02b_engulf_cln

i can't find source of 2nd half.

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

@TNTrader5159
try to include links to original. i try to include a unique name in most of my codes. makes it easier to search for.

try to post code in a code window. it makes a post a lot easier to read.
in the header, look for </> icon. click it and a window pops open . paste code in it.
I will thank you. I'm working on a code outline or decision tree for the PDI and will send it along soon.
 
Here's halcyonguy's code for the Thrust Factor. It's the strength of a completed pattern that breaks in either direction. You take this value and compare it to any Impedance values in the direction of favorable movement once both ends of the engulfed range have been eclipsed. The first Impedance Point reached, based upon the Pivots or the PDI as mentioned earlier that are >= the Thrust Factor determines your exit point. Take the pre-defined (as an input) percentage of the move from the entry point to that pivot-based Impedance Point as the price to exit MIT. In the case of the PDI stopping a trade, it is AT the first PDI reached that is >= The Thrust Factor.
<p>
The endless (we hope) battle of the irresistible force and the immovable object is always in play with this strategy. It's not omniscient or 100% accurate as far as the comparative values while actual market action theoretically takes into account other mundane factors such as volume and its variations, but I think it's close enough to perfect for me.
<p>
The Thrust Ratio in the following code is really not necessary, though it might be interesting to see how many times you have 3 or more bars engulfed without at least a 3 Thrust Factor. Hats off to halcyonguy for his knowledge and efforts here!...
<p>
# outsidebars_02b_engulf_cln

# mod with his rules
# rework engulf , # with thrust terms
# https://usethinkscript.com/threads/...thin-a-known-group-of-bars.12721/#post-108393
# post10 TNTrader5159
#------------------------------------

# engulfing pattern,
# find qty of engulf bars, display in a bubble
# draw lines to mother bar

def na = double.nan;
def bn = barnumber();

input minimum_engulfed_bars = 3;
input show_engulfed_count_bubbles = yes;
input show_horizontal_engulf_lines = yes;
def lookback = 48;
#def offset = lookback;
def barup = (close > open);

# find engulfing bar
# look backwards for an engulfing bar
# count how many previous bars are smaller than the current bar
#def lookback = 48;
def bigbarcnt1 = fold k = 1 to lookback
with p
while (high >= getvalue(high, k) and low <= getvalue(low, k))
do p + 1;

# disable engulfing bars with too few smaller bars
def bigbarcnt2 = if bigbarcnt1 >= minimum_engulfed_bars then bigbarcnt1 else 0;

# is the next future engulf bar, engulfing the current engulf bar?
# if yes , then disable current engulf bar
def bigbar_off2 = fold m = 1 to lookback
with q = 1
while getvalue(bigbarcnt2, -m) == 0
do q + 1;
def bigbarcnt3;
if isnan( getvalue(high, -bigbar_off2) ) then {
bigbarcnt3 = bigbarcnt2;
} else if (getvalue(high, -bigbar_off2) > high and getvalue(low, -bigbar_off2) < low) then {
bigbarcnt3 = 0;
} else {
bigbarcnt3 = bigbarcnt2;
}

def outbar = if (bigbarcnt3 >= minimum_engulfed_bars) then 1 else 0;

# bubble with qty of engulfed bars
addchartbubble(show_engulfed_count_bubbles and outbar,(low * 0.999), bigbarcnt3, if bigbarcnt3 == 0 then color.dark_gray else if barup then color.green else color.red, no);

# look ahead to find qty of bars to next mother bar
def engulf_off = fold n = 0 to lookback
with r
while getvalue(bigbarcnt3, -n) == 0
do r + 1;

def gulf_hi = if (show_horizontal_engulf_lines and getvalue(bigbarcnt3, -engulf_off) >= engulf_off) then getvalue(high, -engulf_off) else na;
def gulf_lo = if (show_horizontal_engulf_lines and getvalue(bigbarcnt3, -engulf_off) >= engulf_off) then getvalue(low, -engulf_off) else na;
plot zhi = gulf_hi;
plot zlo = gulf_lo;
zhi.SetDefaultColor(Color.cyan);
zhi.hidebubble();
zlo.SetDefaultColor(Color.cyan);
zlo.hidebubble();


def engulf_first = bn - bigbarcnt3;
input test_show_first_last_bns = yes;
addchartbubble(test_show_first_last_bns and outbar,(low * 0.999),
bn + " this bn\n" +
engulf_first + " first bn\n"
, color.gray, no);


# find the first bar in an engulfed line, which is the same as the engulfed group
def line_start = if (isnan(gulf_hi[1]) and !isnan(gulf_hi)) then 1 else 0;
def start_bn = if line_start then bn else start_bn[1];


input test_show_first_bn = yes;
addchartbubble(test_show_first_bn and line_start, gulf_hi,
start_bn + " start bn\n" +
engulf_off + " engulfed bars"
, color.yellow, yes);


#-----------------------------
# test stuff

input test1 = no;
addchartbubble(test1 , high,
engulf_off + "\n" +
line_start + "\n" +
start_bn
, (if line_start then color.yellow else color.gray), yes);

input test2 = no;
addchartbubble(test2, (low * 0.999),
bigbarcnt1 + " 1\n" +
bigbarcnt2 + " 2\n" +
bigbar_off2 + " off2\n" +
bigbarcnt3 + " 3\n"
# engulf_off
, color.cyan, no);


#input test_bubbles1 = no;
def test_bubbles1 = 0;
addchartbubble((test_bubbles1 and bigbarcnt1 > 0),(low * 0.999), bigbarcnt1 + " 1", if bigbarcnt1 == 0 then color.dark_gray else if barup then color.green else color.red, no);

addchartbubble((test_bubbles1 and bigbarcnt2 >= minimum_engulfed_bars),(low * 0.999), bigbarcnt2 + " 2", if bigbarcnt2 == 0 then color.dark_gray else if barup then color.green else color.red, no);

addchartbubble((test_bubbles1 and bigbarcnt3 >= minimum_engulfed_bars),(low * 0.999), bigbarcnt3 + " 3", if bigbarcnt3 == 0 then color.dark_gray else if barup then color.green else color.red, no);

# mod with his rules in post#10
# rework engulf , with thrust terms
# https://usethinkscript.com/threads/...thin-a-known-group-of-bars.12721/#post-108393
# post10 TNTrader5159
#------------------------------------
# make new vars, labels

# 1. Yes, first to see HOW MANY bars the current bar may engulf.
# recent engulf quantity
def engulf_bars = if outbar then bigbarcnt3 else engulf_bars[1];
addlabel(1, "recent engulf bars, quantity " + engulf_bars, color.yellow);


# 2. Then to find the relative positions of the highest and lowest prices within the engulfed range.

# loop , from line_start to outbar
# loop , 0 to engulf_off ( the qty of engulded bars )

def engulfed_hi;
def engulfed_lo;
def engulfed_hibn;
def engulfed_lobn;
def xbn;
if line_start then {
xbn = bn;
# start at the 1st bar of an engulfed period,
# look at future bars for the highest price
engulfed_hi = fold g1 = 0 to (engulf_off-0)
with g2
while !isnan(gulf_hi)
do (if getvalue(high, -g1) > g2 then getvalue(high, -g1) else g2);

# look at future bars for the lowest price
engulfed_lo = fold h1 = 0 to (engulf_off-0)
with h2 = 99999
while !isnan(gulf_hi)
do (if getvalue(low, -h1) < h2 then getvalue(low, -h1) else h2);


# look for the highest and lowest price , and read the bn
engulfed_hibn = fold g3 = 0 to (engulf_off - 0)
with g4
while !isnan(gulf_hi)
do (if engulfed_hi == getvalue(high, -g3) then (bn + g3) else g4);

engulfed_lobn = fold h3 = 0 to (engulf_off-0)
with h4
while !isnan(gulf_hi)
do (if engulfed_lo == getvalue(low, -h3) then (bn + h3) else h4);
} else {
engulfed_hi = engulfed_hi[1];
engulfed_lo = engulfed_lo[1];
engulfed_hibn = engulfed_hibn[1];
engulfed_lobn = engulfed_lobn[1];
xbn = xbn[1];
}


# plot points on highest and lowest prices, that are engulfed
input show_points_onhighest_lowest_in_engulfed_group = yes;
plot zenhi = if show_points_onhighest_lowest_in_engulfed_group and bn == engulfed_hibn then high else na;
zenhi.SetPaintingStrategy(PaintingStrategy.POINTS);
zenhi.SetDefaultColor(Color.white);
zenhi.setlineweight(2);
zenhi.hidebubble();

plot zenlo = if show_points_onhighest_lowest_in_engulfed_group and bn == engulfed_lobn then low else na;
#plot zenlo = if bn == xbn then low else na;
zenlo.SetPaintingStrategy(PaintingStrategy.POINTS);
zenlo.SetDefaultColor(Color.white);
zenlo.setlineweight(2);
zenlo.hidebubble();


input test_hi_lo_bns = yes;
addchartbubble(test_hi_lo_bns and line_start, gulf_lo*0.999,
"hi $" + engulfed_hi + " at bn: " + engulfed_hibn + "\n" +
"lo $" + engulfed_lo + " at bn: " + engulfed_lobn
, color.yellow, no);


# 3. Then to take the farther one back or lower bar number of those two prices, and subtract it from the current bar number.

def engulf_minbn = min( engulfed_hibn, engulfed_lobn);
def t = if line_start then ((bn + engulf_off) - engulf_minbn) else t[1];

# offset from first engulfed bar , to the first low/hi
def t_start_off = engulf_minbn - bn;


# 4. This returns the final value I call the Thrust Factor.
# The Thrust Factor measures the strength of the pattern once a breakout to either the upside or downside of the engulfed range occurs in real time.
# And of course which occurs first is the key to trade direction. That's another matter though.


# is the offset t pointing to the highest price in the group?
def isfirst_hi = if getvalue(high, -t_start_off) == engulfed_hi then 1 else 0;

# show a green or red bubble, on the first bar of engulfed group, that lists which comes first, a low or a high.
addchartbubble(line_start, gulf_lo*0.999,
getvalue(high, -t_start_off) + " t hi\n" +
#engulfed_hi + " ehi\n" +
(if isfirst_hi then "High" else "Low") + " is first"
, (if isfirst_hi then color.green else color.red), no);



# rule 4 questions
# you will have to define what a breakout is.
# there will be a highest price and a lowest price DURING a group of engulfed bars.
# but thos 2 points are within the engulfed price range. they didn't 'breakout'.

# there is only 1 breakout during a group of engulfed bars, on the bar after the last, big, engulfing bar.
# ( we could call the first bar, a breakin )


# 5. The Thrust Factor must be a minimum of 3 to qualify for a legit pattern per my definition. Otherwise it would be discarded from further qualifications for a trade, ie the Impedance Factor, which is irrelevant to the current discussion.

def t_min = 3;
def thrust_factor = if t < t_min then 0 else t;
def thrust_ratio = round(thrust_factor/ engulf_off,2);

addchartbubble(line_start, gulf_lo*0.999,
thrust_factor + " thrust_factor \n" +
#t + "\n" +
"out of\n" +
engulf_off + " engulfed bars\n" +
"is a ratio of\n" +
thrust_ratio + " : 1"
, (if isfirst_hi then color.green else color.red), no);


# 6. So for now, if I can determine the Thrust Factor, that part will be complete.

# 7 Your code shows the sizes of all engulfed ranges, which is good, and now only the highs and lows of those engulfed ranges need to be determined, with the bar number of the farther one back subtracted from the number of the engulfing bar to return the Thrust Factor.

# 8. It looks like the Thrust Factor of the first example on your chart with 21 total bars engulfed would be either 16 or 21, as it's hard to tell which of those two bars was higher. The second example with 7 total bars engulfed would be 6, with the high occurring on Bar 179 and the low on Bar 176 vs Bar 182 as the engulfing bar.

# 9. Both signals indicated taking Short positions.
I tested this study yesterday and today using real time trading on a chart with 1- and 2-minute timescales. So far, every signal that this study has produced has been accurate. Thank you very very much TNTrader5159, Halcyonguy and Svanoy
 
I tested this study yesterday and today using real time trading on a chart with 1- and 2-minute timescales. So far, every signal that this study has produced has been accurate. Thank you very very much TNTrader5159, Halcyonguy and Svanoy
Yes, it does work as long as you know how to read the Impedance values to filter out some signals that won't result in any significant favorable movement. These weak signals that turn around and go the other way should in most cases initiate good trades in the opposite direction, with the same rules applying in that other direction.
<p>
We can test this more thoroughly when the entire system is assembled. Corroboration is GREAT to hear Santhosh! Thanks.
 
One tweak to the pattern code:

In a Short trade setup, the High of the engulfed range must precede the Low of the engulfed range for it to count. In a Long trade setup the Low must come first.

Thrust Factor rules for number of bars back to the High for a Short setup and the Low for a Long setup still apply with a minimum of 3. You could trade with a 2 Thrust Factor, though Impedance would have to be minimal for a trade to work. It can be done though. The Minimum Thrust Factor could have a default value of 3 but be changeable as an input by the user.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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