Position Sizing inside loop

Hello,
Im trying to position size inside a loop to simulate placing a stop at the previous bars low, while risking 1% of my current balance on that stop.
Its in a loop because i would like to add a few advanced exits.
I tried this too: AmiBroker Knowledge Base » Position sizing based on risk as you can see in the commented out part in the loop. but it wasnt producing any trades.

This is what I have as a skeleton code - but occasionaly the backtester buys waaay to much stock on a position:

SetOption( "InitialEquity", 40000); 
SetOption( "MinShares", 1 ); 
SetOption( "MarginRequirement", 100); 
SetTradeDelays( 0, 0, 0, 0 ); 
SetOption( "AllowSameBarExit", true ); 
SetOption( "HoldMinBars", 0 ); 
SetOption("SettlementDelay", 0); 
Numberpositions = 10; 
SetOption("Maxopenpositions",numberpositions); 
RoundLotSize	= 1; //1 for stocks 
 
Sell = 0;
Buy = 0;
BuyPrice = Open;

BuyConditionMet = C > O AND V > MA(V,5)*2;
RiskPercentage = 1; // Risk percentage per trade

PriceAtBuy = 0; 
InitialStop = 0;
Exit = 0;  

for( i = 1; i < BarCount; i++ ) 
{ 
	//Entry
	if( PriceAtBuy == 0 AND BuyConditionMet[ i - 1 ]) 
	{ 
		Buy[ i ] = 1;
		PriceAtBuy = Open[ i ];
		InitialStop = Low[i - 1];
		PrevRange = C[i-1] - L[i-1] + 0.001; //ensure some val for when C = L
		MaxRiskAmount = Equity(0) * (RiskPercentage/100);
		SharesToBuy = floor(MaxRiskAmount / PrevRange);
		

		//// I also tried this but it didnt produce any results!
		//ApplyStop( stopTypeLoss, stopModePoint, PrevRange, True );
		//PctSize =  RiskPercentage * MarginDeposit  / ( PrevRange * PointValue );
		//SetPositionSize( PctSize, spsPercentOfEquity );

		_TRACE("Stock: " + Name() + "RiskAmt: " + MaxRiskAmount + " | PrevRange: " + PrevRange + " | Shares: " + SharesToBuy);
		SetPositionSize(SharesToBuy, spsShares);
	} 
	
	if( PriceAtBuy > 0 ) 
    { 
        if( Low[ i ] <= InitialStop)
        {
			//initial stop
			Exit = 6;
			SellPrice[ i ] = Min(Open [ i ], InitialStop);
        }
	}
	
	if( Exit > 3 ) 
	{ 
	  Buy[ i ] = 0; 
	  Sell[ i ] = Exit; // mark appropriate exit code  
	  // reset vars 
	  Exit = 0;
	  PriceAtBuy = 0;
	  InitialStop = 0;  
	}
}

Any help will be greatly appreciated!
Thank you!

You need to use this:

// inside loop
numberOfSharesArray[ i ] = sharesToBuy;
.....

// outside the loop (ONCE at the end)
SetPositionSize( numberOfSharesArray, spsShares );

Thank you @Tomasz!