Backwards while loop

Hello,

I am trying to create an indicator/loop that looks back and finds the last 10 up closes and then sums up the volume and also sums the movement from up closes.

although i keep getting this out of array range error on this bit:
If(Close[i]>Close[i-1])
i have tried this work around i found on this forum :
if( i > period ) // only access C[ i - 1 ] when i is greater than period

but i cant get it to work, any help would be greatly appreciated.

Period=10;

j=0;
ii=0;
upvol=null;
upcount =null; 
while (j < period) 
{
i=(BarCount-ii);

if( i > period ) // only access C[ i - 1 ] when i is greater than period 
{   
    
	If(Close[i]>Close[i-1])
		{
		upvol[i] = (Volume[i]+upvol[i]);
		upcount[i] = (upcount[i]+(Close[i]-Close[i-1]));
		j++;
		ii++;
		}
	else
		{
		ii++; // Move onto previouc candle to check next C>ref(c,-1)
		}

}

ii++; //  Move onto previouc candle until "i" inside array

}

Cheers
Jon

Array functions , SparseCompress()/Expand() wouldn't help?
Please search for @fxshrat 's posts.

1 Like

@kastin, as suggested by @NowToLook, for this kind of calculations, in general, it is better to use the array functions.

I'm not sure to correctly understand your idea, but something along this lines should give you a hint how to proceed (I use exploration to verify the results - apply to a single ticker - current - for the last 20/30 days or bars if you work intraday).


period = 3; // Change as needed - I'm using a low range to make visual verification easier

upBar = C > Ref( C, -1 );
ClosePositive  = IIf( upBar, C - Ref( C, -1 ), 0 );
VolumePositive = IIf( upBar, V, 0 );
upBarCloseSum = Sum( ClosePositive, period );
upBarVolumeSum = Sum( VolumePositive, period );

// this small utility function is used to display an "empty" cell when the passed array value is zero
function nil( a )
{
    return ( IIf( a, a, Null ) );
}
Filter = 1; // show all bars values
AddColumn( C, "Close" );
AddColumn( Volume, "Volume", 1 );
AddColumn( nil( upBar ), "Up Day", 1 );
AddColumn( nil( ClosePositive ), "Close Positive" );
AddColumn( nil( VolumePositive ), "Volume Positive", 1 );
suffix = " (in the last " + period + " bars)";
AddColumn( upBarCloseSum, "Sum of Pos. Closes" + suffix );
AddColumn( upBarVolumeSum, "Sum of Volume on Pos. Closes" + suffix, 1 );
SetSortColumns( -2 ); // sort by more recent date

5 Likes

Thanks guys,
i believe i can get that to work, i was overthinking it!

Perfect.

Cheers
Jon

2 Likes