amibroker

How to make convert this long assignment statement into a function in Amibroker?


I have this long assignment statement in Amibroker.

num_times_above = iif(Ref(CLOSE, -0)>Ref(CLOSE, -4) , 1, 0)
                    + iif(Ref(CLOSE, -1)>Ref(CLOSE, -4), 1, 0)
                    + iif(Ref(CLOSE, -2)>Ref(CLOSE, -4), 1, 0)
                    + iif(Ref(CLOSE, -3)>Ref(CLOSE, -4), 1, 0)
                    + iif(Ref(CLOSE, -4)>Ref(CLOSE, -4), 1, 0)
                    ;

I would like to convert this long statement into a generic function that accepts a parameter n.

function get_num_times_above(n)
{
  //code
}

The code on top is for the case when n == 4. I am stuck at this seemingly simple problem because of the array format used in Amibroker.

if n == 3, the equivalent code will be;

num_times_above = iif(Ref(CLOSE, -0)>Ref(CLOSE, -3) , 1, 0)
                    + iif(Ref(CLOSE, -1)>Ref(CLOSE, -3), 1, 0)
                    + iif(Ref(CLOSE, -2)>Ref(CLOSE, -3), 1, 0)
                    + iif(Ref(CLOSE, -3)>Ref(CLOSE, -3), 1, 0)
                    ;

I am using Amibroker ver6.28


Solution

  • Try this.

    function get_num_times_above(n)
    {
        num_times_above = 0;
        refn = Ref(C, -n);
        for (i=0; i<n; i++) 
            num_times_above += Ref(C, -i)>refn;
        return num_times_above;
    }   
    

    Credit goes to fxshrat who provided the answer here.

    https://forum.amibroker.com/t/how-to-make-convert-this-long-assignment-statement-into-a-function/7181/2