Order management and backtesting (my first post here)

 
Hello,
This is my first post. I have gained alot from reading through this forum and I thank all of you that contribute to it. I have been learning MQL4 (the first progamming language I have tried to learn) for the past couple of weeks so that I may test and optimize my systems. I have no intention of using an EA for live trading. I can get my EAs to make trades and can even optimize them to be long term winners. However, they never work in quite the way I expect them to. The structure of my EA's are similar to others I have found on this forum and elsewhere. I have stripped them down to the bare minimum so I can isolate the errors. Let's take a moving average crossover as a simple example. The code structure I use is as follows:

declare external variables such as moving average period, stop loss, etc.

start function (am I correct that this is the part of the code that is run every time a new bar is added?)

declare local variables to represent the moving averages

close open postitons using a for loop if moving averages cross in diection away from open position (ie close long position if fast moving average crosses slow moving average top down and vise versa)

open a position if moving averages cross according to direction of cross

end of EA

I am running the tester on the daily time chart and open prices only model.

The problem is that when I test the EA a position isn't opened in the same bar that a position is closed (ie when the moving average crosses, it closes the open position but doesn't open a new one in the in the other direction). And sometimes it just doesn't open an order even if there is a crossover and there are no open orders. I've been pulling my hair out over this for days and I would appreciate any help you more experienced programmers can give me. I have attached my code. It is very short and simple with clear notes. Please take a look.

Hopefully I can become a competent programmer with your help and contribute to this forum with good EA's and knowlege.
 
Hi,

Have you try to change the maslow & mafast shift to 1 and maslowprevious & mafastprevious to 2?

because to my understanding current closing price is constantly changing depending on current price level, and if you use closing price in the MA, the current MA will constantly changing, however previous period MA's are alway fixed.

But, I maybe wrong, I am also new to this programming and MQL4 is the first programming that I ever learn.

Cheers.
 
Thanks for the suggestion,
I tried it and it changes the ea so that the order is placed one bar after the cross as you would expect.  Thanks anyway.
Reason: