How to store the last order type (Buy/Sell)?

 

How to store the last order type buy or sell in to order to be used as controller for other operators/expressions?

and which type of declaration should be used? Global or Local variable?

 
static string LastOrderWas; 

int Start()

{ 
        LastOrderWas = LastOrderType();
} 

 

string LastOrderType()

{ 
OrderSelect(0,SELECT_BY_POS,MODE_TRADES)

        if(OrderType() == OP_BUY) return("buy");

        if(OrderType() == OP_SELL) return("sell")  
}
 
Humm, example could be better.

Avoid Static or Global Variables as much as possible.

*OrderSelect() need to be tested with if( orderselect(...) ).

*Position 0 may-not be of type op_buy nor op_sell.

Thus process OrderSelect() within a for( index ) Loop.

*For better examples, use the search function on top of page.

Or Google.
 
ubzen:
Humm, example could be better.

Avoid Static or Global Variables as much as possible.

*OrderSelect() need to be tested with if( orderselect(...) ).

*Position 0 may-not be of type op_buy nor op_sell.

Thus process OrderSelect() within a for( index ) Loop.

*For better examples, use the search function on top of page.

Or Google.

I wrote an example, nothing more, nothing less.

But back to the original request:

"How to store the last order type buy or sell in to order to be used as controller for other operators/expressions?"

-Store the last order type buy or sell => He apparently only cares about buy or sell.

-Store the last order => The last order is position zero.

-Store => If you are storing a value, static would be my go-to thought.

-For other operators/expressions => Global is most likely the best way of handling this value if it is being utilized across multiple operators.

Now, as for the errors and validation, sure that is necessary. But I believe that is the responsibility of the programmer; not the one giving an explanation.

And, as for the type not being buy or sell, you could easily add an else statement. But that is hardly the point. The real issue here is the fact that if you want to critique someones work, you should probably offer something of value in return.

 

I give an opinion, nothing more, nothing less.

-For other operators/expressions => Global is most likely the best way of handling this value if it is being utilized across multiple operators. Nope, Globals lose their values when he performs the simple act of restarting the terminal or computer.

-Store => If you are storing a value, static would be my go-to thought. Static suffers form the same problems as above.

-Store the last order type buy or sell => He apparently only cares about buy or sell. OrderType can also be These.

-Store the last order => The last order is position zero. If select by position fails (example when there is no active trade). It'll take the order-type from the last known order-select. In this case it'll return 0 or Op_Buy. + what good is saving values if you're going to process the same function every-tick tho nothing changed.

The real issue here is the fact that if you want to critique someones work, you should probably offer something of value in return... I did provide something of value, I told him to search, this is what separates the boys from the men around here. I'm not about to re-write nor search for a function I've already posted 10-times earlier.

As far as critique, my codes gets-it half the time I post them. Tho our ego gets in the way initially, I just view em as constructive criticism. If I couldn't handle that, I wouldn't post codes on a public forum.

 

Dear All,

Thanks for your valuable support at all, and remember that; We're here to find out the most easy and effective way to control MQL codes.

well, simply I've found the following code:

enum                 lastdeal {no,buy,sell}; // variable for storing the direction of the last trade (buy or sell)
lastdeal             ld     =buy;
.
.
.
bool Direction()
  {
   //--- reverse entry
   if(ld==buy) {ld=sell; return(false);};
   if(ld==sell) {ld=buy; return(true);};
   return(true);
  }
.
.

But, This is for MQL5, and the reason behind my question is that; Is there any equivalent coding for MQL4?

 
But, This is for MQL5, and the reason behind my question is that; Is there any equivalent coding for MQL4? Yes, use Global Integer or Bool instead of Enum. Easy=Yes, Effective=No. You should be able to duplicate that code if you read the first few chapters from the mql4-book.
 
ubzen:

I give an opinion, nothing more, nothing less.

-For other operators/expressions => Global is most likely the best way of handling this value if it is being utilized across multiple operators. Nope, Globals lose their values when he performs the simple act of restarting the terminal or computer.

-Store => If you are storing a value, static would be my go-to thought. Static suffers form the same problems as above.

-Store the last order type buy or sell => He apparently only cares about buy or sell. OrderType can also be These.

-Store the last order => The last order is position zero. If select by position fails (example when there is no active trade). It'll take the order-type from the last known order-select. In this case it'll return 0 or Op_Buy. + what good is saving values if you're going to process the same function every-tick tho nothing changed.

The real issue here is the fact that if you want to critique someones work, you should probably offer something of value in return... I did provide something of value, I told him to search, this is what separates the boys from the men around here. I'm not about to re-write nor search for a function I've already posted 10-times earlier.

As far as critique, my codes gets-it half the time I post them. Tho our ego gets in the way initially, I just view em as constructive criticism. If I couldn't handle that, I wouldn't post codes on a public forum.

No problem Meng, I am learning and have no problem exercising my brain into new realms of understanding.

So, as to address your first two statements, I thought that was the point of using a Static. Static doesn't save the value when you close the terminal? I was under the impression that they were stored as permanent memory objects. If that is the case, your only option is to write to a file?

As for the last order type, I realized two things. First, I chose MODE_TRADES which is only open orders, so I would never have seen your other examples of orderType(), but that doesn't take into consideration the fact that his last order could have been a closed order requiring MODE_HISTORY; this of course would imply a whole new set of code validation.

"what good is saving values if you're going to process the same function every-tick tho nothing changed." - Well, I suppose it comes down to his requirements on being updated. For instance, a scalping EA would require knowing the last order type on a tick by tick basis (or perhaps every time a signal is generate) whereas a trend trading system wouldn't require such a monotonous task.

But, I will give you this, I enjoy the spirit of debate, and I thoroughly love the feedback loop that incites better coding design/output.

Thanks for keeping me honest. =D

 
thekaptain:
As for the last order type, I realized two things. First, I chose MODE_TRADES which is only open orders, so I would never have seen your other examples of orderType(), but that doesn't take into consideration the fact that his last order could have been a closed order requiring MODE_HISTORY; this of course would imply a whole new set of code validation.

If you used SELECT_BY_TICKET it doesn't matter which mode you use. Otherwise yes.

If you want the last closed order, you must find it, the order in the list is not defined. Order History sort by closing date - MQL4 forum

 

If that is the case, your only option is to write to a file? You can use File, GlobalVariableSet(), or Re-Calculate. I've used GlobalVariableSet() for storing values for a long time, of-course thats after I realized global-variables do-not save the values on restarts. The order of reliability would be GlobalVariableSet>File>Re-Calculate with Re-Calculating being the strongest.

Global variables are nice and very convenient but it comes at the cost of memory and speed in mql4. I realize that using local memory within functions makes my ea's run faster because the function give back the memory after it's done doing its work. And seems mql4 only processes one function at a time.

Lastly, every-tick vs something-change comes down to processing time IMO. Example: lets say we wanted to know the total profit of all EURUSD orders in history.

*Summing all profits of EURUSD every-tick would be very-slow as the history grows.

*Summing all profits of EURUSD every-tick and then saving it to a global-variable would make little sense, would-not cut down on the processing, and would lock-up memory somewhere which is not safe. Even if it was safe, this type of function don't care as it'll just re-calculate again next time.

*The best options here are

a) Use the value you've saved within the function. Example: double All_Profit_Of_Symbol_History=Old_Profit + New_Profit; Where Old_Profit=A Static variable which holds the value from the last time you summed up the EURUSD profits.

b) Use some form of status change before re-calculating. Example: if( Last_History_Total==OrdersHistoryTotal() ){ return(Old_Profit); } (Static) Last_History_Total=OrderHistoryTotal();

c) A combination of both by just checking if a new historical order have formed. And instead of adding everything again, use the value from the old_calculations with the newly closed orders. With something like above, if the computer restarts, it'll calculate everything the first time and then just add-on as you go.

Now I'll admit, I don't know if Static Variables used in this manner would lock-up the same amount of memory as a global_variable. But then again, I don't use too many processor intensive functions within my experts. Perhaps a career programmer could answer this question for us. Or maybe I should just run my own damm test lol.

 

Here is an example i wrote, which scans the orders history, and determines the last trade, and stores the following about the last order: orderticket, orderclosetime, orderprofit, orderlots.

I put comments, where you can store if the last order was a buy or a sell...

Hope this helps!!!

double lastTradeLots=0;
int dtrmProfitLastTrade()
{
   int historyTotalTrades = OrdersHistoryTotal();
   datetime lastTradeTime;
   int tNumber=0;
   double tProfit=0;

   
   for(int x=0;x<historyTotalTrades;x++)
   {      
      OrderSelect(x,SELECT_BY_POS,MODE_HISTORY);
      if(OrderMagicNumber()==mNumber && OrderSymbol()==Symbol())
      {         

         lastTradeTime=OrderCloseTime();
         for(int xx=0;xx<historyTotalTrades;xx++)
         {
            OrderSelect(xx,SELECT_BY_POS,MODE_HISTORY);
            if(OrderMagicNumber()==mNumber && OrderSymbol()==Symbol())
            {
               if(OrderCloseTime()>lastTradeTime)
               {
                  tNumber=OrderTicket();
                  lastTradeTime=OrderCloseTime();
                  tProfit=OrderProfit();
                  lastTradeLots=OrderLots();
		  // PUT YOUR BUY OR SELL HERE	
		  // string oType=OrderType();
               }
            }
         }
         
      }
   }
   //Print("TicketNumber: "+tNumber+" Time: "+TimeToStr(lastTradeTime,TIME_DATE|TIME_SECONDS));
   
   if(tProfit>0)
   {
      return(1);
   }
   else if(tProfit<0) 
   {
      return(0);
   }
   else if(historyTotalTrades==0)
   {  
      return(2);
   }
}
Reason: