Having problems with ATR-based trailing stop logic in a for loop

Hi all,

I have been trying to adapt the example trailing stop loss for-loop as supplied in AFL (and referenced in manuals) in a relatively basic analysis module i'm trying to develop for Forex backtesting.

Objective: to use an ATR-multiple to adjust the trailing stop throughout the trade.

Sample Code Below:

SetBacktestMode( backtestRegularRawMulti );
SetOption("FuturesMode", 1);
SetOption("CommissionMode", 2);
SetOption("CommissionAmount", 3.5);
SetOption("InitialEquity", 20000);
SetChartOptions( 0, chartShowArrows, 0 );

RoundLotSize 			= 1;
TickSize 				= IIf(StrFind(Name(),"JPY"),0.01,0.0001);
MarginDeposit 			= -1; 	// 100:1 leverage; '-1' equates to 1%
PointValue 				= 1;
Buy = Sell = Short = Cover = BuyPrice = SellPrice = ShortPrice = CoverPrice = 0;

//=============================================================================================================
// specific parameters for this trading system
//=============================================================================================================

Param_LongPeriod		= 60;	// parameter to control long-timeframe signals (eg highs, lows)
Param_ShortPeriod		= 10;	// parameter to control short-timeframe signals (eg ATR retracement period)
RiskAppetitePct			= 1.5;	// initial risk appetite = 1.5 %
StopLoss_ATR_Range		= 2;	// calculate 1R exit based on 2xATR retracement
Trail_ATR_Range			= 4;	// trail stop based on 4xATR retracement

//=============================================================================================================
// risk and position size calculation
//=============================================================================================================

AvgTrueRange			= Ref( ATR( Param_ShortPeriod ), -1);	// calc short period average true range (from prior day data)
StopLossRiskPerShare	= StopLoss_ATR_Range * AvgTrueRange;  	// calc stop loss
TrailExitRiskPerShare	= Trail_ATR_Range * AvgTrueRange;  		// calc trailing stop

if (StrFind(Name(),"JPY") )
	SingleTradeEquityRiskPct =  RiskAppetitePct / 100 / StopLossRiskPerShare /100;
else
	SingleTradeEquityRiskPct =  RiskAppetitePct / 100 / StopLossRiskPerShare;

SetPositionSize( SingleTradeEquityRiskPct, spsPercentOfEquity );

//=============================================================================================================
// signals
//=============================================================================================================

Buy = 		Ref(Close,-1) == HHV( Ref(Close,-1), Param_LongPeriod);  	// 60-bar high

//=============================================================================================================
// stop loss calculation sequence for long positions
//=============================================================================================================

trailARRAY = Null;
trailstop = 0;

for( i = Param_ShortPeriod+1; i < BarCount; i++ )
 {

   if( trailstop == 0 AND Buy[ i ] ) 
    { 
       trailstop = High[ i ] - AvgTrueRange [ i ];
       BuyPrice[ i ] = Open [ i ];
    }
    else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Low[ i ] < trailstop )
    {
       Sell[ i ] = 1;
       SellPrice[ i ] = trailstop;
       trailstop = 0;
    }

   if( trailstop > 0 )
    {   
       trailstop = Max( High[ i ] - AvgTrueRange [ i ], trailstop );
       trailARRAY[ i ] = trailstop;
    }

}

Problem Statement: when debugging, it appears that when referenced from within the for-loop, the 'AvgTrueRange' array shows "Null" for the first series of bars until 'i' is >= Param_ShortPeriod.
As a result this is setting 'trailstop' to Null in some of the earlier loop iterations (i.e if a Buy signal is present) and the code doesn't work after that point as i'm not looking for or handling a Null value in trailstop.

I assume i am doing something fundamentally wrong in the way I've tried to reference AvgTrueRange within the for loop, but would welcome any advice or input from other more experienced users.

Thanks in advance :+1:t4:

Update - have solved it. I wasn't aligning the dates of the bar range in my for loop with the date range in analysis window. Cheers all :slight_smile: