How to color charts based on buy/sell position

Hi,

I have started using AmiBroker and programming with AFL 2 days ago, and i would like to know how to color the bars of a chart based on my buy/sell position. This is the code i came up with, however it doesn’t seem to be working.

Value1 = 14;
Value2 = 28;

BuyCross = Cross(MA(Close, Value1), MA(Close, Value2));
ShortCross = Cross(MA(Close, Value2), MA(Close, Value1));

Color = colorWhite;


for( i = 0; i < BarCount; i++ )
{
 	if(BuyCross[ i ] == True)
		Color = colorGreen;
	if(ShortCross[ i ] == True)
		Color = colorWhite;
}

Plot( Close, "Colored Price", Color, styleBar );

Any help would be appreciated.

1 Like

Your loop is incorrect. But you do not need loop.

Value1 = 14;
Value2 = 28;

BuyCross = Cross(MA(Close, Value1), MA(Close, Value2));
ShortCross = Cross(MA(Close, Value2), MA(Close, Value1));

in_buy = Flip(BuyCross, ShortCross);
in_short = Flip(ShortCross, BuyCross);
Color = IIf(in_buy, colorGreen, IIf(in_short, colorWhite, colorDefault));
Plot( Close, "Colored Price", Color, styleBar );

14

How to color charts based on buy/sell position

BTW, Short is not Sell.

3 Likes

Thank you for your support. How would i go about adapting the code you sent above to color a chart with 3 colors (red for short, green for long, and white for flat)?

For that you need exit rules first since Buy and Short are entry rules.
Here I used nbar stop for exiting long and short.

SetOption("ReverseSignalForcesExit", 0);

Value1 = 14;
Value2 = 28;

Buy = Cross(MA(Close, Value1), MA(Close, Value2));
Short = Cross(MA(Close, Value2), MA(Close, Value1));

Sell = Cover = 0;
ApplyStop( stopTypeNBar, stopModeBars, bars = 10, True );

if ( Status("action") == actionIndicator ) {
	eq = Equity(1, 0);

	in_buy = Flip(Buy, Sell);
	in_short = Flip(Short, Cover);

	Color = IIf(in_buy, colorGreen, IIf(in_short, colorRed, colorWhite));
	Plot( Close, "Colored Price", Color, styleBar );
}

14

7 Likes