simple sma ea - not entering orders in correct position

 

Hello!!
I'm initiating in programming in MT4 and as such starting with a very simple code using SMAs and simply trying to open a BUY and then closing it (code attached).

But when I do backtesting (.png attached) [1] the order is being placed in the wrong position and [2] the order never closes.

Could someone help me resolving these issues?
Thanks!!!

 
#property strict

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{

 double sma_4     = iMA (_Symbol,_Period,4,0,MODE_SMA, PRICE_CLOSE,0);    //magenta
 double sma_15    = iMA (_Symbol,_Period,15,0,MODE_SMA, PRICE_CLOSE,0);   //dash white
 double sma_100   = iMA (_Symbol,_Period,100,0,MODE_SMA, PRICE_CLOSE,0);  //orange
    
// go_buy
    if((sma_15 > sma_100) && (sma_4 > sma_100)){ 
      if(OrdersTotal()<=0)
         OrderSend(_Symbol,OP_BUY,0.01,OrderOpenPrice(),3,0,0,"BUY order placed",1,0,clrGreen);
    }      
// close_buy
    if(sma_4 < sma_100){
      if(OrdersTotal()>0)    
        if(OrderType() == OP_BUY)
           OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrWhite);
    }

}
      
 

Check this price : 

OrderSend(_Symbol,OP_BUY,0.01,OrderOpenPrice(),3,0,0,"BUY order placed",1,0,clrGreen); 

We buy at Ask and Sell at Bid




Which order is this ?

if(OrderType() == OP_BUY
OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),3,clrWhite);
 

As Daniel already pointed out, you can not use any Trade Functions until you first select an order.