Select last orderType

 
I coded this ea but there is something wrong that I can not solve. The EA should not place an order buy if the last order is Buy and it should not place a sell order if the Last orderType is Sell. Sometes it is ok but if there are many open order so there is something wrong(it place same order successively).This is my code:

Thanks for your help and I apreciate it

#property copyright "Copyright 2021"

#property link      "http://www.mql5.com/"

#property description "Author: AndryRobot"





//--- Inputs

input string Parameter0="INFO GENERALE";

input int MAGICMA= 20131111;

input string Parameter1="Management";

input double Lots          =0.01;

input double UseMM = 0;

input int      StopLoss=200;      // Stop Loss

input int      TakeProfit=400;   // Take Profit



input string Parameter2="Moving Average parameters";

extern int    MovingPeriod   = 10;

extern int    MovingShift    = 0;

extern double   PipsDistance = 100;



input string Parameter3="Time Filter";

extern    string TradeStartTime = "03:30";

extern    string TradeStopTime = "23:00";



input string Parameter4="Close Parameter:Profit=Profit minimum";

extern double Profit= 0;



string EA_Comment="AndryRobot";

 string signal=""; 

//+------------------------------------------------------------------+

//| Calculate open positions                                         |

//+------------------------------------------------------------------+

int CalculateCurrentOrders(string symbol)

  {

   int buys=0,sells=0;

//---

   for(int i=0;i<OrdersTotal();i++)

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;

      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)

        {

         if(OrderType()==OP_BUY)  sells++;

         if(OrderType()==OP_SELL) buys++;

        }

     }

//--- return orders volume

   if(buys>0) buys++;

   else       sells++;

  return 0;}



//+------------------------------------------------------------------+

//| Check for open order conditions                                  |

//+------------------------------------------------------------------+

void CheckForOpen()

  {

  

   int    res;

       double ima_0=iMA(Symbol(),0,MovingPeriod,0,MODE_SMA,PRICE_CLOSE,MovingShift);

       double Lot;

       

          

      double LastLot=OrderLots();

      double LastOrder=OrderType();

              if(AccountProfit() > 0 && OrderMagicNumber()==MAGICMA) Lot=Lots;

              if(AccountProfit() < 0 && OrderMagicNumber()==MAGICMA) Lot=LastLot*2;

       

   //TIME FILTER

   bool sell= Bid<ima_0-(PipsDistance*Point);

   bool buy= Ask>ima_0+(PipsDistance*Point);

   //END TIME FILTER

   



//--- get Moving Average 

  //--- sell conditions

datetime TicketTime=0;

  if(TimeCurrent()>StrToTime(TradeStartTime) && TimeCurrent()<StrToTime(TradeStopTime)){

      if (buy && (OrderType()==OP_SELL)) {

      res=OrderSend(Symbol(),OP_BUY,NormalizeLots(Lot,Symbol()),Ask,3,(Ask-StopLoss*Point)*UseMM,(Ask+TakeProfit*Point)*UseMM,EA_Comment,MAGICMA,0,Blue);

      Sleep(54000);

      }

      if (sell && (OrderType()==OP_BUY)) {

      res=OrderSend(Symbol(),OP_SELL,NormalizeLots(Lot,Symbol()),Bid,3,(Bid+StopLoss*Point)*UseMM,(Bid-TakeProfit*Point)*UseMM,EA_Comment,MAGICMA,0,Red);}

      Sleep(54000);

      return;

//---

      }

  }

void CheckForClose()

  {

//--- go trading only for first tiks of new bar

//--- get Moving Average 

       double ima_0=iMA(Symbol(),0,MovingPeriod,0,MODE_SMA,PRICE_CLOSE,MovingShift);

   bool sell= Bid<ima_0-(PipsDistance*Point);

   bool buy= Ask>ima_0+(PipsDistance*Point);

//---  double pBid, pAsk;

  double pBid, pAsk;



  bool  UseCurrSymbol = False;  // Use one symbol only

  if (AccountProfit()>Profit) {

    for (int i=OrdersTotal()-1; i>=0; i--) {

      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {

        if (!UseCurrSymbol || OrderSymbol()==Symbol()) {

          if (OrderType()==OP_BUY) {

            pBid=MarketInfo(OrderSymbol(), MODE_BID);

            OrderClose(OrderTicket(), OrderLots(), pBid, 3, White);

            Sleep(54000);

          }

          if (OrderType()==OP_SELL) {

            pAsk=MarketInfo(OrderSymbol(), MODE_ASK);

            OrderClose(OrderTicket(), OrderLots(), pAsk, 3, White);

            Sleep(54000);

          }

        }

      }

    }

  }

//---

  }

//+------------------------------------------------------------------+

//| OnTick function                                                  |

//+------------------------------------------------------------------+

void OnTick()

  {

//--- check for history and trading

   if(Bars<100 || IsTradeAllowed()==false)

      return;

   

//--- calculate open orders by current symbol

   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();

                                          CheckForClose(); 

//---

//---

  }



double ND(double Value,int Precision){return(NormalizeDouble(Value,Precision));}



//make lots to right format

double NormalizeLots(double _lots,string pair="")

  {

   if(pair=="") pair=Symbol();

   double  lotStep=MarketInfo(pair,MODE_LOTSTEP),

   minLot=MarketInfo(pair,MODE_MINLOT);

   _lots=MathRound(_lots/lotStep)*lotStep;

   if(_lots<MarketInfo(pair,MODE_MINLOT)) _lots=MarketInfo(pair,MODE_MINLOT);

   if(_lots>MarketInfo(pair,MODE_MAXLOT)) _lots=MarketInfo(pair,MODE_MAXLOT);

   return(_lots);

  }

//+------------------------------------------------------------------+

Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Trade Orders in DOM
Documentation on MQL5: Constants, Enumerations and Structures / Trade Constants / Trade Orders in DOM
  • www.mql5.com
Trade Orders in DOM - Trade Constants - Constants, Enumerations and Structures - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
  1. Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place. The moderators will likely move this thread there soon.

  2. tolotra25: I coded this ea but there is something wrong that I can not solve. The EA should not place an order buy if the last order is Buy and it should not place a sell order if the Last orderType is Sell.

    Where in your code do you find the last closed order, its type, before opening?

  3. void CheckForOpen()  {
      ⋮
          double LastLot=OrderLots();
          double LastOrder=OrderType();

    MT4: You can not use any Trade Functions until you first select an order.

  4. Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number/symbol filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
              Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum (2013)
              PositionClose is not working - MQL5 programming forum (2020)
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
              Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
              Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)

    You need one Magic Number for each symbol/timeframe/strategy. Trade current timeframe, one strategy, and filter by symbol requires one MN.

  5. int CalculateCurrentOrders(string symbol)
      {
      ⋮
      return 0;}
    What is the purpose of this function?
 
tolotra25:
I coded this ea but there is something wrong that I can not solve. The EA should not place an order buy if the last order is Buy and it should not place a sell order if the Last orderType is Sell. Sometes it is ok but if there are many open order so there is something wrong(it place same order successively).This is my code:

Thanks for your help and I apreciate it

Try this function , it is commented out with what is going on at each point . 

Cheers

#property copyright "Read more here "
#property link      "https://www.mql5.com/en/forum/440394"
#property version   "1.00"
#property strict

/* Let's create a function that finds the last order type placed by the ea , live or pending
   That function can return the order type as is but you are probably interested
   in getting the buy or sell 
   so , let's create a small enumeration , meaning our type with our values :
*/
enum orderType{
type_void=0,//nothing
type_buy=1,//buy
type_sell=2//sell
};
/* now we can create a function that returns the above type 
   what do we need to send the function ?
   -the symbol
   -the magic number
   -whether or not to account for pending orders
   -whether or not to look in the history 
   -and a return value for whether or not the order was pending
   -    a return value for the lot 
   -    a return value for whether or not the order is still open
   -    and a return value for the order profit
   Return values mean we will send a variable and it will be filled up with 
                 data inside the function instead of provide data for the function
                 so: 
*/
orderType findLastOrder(string _symbol,//for this symbol
                        int    _magic,//for this magic number 
                        bool   _pending_too,//account for pending orders
                        bool   _look_in_history,//look in history 
                        bool   &is_pending,//return value 
                        double &had_lot,//return value
                        bool   &still_open,//return value
                        double &has_profit,//return value
                        double &open_price){//return value
//set a resulting variable based on the type the function returns 
  orderType result=type_void;
  //so we will now scan the open orders - that is going to happen anyway
    //we setup a time variable that represents the time of the latest order 
      datetime latest_time=0;
    //and one that represents the ticket of that order 
      int latest_ticket=-1;
    for(int i=0;i<OrdersTotal();i++)
    {
    //select an order by its index in the open orders 
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
        //if the order is selected check if we care about it 
        if(OrderSymbol()==_symbol&&OrderMagicNumber()==_magic){
        if(OrderType()==OP_BUY||OrderType()==OP_SELL||(_pending_too&&OrderType()<=5)){
        if(OrderOpenTime()>latest_time){
        latest_time=OrderOpenTime();
        latest_ticket=OrderTicket();
        }}}
      }
    }
    //if we look in history too
    if(_look_in_history){
    for(int i=0;i<OrdersHistoryTotal();i++)
    {
    //select an order 
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
        //if the order is selected check if we care about it 
        if(OrderSymbol()==_symbol&&OrderMagicNumber()==_magic){
        if(OrderType()==OP_BUY||OrderType()==OP_SELL){//we don't care about history orders that were pending because they might have opened
        if(OrderOpenTime()>latest_time){
        latest_time=OrderOpenTime();
        latest_ticket=OrderTicket();
        }}}      
      }
    }
    }
//we are done searching now , if we found anything get its specs
  if(latest_ticket>-1){
  //select the order by its ticket 
    if(OrderSelect(latest_ticket,SELECT_BY_TICKET)){
    //get its direction  if the check is true set it as buy , else set it as sell
      result=(OrderType()==OP_BUY||OrderType()==OP_BUYSTOP||OrderType()==OP_BUYLIMIT)?type_buy:type_sell;
    //is it a pending ? If not market buy and not market sell set as true else false 
      is_pending=(OrderType()!=OP_BUY&&OrderType()!=OP_SELL)?true:false;
    //get lots 
      had_lot=OrderLots();
    //get profit 
      has_profit=OrderProfit()+OrderCommission()+OrderSwap();
    //if its pending or not closed its still open 
      still_open=(is_pending||OrderCloseTime()==0)?true:false;
    //open price 
      open_price=OrderOpenPrice();
    //and done 
    }
  }

//return result
  return(result);  
}
int OnInit()
  {
  return(INIT_SUCCEEDED);
  }

void OnTick()
  {
//---
  //now you can call the function and get the direction and various info
    //don't just throw it in the on tick this is for example , use it before you 
    //want to open a trade
      orderType _last_direction;
      double _last_open_price; 
      double _last_lot,_last_profit;
      bool _last_was_pending,_last_still_open;
      _last_direction=findLastOrder(_Symbol,342,true,true,_last_was_pending,_last_lot,_last_still_open,_last_profit,_last_open_price);
  }

 
Topics concerning MT4 and MQL4 have their own section.
In future please post in the correct section.
I have moved your topic to the MQL4 and Metatrader 4 section.
 

Hi

You haven’t checked last opened order properly. In this function you need to go through all trades and find the last opened trade (by comparing their open time) and save the values you need like orderLot etc Right now you call OrderLots but have not select any trade earlier so it’s just really a “random” value here from “random” trade.

Just go in a loop for all trades and find the one that it’s opened last and then call those functions.

Reason: