OrdersTotal() Function

 

Hi all,


I'm not a programmer and trying to do something - this can be easy for you. So, apologize firstly.

I need to limit my trades. I've used OrdersTotal() function but there seems like a problem. It does not work properly and EA keeps going to open new positions.

Can you guys help to check and fix problem, please?

Thanks in advance,




int OpenOrders = OrdersTotal();



void OnTick()

 {

   if(OpenOrders<50)

   {   

            if (Close[1]>Open[1])

    	     {

                  int orderID = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-(StopLoss*pips),0,"BT",MagicNumber,0,clrBlue);

             }

            else if (Close[1]<Open[1])

             {      

                  int orderID = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+(StopLoss*pips),0,"ST",MagicNumber,0,clrRed);

             }

     

   }

 }
Documentation on MQL5: Trade Functions / OrdersTotal
Documentation on MQL5: Trade Functions / OrdersTotal
  • www.mql5.com
Do not confuse current pending orders with positions, which are also displayed on the "Trade" tab of the "Toolbox" of the client terminal. An order is a request to conduct a transaction, while a position is a result of one or more deals.
 
void OnTick()
 {

int OpenOrders = OrdersTotal();
   if(OpenOrders<50)    {               if (Close[1]>Open[1])     {                   int orderID = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-(StopLoss*pips),0,"BT",MagicNumber,0,clrBlue);              }             else if (Close[1]<Open[1])               {                         int orderID = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+(StopLoss*pips),0,"ST",MagicNumber,0,clrRed);               }         } }
 
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. int OpenOrders = OrdersTotal();
    
    void OnTick(){ …

    Global and static variables work exactly the same way in MT4/MT5/C/C++.

    1. They are initialized once on program load.

    2. They don't update unless you assign to them.

    3. In C/C++ you can only initialize them with constants, and they default to zero. In MTx you should only initialize them with constants. There is no default in MT5, or MT4 with strict (which you should always use.)

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:
      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.

    4. Unlike indicators, EAs are not reloaded on chart change so you must reinitialize them, if necessary.
                external static variable - MQL4 programming forum

  3. 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 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
              PositionClose is not working - MQL5 programming forum
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles

  4. int orderID = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-(StopLoss*pips),0,"BT",MagicNumber,0,clrBlue);
    You buy at the Ask and sell at the Bid.
    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using the Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

 
alptugcanpolat:

Please edit your (original) post and use the CODE button (Alt-S)

In future please post in the correct section

I will move your topic to the MQL4 and Metatrader 4 section.


General rules and best pratices of the Forum.
General rules and best pratices of the Forum.
  • 2018.01.29
  • www.mql5.com
General rules, enforced by moderators : ‌...
 

Guys, 


Thank all of you so much for your detailed answers. I've been fixed it and also edited my post too.

 
int OnInit()
{
        EventSetMillisecondTimer(1000);
    
        return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
        EventKillTimer();
}
  
void OnTimer()
{
        Print("Orders: " + OrdersTotal());
}

Hi! I'm using that code into a custom indicator. The weird thing is that even if I have 1 order running, when the MT4 app is launched, "Orders: 0" is printed on the first OnTimer event. On the second OnTimer event it prints "Orders: 1" correctly. If I set 1000 * 10 milliseconds timer, OrdersTotal() returns 1 correctly already on the first OnTimer event. So OrdersTotal() clearly uses asynch calls under the hood but I was expecting that all "system" functions would be ready after the OnInit completion. Am I missing something?

 
First Last #:

Hi! I'm using that code into a custom indicator. The weird thing is that even if I have 1 order running, when the MT4 app is launched, "Orders: 0" is printed on the first OnTimer event. On the second OnTimer event it prints "Orders: 1" correctly. If I set 1000 * 10 milliseconds timer, OrdersTotal() returns 1 correctly already on the first OnTimer event. So OrdersTotal() clearly uses asynch calls under the hood but I was expecting that all "system" functions would be ready after the OnInit completion. Am I missing something?

After launching, the terminal needs some time to connect to the server

#property strict
#property indicator_chart_window

int OnInit()
  {
   EventSetMillisecondTimer(1000);
   return(INIT_SUCCEEDED);
  }

void OnTimer()
  {
   if(IsConnected())
      Print("Orders: ", OrdersTotal());
   else Print("No connection to trade server");
  }

void OnDeinit(const int reason)
  {
   EventKillTimer();
  }

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   return(rates_total);
  }

But, apparently, even after connecting to the server, information about orders does not become available immediately

2024.01.05 01:48:34.928 test EURUSD,M5: Orders: 1
2024.01.05 01:48:33.927 test EURUSD,M5: Orders: 1
2024.01.05 01:48:32.940 test EURUSD,M5: Orders: 1
2024.01.05 01:48:31.931 test EURUSD,M5: Orders: 0
2024.01.05 01:48:30.928 test EURUSD,M5: Orders: 0
2024.01.05 01:48:29.936 test EURUSD,M5: No connection to trade server
2024.01.05 01:48:29.204 test EURUSD,M5: No connection to trade server
 
Vladislav Boyko #:
But, apparently, even after connecting to the server, information about orders does not become available immediately

Even the second Calculate event does not guarantee data availability:

2024.01.05 02:05:57.258 test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:05:55.204 test EURUSD,M5: OnCalculate Orders: 0
2024.01.05 02:05:52.271 test EURUSD,M5: OnCalculate No connection to trade server
2024.01.05 02:05:52.270 test EURUSD,M5: initialized
2024.01.05 02:05:52.213 Custom indicator test EURUSD,M5: loaded successfully
#property strict
#property indicator_chart_window

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   printOrdersTotal(__FUNCTION__);
   return(rates_total);
  }

void printOrdersTotal(string function)
  {
   if(IsConnected())
      Print(function, " Orders: ", OrdersTotal());
   else Print(function, " No connection to trade server");
  }
 

I hope the tick event is not generated before the orders data is available😄

Apparently, the expert will be initialized after updating the orders data. But that's not for sure

2024.01.05 02:22:53.166 advisor_test EURUSD,M5: OnTick Orders: 1
2024.01.05 02:22:53.166 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.152 advisor_test EURUSD,M5: initialized
2024.01.05 02:22:53.106 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.105 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.105 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.105 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.104 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.104 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.104 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.103 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.103 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.103 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.102 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:53.097 indi_test EURUSD,M5: OnCalculate Orders: 1
2024.01.05 02:22:50.715 indi_test EURUSD,M5: OnCalculate Orders: 0
2024.01.05 02:22:47.816 indi_test EURUSD,M5: OnCalculate No connection to trade server
2024.01.05 02:22:47.815 indi_test EURUSD,M5: initialized
2024.01.05 02:22:47.760 Expert advisor_test EURUSD,M5: loaded successfully
2024.01.05 02:22:47.707 Custom indicator indi_test EURUSD,M5: loaded successfully

void OnTick()
  {
   printOrdersTotal(__FUNCTION__);
  }

void printOrdersTotal(string function)
  {
   if(IsConnected())
      Print(function, " Orders: ", OrdersTotal());
   else Print(function, " No connection to trade server");
  }
 
First Last #: The weird thing is that even if I have 1 order running, when the MT4 app is launched, "Orders: 0" is printed on the first OnTimer event
Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
  1. Terminal starts.
  2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
  3. OnInit is called.
  4. For indicators OnCalculate is called with any existing history.
  5. Human may have to enter password, connection to server begins.
  6. New history is received, OnCalculate called again.
  7. A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
Reason: