i want to plot the number of bars since it rises up the moving average ( close > ma ) 20 and the moving average must make rising price (ma > ma[1]), if any of these two conditions is break, the bar counter should reset to 0. i want to calculate the 4 hours timeframe bars and moving average, but when i switch to 2 hours, the value returned is changing
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jeckwilke
//@version=5
indicator("My script")
ma = request.security(syminfo.tickerid, "240", ta.sma(close, 20))
lma = request.security(syminfo.tickerid, "240", ta.sma(close[1], 20))
_close = request.security(syminfo.tickerid, "240", close)
var counter = 0
if _close > ma and ma > lma
counter += 1
else
counter := 0
plot(counter)
553BARS In this case, it is counting the bars in the 5 minute timeframe.
i want the 4 hours timeframe bars value on 5 minutes timeframe, like that but in others timeframes
I updated my post accordingly.
This is the result...
//@version=5
indicator("My script")
my_function() =>
float sma20 = ta.sma(close, 20)
bool is_crossover = ta.crossover(close, sma20)
bool is_crossunder = ta.crossunder(close, sma20)
bool is_rising = ta.rising(sma20, 1)
int barssince_crossover = ta.barssince(is_crossover)
int barssince_crossunder = ta.barssince(is_crossunder)
//log.info(str.format("\nis_crossover: {0}\nis_crossunder: {1}\nis_rising: {2}\nbarssince_crossover: {3}\nbarssince_crossunder: {4}", is_crossover, is_crossunder, is_rising, barssince_crossover, barssince_crossunder))
if barssince_crossunder > barssince_crossover and is_rising
barssince_crossover
else
0
int counter = request.security(syminfo.tickerid, "240", my_function())
plot(counter)
What I did...
I created a function with all the stuff that is needed and put that into request.*()
.
HERE you can read about functions.
All ta.*()
functions are self explanetory.
When you hover your mouse over it or use STRG+MouseClick
it will pop-up an Information on how to use them.
Addtion...
i want to reset the counter when the moving average decreases and starts counting from 0 again.
Change the variable name of the request output and add a new persistent variable to the game.
The simple if
statement counts your bars then.
int barssince = request.security(syminfo.tickerid, "240", my_function())
var counter = int(0)
if barssince > 0
counter += 1
else
counter := 0
plot(counter)
This will count the bars on your chart and not those in HTF.
When you want to count the bars of HTF instead
then you have to change the end of the function into this...
var counter = int(0)
if barssince_crossunder > barssince_crossover and is_rising
counter += 1
else
counter := 0
counter
As a side note...
You have to use barmerge.lookahead_on
when accessing historical data via []
within request.*()
,
other wise it will result in unpredictable garbage.
You should read about Repainting, and then about Future Leaks.