Trailing stop loss based on ATR auto exits despite Not hitting SL level

Hi All,

I have a problem with my code and I cannot figure out where I am going wrong, would appreciate any help here pls.

I have a code which buys on a positionscore + RSI () > 50 and then use a trailing stop loss based on ATR

Below is the scan results for a particular basket and my issue is with one trade in particular.

The scan results for IB Ventures looks great. RSC ranking in one of the top vs peers

image

image

Individual scores for the scan dates meet my criteria and stock closing remains above Stop Loss levels

My problem is that the system buys IB ventures on 20-4-2018 (Green) great !! BUT sells it on 01-06-2018. I do not want to sell it esp when it meets the criteria with (1st Rank and RSI > 50 and Closing > Stop Level…. Basically, a perfect hold/scale in stock for my system and instead it sells it…

image
Red Horizontal Line is Stop Loss level, Price doesn’t hit the SL level and still system sells it on red arrow day.

image
image
** Note RSC Rank for IBVENTURES on 1 June (37.94) is higher than Graphite (30.58) in screenshot above

Any idea what could be going wrong here?

I use a scale in and a trailing stop loss based (formula below)

//---------------------------------------------- Scaling In ----------------------------------------------//   
Sellsignal = 0;   
  
x = SumSince(sellsignal, buysignal); 
xsigs = x <=50; 
firsttrade = x <=0; 

TimeFrameRestore(); 

BuySignalX = TimeFrameExpand( BuySignal, inWeekly );///@link https://www.amibroker.com/guide/a_mistakes.html#TIMEFRAME 
xsigsX = TimeFrameExpand( xsigs, inWeekly ); 

SellsignalX = TimeFrameExpand( Sellsignal, inWeekly ); 

Friday = DayOfWeek()==5; 
Monday =  DayOfWeek()==1; 
 
Buy = IIf(Friday AND BuySignalX AND  xsigsX, sigScaleIn, 0); 
 
exitLastBar = datetime() >= GetFnData("DelistingDate"); 
Sell = Friday AND SellsignalX OR exitLastBar; 
 
 
//SetPositionSize( PctSize, spsPercentOfEquity ); 
 
//--------------------------------------------------------------------------------------------------------//   
    
   
   
   
//-------------------------------------------- Trailing Stop ---------------------------------------------//   
delay = 2; 
stopAmount = IIf( Friday, RiskPerShare, 100000 );//if it's not Monday, sends a very high stop amount to ApplyStop 
ApplyStop( stopTypeTrailing, stopModePoint, StopAmount, 2, True, 0, delay);///@link http://www.amibroker.com/kb/2014/10/17/using-price-levels-with-applystop-function/ 
//--------------------------------------------------------------------------------------------------------//   

thanks,
Gautam

@gautamlaungani the posted formula is incomplete.

Maybe someone else can figure out the issue anyway, but if you publish the entire code, you will be more likely to be helped (although it is often difficult to replicate and debug this type of problems without having the same data).

Just a note on a line that may confuse the readers:

stopAmount = IIf( Friday, RiskPerShare, 100000 );//if it's not Monday, sends a very high stop amount to ApplyStop 

The comment seems not to agree with the statement.

In the statement, if IT IS a Friday (by the way, June 1st was a Friday) the stopAmount is set to RiskPerShare. All the other days (Mon, Tue, Wed and Thu it is set to 100000).
The comment indicates to use this logic on Monday (a variable defined some lines above but not used).
Is the comment wrong or the wrong variable name was typed in the statement?

If you will repost the code, please, verify it and make it consistent.

1 Like

hi @beppe,

thanks for the check. yes the comment is incorrect. It should read Friday. My entire code is below if you have the time to help. thanks again in advance.

//Initial Parameters   
SetOption("PortfolioReportMode", 1);  
SetBacktestMode( backtestRegular );  
base =  RelStrength("NIFTY50"); 
lookBack = 90; 
//--------------------------------------------- TRADE DELAY ----------------------------------------------//   
Tradedelay = 0; 
SetTradeDelays( Tradedelay,Tradedelay,Tradedelay,Tradedelay); 
BuyPrice = SellPrice = ShortPrice = CoverPrice = Close; 
//--------------------------------------------------------------------------------------------------------//   
 
// ********************************* Technical Parameters Used ******************************** 
 
ATRLength =  15; 
ATRMultiplier = 3.2;
RSILength = 15; 
TEMA3Length = 144; 

RS_1 =   2; 
RS_2 =   4; 
RS_3 =   12; 
RS_4 = 24; 
RS_5 = 48; 
RS_6 = 96;


//---------------------------------------- Initial Capital & Risk ----------------------------------------//   
SetOption("InitialEquity", 1000000);   
SetOption( "UsePrevBarEquityForPosSizing", 1 ); 
SetOption("MinPosValue", 2000); 
RiskPerShare = ATRMultiplier * ATR( ATRLength ) ;
PositionRisk = 1; 
PctSize =  PositionRisk * BuyPrice / RiskPerShare; 
SetOption( "AllowPositionShrinking", True ); 
RoundLotSize = 1; 
TickSize = 0.05; 
SetOption("RefreshWhenCompleted",True); 
//--------------------------------------------------------------------------------------------------------//   
   
//--------------------------------------------- COMMISSIONS ----------------------------------------------//   
SetOption("CommissionMode", 1); 
SetOption("CommissionAmount",0.16); 
//--------------------------------------------------------------------------------------------------------//   
   
//-------------------------------------------- Max Positions ---------------------------------------------//   
Totalpositions = 50;  
SetOption("MaxOpenPositions", Totalpositions ); 
//--------------------------------------------------------------------------------------------------------//   
   
//----------------------------------------- Foreign Base Ticker ------------------------------------------//   
SetForeign("Nifty50"); 
TimeFrameSet(inWeekly); 
 
marketup =  C > TEMA(C, TEMA3Length);   
marketdown = NOT marketup;      
  
ROCI_1 = ROC (C,RS_1);   
ROCI_2 = ROC (C,RS_2);   
ROCI_3 = ROC (C,RS_3);   
ROCI_4 = ROC (C,RS_4);   
ROCI_5 = ROC (C,RS_5);   
ROCI_6 = ROC (C,RS_6);   
   
RestorePriceArrays();     //restore original ticker arrays//   
//--------------------------------------------------------------------------------------------------------//   
   

   
//----------------------------------------- Other Parameters ---------------------------------------------//   
 
ROCS_1 = ROC (C,RS_1);   
ROCS_2 = ROC (C,RS_2);   
ROCS_3 = ROC (C,RS_3);   
ROCS_4 = ROC (C,RS_4);   
ROCS_5 = ROC (C,RS_5);   
ROCS_6 = ROC (C,RS_6);   
   
total = (RS_1 + RS_2 + RS_3 + RS_4 + RS_5 + RS_6);   
 
RSC_1 = (ROCS_1/ROCI_1)*(RS_1/total);    
RSC_2 = (ROCS_2/ROCI_2)*(RS_2/total);    
RSC_3 = (ROCS_3/ROCI_3)*(RS_3/total);    
RSC_4 = (ROCS_4/ROCI_4)*(RS_4/total);    
RSC_5 = (ROCS_5/ROCI_5)*(RS_5/total);    
RSC_6 = (ROCS_6/ROCI_6)*(RS_6/total);    
   
RSCTotal = (RSC_1 + RSC_2 + RSC_3 + RSC_4 + RSC_5 + RSC_6);   
 
rank = IIf(RSCtotal < 1, 0, RSCTotal); 
 
PositionScore = RSCTotal;  
   
//--------------------------------------------------------------------------------------------------------//   
   
   
   
   
//-------------------------------------- System Buy/Sell Rules ------------------------------------------//   
valtraded = (C * V);  
BuySignal = RSI(RSILength) > 65
AND marketup        
AND TEMA(valtraded, TEMA3Length)  > 10000000 
AND C < H 
And C > low;
   
//--------------------------------------------------------------------------------------------------------//   
  
      
//---------------------------------------------- Scaling In ----------------------------------------------//   
Sellsignal = 0;   
  
x = SumSince(sellsignal, buysignal); 
xsigs = x <=50; 
firsttrade = x <=1; 

TimeFrameRestore(); 

BuySignalX = TimeFrameExpand( BuySignal, inWeekly );///@link https://www.amibroker.com/guide/a_mistakes.html#TIMEFRAME 
xsigsX = TimeFrameExpand( xsigs, inWeekly ); 

SellsignalX = TimeFrameExpand( Sellsignal, inWeekly ); 

Friday = DayOfWeek()==5; 
Monday =  DayOfWeek()==1; 
 
Buy = IIf(Friday AND BuySignalX AND  xsigsX, sigScaleIn, 0); 
 
exitLastBar = datetime() >= GetFnData("DelistingDate"); 
Sell = Friday AND SellsignalX OR exitLastBar; 
  
SetPositionSize(IIf(firsttrade, PctSize, PctSize / (x * 2)), spsPercentOfEquity ); 
 
//--------------------------------------------------------------------------------------------------------//  
  
   
//-------------------------------------------- Trailing Stop ---------------------------------------------//   

stopAmount = IIf( Friday, RiskPerShare, 100000 );//if it's not Friday, sends a very high stop amount to ApplyStop 
ApplyStop( stopTypeTrailing, stopModePoint, RiskPerShare, 2, True, 0);///@link http://www.amibroker.com/kb/2014/10/17/using-price-levels-with-applystop-function/ 
//@link http://www.amibroker.com/guide/afl/applystop.html
//2 in the formula applystop is for 
//--------------------------------------------------------------------------------------------------------//   
RestorePriceArrays(); 

has same effect as

TimeFrameRestore(); 

So you are restoring without expanding after restore.

You have to re-organize the code.


Also these lines make no sense to me

Sellsignal = 0;   
  
x = SumSince(sellsignal, buysignal); 

1 Like

Hi @fxshrat,

Thanks for your response. I have barely 4 months experience with afl so pls excuse my mistakes.

What I’m trying to do is keep adding to my initial position as long as the stock meets the condition. Basically keep scaling in on every subsequent buy signal as long as capital permits and it should use weekly data and signals should be generated every Friday.

I would really appreciate if you could help me clean up the code or point me in the right direction where I could learn from an example.

Thanks