Forex buy and sell expert advisor

MT4 EA Course: Buy And Sell

This article is part of a series. Here are the other parts:

 

Welcome to the fourth part of our MetaTrader4 Expert Advisor course! If you haven’t done so, please have a look at first three instalments.

Forex Wall-E

 

Up until now, we’ve just been working with buy orders. But we’re traders, not investors! So rather than a buy-only system, it would be nice if our expert advisor could also short the market. In other words, we want to support going both long and short; buy and sell. We’re still working on our Forex Wall-E expert advisor, so let’s continue where we left off!

 

 

Buy and Sell Orders

 

We’ve been building our expert advisor, but up until now, it could only buy the market. While that’s a good first step, there are situations where you might want to sell a specific forex pair as well! There isn’t a lot of difference between a buy and sell order but there are, however, a couple of things we need to keep in mind. Let’s go over this before we jump into the code.

 

Bid and Ask

 

You might’ve noticed in the previous instalments that every time we create a buy order, we used the Ask as a parameter to the OrderSend() function:

 

        if (OrderSend(Symbol(), OP_BUY, lots, Ask, 3, Ask - stopLoss * Point, Ask + takeProfit * Point, "my forex wall-e order", 12345, 0, Red)) {

 

This is because the Ask price is the lowest price someone selling units of the pair is Asking. In other words, the Ask price is the lowest price that sellers are willing to take for it. When we buy a given pair, we use the Ask price as our entry price.

 

On the other hand, the Bid price is exactly the opposite: it’s the highest price someone buying units of the pair wants to give for it. Like in an auction, a buyer is then Bidding to get units of a forex pair. When we sell a given pair, therefore, we use the Bid price as our entry price.

 

Forex bid and ask

 

Now, you might be wondering if it’s possible that there’s a difference between the two prices. If you thought this, you’re absolutely right, there often is! The difference between Bid and Ask is called the Bid-Ask spread or simply spread.

 

It’s important to know the difference between Bid and Ask, since we’re going to use both once we start to support both buy and sell orders in our Wall-E expert advisor.

 

 

When To Buy, When To Sell?

 

Up until now, we could only create a buy order. If you recall, the condition for entering a buy order was as follows:

 

    if (Ask + 500 * Point < ema) {

 

In other words, we checked if the Ask price was more than 50 pips below our 300 exponential moving average, we buy. Although very basic, this could form the base for a mean-reversion strategy, since we assume that if the price deviates too much from the moving average, it will return to the mean.

 

Let’s see again how this buy-only strategy performed in 2016 on the EURUSD 4H charts:

 

forex wall-e results 2016

 

Ok, not great, but not losing money either! Now, given the condition for buys above, what would be the condition for sells?

 

Right! We’re going to sell if the Bid price is more than 50 pips above the 300 exponential moving average! Adding this conditions shouldn’t be too hard, so let’s dive into the code.

 

 

Adding code for sell orders

 

In step one, we’re going to add a block of code, right after line 47. It looks similar to when we create buy orders, but this will do the opposite. Notice that the OP_BUY constant has changed to OP_SELL and that we use the Bid price instead of the Ask price. Our if-statement will also have changed to check for the right condition:

 


    if (Bid - 500 * Point > ema) {
        if (OrderSend(Symbol(), OP_SELL, lots, Bid, 3, Bid + stopLoss * Point, Bid - takeProfit * Point, "my forex wall-e order", 12345, 0, Red)) {
            Print("Sell order succeeded!");
        }
    }

 

For the stop loss and take profit values, also notice that we have changed the operator from + to – and from – to +. In a buy order, our stop loss will be below the entry price and our take profit will be above the entry price. For sell orders, this is just the opposite!

 

 

Updating our trailing stop

 

Remember that in chapter 3, we added a trailing stop? Up until now, this only supported buy orders, so we will need to update that part of our expert advisor as well! In order to do this, we will need to change the if-statement on line 73 in our TrailStops() function slightly. This is the modified code with an if-statement that also supports sell orders:

 

        if (OrderType() == OP_BUY) {
            if (Bid - OrderOpenPrice() > trailingStop * Point && OrderStopLoss() < Bid - trailingStop * Point) {
                if (!OrderModify(OrderTicket(), OrderOpenPrice(), Bid - trailingStop * Point, OrderTakeProfit(), 0, Green)) {
                    Print("OrderModify error ",GetLastError());
                }
                return;
            }
        } else if (OrderType() == OP_SELL) {
            if (OrderOpenPrice() - Ask > trailingStop * Point && OrderStopLoss() > Ask + trailingStop * Point) {
                if (!OrderModify(OrderTicket(), OrderOpenPrice(), Ask + trailingStop * Point, OrderTakeProfit(), 0, Green)) {
                    Print("OrderModify error ",GetLastError());
                }
                return;
            }
        }

 

As you can see, we have added an else-block to support sell orders (else if (OrderType() == OP_SELL)). Inside this block, we check if the Ask price is already lower than the open price minus our trailing stop threshold AND we check if the stop loss actually needs changing.

 

If both conditions are valid (or evaluate to TRUE), we will execute the OrderModify() function on line 82 to alter the stop loss for our sell order, essentially implementing a trailing stop for our sell orders.

 

You can find the full code (including our sell changes) here.

 

Bid and Ask revisited

 

Notice how, when we created the order, we used the Ask price for buy orders and the Bid price for sell orders. The attentive reader, however, might have noticed that to alter our stop loss, we use the Bid price for buy orders and the Ask price for sell orders! How is that possible?

 

If you buy lots for a forex pair, we use the Ask price. But what happens if you want to close the order? The lots you previously bought will need to be sold again! Which means the roles have reversed and you will now use the Bid price to get the best possible price to sell your lots to someone else in the market. Conversely, if you sell lots for a forex pair, we use the Bid price. If we then want to close the order, we need to buy those lots again, which means that we use Ask price.

 

If this sounds a bit confusing, don’t worry too much about it. Your trading platform usually takes care of this automatically, but when we’re developing expert advisors, this is something we have to define explicitly. Just know that when modifying or closing your order, you’ll probably want to use Bid and Ask the other way around.

 

 

Conclusion

 

Now that we implemented all the code for our sell orders as well, let’s run our strategy tester again. With the same parameters as before, will we get a different result?

 

forex wall-e results 2016 with sell

 

 

That sure does look a little bit smoother than our previous, buy-only strategy! Making sure your strategy works for both buy and sell orders will usually have this smoothing effect, since it will work in both bullish and bearish markets. Any big whipsaws will be flattened a bit in order to get a nicer equity curve.

 

In this chapter, we looked at three things:

  • The difference between Bid and Ask
  • Add a condition to create sell orders
  • Update our trailing stops to support both buy and sell orders

 

We’re still not completely there yet and the conditions for entering and exiting trades are very basic, but we’re slowly but surely expanding our expert advisor to include more functionality. Stay tuned for the next chapter, where we will have a look at position sizing. If you have questions, please let me know in the comments or use the contact form!

 

Subscribe to my newsletter below if you want to be kept up to date on when the next part of this course is published!

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on TumblrShare on RedditDigg thisShare on StumbleUpon

Felix

I'm a full-time, independent forex trader. I've been trading for over 10 years and specialise in reversal trading, trading psychology, algorithmic trading and coaching others. When I'm not trading, I'll either be travelling the world or rock climbing (likely both). Read my story here.

3 Pingbacks/Trackbacks

  • Pingback: MT4 Expert Advisor Forex Course Intro - Smart Forex Learning()

  • Pingback: MT4 EA Course: create your own expert advisor()

  • Pingback: MT4 EA Course: Trailing Stops - Smart Forex Learning()

  • tasaoirse

    gr8 info…bt i didnt find anything on “ORDER CLOSE” OR EXIT

    • Hi, thanks! The order is closed either by hitting the trailing stop or the original take profit level. You can manually close the order using the OrderClose() method in MQL.

      • tasaoirse

        How do i code “ORDERCLOSE”

        • An example would be something like this:
          if (!OrderClose(OrderTicket(), OrderLots(), Bid, 3, Green)) {
          Print(“OrderClose error: “, GetLastError());
          }

          Remember to use the Bid for buy orders and Ask for sell orders. Good luck!

          • Cliff V

            Hi Felixwould you be able to teach or show us a EA code a inside candle with a RMI,stochastic or RSI, Buy/Sell when Indicator is at 75/sell, 25 buy after an inside candle ,

          • Hi Cliff,
            An inside candle would be something like:
            if (High[1] Low[2]) {
            // Create an order
            }

            If you want to add additional filters by using indicators, it’s best to have check if there is a built-in function for this indicator, by trying “i”, such as iRSI, iStochastic, etc. An example would be:

            if (High[1] Low[2] && iRSI(NULL, 0, 14, PRICE_CLOSE, 1) > 70) {
            // Create order
            }

            You probably get the idea of this example. I am working on a more complete video course on EA development from start to finish because I get a lot of questions about this. It will include recipes such as the things you are asking. If you are interested in this, subscribe to my mailinglist and I’ll let you know once it’s ready. Good luck!

          • tasaoirse

            well done