Math on indicator bars only

MFitz73

Member
Hi guys, I am trying my best but can't figure which way to go. I have a chart indicator that paints an arrow below the criteria met candle or candles. What I am trying to do is add up a value(say close price, if more than one I would want the average of the close prices) for each candle bar and paint a horizontal line on the chart.
What I can do is I can script the indicator. but I can not figure how to go about collecting the data and draw the line.
would I use the fold script here? I'm currently trying to write simple fold scripts to get a handle on it but... well here I am. lol
any help would be greatly appreciated.
thanks
Mike
 
Solution
@MFitz73
Replace <Signal> with your criteria.

Code:
def RunningClose;
def SignalCount;

If <Signal> {
RunningClose = RunningClose[1] + close;
SignalCount = SignalCount[1] + 1;
} else {
RunningClose = RunningClose[1];
SignalCount = SignalCount[1];}

plot AverageClose = RunningClose / SignalCount;
AverageClose.SetPaintingStrategy(PaintingStrategy.Horizontal);
@MFitz73
Replace <Signal> with your criteria.

Code:
def RunningClose;
def SignalCount;

If <Signal> {
RunningClose = RunningClose[1] + close;
SignalCount = SignalCount[1] + 1;
} else {
RunningClose = RunningClose[1];
SignalCount = SignalCount[1];}

plot AverageClose = RunningClose / SignalCount;
AverageClose.SetPaintingStrategy(PaintingStrategy.Horizontal);
 
Solution

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

Svanoy, I have to admit I don't fully understand how you coded this. And that is why I am asking you this question...
So if I wanted to only calculate the last x number of bars that have met the criteria. Like say there are 10 signal bars on the chart where the bar has the criteria me, but I would like to only calculate the last 3? Or maybe the last 4? something that the user could change as a preference? how can I do this?
thank you in advance
Mike
 
Last edited:
@MFitz73
Replace both instances of <Signal> with your criteria.
Code:
input Number_Of_Signals_To_Be_Averaged = 3;
input Value_To_Be_Averaged = close;

def TotalSignalCount = if <Signal> then TotalSignalCount[1] + 1 else TotalSignalCount[1];
def FinalCount = fold b = 0 to 1000 while !IsNaN(GetValue(close, -b)) do GetValue(TotalSignalCount, -b);
def SignalRangeTotal;
if BarNumber() == 0 {
    SignalRangeTotal = 0;
} else if FinalCount - TotalSignalCount < Number_Of_Signals_To_Be_Averaged and <Signal> {
    SignalRangeTotal = SignalRangeTotal[1] + Value_To_Be_Averaged;
} else {
    SignalRangeTotal = SignalRangeTotal[1];
}
def RangeAverage = if (SignalRangeTotal / Number_Of_Signals_To_Be_Averaged) > 0 and (FinalCount - TotalSignalCount) <= 0 then (SignalRangeTotal / Number_Of_Signals_To_Be_Averaged) else Double.NaN;
def FinalAverage = fold c = 0 to 1000 while !IsNaN(GetValue(close, -c)) do GetValue(RangeAverage, -c);

plot RangeAveragePlot = If FinalAverage > 0 then FinalAverage else Double.NaN;
RangeAveragePlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
 
Last edited:
Hi Svanoy, ok after using the script, its main function seems to be there. there are some parameters that would really make it great! I have included a picture that shows 3 separate trade opportunities on one chart.

1. if there is an indicator signal, the script would look back -a user defined number of bars. say 10(could be 3 or 5 whatever the user chooses etc..).
2. if the indicator is true, it looks back "10" bars(user defined). with in that look back range, the script will calculate
1 to however many indicator bars the user wants out of the "10" bars. meaning if the user sets look back 10 bars and 4 maximum hits. then any indicators bars over 4 with in that 10 bar range are not calculated they are ignored.

If only 1 bar has the indicator out of the 10 bars, the math is reflective of 1 bar. if only 2 bars of the look back are true then the math is only on those 2 bars, if 3 out of the look back are true then the math is done on the 3 bars. however many bars it looks for would be user defined with in the user defined range.
3. the line drawn would be from the bar to the right. It could be set however many bars to the right.
I don't have any online image storage so I tried an instagram account. let me know if you can't see it.
thank you, Mike

https://www.instagram.com/p/CZzresSpTxE/
 
Svanoy, one thing I forgot to mention on the code is... if there is an indicator or a few that are close to eachother they are in relation to eachoter in the trading system. But the current script as is... if there are 2 indicators at 2pm and there is one indicator say a few hours earlier, its getting calculated in the most recent ones which is not what we want. thanks
Mike
 
Last edited:
@MFitz73

Thinkscript doesn't have a reserved function for 'a few', so not much I can do with that.

Here is the code for your post prior.
Replace the 3 instances of <Signal> with your criteria.
Ruby:
input Look_Back_Period = 10;
input Number_Of_Signals_To_Be_Averaged = 5;
input Value_To_Be_Averaged = close;

def BarNumber_Offset = 1000;
def bar = BarNumber();
def BarNum = if !IsNaN(close) and BarNumber() > 0 then bar else BarNum[1];
def VBar = if if(!IsNaN(close[-BarNumber_Offset]),!IsNaN(close[-BarNumber_Offset]),IsNaN(close[-BarNumber_Offset])) then barNum[-BarNumber_Offset] else VBar[1];

def TotalSignalCount = if <Signal> then TotalSignalCount[1] + 1 else TotalSignalCount[1];
def SignalBarNumber = if <Signal> then BarNumber() else SignalBarNumber[1];
def LastBarNumber = VBar;
def FinalCount = fold fc = 0 to VBar while !IsNaN(GetValue(close, -fc)) do GetValue(TotalSignalCount, -fc);

def SignalRangeTotal;
def SignalStop;
if BarNumber() == 0 {
    SignalRangeTotal = 0;
    SignalStop = Number_Of_Signals_To_Be_Averaged;
} else if FinalCount - TotalSignalCount < Number_Of_Signals_To_Be_Averaged and LastBarNumber - SignalBarNumber > Look_Back_Period {
    SignalRangeTotal = 0;
    SignalStop = FinalCount - TotalSignalCount;
} else if  FinalCount - TotalSignalCount < Number_Of_Signals_To_Be_Averaged and LastBarNumber - SignalBarNumber <= Look_Back_Period and <Signal> {
    SignalRangeTotal = SignalRangeTotal[1] + Value_To_Be_Averaged;
SignalStop = SignalStop[1];
} else {
    SignalRangeTotal = SignalRangeTotal[1];
SignalStop = SignalStop[1];
}
def RangeAverage;
if (SignalRangeTotal / SignalStop) > 0 and (FinalCount - TotalSignalCount) <= 0 {
    RangeAverage = (SignalRangeTotal / SignalStop);
} else {
    RangeAverage = Double.NaN;
}

def FinalAverage = fold c = 0 to VBar while !IsNaN(GetValue(close, -c)) do GetValue(RangeAverage, -c);

plot RangeAveragePlot = If((LastBarNumber - BarNum) <= Number_Of_Signals_To_Be_Averaged and FinalAverage > 0, FinalAverage, Double.NaN);
RangeAveragePlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
 
Last edited:
@Svanoy, what I am doing is when a price moves to far away/below from the 9ema and also 25ema ( use a combination of the 2) on the 2min chart it registers a signal on that bar as the price will come back up to the ema lines. when that happens I want to collect the close(or low or hl/2 etc) price on the bars that are giving that signal.
My strategy is to add those bars up and divide by the number of those bars to get the average. that gives me
theoretical threshold price that the price has to get back above to get me into the trade. I have been manually
calculating this for years and Im too slow lol.
after reading this and looking at the link picture I posted you should be able to see my strategy.
So in looking at that picture there are 3 trade opportunities. I don't want the numbers from dip1 and dip2 to be calculated in the numbers on the 3rd or any combination. the are all separate dips/trade opportunities. In the original code, all the signal bars would be added up and average for the entire chart. So an indicator from 10am is getting added to the indicator at 3pm and they have no bearing on each other being so far away from each other. which was not what I wanted, but I did not explain that. sorry.
 
@MFitz73
The script I posted today will only look for signals within the look back period and calculates based on how many signals are found within that period up to the set limit. So it should work for your purpose.
 
@Svanoy, I'm running it in ondemand now, looks like it's working good. Will let you know after afew days.
Thanks so much for putting the script together. I wish I was able to do this at your level!
Thank you,
Mike
 
Simple Query....should be. But no luck with TOS. I want to AVERAGE the past 10 bear candles. This would be a label on a graph. I've come up with this



def bull =close>open;

def bulla= Average(length = 10, data = bull);

AddLabel(visible = yes, text = bulla);

It Never seems to calculate correctly though. Any help is appreciated!!
 
Simple Query....should be. But no luck with TOS. I want to AVERAGE the past 10 bear candles. This would be a label on a graph. I've come up with this
It Never seems to calculate correctly though. Any help is appreciated!!

here is @Svanoy code from post#7, modified to find 10 bull bars.

the only minor thing with this is, you have to guess at a big number for
input Look_Back_Period = 50;
to make sure you will find your desired bars. i set it to 50.


Ruby:
input Look_Back_Period = 50;
input Number_Of_Signals_To_Be_Averaged = 10;
input Value_To_Be_Averaged = close;

def signalbull = close > open;

#def TotalSignalCount = if <Signal> then TotalSignalCount[1] + 1 else TotalSignalCount[1];
#def SignalBarNumber = if <Signal> then BarNumber() else SignalBarNumber[1];
def TotalSignalCount = if signalbull then TotalSignalCount[1] + 1 else TotalSignalCount[1];
def SignalBarNumber = if signalbull then BarNumber() else SignalBarNumber[1];

def LastBarNumber = fold lbn = 0 to 1000 while !IsNaN(GetValue(close, -lbn)) do GetValue(BarNumber(), -lbn);
def FinalCount = fold fc = 0 to 1000 while !IsNaN(GetValue(close, -fc)) do GetValue(TotalSignalCount, -fc);


def SignalRangeTotal;
def SignalStop;
if BarNumber() == 0 {
    SignalRangeTotal = 0;
    SignalStop = Number_Of_Signals_To_Be_Averaged;
} else if FinalCount - totalSignalCount < Number_Of_Signals_To_Be_Averaged and LastBarNumber - SignalBarNumber > Look_Back_Period {
    SignalRangeTotal = 0;
    SignalStop = FinalCount - totalSignalCount;
} else if  FinalCount - TotalSignalCount < Number_Of_Signals_To_Be_Averaged and LastBarNumber - SignalBarNumber <= Look_Back_Period and signalbull {
    SignalRangeTotal = SignalRangeTotal[1] + Value_To_Be_Averaged;
SignalStop = SignalStop[1];
} else {
    SignalRangeTotal = SignalRangeTotal[1];
SignalStop = SignalStop[1];
}
def RangeAverage;
if (SignalRangeTotal / SignalStop) > 0 and (FinalCount - TotalSignalCount) <= 0 {
    RangeAverage = (SignalRangeTotal / SignalStop);
} else {
    RangeAverage = Double.NaN;
}
plot RangeAveragePlot = RangeAverage;
RangeAveragePlot.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);

addlabel(1, "bull avg " + RangeAverage, color.green);

input show_test1 = no;
addchartbubble(show_test1, low,
SignalRangeTotal + " sigrng"
,color.yellow, no);
#
[code]
 
Simple Query....should be. But no luck with TOS. I want to AVERAGE the past 10 bear candles. This would be a label on a graph. I've come up with this
It Never seems to calculate correctly though. Any help is appreciated!!
here is another way to find the averages

hello and welcome
there are several things wrong with your post

1. your words say bear, but your formulas say bull.

2. i assume you want to average the close of the bull candles? you didn't specify.

3. your variable , bull , is equal to a boolean value, true or false, a series of 1's and 0's. using bull in the average formula, bulla , will create an average of a bunch of 1's and 0's , some fractional number.

4. minor thing, although you used parameter names to set the parameters in the average function, they are in the wrong order. it is good practice to put parameters in the correct order in functions, (then you dont need to use the names), average( data , length )

5. minor thing, no color defined in label.

-----------------------
not all bars are bull. there isn't going to be 10 bull candles in a row. looking back 10 bars won't find 10 bull candles.
you need a way to look back at an unknown quantity of bars and find 10 bull candles, add up

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

this will,
. ask for a quantity of bull bars and a quantity of bear bars, then find the average of each.
. 2 labels are drawn, for the bull average and bear average.
. can show wedges (tiny arrows) on bull bars and bear bars.


this study uses a reverse counter to determine when a group of bars, are desired.
increments a counter on each bull candle, and a separate counter for bears.
finds the highest counter value of both.
calculates a reverse counter for each. it counts down to 1, at the last desired candle.
the counter values are compared to the desired quantity, to know when a candle is to be summed for the average.

if you need help visualizing the counters, at the end is a test bubble. change show_bull_counters = no , to yes to have it draw bubbles with bull counter values.

Ruby:
def bn = barnumber();

input bull_qty = 10;
input bear_qty = 10;

def bull = close > open;
def bear = close < open;

# bull data----------------------------------
def bullcnt =
if bn == 1 then 0
else if bull then bullcnt[1] + 1
else bullcnt[1];

def bullcntlast = highestall(bullcnt);
def bullrevcnt = bullcntlast - bullcnt + 1;

# add up desired values
def bullsum =
  if bn == 1 then 0
  else if (bullrevcnt <= bull_qty and bull) then bullsum[1] + close
  else bullsum[1];

def bullavg = round(bullsum / bull_qty, 2);
# -------------------------------------------


# bear data----------------------------------
def bearcnt =
  if bn == 1 then 0
  else if bear then bearcnt[1] + 1
  else bearcnt[1];

def bearcntlast = highestall(bearcnt);
def bearrevcnt = bearcntlast - bearcnt + 1;

# add up desired values
def bearsum =
  if bn == 1 then 0
  else if (bearrevcnt <= bear_qty and bear) then bearsum[1] + close
  else bearsum[1];

def bearavg = round(bearsum / bear_qty, 2);
# -------------------------------------------

addlabel(1, "averages of past " + bull_qty + " bull candles: " + bullavg, color.yellow);
addlabel(1, "averages of past " + bear_qty + " bear candles: " + bearavg, color.yellow);

input show_wedge_on_bull_candles = yes;
plot bullw = if (show_wedge_on_bull_candles and bullrevcnt <= bull_qty and bull) then 1 else 0;
bullw.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_up);
bullw.SetDefaultColor(Color.green);
bullw.setlineweight(1);
bullw.hidebubble();

input show_wedge_on_bear_candles = yes;
plot bearw = if (show_wedge_on_bear_candles and bearrevcnt <= bear_qty and bear) then 1 else 0;
bearw.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_down);
bearw.SetDefaultColor(Color.red);
bearw.setlineweight(1);
bearw.hidebubble();


# -------------------------------------------
# test data

input show_debug_counters = no;
Addchartbubble(show_debug_counters and bullrevcnt <= bull_qty and bull, high*1.005,
bullcnt + " cnt\n" +
bullrevcnt + " rev\n" +
bullcntlast + " last\n" +
close + " cls"
, color.green, yes);

Addchartbubble(show_debug_counters and bearrevcnt <= bear_qty and bear, low*0.995,
bearcnt + " cnt\n" +
bearrevcnt + " rev\n" +
bearcntlast + " last\n" +
close + " cls"
, color.red, no);
#
 
A big thanks to everyone.
I've spent several hour working on this in the past and a couple hours this AM. I have a more complex study but just wrote this one up very quick since it was fundamentally what kept coming back incorrectly. @halcyonguy , you're right. This AM...just after posting this I realized the boolean nature of the bull definition and I changed that to actually return HIGH-LOW. However something was still off. I'll play with it some more

I actually am interested in looking only at the past x number of bars ....if there are 0 Bullish/Bearish candles...that's okay.

Thanks again for the references and code above!!
 
@MFitz73
Updated my code in post #7 as TOS seems to have limited the functionality of the FOLD statement for passing a value backwards.
Code has been edited with alternative method.
Works in real time now.
 
Last edited:
@MFitz73
Updated my code in post #7 as TOS seems to have limited the functionality of the FOLD statement for passing a value backwards.
Code has been edited with alternative method.
Works in real time now.
ok wow great. I will check it out thanks!! I'm still testing the original and had some issues so will see how this works.
thanks again and will report back.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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