Using ValueWhen


My profit booking and stop loss criteria are as follows
PBVal = (H-L)*1.618 of 2 bars before the Buy Signal
SL = L value of 2 bars before the Buy Signal

while plotting the same values, i ran into 2 issues:

  1. SL is plotted properly but PBVal is for some reason is not. It is taking values of trailing 2 bars.
  2. I would not want to plot if there is no trade is active. As you can see SL/ProfitBooking line extended even after trade is closed. How do i avoid that?

Please find below the code snippet i was using. I am new to AFL and experimenting with various functions. Could not quite understand where i am going wrong. Any help is greatly appreciated.

Buy = (lncon1 AND con2 AND con3 AND lncon4);
pbval =  (ValueWhen(Buy, Ref(H, -2)) - ValueWhen(Buy, Ref(L, -2))) * 1.618;
sl =  BuyPrice - ValueWhen(Buy, Ref(L,-2));
Plot(BuyPrice + pbval, "Profit Booking", colorGreen);
Plot(BuyPrice -sl, "Stop Loss", colorRed);

the result chart is as below


Hi . I bet you try to minimize your code instead to make a nice code for your question, or at least to send your last code you are working with. . This is the reason now we cannot make any correction to your main one

Honest there are so many examples in the forum for both of your Questions. You need to search just little bit.

one main mistake is :
In the code that you post above I notice your buyprice is not assign please read here.

// ValueWhen example
Buy = cross( close, ema(close,9) ) ;
BuyPrice= Close;

/// @link

ActualEntryPrice = ValueWhen( Buy, BuyPrice );
stoplost = ValueWhen(Buy,Ref(L,-2));  // if BUY then hold the value 
Plot( ActualEntryPrice, "ActualEntryPrice", colorRed,styleDashed );
Plot(stoplost, "Close-Stop Loss", colorRed);

 pbval =  ValueWhen(Buy, Ref(H, -2)-Ref(L, -2) ); //if BUY hold the value (H-L difference of two bars ago the event)  
//pbval =  ValueWhen(Buy, Ref(H, -2)-Ref(L, -2) + ActualEntryPrice );
Plot( pbval+ ActualEntryPrice, "Profit Booking", colorGreen,styleLine);

Plot( C, "Price", colorDefault, 128 );
PlotShapes(IIf(Buy, shapeSmallCircle,shapeNone),colorYellow,0,BuyPrice,0); 

1 Like


Thank you for the help. I will explore the links shared and get back if I have any questions.