# Why is it that i am getting Loss when i am backtesting my AFL in the analysis segment with Buy Price as - Close

I am a newbie to the AFL world. When i am backtesting my AFL with Buy price as Open i am getting Profits and when i am changing the setting to Close i am getting losses. Where am i going wrong. Shall the results be similar when i trade live with Buy on Close. Can't we trade as soon as the signal is generated or on the opening of the candle in real time? Please Help. The query might sound stupid but has kept me wondering. :'(

As per the above query that is settings for the backtest, if you select on close the amibroker checks and alert come when the close of each candle and generally use for close so that it will be accurate

1 Like

If your AFL code uses closing candles for example EMA(CLose, 5) then in the backtest settings you must use all trade prices at close ONLY. Otherwise Amibroker will you give results which makes no sense in real time.

For example lets say Buy = Cross(EMA(CLose, 5), EMA(CLose, 18);

Lets says there is an uptrend at end of the hourly candle of 9.15 to 10.15 and EMA crossover is generated. So you are expecting a buy signal at whatever price at 10.15. But if you use OPEN in backtest trade settings Ami will show that 10.15 you buy whatever the price was at 9.15. Now this is like saying nifty 1 hour back was at 7800, now its 7900, only if I could buy Nifty at 7800 right now

How do I know this? A friend of mine simulated for banknifty the simplest of moving average crossover system AFL and showed in 5 years he is able to make 150 crores , starting from 50K rupees!!! I looked at his backtest settings, he was again using open in trade settings but his AFL referenced CLose in his formulas. Once I corrected the error, he wasn’t even left with 50K in the backest !

If you are using open , then your AFL must reference EMA(open, 5) etc.

1 Like

Thank you

hahahaha " he wasn’t even left with 50K" hahahaha. I am in such a similar situation. Coming from non coding background makes it difficult plus the excitement to enter the markets makes things a bit tricky. The AFL i want to has the Buy -Sell condition as below:
ZLHa = ZeroLagTEMA( HaClose, period );
ZLTyp = ZeroLagTEMA( Avg, period );
Buy = Cross( ZLTyp, ZLHa );
Short = Cross( ZLHa, ZLTyp );
Is it OK to use the backtester settings with “Open” as the Buy / Sell price with the above code or in real time?
BTW Thanks a tonne Arshad bhai for a great reply. Thank you !