Plotshapes (within IF) working even when IF condition isnot true


(New to AFL, learning the coding and testing samples.)
When I was testing the Trailing Stoploss code (with minor changes) from the KB (AmiBroker Knowledge Base » How to plot a trailing stop in the Price chart) , observed that the plotshapes are working even when the If condition is not true.
Its plotting the star shape whenever there is a valid signal, but should it even do that if the IF condition (within which it resides) is not True.

Have gone through reference for plotshapes, If else, chart execution etc., but couldn't find a reason.

Would be helpful if someone can clarify.

tStopLevel = 1 - Param("trailing stop %", 1, 0.1, 10, 0.1)/100;

Buy = Cross( MACD(), Signal() );
Sell = 0;
//Buy = ExRem (Buy, Sell);

trailARRAY = Null;
trailstop = 0;
dist1 = 1.5*ATR(10);

for( i = 1; i < BarCount; i++ )
   if( trailstop == 0 AND Buy[ i ]) 
      trailstop = High[ i ] * stoplevel;
      PlotShapes(Buy*shapestar, colorGreen, 0, High, Offset=20);    //Marking First buy signal}
      PlotText( "TS1:" + trailstop, i, H[ i ]+dist1[i], colorRed, colorYellow ); //Labelling starting SL value
   Buy[ i ] = 0; // remove excess buy signals
   //PlotShapes(Buy*shapestar, colorRed, 0, High, Offset=40); // Testing to see if the exection flow gets into else statement

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

   if( trailstop > 0 )
      trailstop = Max( High[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;



Plot( Close,"Price",colorBlack,styleCandle);
Plot( trailARRAY,"trailing stop level", colorRed );

Those assumptions are incorrect!

Buy, Sell, Short, Cover are just like any other array, those names are simply AFL keywords.

PlotShapes( shape, color, layer = 0, yposition = graph0, offset = -12, XShift = 0 );

When we associate a condition to shape (1st argument of PlotShapes function), it simply means:

IIf( conditionIsTrue, plotMyShapeChoice, elseShapeNone )

The same can be expressed in a shorter form like this:

condition * myShapeChoice

condition is boolean, so:

  • when condition = 1 (True) then 1 x myShapeChoice = myShapeChoice,
  • when condition = 0 (False) then 0 x myShapeChoice = 0 = shapeNone.

Observe PlotShapes behaves as it should:


_SECTION_BEGIN( "Testing PlotShapes" );
	maPer1 = 5;		ma1 = MA( C, maPer1 );
	maPer2 = 10;	ma2 = MA( C, maPer2 );

	Buy = Cross( ma1, ma2 );

	if( Status( "actionEx" ) == actionIndicator ) {
		SetChartBkColor( colorBlack );
		SetChartOptions( 1, chartShowDates );
		styleOnlyLine = styleNoTitle | styleNoLabel;

		Plot( C, "Price", colorDefault, styleCandle );
		Plot( ma1, "MA(" + maPer1 + ")", colorWhite, styleOnlyLine );
		Plot( ma2, "MA(" + maPer2 + ")", colorGold, styleOnlyLine );
		Title = StrFormat( "{{DATE}}\n\nO %1.2f H %1.2f L %1.2f C %1.2f\nMA(%1.0f) %1.2f, MA(%1.0f) %1.2f\n\n%s",
			maPer1, ma1,
			maPer2, ma2,
			WriteIf( Buy, "Buy = True", "Buy = False" )

		PlotShapes( Buy * shapeUpArrow, colorBrightGreen, 0, L, -12 );

	if( Status( "actionEx" ) == actionExplore ) {
		Filter = 1;
		colHeader = StrFormat( "MA(%1.0f)", maPer1 );
		AddColumn( ma1, colHeader, 1.2, colorDefault );
		colHeader = StrFormat( "MA(%1.0f)", maPer2 );
		AddColumn( ma2, colHeader, 1.2, colorDefault );
		colFontColor = IIf( Buy, colorBlue, colorDefault );
		colBkColor = IIf( Buy, colorBrightGreen, colorDefault );
		AddColumn( Buy, "Buy array", 1.0, colFontColor, colBkColor );

In above code if Buy is reversed like this:

Buy = NOT Cross( ma1, ma2 );

Observe now:


Computer is not Aladin's Jinnī - wish is yours, so are your commands. Problem occurs when we hold wish but our command faults. :slightly_smiling_face:

Observing arrays from charts shows half-hearted effort. Also visualizing those in Analysis shall help you debug actual cause.

Hello Cougar,

Thanks for the detailed response, appreciate it.
Sorry I was not asking the precise question.

I understand Buy * ShapeStar and hence i have used it . And I know exactly when the secondary buy signals are coming after the first Buy.
My question is when the preceding IF statement if( trailstop == 0 AND Buy[ i ]) is not True as trailstop > 0 for any iteration after first Buy (till a Sell happens), Plotshape is still being executed (when the next Buy signal happens) whereas plotText is not executed (which is correct).
So why is the conditional flow making an exception for plotshapes and executing it.
I have marked these secondary Buy signals in blue in the attached snapshot. please note that only plotshapes is printing star for the those buy signals but plotText doesn't.


My worry is not how to handle the additional Buy signals, rather why the If statement is allowing plotshapes to execute when the condition is false.

No you do not...

You continue to make your own assumptions, one after another, concocting baseless fallacies.

You (sorry your ego) ignored all that was suggested, if you would've cared to solve your own problems, you would've found the solution on your own. Believe me, its not hard at all...

Do you notice any difference between:

  • Buy[ i ] of expression trailstop == 0 AND Buy[ i ], and,
  • Buy of Buy * shapestar?

My friend, are Buy[ i ] and Buy same?

Hello Cougar,

Thanks for your response.
I was expecting someone would simply correct my mistake and help me learn something new. Your attempt/effort is not helping me and I don't want to discuss my ego and problems with you.
I appreciate your effort, But 'll wait for other responses.


You might not like @Cougar style, but he makes few good points. I would suggest re-reading his response and take the good bits about the fact that you are displaying two different expressions and assuming they are the same while they are not.

Use exploration, use _TRACE, use debugger and other techniques given here: How do I debug my formula?

Hello Tomasz,

Glad to see a response from you! Let me be the ‘n+1’th person to admire & praise you for creating such an Outstanding software. I’m sure ‘n’ will be infinite.
Creating such a software would have needed a great vision, lot of patience & perseverance, brilliance and much more to achieve it. Hats off to you!

Its not about liking or disliking the style. It’s about whether I really need to accept that style to learn. A style which analyzes the state of my ego and a style that advocates how to handle my problems.
If I can solve my own problems, why would I buy a software or present my question in a forum. I’m here to understand a technical scenario that I couldn’t and correct my mistake if be it. Not to present myself for psych eval.

If the aforementioned style is indeed accepted in this forum, then simple people like me who want to learn something new by making mistakes, need to be careful in asking questions or atleast be careful in responding to responses that make you squirm. Which defeats the whole purpose of being in a moderated forum/community that's supposed to help/guide each other.

Again, I respect & appreciate Cougars’ time, effort and patience. And I’ll take in his inputs and work on it.

Karthik P


Please distinguish between two ways of asking same question:


I was referring to How to plot a trailing stop in the Price chart, and wrote this with some minor changes:

/*my code*/

In my case, unable to figure out how come PlotShapes written inside if() shows shape when it should not.

When I observe Sun rises from East, my observation is correct.

When I observe Sun rises from West, one can never observe such a thing. Because that observation can never form to begin with.

Similarly, one can never observe:

My first response makes it very clear that:

Even shared a code there, hoping that you'll test it mixing with your own and figure the issue by yourself. That would've resolved the matter!

Self-learning, self-exploration is immensely powerful than someone else telling you what to do. So powerful, that it'll gravitate you closer to reality (unseen by 99%) and enable you to accomplish anything.

Have a beer (or whatever your poison is :slightly_smiling_face:) and re-read your second response, you kept your stigma attached (traces of which you still hold). No sign of introspection, no readiness to accept that you could be wrong in your understanding, the fault still lies with:

Everyone will help you here. Only thing is that, you'll be tested whether you're approaching well researched or not. Even if you do not research and approach, you'll still be helped with tools, recommendations, suggestions. Still you do not research (or work), constructive criticism may be used. This is a no-nonsense forum, unlike any other online forum, that will help you form independent outlook for the long-run.

When you come out of this ego, alter-ego phase, you'll find me as a good friend.

Anyways, markets a ruthless place. :slightly_smiling_face:


One important thing to understand is tha PlotShapes is plural, which means it evaluates entire array and plots not one, but MANY shapes in one call. Therefore with just one call it can draw in all bars.

All your doubts come from misunderstanding how PlotShapes works.

“PlotShapes is plural, which means it evaluates entire array and plots not one, but MANY shapes in one call. Therefore with just one call it can draw in all bars.”

Thanks Tomasz, that clarifies my confusion and I have tested the correct usage for my understanding. I noticed you have had to mention/clarify this in one other post.

Perhaps it would help to add this statement in the comments section in AFL Function Reference - PLOTSHAPES page, so that it would help beginners like me.

@Cougar, Market is indeed a ruthless place. Thanks for reminding me this fact on the plotshapes post. It’ll serve as a visual reminder for me every time I see an up arrow or down arrow shape on the chart. :blush:
Thanks for your patience with me.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.