Showing posts with label MT4 programming. Show all posts
Showing posts with label MT4 programming. Show all posts

Tuesday, December 8, 2015

How to detect fractals in MT4 (+code sample)

When your DIY MT4 programing project requires you to implement swing detection or breakout levels, it's almost impossible not to think about working with fractals.

However, the MT4 fractals don't allow you to change the 2-bar lookback period that the Bill Williams indicator uses to find where the market made a swing lower or higher.
In some cases, you may want to have this period adjustable, so you can validate a fractal only if 5 or more bars are swinging lower and lower before a low fractal is formed.

As you know, the default behavior of the default fractal indicator uses repainting. So it prints the lower fractal as soon as the market steps 2 consecutive candles lower, before waiting for the next 2 candles to be closed and the swing confirmed. Later, if the middle candle was broken below, price went lower and lower, the fractal will be repainted.

You may also want to configure this confirmation period to 1 full candle or even more with a '5-bar fractal'. So how do you implement a custom fractal checking function in MQL4? Here're a few lines of code that will guide you, the sample is pretty straightfoward.


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool fractal_lower(int idx)
  {
   for(int i=1; i<=CANDLES; i++)
     {
      if(Low[idx+i]<=Low[idx]) return false;
     }

   for(int i=1; i<=CANDLES; i++)
     {
      if(idx-i>=0 && Low[idx-i]<=Low[idx]) return false;
     }
   return true;
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
bool fractal_upper(int idx)
  {
   for(int i=1; i<=CANDLES; i++)
     {
      if(High[idx+i]>=High[idx]) return false;
     }

   for(int i=1; i<=CANDLES; i++)
     {
      if(idx-i>=0 && High[idx-i]>=High[idx]) return false;
     }
   return true;
  }

Saturday, October 24, 2015

How to manually confirm a trade taken by the EA

Automated trading is great, you can have your strategy execute the transactions with near perfect precision at the right time, at the right level.
But what happens when you're not 100% confident on the rules of your strategy and you believe that you need your own discretion to choose which signals should turn into market orders and which should be ignored (due to aspects that cannot be put into mathematical formulas)?

MT4 programming can also allow you to create semi-automated Expert Advisors. This basically means that you are able to create an EA that runs continuously, checking the markets for a valid trade setup, but it does not place the orders without you confirming what is has found.
Whenever a valid setup is detected, a popup will appear, asking you if you want to continue by placing an order or ignore this signal and wait for a better one.
Here's how you can do this:



bool ManuallyConfirmed(int sign) // BUY - sign=1, SELL - sign=-1 
  {
   if(!_AskForManualConfirmation) return true;

   string s_type="BUY";
   if(sign<0) s_type="SELL";

   return Verify(WindowExpertName()+ " wants to open a "+s_type+" trade on "+Symbol()+", "+timeFrameToString(Period())+". Do you allow it?");
  }

This function takes an int parameter signaling the type of the trade (buy or sell), and returns true or false after the user has manually confirmed or denied the trade operation.

bool Verify(string message,string subject="Manual confirmation required")
  {
   return (MessageBox(message,subject,MB_YESNO)==IDYES);
  }

The fucntion Verify uses the MQL4 function MessageBos and returns true if the user confirmed (IDYES).

And once you have these 2 functions, all you need to do is call the ManuallyConfirmed function once you have a BUY or SELL signal, and only open the trade if it returns true.

      bool confirmed=ManuallyConfirmed(sign);
      if(confirmed)
        {
             // OPEN BUY or SELL here
         }

Monday, September 7, 2015

How to close all orders in MT4

In order to close all open market orders that are opened in MT4, you need to write and then call a similar function to the one below:


void CloseBuyOrders(string symbol=NULL,int magicNumber=-1)
  {
   int total=OrdersTotal();
   for(int b=0; b<=total-1; b++)
     {
      if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
        {
         if((OrderMagicNumber()==magicNumber || magicNumber==-1) && (OrderSymbol()==symbol || StringLen(symbol)==0) && OrderType()==OP_BUY)
           {
            ResetLastError();
            color arrowColor=clrSteelBlue;
            if(!_ShowArrows) arrowColor=clrNONE;
            if(!OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),10,arrowColor))
              {
               Print("Failed to close order in "+__FUNCTION__+", error="+(string)GetLastError());
               return;
              }
            else
              {
               total=OrdersTotal();
               b--;
              }
           }
        }
     }
  }

As you can clearly see in the name of this MQL4 function, this is supposed to close the BUY positions only. A function/method for SELL orders would be quite the same, except for one difference - can you guess what that is? Post in the comments below if you know what needs to be changed in the "CloseSellOrders" function.

In the next post I'll probably do a generic function for closing both BUY and SELL orders, or only the type that was sent as a parameter. Thanks for learning MT4 with me!