dharmatech
dharmatech

Reputation: 9497

Range bound indicator

Context

For around 12 days, $SPX has been range bound:

enter image description here

The range is a little over 100.

Code

I have a simple indicator which aims to show when the price has moved within a range of 100.

//@version=5

indicator("My script", "", true)

val = close[0]

n = ta.barssince(math.abs(val - close[1]) > 50)

if n > 1
    label.new(bar_index, hl2[1], str.tostring(n), color = color(na), textcolor = color.orange)

The logic here should be:

Search backwards until we find a bar with a `close` such that:

    abs(close - current_close) < 50

It seems to kind of work for the range shown above:

enter image description here

Issue

However, there seems to be an issue. If we zoom out, the indicator labels don't show up anywhere else on the chart:

enter image description here

There should be many other places on the chart where it shows up.

Question

What's a good way to set this indicator up so that the other places in the chart that are rangebound are shown?

Update

Here's another version which uses while instead of barssince. However, it appears to have similar results.

//@version=5

indicator("Range Bound - while", "", true)

n = 1

while math.abs(close - close[n]) < 50
    n := n + 1

if n > 1
    label.new(bar_index, hl2[1], str.tostring(n), color = color(na), textcolor = color.orange)

Update - max_labels_count

Thank you to Bjorn for his answer below.

He mentions:

By default, there are only about 50 drawing objects (lines, labels) allowed on a chart.

With that in mind, I used n > 50 to only draw labels if n is sufficiently large. This led to more labels showing up.

if n > 50
    label.new(bar_index, high, str.tostring(n), color = color(na), textcolor = color.orange)

He also mentions max_labels_count.

Here's another version which appears to work better:

//@version=5

indicator("Range Bound - while", "", true, max_labels_count=500)

n = 1

while true

    if n > 1000
        n := 0
        break

    if (math.abs(close - close[n]) > 55)
        break
        
    n := n + 1

if n > 50
    label.new(bar_index, high, str.tostring(n), color = color(na), textcolor = color.orange)

Here we can see many more labels showing up:

enter image description here

Upvotes: 0

Views: 496

Answers (1)

Bjorn Mistiaen
Bjorn Mistiaen

Reputation: 6865

By default, there are only about 50 drawing objects (lines, labels) allowed on a chart.
Any number greater than that will automatically be cleaned up by the garbage collector process.
See garbage collection explained in the usrman.

A while ago, the user has been given control over the amount of lines or label objects on a chart (with a maximum of 500) through extra parameters in the study() function: max_lines_count and max_labels_count.

indicator("My Script", overlay=true, max_labels_count=100)

This new limit is also explained in the garbage collection topic.

Upvotes: 1

Related Questions