0

Similar to the PreDefined Study "PriceChannel" that only changes it's value if there is a new low or a new high, I want it to only change it's value when a condition is met, then keep that value until it is met again.

This is the code I have so far, right now it checks for the last bar's "b" value, if it's > 0, then it plots "b", if not, it tries again from the 2nd most recent bar, then the 3rd, etc, until it finds a value of "b" that is > 0.

The code works, but I have to add a new "else if" statement for every nth bar in the past, 300 bars would be sufficient enough, however that would mean I would have to type out the same line 300 times and just change the number every time, I want to avoid doing this, plus, it's much cleaner if it checks n=n+1 number of times.

Any recommendations on what I should do?

plot b = if SMA30 crosses below 0 or
SZO crosses below 7 and SMA30 < SMA30[1]
then open
else 0;

plot g = if b>0
then b
else if b[1]>0
then b[1]
else if b[2]>0
then b[2]
else if b[3]>0
then b[3]
else 0;

1 Answers1

1

You can use a recursive variable. There are two ways to do this:

  • simple recursive variable:
def gVal = if b > 0 then b else gVal[1];
plot g = gVal;
  • CompoundValue recursive variable:
def gVal = 
    CompoundValue(
      1, 
      if GetValue(b, 0) > 0 then GetValue(b, 0) else GetValue(gVal, 1),
      GetValue(b, 0)
    );
plot g = gVal;

Usually, the recursive variable will work just fine. CompoundValue is necessary if you have varied "lengths" or "offsets" in your code (check my answer here to understand how that works).


Code I used for testing:

  • regular recursive variable
#hint: SO q: https://stackoverflow.com/q/66805478/1107226

def price_to_beat = 2.06;

declare lower;

# b could also be a plot; I had a separate plot, so I `def`d it here
def b =
    if open > price_to_beat
    then open
    else 0;

def gVal = if b > 0 then b else gVal[1];
plot g = gVal;

AddChartBubble(yes, gVal, "gVal:" + gVal, Color.YELLOW, no);

AddLabel(yes, "RecursiveVariable", Color.CYAN);

  • CompoundValue
#hint: SO q: https://stackoverflow.com/q/66805478/1107226

def price_to_beat = 2.06;

declare lower;

# b could also be a plot; I had a separate plot, so I `def`d it here
def b = if open > price_to_beat
        then open
        else 0;

def gVal = 
    CompoundValue(
      1, 
      if GetValue(b, 0) > 0 then GetValue(b, 0) else GetValue(gVal, 1),
      GetValue(b, 0)
    );
plot g = gVal;
g.SetDefaultColor(Color.CYAN);

AddChartBubble(yes, g, "b: " + b + ", g: " + g, Color.YELLOW, yes);

AddLabel(yes, "CompoundValue", Color.CYAN);

Image of test results on a 6-bar chart:

6-Bar Chart showing results of test code for comparison

leanne
  • 7,940
  • 48
  • 77