Inside loop, how to reference close 1 year ago?

I’m trying to reference Close price of one year ago [ref(close,-260) ?]inside a loop but AB rejects it because it’s out of range(i:0-barcount). I’m using a loop to implement chandelier/atr trailing stop.

I tried the following:

PrevYearCls = ref(close,-260);
For (i=0; i< barcount; i++)
{

If (Close[i] < PrevYearCls[i])
{
Do my actions
}

}

Any suggestions greatly appreciated, thanks
Jacc

Hello,

I am thinking maybe it could be :

For (i=0; i< barcount; i++)
{

If (Close[i] < Close[i - 260])
{
Do my actions
}

}

Anthony

Thanks Anthony for the suggestion - tried that initially but it would be out of range so AB rejects that.

Have you considered ROC(C, 252)<0; ?

But you mention Chandelier Stops.

The Chandelier Stop is addressed without any loops in multiple places. Recently on this forum,

In the User Guide scroll down to the examples https://www.amibroker.com/guide/afl/applystop.html

In a video,

If you want Loop examples from TASC article, http://www.amibroker.com/members/traders/05-2009.html

1 Like

Thanks very much for the links particularly the video link but I deliberately avoided applystop previously as I often encountered situations where the close visually crossed the trail stop line and the trade did not exit.

Exitatstop is set to 0 to follow trade price or sellprice=close.

Thanks again for all the links I will follow up and read through.

PortfolioBuilder

Here's an example which I tried but couldn't resolve for the longest time.

Hello,

Is the error specific to that line of code or somewhere else in the formula ? could you post it ?

Anthony

@Anthony an @Jacc - you really should read “HOW TO USE THIS SITE” and use CODE TAGS !

Following rules is mandatory. If people don’t follow the rules their posts will be deleted.

ok Tomasz sorry about that.

apologies everyone sorry for the slow reply was moving around all day.

Anthony, here’s my applystop code for the picture above:

#include_once "Formulas\Norgate Data\Norgate Data Functions.afl"

// ******** 1. Basic Settings/SetOption ********
//OptimizerSetEngine("cmae");   
SetBacktestMode( backtestRegular ); 
SetOption("AllowPositionShrinking", False );
//SetOption("AllowSameBarExit", False ); 
//SetOption("ActivateStopsImmediately", True ); 
SetOption("MinPosValue", 0 );  // 0 == No limit!
SetOption("PriceBoundChecking", False ); //FALSE == flag errors !
SetOption("PortfolioReportMode", 0 ); //0-Trade list, 1-Detailed Log, 2-Summary, 3-No output
SetOption("ReverseSignalForcesExit", False );  
SetOption("UsePrevBarEquityForPosSizing", True ); // Equity - True = Yesterday Equity, False = Today's
SetTradeDelays( 0,0,0,0 ); // ( Buydelay,Selldelay,Shortdelay,Coverdelay )  


// Entry Trigger
LongTrig = 
 Close > 1.00  AND  
 Close > Ref(Close,-250)  AND 
 MA(Close * Volume,50)  > 500000  AND  
 DayOfWeek() == 5; //Check on Fridays
 
ExitTrig =  
 Close < Ref( Close, -250 )  AND 
 DayOfWeek() == 5; 

Short = Cover = 0;   //Long Only system
 
Buy  = Ref(LongTrig,-1); 
Sell = Ref(ExitTrig,-1); 
BuyPrice = Close; 
SellPrice = Close; 


stopLength = 8.00 * ATR(50); 

ApplyStop( stopTypeTrailing, stopModePoint, stopLength, exitatstop = 2, volatile = true );  
//ApplyStop( stopTypeLoss, stopModePercent, 10, exitatstop = 0, volatile = true );  

Equity( 1, 0); //evaluates the stops, over all quotes. 

inTrade = Flip( Buy, Sell ); //True when Buy, False when Sell 

SetOption( "EveryBarNullCheck", True); //null bars throws off our stop loss

stopLine = IIf( inTrade, HighestSince(Buy, H-stopLength), Null ); 
Plot( stopline, "ATR stopLine", colorTeal, styleLine, 0,0,0,0 ); 


//  2. Posize/Risk 
RoundLotSize = 10; 
TickSize = 0.01;  
//SetOption( "CommissionMode", 0 );  // 0 - Table (Backtester, Settings->General)
SetOption( "CommissionMode", 1 );  // 1 - Percent
OptEq = 1.5 * 1000000;//Optimize( "OptEq", 1500000, 300000, 900000, 25000 );  
SetOption("InitialEquity", OptEq );  
MaxOpen = 200;
SetOption("MaxOpenPositions", MaxOpen );  
possize = 10000;
SetPositionSize( possize, spsValue );

Sorry forgot to mention, tried both parms - exitatstop = 0 and 2. with no visible difference.

rgds
jacc

In the first 10 minutes you can edit your post. You can change or add whatever you want, so there’s no need to make another post just to correct the previous one …

Sorry Tomasz, I thought that it not being any kind of complete code, just some lines.

Will remember for next time.

Anthony

ok Milosz thanks for the tip, sorry still new to this forum’s workings.

Do you have any suggestions for my ApplyStop code above ?

thanks

In the line:
for (I=0, I< barcount, I++)
You will have to start at I=260. With your code, PrevYearCls[0] would be = Close[-260] and there isn’t such an item in the array. Close[0] is the first item in the Close array.

1 Like

Hi Bushido,

thanks very much for that, i have since tried and it works. Code I tried subsequently is:

LongTrig = 
 Close > 1.00  AND  
 Close > Ref(Close,-260)  AND 
 MA(Close * Volume,50)  > 500000  AND  
 DayOfWeek() == 5; //Check on Fridays
 

Buy = Ref(LongTrig,-1);
BuyPrice = Close; 
Sell = 0;
SellPrice = Close; 

trailArray = Null;   
DoW = DayOfWeek(); 
Cls1YrAgo = Ref(Close,-.260); 
IS = TS = DaysInTrade = 0; 

for( i = 260; i < BarCount; i++ )
{
  if ( TS == 0  AND  Buy[ i ]  )  
    {
      EntryDayPrice = BuyPrice[ i ]; 
      TS = Cls1YrAgo[i];   
    }             
  else  Buy[ i ] = 0;  

  if ( TS > 0  AND  DoW[i] = 5  AND 
     ( 
         Close[i] < TS 
        //OR  DaysInTrade > NBar 
      )) 
    
  if ( TS > 0 )   
    { 
      TS = Max( TS, Cls1YrAgo[i] ); 
      trailArray[ i ] = TS; 
    }
}

Anthony’s right i probably had a syntax error somewhere in the code. I was just trying to replicate the “normal” sell code (below) in a loop to see if i got identical results but obviously if I’m starting at i=260 so some trades will be skipped:

Sell = C < ref(C,-260); 

thanks again for the suggestion. appreciate the help
rgds j