MQL4 How To Create A Simple Forex MT4 Expert Advisor Template Using the RSI That Trades Once Per Bar (part 2)

If you missed the first part of this MQL4 RSI EA code tutorial, please rewind to MQL4 How To Create A Simple Forex MT4 Expert Advisor Using the RSI That Trades Once Per Bar. All that's left is to add a simple buy/sell routine to the successful completion of the buy or sell trade. Here is a simple buy routine:

bool OpenSingleBuy() {
    if (Position != 0) return(false);
    int ticket = -1;
    while(IsTradeAllowed() == false)  Sleep(100);
    RefreshRates();
    ticket = OrderSend( Symbol(), OP_BUY, Lots, Ask, Slippage, 0.0, 0.0, comment + " buy", MagicNumber, 0, Lime);
    if (ticket <0) {
      Print ("Failed to OpenSingleBuy, error # ", GetLastError());
      return (false);
    } else {
      Print ("Successfully placed order with OpenSingleBuy");
      return (true);
    }
   return (false);
}

Note that preparatory function calls to IsTradeAllowed() and RefreshRates() are made to ensure that the expert advisor can place a trade when it gets to the OrderSend() function. The Sleep() function is used to delay execution 100 milliseconds before retrying and is enclosed in a while loop with the IsTradeAllowed() function.

Sending an order with OrderSend

Placing a simple opening order in MT4 is relatively straightforward. The OrderSend() function takes the following arguments:

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)

The return value is the ticket number of a successfully opened order. OrderSend() returns -1 if no order has been placed. In this case an error will be set which may be retrieved via the GetLastError() function. Some errors are temporary and others are permanent. For the purposes of simplicity in this tutorial the error code is simply returned and the code terminates. Retries occur whenever the buy condition is valid so permanent and temporary errors should sort themselves out. Updating the code in the Start routine gives us the following:

int start() {
    double RSI = 0.0;
    bool closed = false;
    if ( ThisBarTrade != Bars) {
        RSI = iRSI(NULL, PERIOD_H1, RSILength, PRICE_CLOSE, 0);
        // Buy Condition
        if ( RSI >= BuyThreshold && Position <=0) {
            CalcPosition();
            if (Position < 0) {
               if ( CloseSingleSell() == false) return (0); // failure but it may try again
            }
            if (OpenSingleBuy() == false) return (0); // failure to buy but it may try again
            ThisBarTrade = Bars;
        }
        // Sell Condition
        if ( RSI <= SellThreshold && Position >=0) {
            CalcPosition();
            if(Position > 0) {
               if(CloseSingleBuy()== false) return(0);  // failure but it may try again
            }
            if (OpenSingleSell() == false) return (0); // failure to sell but it may try again
            ThisBarTrade = Bars;
        }
    }
}

When a buy condition is met, the user functions previously described called CalcPosition(), CloseSingleSell() and OpenSingleBuy() are used to add up open positions via the Position module level variable, close out a short position if (Position < 0), and open up a new long position respectively. By splitting the code up into functional parts, it is much easier to add specific error checking or other requirements to the individual parts without disturbing the functioning of the unrelated components. To see how the code all fits together into a single module, please follow the instructions and download the RSI_Template MQ4 file below.

The MQL4 code is attached in viewable MQ4 format below for free download and use. Download the free MT4 expert advisor now! You may post this MT4 expert advisor to other sites, but if you do, you must post a link to this page directly and you may not sell this expert advisor or the source code. You are otherwise free to copy, use and distribute this MT4 expert advisor for non-commercial use. Place the RSI_Template MT4 expert advisor file in your experts folder.

Follow patrickmwhite on Twitter

For updates