Help with my EA malfunctioning.

 
Hi All, 
I have created an EA that relies so much on candle and MA statuses at the close of period for both entry and exiting of trade condition. The only exception is if SL is triggered or max drawdown reached. This means that considering I use the 1H time frame, it can only place a trade or exit a trade (if the conditions for entry or exit are met) at exactly hourly interval at the close of candles. 
I observe the EA correctly observes the entry conditions and places orders correctly. However, it exits trade within 5secs of entry or exactly at the close of the period without any condition met.
Worse still, EA is active on several charts simultaneously. It closes all active orders simultaneously. It is so annoying cos the closed trades turns out to be great moves most times.
I have reviewed the code multiple times but cannot figure out what could be wrong.
Note on strategy tester, it behaves just fine allowing the trade run through completely. 
Below is the snippet for opening and closing orders

//| Open an order |
//+------------------------------------------------------------------+
void OpenOrder(int orderType)
{
double stopLoss = orderType == OP_BUY ? Bid - InitialStopLoss * Point : Ask + InitialStopLoss * Point;
double takeProfit = orderType == OP_BUY ? Bid + StaticTakeProfit * Point : Ask - StaticTakeProfit * Point;
int ticket = OrderSend(Symbol(), orderType, LotSize, orderType == OP_BUY ? Ask : Bid, Slippage, stopLoss, takeProfit, "EA Order", MagicNumber, 0, Blue);
LogTradeDetails("Open", orderType, LotSize, orderType == OP_BUY ? Ask : Bid, stopLoss, takeProfit);

if (ticket < 0)
Print("OrderSend error: ", GetLastError());
else {
Print("Order opened successfully. Ticket: ", ticket);
totalTrades++;
}
}

//+------------------------------------------------------------------+
//| Close all orders |
//+------------------------------------------------------------------+
void CloseAllOrders()
{
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
CloseOrder();
}
}
}
//+------------------------------------------------------------------+
//| Close the current selected order |
//+------------------------------------------------------------------+
void CloseOrder()
{
double profit = OrderProfit();
bool result = OrderClose(OrderTicket(), OrderLots(), OrderType() == OP_BUY ? Bid : Ask, Slippage, Red);
LogTradeDetails("Close", OrderType(), OrderLots(), OrderType() == OP_BUY ? Bid : Ask, 0, 0);

if (!result)
Print("OrderClose error: ", GetLastError());
else {
Print("Order closed successfully. Ticket: ", OrderTicket());
totalProfit += profit;
if (profit > 0) {
totalWin += profit;
winTrades++;
} else {
totalLoss += profit;
lossTrades++;
}
}

// Exit conditions
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderType() == OP_BUY && Close[1] < MA_A_Current)
CloseOrder();
if (OrderType() == OP_SELL && Close[1] > MA_A_Current)
CloseOrder();
}
}
}

 

I don't know much about Mql4 EA writing... but I think this will be an issue due to the fact that volatility makes the price jump up and down and maybe that's why it's closing too soon

// Exit conditions
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderType() == OP_BUY && Close[1] < MA_A_Current)
CloseOrder();
if (OrderType() == OP_SELL && Close[1] > MA_A_Current)
CloseOrder();
}
}


maybe you have to add more to the exit condition, such as this:  

// Exit conditions
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderType() == OP_BUY && Close[1] < MA_A_Current && (current_price - open_price) > 50 * Point)
CloseOrder();
if (OrderType() == OP_SELL && Close[1] > MA_A_Current && (open_price - current_price) > 50 * Point)
CloseOrder();
}
}


For buy positions the current price is desired to be above open price, for sell positions the current  price is desired to be below open price, that's why I write it that way (you seek a positive number to indicate that the position is in profit)

Use bid or ask to get the current price and use this for obtaining the open price https://docs.mql4.com/trading/orderopenprice

OrderOpenPrice - Trade Functions - MQL4 Reference
OrderOpenPrice - Trade Functions - MQL4 Reference
  • docs.mql4.com
OrderOpenPrice - Trade Functions - MQL4 Reference
 
Thanks Conor for your feedback. The problem of closing too soon seems to be during to the EA checking for exit conditions on every tick rather than waiting for the close of candles as required. This is the only thing I can think of right now. On tick checks probably returns false candle closes and and price positions wrt to MA used. I ll need to figure out how to stop it from checking at every tick.
I trade mainly the pairs gold. BtC, Nas 100 but the volatility isn't really a problem as can be seen when using strategy tester or manually backtesting.
 

Hi

Here the problem would not be probably connected with open/close function but with the logic of the EA (algorithm). You need to show us the code where the CloseAllOrders function is called or where those exit conditions are checked? There is probably some problem with update of MA_A_Current value and it gives you always “true” condition for closing trade. The problem is somewhere within the algorithm, not here.

Best regards