Saturday, 9 February 2013

Close All Trades All Symbols MQL4 Script for Metatrader 4

There are times when having the quick ability to close out all trades on an account or on a given magic number comes in handy. Whether you are taking a large profit or getting out of a jam, the CloseAll_AllSymbols MQL4 script for Metatrader belongs in every forex trader's arsenal of tools. Simply double click the script from the Navigator pane after copying it into the correct folder, and all open trades should be closed for the magic number selected. The default value is to close all trades for all magic numbers (MagicNumber = -1).

CloseAll_AllSymbols MQL4 is a Metatrader 4 Script that searches through an account and closes out all open trades that match the selected magic number. By default all trades are closed so this makes a handy way to exit the market and get flat in a flash. The script contains default values that will execute unless you manually edit the code from within the MetaEditor.

// when MagicNumber = -1 then close all magic numbers
extern int MagicNumber = -1;

// pips of slippage to allow
extern int Slippage = 7; 

If you wish to change the maximum allowance for slippage, you must change the value in the code prior to executing the script on your chart. Right-click on the navigator pane while selecting the script's name, and choose Modify. This should open up the MetaEditor and load the script into memory. Change the value as desired, then click the "Compile" button at the top of the MetaEditor. 

How to use CloseAll_AllSymbols.mq4

Download the file below and copy it into your "..\experts\scripts" folder. After restarting Metatrader 4 so that it has a chance to compile and find the script and place it in the Navigator pane. You should see the script CloseAll_AllSymbols listed under "Scripts" if you copied the file into the right location, and restarted your Metatrader. Be careful because when you double click the MT4 script all trades on ALL selected charts should close immediately!

You may post this MT4 script to other sites, but if you do, you must post a link to this page directly and you may not sell it or the source code. You are otherwise free to copy, use and distribute this MQL4 script for non-commercial use. 

Note: updated 11/11/2011 to eliminate a small bug that prevented the script from unloading correctly, and reworked the for loop direction to take all fill possibilities into account.

Updated 12/1/2012 to make script compatible with FIFO order exit rule.

Close All Orders This Symbol Only MQL4 Script for Metatrader

If you trade like me, sometimes you just need to exit a particular forex pair, and quickly! This script will do that for a single currency chart. Simply double click the script from the navigator pane after copying into the correct folder, and the selected chart's open trades should all be closed.

CloseAll_ThisSymbol.mq4 is a MQL4 script for closing all orders for a single forex symbol. The code is explained in greater detail in the MQL4 code tutorial titled, "How To Write a Close All Script in MQL4?" If you have questions about the MQL4 code, please refer to that document. 

Default values for slippage and magic number have been placed in the script as follows:

// when MagicNumber = -1 then close all magic numbers
extern int MagicNumber = -1;

// pips of slippage to allow
extern int Slippage = 7; 

If you wish to change the maximum allowance for slippage, you must change the value in the code prior to executing the script on your chart. Right-click on the navigator pane while selecting the script's name, and choose Modify. This should open up the MetaEditor and load the script into memory. Change the value as desired, then click the "Compile" button at the top of the MetaEditor. 

The default value for MagicNumber is -1. This value indicates that magic number should not be used to limit the trades that should be closed for this fx symbol. In other words, when MagicNumber equals -1, all open trades for the currently selected chart will be closed. Change MagicNumber to the desired number if you wish to only close out certain trades that use the magic number tag.

How to use CloseAll_ThisSymbol MQL4

Download the file below and copy it into your "..\experts\scripts" folder. After restarting Metatrader 4 so that it has a chance to compile and find the script and place it in the Navigator pane. You should see the script CloseAll_ThisSymbol listed under "Scripts" if you copied the file into the right location, and restarted your Metatrader. Be careful because when you double click the MT4 script all trades on the currently selected chart should close immediately!

You may post this MT4 script to other sites, but if you do, you must post a link to this page directly and you may not sell it or the source code. You are otherwise free to copy, use and distribute this MQL4 script for non-commercial use. 

Note: updated 11/11/2011 to eliminate a small bug that prevented the script from unloading correctly, and reworked the for loop direction to take all fill possibilities into account.

Updated 12/1/2012 to make script compatible with FIFO order exit rule.

How to Use the MarketInfo MQL4 function?

This how to MQL4 article covers the MarketInfo() function and touches on some other useful functions including, Symbol(), OrderSelect(), OrderSymbol(), OrderClose(), and NormalizeDouble(). In addition this article discusses the constants MODE_BID, Bid, MODE_ASK, Ask, MODE_DIGITS, Digits and NULL.
Let's say you wish to create an expert advisor or indicator that references data from another chart. How would a trader go about doing that in MQL4? The MarketInfo() function has many useful request identifiers. (Please consult the help within MetaEditor for a complete list). But first read on! MarketInfo() is defined as follows:
double MarketInfo(string symbol, int type)

To reference the current chart's data, simply insert NULL or Symbol() where it says symbol, such as MarketInfo(NULL, ...) or MarketInfo(Symbol(), ...).
string Symbol()

If you'd like to use MarketInfo() to reference other forex charts within Metatrader, there are several ways to do this and they are context specific. Let's assume you wish to close out a group of trades on a different symbol. For instance in the scripts Close All Orders This Symbol Only, and Close All Trades All Symbols trades are closed out via a loop. Here is a snippet from the second link.

bool closed = false;
   for (int i = 0; i < OrdersTotal(); i++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        .............
      if (OrderType() == OP_BUY && (MagicNumber == OrderMagicNumber() || MagicNumber == -1)) {
        closed = OrderClose( OrderTicket(), OrderLots(), 
        NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)), Slippage,        White);
      }
.................

Note that within the close out for loop, OrderSelect is called. This effectively opens up some opportunities to use built-in MQL4 functions to reference information about trades that have originated from charts other than the current chart. 
bool OrderSelect(int index, int select, int pool=MODE_TRADES)

The OrderClose function calls for a ticket number, the number of lots to close, a closing price, a slippage amount, and a color. Notice the presence of the MarketInfo function in the parameter that refers to a closing price. 
bool OrderClose(int ticket, double lots, double price, int slippage, color Color=CLR_NONE)

In this case functions are nested to ensure that data is formatted in the correct way. The first term of the MarketInfo function is OrderSymbol which references the selected order's symbol. This handy function provides the symbol term that is needed to fill the first term of MarketInfo. The bid price is referenced by using the MODE_BID request identifier. MODE_BID is a constant with the value of 9. 

It is not hard to see how this MQL4 example could be easily adapted to close out a long trade by using MarketInfo along with the MODE_ASK request identifier. That block of MQL4 code would look something like this:    
if (OrderType() == OP_SELL && (MagicNumber == OrderMagicNumber() || MagicNumber == -1)) {
        closed = OrderClose( OrderTicket(), OrderLots(), 
        NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)), Slippage, White);
}

The NormalizeDouble function is called to ensure the proper decimal places are used to round the price before order submission. I have noticed that Metatrader brokers tend to be VERY picky about the formatting of orders with the OrderClose function, thus the need for extra special care by using the NormalizeDouble function. The help file declares NormalizeDouble as follows:
double NormalizeDouble( double value, int digits)

In this case the market price that will be used to close the open trade is referenced either by MODE_BID or MODE_ASK. Thus the bid or ask price will be used as returned from the MarketInfo function. Metatrader brokers will reject orders if the incorrect price is used in an OrderClose function. Ensure that MODE_BID is used to close a long trade, and MODE_ASK is used to close a short trade. Referencing Close[0] or any other price will often kick out a dreaded error usually in the range of 135-138 (see your MetaEditor help file under "Error codes") or some similar error that prevents trade execution in the Metatrader terminal, so it pays to double check your MQL4 code.

The second term of NormalizeDouble requires the number of Digits. Because this routine may be referring to a symbol that may be different than the local variable Digits, the correct value is retrieved by making another call to MarketInfo as below:
MarketInfo(OrderSymbol(),MODE_DIGITS)
If the symbol is a Japanese Yen pair and the broker is using pippettes, then the function above will return 3 for Digits. If pips are used it will return 2. For non-JPY pairs the return values will be 5 or 4 respectively for Digits. 

For more information about how to close all open trades, or how to close all open orders for the selected symbol only, please see the referenced scripts, or read the tutorial for a full blow-by-blow walkthrough of how to write a close all script in MQL4.

These are just two short examples of how to use the MarketInfo function to reference data that may or may not be on a different chart. There are many other possible uses for this function (see the MetaEditor help file under "MarketInfo" for more information about request identifiers) but the form of the MarketInfo function is similar to the form discussed in this short tutorial.

MQL4 OrderClose, OrderCloseBy, OrderDelete, OrderModify, OrderSend OrderClose


OrderCloseBy
OrderDelete
OrderModify
OrderSend
Trade Operation (OP_BUY, OP_SELL, OP_BUYLIMIT, OP_SELLLIMIT, OP_BUYSTOP, OP_SELLSTOP)



OrderClose Closes an open trade with the matching ticket number at the specified price. 
bool OrderClose(int ticket, double lots, double price, int slippage, color Color=CLR_NONE)
Returns TRUE if OrderClose succeeds and the open trade is closed, and FALSE if the OrderClose function fails and order doesn't close. Detailed error information may be retrieved on failure with the GetLastError function.

Parameters:
int ticket    Order ticket number of order to close
double lots   Amount of Lots to close
double price  Requested order closing price
int slippage  Amount of slippage in pips (for 4/2 digit brokers) or pippettes (for 5/3 digit brokers)
color Color   (Optional) Color of the closing arrow on the chart.
              The default value is CLR_NONE or no arrow drawn.

Example: Routine to close all orders for all symbols with given Slippage and OrderMagicNumber.

void CloseAll(int Slippage, int MagicNumber) {
bool closed;
for (int i = 0; i < OrdersTotal(); i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    while(IsTradeContextBusy()) Sleep(100);
    RefreshRates();
    if (OrderType() == OP_BUY && MagicNumber == OrderMagicNumber()) {
        closed = OrderClose(OrderTicket(),OrderLots(),
         NormalizeDouble(MarketInfo(OrderSymbol(),
         MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)),Slippage,White);
    }
    if (OrderType() == OP_SELL && MagicNumber == OrderMagicNumber()) {
        closed = OrderClose(OrderTicket(),OrderLots(),
         NormalizeDouble(MarketInfo(OrderSymbol(),
         MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)),Slippage,White);
    }
}
}






OrderCloseBy Closes an open order by an opposite open order.
bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE)
Returns TRUE if OrderCloseBy succeeds and the open trade is closed, and FALSE if OrderCloseBy fails and the order doesn't close. Detailed error information may be retrieved on failure with the GetLastError function.

Note: lot sizes must be the same for both orders.

Parameters:
int ticket    Order ticket number of order to close
int opposite  Ticket number of the opposite order.
color Color   (Optional) Color of the closing arrow on the chart.
              The default value is CLR_NONE or no arrow drawn.

Example:
if (iRSI(Symbol(), 0, 30, PRICE_CLOSE, 0) < 50) {
    if( OrderCloseBy(ticket, opposite, White) == true) {
        return(-1);
    } else {
        Print("OrderCloseBy failed. Ticket #" + ticket + " opposite #" + opposite + "Error# " + GetLastError());
        return(0);
    }
}

OrderDelete Deletes previously opened pending order.
bool OrderDelete(int ticket, color Color=CLR_NONE)
Returns TRUE if OrderDelete succeeds and the order is deleted, otherwise FALSE if OrderDelete fails. Detailed error information may be retrieved on failure with the GetLastError function.

Parameters:
int ticket    Order ticket number of pending order to delete.
color Color   (Optional) Color of the closing arrow on the chart.
              The default value is CLR_NONE or no arrow drawn.

Example: Routine to delete all buy stop orders for the current symbol with given OrderMagicNumber.
void DeleteThis_BUYSTOP(int MagicNumber) {
bool deleted;
for (int i = 0; i < OrdersTotal(); i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    while(IsTradeContextBusy()) Sleep(100);
    if (OrderType() == OP_BUYSTOP && MagicNumber == OrderMagicNumber()
     && OrderSymbol() == Symbol() ) {           deleted = OrderDelete(OrderTicket(), CLR_NONE);
         if(deleted == false) {
             Print("Error deleting buy stop order " + OrderTicket() + " Err#:" GetLastError());
         }
    }
} }



OrderModify Modifies a pending order or open trade.
bool OrderModify(int ticket, double price, double stoploss, double takeprofit, datetime expiration, color arrow_color=CLR_NONE)
Returns TRUE if OrderModify succeeds and the order is modified otherwise FALSE if OrderModify fails. Detailed error information may be retrieved on failure with the GetLastError function.

Note: Price and expiration may only be changed on pending orders.  Error #1 (ERR_NO_RESULT) will be generated if  unchanged values are passed as function parameters. Some trade servers may disable pending order expiration time. If the broker has disabled expiration time, error #147 (ERR_TRADE_EXPIRATION_DENIED) will occur.

Parameters:
int ticket          Order ticket number of pending order to modify.
double price        Requested order price.
double stoploss     Requested stop loss level.
double takeprofit   Requested take profit level (profit target).
datetime expiration Pending order expiration time.
color arrow_color   (Optional) Color to show stoploss/takeprofit modification arrow on the chart. 
                    The default value is CLR_NONE or no arrow drawn.

Example: Function to modify a newly entered MT4 order to add the stoploss and takeprofit fields with a given ticket called OrderModify. This MQL4 function is taken from SnowRoller_1_008.
bool ModifyOrder(int ticket) {
   if(ticket == -1) return(false);
   bool dotp = false;
   double sl = 0.0, tp = 0.0;
   int repeats = 0;
   ordernumber +=1;
   if (MathMod(ordernumber,2) == 0) {
      dotp =true;
   }
   bool result = false;
  
      RefreshRates();
      while(!IsTradeAllowed()) Sleep(100);
      if (OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES) == true) {
         Print("Order Selected " + ticket);
         if(OrderType() == OP_BUY) {
            sl = NormalizeDouble(OrderOpenPrice() - stoploss * Point * NormalizeLots, Digits);
            if (takeprofit > 0 && dotp == true ) {
               tp = NormalizeDouble(takeprofit * Point * NormalizeLots + OrderOpenPrice(), Digits);
            } else {
               tp = 0.0;
            }
         }
         if(OrderType() == OP_SELL) {
            sl = NormalizeDouble(stoploss * Point * NormalizeLots + OrderOpenPrice(), Digits);
            if (takeprofit > 0 && dotp == true) {
               tp = NormalizeDouble(-takeprofit * Point * NormalizeLots + OrderOpenPrice(), Digits);
            } else {
               tp = 0.0;
            }
         }
         Print("minimum: " + MarketInfo(Symbol() , MODE_STOPLEVEL) +   " Order Type: " + OrderType() + " Entry Price: " + OrderOpenPrice() +  " Moving SL to: " + sl + " and TP to " + tp);
         result = OrderModify(ticket, NormalizeDouble(OrderOpenPrice(), Digits), sl, tp, OrderExpiration(), CLR_NONE);
         if (result == true) return (true);
      } else
      repeats += 1;
      if (repeats > 5) {
         Print("Unable to select ticket # " + ticket);
         return(false); // failure
      }
}



OrderSend Creates a new order and sends it to the Metatrader broker.
int OrderSend(string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)
Returns the ticket number of the order if the OrderSend function succeeds, otherwise returns -1 on failure of the OrderSend function. Detailed error information may be retrieved on failure with the GetLastError function.

Notes
MT4 requires the latest Bid (for OP_SELL orders) or Ask (for OP_BUY orders) for price. Volume is referred to in other functions as Lots. These terms are synonymous.

Use the MarketInfo function to retrieve Bid (MODE_BID) or Ask (MODE_ASK) prices for symbols other than the currently selected symbol. Prices used to open (or close) trades must be normalized using the NormalizeDouble function with Digits as the second parameter.

To reference Digits for other symbols, use the MarketInfo function to retrieve Digits (MODE_DIGITS). Failure to normalize prices will trigger error# 129 (ERR_INVALID_PRICE). Stale quotes will trigger error# 138 (ERR_REQUOTE) independent of the slippage parameter.

Use the RefreshRates function before any OrderSend function call to ensure up-to-date prices are held in the Bid/Ask variables. If price on the broker's server moves since the last variable update, on the MT4 terminal client, but is within the slippage amount entered, the order will be filled, otherwise error# 138 (ERR_REQUOTE) will trigger.

Due to U.S. brokerage rules, the best practice is to enter orders without an attached stoploss or takeprofit, then use the OrderModify function to edit the order and attach a stoploss and takeprofit amount as is shown in the ModifyOrder function example.

StopLoss, TakeProfit, and pending order levels may not be placed closer than the distance indicated by the MarketInfo function with MODE_STOPLEVEL parameter. If stop levels are too close or are not properly normalized, error# 130 (ERR_INVALID_STOPS) will be triggered.

Some brokers have disabled the expiration time on their trade servers. Transmitting a non-zero expiration parameter to a broker with disabled expiration time will lead to error# 147 (ERR_TRADE_EXPIRATION_DENIED).

If your broker limits the total number of pending and open orders and trades, error# 148 (ERR_TRADE_TOO_MANY_ORDERS) may be triggered if your order would exceed the broker's order limit.

Parameters:
string symbol       Trade symbol name.
int cmd             Trade operation type. This may be any trade operation enumeration.
double volume       Amount of Lots for order.
double price        Requested order price.
int slippage        Amount of slippage in pips (for 4/2 digit brokers) or pippettes (for 5/3 digit brokers)   
double stoploss     Requested stop loss level.
double takeprofit   Requested take profit level (profit target).
string comment      (Optional) Comment attached to order. This may be used to differentiate between orders.
                    The default value is NULL.
int magic           (Optional) Magic number attached to order. May be used to differentiate between orders.
                    The defalut value is 0.
datetime expiration (Optional) Pending order expiration time.
                    The default value is 0 (no expiration).
color arrow_color   (Optional) Color to show the opening order arrow on the chart. 
                    The default value is CLR_NONE or no arrow drawn.

Trade Operation Constants used in the OrderSend function.
Constant        Value        Description
OP_BUY          0            Buy order
OP_SELL         1            Sell order
OP_BUYLIMIT     2            Buy limit pending order
OP_SELLLIMIT    3            Sell limit pending order
OP_BUYSTOP      4            Buy stop pending order
OP_SELLSTOP     5            Sell stop pending order


Example: SendTrade function taken from SnowRoller_1_008. This function takes the trade operation as the type parameter, and returns the ticket number if the OrderSend function succeeds, otherwise -1 if OrderSend fails. On failure, use the Print routine with the GetLastError function to return the error number such as:
if(ticket == -1) Print("Error Opening Buy Order: " + GetLastError());

The ticket number returned by the OrderSend function is then sent to the ModifyOrder function (see code) to attach a stoploss and takeprofit via the OrderModify function. Normally, error checking should be done after OrderSend returns a ticket number with -1.
int SendTrade(int type)
{
   bool dotrades = false;
   int expiry = 0;
   color clr = Red;
   bool result = false;
   if (type == OP_BUY || type == OP_BUYSTOP) clr = Green;
   int ticket = -1;
  
   while(!IsTradeAllowed()) Sleep(100);
   RefreshRates();
   MaxEquity = GlobalVariableGet("SRMaxEquity");
   if (OpenTrades >= MaxTradesThis) return;
  
   if ((type == OP_BUY )) {
         if(Position == 0) {
            initialAnchor = Close[0];
         }
         if(Close[0] < initialAnchor - MaxNegExcursion * Point * NormalizeLots) return;
         if(Ask - Bid > MaxSpread * Point * NormalizeLots) return;
         ticket = OrderSend(Symbol(), type, (MinLotSize * lotsize * LotMultiplier), NormalizeDouble(Ask,Digits), Slippage * NormalizeLots, 0, 0, comment, MN, expiry, clr);
         return(ticket);
   }
   if ((type == OP_SELL)) {
         if(Position == 0) {
            initialAnchor = Close[0];
         }
         if(Close[0] > initialAnchor + MaxNegExcursion * Point * NormalizeLots) return;
         if(Ask - Bid > MaxSpread * Point * NormalizeLots) return;
         ticket = OrderSend(Symbol(), type, (MinLotSize * lotsize * LotMultiplier), NormalizeDouble(Bid,Digits), Slippage * NormalizeLots, 0, 0, comment, MN, expiry, clr);
         return(ticket);
   }
   return(-1);
}

MQL4 OrderSelect, OrdersHistoryTotal, OrdersTotal


OrderSelect
OrdersHistoryTotal
OrdersTotal
Examples

OrderSelect selects a single order and enables the Order Information functions to return information about the selected order. Because so many order information functions rely on OrderSelect, you should be familiar with this function and how it works. Note: in MT4 the term "order" refers to open orders, closed orders, open trades and closed trades.
bool OrderSelect(int index, int select, int pool=MODE_TRADES)
OrderSelect selects a specific order to allow other trading functions to access information about the order.

Return value: The return value is TRUE if the function succeeds at selecting the order with the specified index and FALSE if the function fails. Error information may be retrieved in the case of a failure with the GetLastError function.

Parameters:
int index    An index number or a ticket number, depending on the select parameter.

int select   A flag that determines what index represents. There are two possible values:
             SELECT_BY_POS index uses a sequential index number in the order pool.
             SELECT_BY_TICKET index uses the order ticket number (assigned via OrderSend)

int pool     Optional flag that may be used when the select parameter is set to SELECT_BY_POS.
             MODE_TRADES (default) Selected orders will be drawn from open or pending orders.
             MODE_HISTORY Selected orders will be drawn from closed or cancelled orders.


OrdersHistoryTotal takes no parameters but returns the number of closed orders and trades in the account history.  As the number of orders returned depends on the MT4 terminal settings under the Account History tab, all trades should be selected by right clicking within the Account History tab and selecting All History as shown in the picture to the left.
int OrdersHistoryTotal()

OrdersTotal takes no parameters but returns the total number of open orders and open trades in the trade log.
int OrdersTotal()


Examples
Usage: loops through all open orders and trades and prints out order details to the log:

for (int i =0; i < OrdersTotal(); i++) {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
        OrderPrint();
    }
}

Usage: loops through all historical orders and trades and prints out order details to the log:

for (int i =0; i < OrdersHistoryTotal(); i++) {
    if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
        OrderPrint();
    }
}

MQL4 Specific Order Information


OrderClosePrice
OrderCloseTime
OrderComment
OrderCommission
OrderExpiration
OrderLots
OrderMagicNumber
OrderOpenPrice
OrderOpenTime
OrderPrint
OrderProfit
OrderStopLoss
OrderSwap
OrderSymbol
OrderTakeProfit
OrderTicket
OrderType
Examples

 All MQL4 trading functions on this page require a successful call to the OrderSelect function before any information may be returned. These MQL4 trading functions return specific order information for the selected order.
Parameters: NONE
OrderClosePrice Returns the historical close price for the selected order. To reference the opening price see OrderOpenPrice.
double OrderClosePrice()

OrderCloseTime Returns the historical close time for the selected order.  If the return value is nonzero then the selected order has been closed and is from account history (see OrderSelect, MODE_HISTORY). Open and pending orders return zero. To reference open orders see OrderOpenTime.
datetime OrderCloseTime()

OrderComment Returns the comment for the selected order. Order comments are set at order creation with the OrderSend function.
string OrderComment()

OrderCommission Returns the commission (if any) for the currently selected order. This function returns one of the three possible profit and loss amounts from placing a trade. The other functions are OrderSwap and OrderProfit. The sum of these three functions is the total profit or loss incurred for a given selected order. OrderCommission is generated by the Metatrader broker.
double OrderCommission()


OrderExpiration Returns the expiration date (if any) for the selected pending or open order. OrderExpiration may be set with the OrderSend function. The default value is zero, meaning no expiration on the entered order.
datetime OrderExpiration()

OrderLots Returns the number of lots or the trade size for the selected order. OrderLots is set at order creation with the OrderSend function.
double OrderLots()

OrderMagicNumber Returns the magic number for the selected order. Magic number is a number used to differentiate between orders for a given symbol and account. In theory, all orders could be placed with a separate magic number and closed with a custom close routine. In practice, different strategies or different entry signals within the same strategy may use different magic numbers to open orders for reporting or for trade closure purposes.
int OrderMagicNumber()

OrderOpenPrice Returns the open price of the currently selected order. To reference closing price, see the OrderClosePrice function, which returns the price of historical (closed) orders.
double OrderOpenPrice()

OrderOpenTime Returns the open time for the selected order.
datetime OrderOpenTime

OrderPrint Prints information about the currently selected order in the experts log. The following information is returned:
OrderTicket, OrderOpenTime, OrderType, OrderLots, OrderStopLoss, OrderTakeProfit, OrderCloseTime, OrderClosePrice, OrderCommission, OrderSwap, OrderProfit, OrderComment, OrderMagicNumber, OrderExpiration
void OrderPrint()

OrderProfit Returns the net profit amount for the currently selected order, excluding swap and commission. For open positions, the return value is the open equity for the selected order. For closed positions, the return value is the closed net profit for the selected order.
double OrderProfit()

OrderStopLoss Returns the stop loss price for the currently selected order. If no stop loss price is set, the return value is zero. This value is typically set with the OrderModify function for U.S. brokers, and may be set with the OrderSend function for non-U.S. based brokers.
double OrderStopLoss()

OrderSwap Returns the swap amount (if any) charged to or credited to the account for the selected order. Swap represents an interest charge for carrying a position over night, or an interest payment for holding an interest bearing currency pair over night. Swaps are set by the broker, and are typically fixed at the same time every day, for instance 5:00 PM EST.
double OrderSwap()

OrderSymbol Returns the symbol used in the currently selected order. The OrderSymbol function and the OrderMagicNumber function provide two ways to differentiate between orders placed on a single account and may be useful in order closure routines when only certain symbols or certain magic numbers are to be closed out.
string OrderSymbol()

OrderTakeProfit Returns the take profit price for the currently selected order. If no take profit price is set, the return value is zero. As with OrderStopLoss, the value is typically set with the OrderModify function for U.S. brokers, and may be set with the OrderSend function for non-U.S. based brokers.
double OrderTakeProfit()

OrderTicket Returns the ticket number for the currently selected order. The ticket number is created using the OrderSend function.
int OrderTicket()

OrderType Returns the type of order currently selected. There are several possible values:
OP_BUY         buy position
OP_SELL        sell position
OP_BUYLIMIT    pending buy limit order
OP_BUYSTOP     pending buy stop order
OP_SELLLIMIT   pending sell limit order
OP_SELLSTOP    pending sell stop order
int OrderType()


Examples: Virtually all the functions on this page may be exchanged seamlessly into the examples below.
Usage: loops through all open orders and trades and sums up the total position profit into the double "profit" variable. Total position profit is the sum of OrderProfit, OrderSwap and OrderCommission.
double profit = 0.0;
for (int i =0; i < OrdersTotal(); i++) {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
        profit += OrderProfit() + OrderSwap() + OrderCommission();
    }
}

Usage: loops through all historical orders and trades and sums up OrderLots into the Lots variable for those orders meeting the OrderMagicNumber() == 0 and OrderSymbol() == "EURUSD" criteria. MN is an integer variable containing a magic number, and sym is a string variable containing a symbol name.

double Lots = 0.0;
int MN = 0;
string sym = "EURUSD";
for (int i =0; i < OrdersHistoryTotal(); i++) {
    if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
        if (OrderMagicNumber() == MN && OrderSymbol() == sym) {
            Lots += OrderLots();
        }
     
    }
}

How To Create a Simple Forex MT4 Expert Advisor Template Using the RSI That Trades Once Per Bar

MQL4 - How To Create a Simple Forex MT4 Expert Advisor Template Using the RSI That Trades Once Per Bar

This is a two-part  MQL4 code tutorial discussing how to create a simple Metatrader expert advisor using the RSI that trades only once per bar. At the end of part 2, a fully functioning RSI EA template may be downloaded.   Additionally, the code will reference a different time frame chart for the RSI. So if you're interested in learning how to reference a different time frame from within an EA, this tutorial should prove informative. This MQL4 code tutorial is the sequal to How to place only one trade per bar on a forex MT4 expert advisor. This article will expand on that simple concept and present code that may be used as a template in many different expert advisor applications and with many different types of indicators, including the RSI.

As was discussed in the previous MQL4 tutorial, the key to trading only once per bar is to encapsulate the trading logic within a conditional block that uses a module level variable to keep track of the bar number using the Bars variable. MQL4 has many built-in indicator functions that may be used in system building.
Using the RSI in MQL4
The iBarShift function returns the bar shift for a given time. In the code below, the current bar Time[0] is referenced. If this code is used on a chart other than the 1 hour chart, the bar sequence could be unpredictable. IBarShift allows for determination of the correct bar, or the closest bar if the last term is set to false. The return value may be entered wherever a shift parameter is required, such as in the iRSI  function.

The RSI or Relative Strength Index may be referenced in the MQL4 code and is declared as follows:
double iRSI(string symbol, int timeframe, int period, int applied_price, int shift)

The first term is symbol and if it refers to the current symbol may be entered as NULL or Symbol(), or even successfully as 0 (though best practice suggests you should use NULL instead of 0) all with equivalent meaning.

The second term is timeframe and may be entered as 0 for the currently selected chart's timeframe, or as one of the pre-built timeframe enumeration values (see your help file under "iRSI" for more details).

In this example the PERIOD_H1 variable is used for referencing data from a 1 hour chart.

The third term period refers to the length of the RSI where the variable RSILength is used (below).

applied_price refers to bar prices like close (PRICE_CLOSE) or high (PRICE_HIGH).

shift refers to how many bars to shift the RSI for the calculation. For instance, to calculate the RSI of 5 bars ago you would use 5 in the 5th term. For this example no shift is used so 0 is used (below).

After creating an external input for RSILength and two inputs for Buy and Sell thresholds for the RSI value at 70 and 30 respectively, the code looks like this:

extern int RSILength        =         14;
extern int BuyThreshold   =      70;
extern int SellThreshold    =     30;
extern double Lots           =           0.01;
extern int Slippage           =          7;
extern string comment     =        "RSI_Template";
extern int MagicNumber  =       0;
/////////////////////////////////////
int ThisBarTrade             =      0;
int Position                     =      0;

int start() {
    double RSI = 0.0;
    if ( ThisBarTrade != Bars) {
        int iShift = iBarShift(Symbol() PERIOD_H1, Time[0], false);
        RSI = iRSI(NULL, PERIOD_H1, RSILength, PRICE_CLOSE, iShift);

        // Buy Condition
        if ( RSI >= BuyThreshold ) {
            ThisBarTrade = Bars;
            // Buy code goes here
        }
        // Sell Condition
        if ( RSI <= SellThreshold) {
            ThisBarTrade = Bars;
            // Sell code goes here
        }
    }
}

By setting the buy threshold to 70, buy orders are created when the RSI crosses above 70. When the RSI crosses below 30 the sell condition is triggered and a sell trade is placed.

The RSI system in this MQL4 tutorial will trade as a stop and reversal (SAR) system, going from long to short and short to long with only single positions long or short being opened. The buy code must determine the currently open position. If the position is already long, nothing is done. If the position is short, the short trade must be exited first. Then when the position is flat, a long trade may be initiated.

The opposite will be done when the sell condition is met. A routine called CalcPosition (shown below) loops through all open trades and adds up the current position into the Position module level variable. Long trades (OP_BUY) are added up as positive numbers Position += 1; while short trades (OP_SELL) are added up as negative numbers Position -=1;.

void CalcPosition() {
    Position = 0;
    for (int i = 0; i < OrdersTotal(); i++) {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if( OrderSymbol() == Symbol() ) {
            if (OrderType() == OP_BUY) Position += 1;
            if (OrderType() == OP_SELL) Position -=1;
        }
    }
}

Open trades need to be closed for buy and sell trades respectively. This can be done by creating two routines. A close routine called CloseSingleBuy, and a second routine called CloseSingleSell to close out the open Buy or Sell orders respectively. As the code is essentially the same for both, for brevity only the CloseSingleBuy code will be shown below.

bool CloseSingleBuy() {
    bool closed;
    for (int i = 0; i < OrdersTotal(); i++) {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if(Symbol() == OrderSymbol()) {
            while(IsTradeAllowed() == false)  Sleep(100);
            RefreshRates();
            if ( OrderType() == OP_BUY) {
                closed = OrderClose( OrderTicket(), OrderLots(), Bid, Slippage, White);
                Print ("Attempting to CloseSingleBuy order # " + i + " " + Bid);
                if (closed == -1) {
                    return(false);
                } else {
                    return(true);
                }
            }
        }
    }
}

The CloseSingleBuy routine is a typical looping block of code that works through all open orders and trades (OrdersTotal), matching up by Symbol() = OrderSymbol() and using the OrderClose() function to close a single open trade.

In the next part, all the pieces are put together into a single simple RSI EA template that you may download and use.