Pending Order EA

 

Hello Forum, good day.

I'm trying to finish a Pending Orders Expert Advisor that takes the OHLC prices from the previous candle/bar right when a new bar/candle is created and +DI > -DI for Buy Orders and +DI < -DI for Sell Orders, but somehow there are times that it takes this values from two or more candles behind. Also I need that for Buy Orders only when the previous candle is Black the order is placed/filled and for Sell Orders only when the previous candle is White, but I don't know what I'm missing that this is being ignored sometimes. I'm new to MQL5 and would really appreciate if someone could help me out with this or point me in the right direction.

Here is what I have so far:

 

//+------------------------------------------------------------------+
//|                                                   Pending_EA.mq5 |
//|                        Copyright 2014, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#include <Trade\Trade.mqh>
CTrade  trade;
input double Lot=0.1;
double risk=0.1;//sl is equal ...$
input int ADXperiod=14;

int adx;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {adx=iADX(NULL,0,ADXperiod);
//---

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

  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {int total=0;
   bool newb=NewBar();
     for(int i=0;i<PositionsTotal();i++)
     {
      // position on our symbol
      if(Symbol()==PositionGetSymbol(i))
        {total=1;
         if(newb)Trail();//move sl everday(4.)
        }
      }
   if(total==0&&newb)//if no open positions and newbar (0.)- open
      {OpenOrder();
      }
//---

  }
//+------------------------------------------------------------------+
void OpenOrder()
{double dipl[];
 double dimi[];
 CopyBuffer(adx,1,1,1,dipl);
 CopyBuffer(adx,2,1,1,dimi);
 if(dipl[0]>dimi[0])//di+>di-(1.,2.)
   {if(iClose(NULL,0,1)<iOpen(NULL,0,1))//bear candle 3.1
     {delete_all_stop_orders();//delete old stop orders
     PlaceBuyStop();//3.1
     }
   }
 else//di+<di-(1.,2.)
   {if(iClose(NULL,0,1)>iOpen(NULL,0,1))//bull candle 3.2
     {delete_all_stop_orders();//delete old stop orders
      PlaceSellStop();//3.2
     }
   }
}

void PlaceBuyStop()
{double val=_Point*risk/(NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE),_Digits)*Lot);//+0.1 cent
   double pr=iLow(NULL,0,1);//low form previous bar
   double op_pr=iOpen(NULL,0,1);//open price


 MqlTradeRequest request={0};
   request.action=TRADE_ACTION_PENDING;         // pending order
   request.volume=Lot;                          // lot size
   request.symbol=_Symbol;
   request.price=op_pr;                          //open price
   request.sl=pr-val;                            // Stop Loss
   request.tp=0;
   request.type=ORDER_TYPE_BUY_STOP;            // ordertype
   MqlTradeResult result={0};
   int tic=OrderSend(request,result);


}
void PlaceSellStop()
{double val=_Point*risk/(NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE),_Digits)*Lot);//sl value
   double pr=iHigh(NULL,0,1);
   double op_pr=iOpen(NULL,0,1);

   MqlTradeRequest request={0};
   request.action=TRADE_ACTION_PENDING;         // pending order
   request.volume=Lot;                          // lot size
   request.symbol=_Symbol;
   request.price=op_pr;                          //open price
   request.sl=pr+val;                            // Stop Loss
   request.tp=0;
   request.type=ORDER_TYPE_SELL_STOP;            // ordertype
   MqlTradeResult result={0};
   int tic=OrderSend(request,result);
}
void delete_all_stop_orders()
{int i;
ulong lv_ticket;

    int lv_total = OrdersTotal();
    for (i = 0; i < lv_total; i++ )
      {if ((lv_ticket = OrderGetTicket(i)) > 0)
        if (OrderGetString(ORDER_SYMBOL)==_Symbol)
        {
         if((OrderGetInteger(ORDER_TYPE)==ORDER_TYPE_BUY_STOP||OrderGetInteger(ORDER_TYPE)==ORDER_TYPE_SELL_STOP))
         {
          trade.OrderDelete(lv_ticket);
         continue;
         }
        }
      }
}


bool NewBar()//0. Know when a new bar/candle
{datetime tim[];
  CopyTime(Symbol(),0,0,1,tim);

static datetime lastbar = -1;
datetime curbar = tim[0];
if(lastbar!=curbar)
{
lastbar=curbar;
return (true);
}
else return(false);
}

//have access to the current and previous OHLC rates/prices.
double iClose(string symbol,ENUM_TIMEFRAMES timeframe,int index)

{
   if(index < 0) return(-1);
   double Arr[1];
   if(CopyClose(symbol,timeframe, index, 1, Arr)>0)
        return(Arr[0]);
   else return(-1);
}

double iOpen(string symbol,ENUM_TIMEFRAMES timeframe,int index)

{
   if(index < 0) return(-1);
   double Arr[1];
   if(CopyOpen(symbol,timeframe, index, 1, Arr)>0)
        return(Arr[0]);
   else return(-1);
}


double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)

{
   if(index < 0) return(-1);
   double Arr[1];
   if(CopyHigh(symbol,timeframe, index, 1, Arr)>0)
        return(Arr[0]);
   else return(-1);
}

double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)

{
   if(index < 0) return(-1);
   double Arr[1];
   if(CopyLow(symbol,timeframe, index, 1, Arr)>0)
        return(Arr[0]);
   else return(-1);
}


void Trail()
{MqlTradeRequest request={0};
MqlTradeResult  result={0};


      request.action=TRADE_ACTION_SLTP;
          request.symbol = Symbol();
         if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
           {double sl=iLow(NULL,0,1);

            if(NormalizeDouble(sl-PositionGetDouble(POSITION_SL),_Digits)>0)
              {

               request.sl=NormalizeDouble(sl,_Digits);
               request.tp=NormalizeDouble(PositionGetDouble(POSITION_TP),_Digits);

               int t=OrderSend(request,result);
              }
           }

         if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
           {double sl=iHigh(NULL,0,1);

            if(NormalizeDouble(PositionGetDouble(POSITION_SL)-sl,_Digits)>0)

              {
               request.sl=NormalizeDouble(sl,_Digits);
               request.tp=NormalizeDouble(PositionGetDouble(POSITION_TP),_Digits);


              int t1= OrderSend(request,result);
              }
           }
}

 

Regards and thank you in advance,

codeMolecules 

 
codeMolecules:

Hello Forum, good day.

I'm trying to finish a Pending Orders Expert Advisor that takes the OHLC prices from the previous candle/bar right when a new bar/candle is created and +DI > -DI for Buy Orders and +DI < -DI for Sell Orders, but somehow there are times that it takes this values from two or more candles behind. Also I need that for Buy Orders only when the previous candle is Black the order is placed/filled and for Sell Orders only when the previous candle is White, but I don't know what I'm missing that this is being ignored sometimes. I'm new to MQL5 and would really appreciate if someone could help me out with this or point me in the right direction.

Here is what I have so far:

 

 

Regards and thank you in advance,

codeMolecules 

Please explain your problem more carefully. What is the exact meaning of text I highlighted. Provide screenshots or better logs.

There is no print statement in your code, check your trigger values by printing them to the logs. Also there is almost no error checking/processing.

 
angevoyageur:

Please explain your problem more carefully. What is the exact meaning of text I highlighted. Provide screenshots or better logs.

There is no print statement in your code, check your trigger values by printing them to the logs. Also there is almost no error checking/processing.

Hello angevoyageur, good day. Thanks for your response.

What I’m trying to do is a simple EA that places a BuyStop order when +DI > -DI and the previous candle is black; for SellStop orders +DI < -DI and the previous candle is white. The timeframe is daily (D1) and I need to check for this conditions right at the moment a new candle is being created (at 00:00 h.), but I think that I’m doing this when the candle creates completely, (on new bar, when the day ends: 23:59), not when it starts.


When this conditions must be checked and the order should be placed is right at 00:00 h.; I need the values to be taken from the previous candle, but there are orders that the values are taken from two or more candles behind the day it was placed.


I’ll attach the results from the journal in the Strategy Tester for the first 5 operations and the chart from the MetaTrader so it is better illustrated. I’m testing this EA with XAUUSD on the period of 2014. The next symbology is related to the first 5 orders that are placed and are circled/numbered from 1 - 5:

 

Red circles: Orders that should not exist

Green circles: Orders that should exist

Blue circles: ADX indicators

Red line: first order that should be placed (16.01.2014) with the values of the previous candle (15.01.2014). This is because here is the first time that +DI > -DI and the previous candle is black.

Black arrow: points to the previous candle from where the values should be taken for the first order (16.01.2014).


Chart explanation: 

1. At this point, +DI > -DI but the previous candle is not black, therefore this order should’t exist. The values are taken from two candles behind, not the previous one.

2. As well as the first order, +DI > -DI but the previous candle is not black, so then this order should not exist. The values are taken from two candles behind, not the previous one.

3. This is the first order that is placed correctly, because at this point +DI > -DI and the previous candle is black. This is taking the values correctly, from the previous candle.

4. At this point, +DI > -DI but the previous candle is not black, so then this order should not exist.

5. This order should exist, because at this point +DI > -DI and the previous candle is black. But somehow it first takes the values from the candle 4 days behind (at 31.01.2014) and then it takes the values from this same day (05.02.2014). 

 

Help will be much appreciated. 

 

Regards and thank you in advance,

codeMolecules

Files:
chart_ea.gif  50 kb
table.gif  33 kb