Alex
Alex

Reputation: 1

How I can plot a variable calculating it since the last bar to bar in the past, bar by bar

I want to calculate the summation of the "relative true range" (close>open? TR : -TR) only on some last bars, that is from the barstate.islast to, for example, 50/100 bars in the past.

Here below you can see my script:

indicator("Σ relative True Range", overlay=false)
barsBack = input(50)
TR_rel = close>=open? TR : -TR
TR_rel=0.0
if barstate.islast
    for i = barsBack-1 to 0 
        SumTR_rel := SumTR_rel + TR_rel[i]
        plot(SumTR_rel, title="Σ relative True Range", color=color.new(color.red, 80), linewidth=2)

I tried to do in this way, by inserting a plot in a for cycle, but it happens an error: "cannot use plot in local scope". I tried to use also line, but I saw that it is usable only in the main panel (overlay=true and not in overlay=false).

Is there anyone that can help me?

Upvotes: 0

Views: 837

Answers (1)

Rohit Agarwal
Rohit Agarwal

Reputation: 1368

You can get the last bar index using last_bar_index. Then on each bar you can check if the current bar index is within 50 bars of last bar index. Only then you can add the TR to sum and plot the same. Example below

    //@version=5

indicator("Σ relative True Range", overlay=false)
barsBack = input(50)
TR=ta.tr(true)
TR_rel = close>=open? TR : -TR
var SumTR_rel=0.0
if bar_index>last_bar_index-barsBack
    SumTR_rel := SumTR_rel + TR_rel
plot(SumTR_rel, title="Σ relative True Range", color=color.new(color.red, 80), linewidth=2)

Upvotes: 0

Related Questions