mql4

Code Example

//+------------------------------------------------------------------+
//|                                                    MyFirstEA.mq4 |
//|                                                         IsmSkism |
//|                                             https://ismskism.com |
//+------------------------------------------------------------------+
#property copyright "IsmSkism"
#property link      "https://ismskism.com"
#property version   "1.00"
#property strict

extern double dLots=0.1;
extern int iTakeProfit=200;
extern int iTrailingStop=35;
extern int iStopLoss=30;
extern int iMagicNumber=12444;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(){
    //---

    //---
    return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
//---

}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(){
    //---
    int iTotalOrders,iCrossed;

    // see if we have a new cross
    iCrossed=CheckForCross();

    // get total number or orders
    iTotalOrders=OrdersTotal();

    // do functions
    if(iTotalOrders==0) PlaceOrder(iCrossed);
    if(iTotalOrders!=0) TrailingStop(iTotalOrders);

    //return(0);
}
//+------------------------------------------------------------------+
int CheckForCross() {
    // check if moving averages have crossed
    static int siLastDirection=0;
    static int siCurrentDirection=0;
    double dShortEma,dLongEma;

    // get the current prices for each moving average
    dShortEma= iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0);
    dLongEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0);

    // check if lines have crossed
    if(dShortEma > dLongEma) siCurrentDirection = 1;
    if(dShortEma < dLongEma) siCurrentDirection = 2;

    if(siCurrentDirection!=siLastDirection) {
        // they have crossed so return the new signal
        siLastDirection=siCurrentDirection;
        return (siLastDirection);
    }

    // no cross
    return(0);
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void PlaceOrder(int iSignal) {
    int iTicket;

    if(iSignal==1) {
        iTicket= OrderSend(
                    Symbol(),OP_BUY,dLots,
                    Ask,3,Bid-iStopLoss*Point,
                    Ask+iTakeProfit*Point,"My First EA",
                    iMagicNumber,0,Green);
        if(iTicket>0) {
            if(OrderSelect(iTicket, SELECT_BY_TICKET,MODE_TRADES)){
                Print("BUY order opened : ",OrderOpenPrice());
            }
        } else {
            Print("Error opening BUY order : ",GetLastError());
        }
    }

    if(iSignal==2) {
        iTicket=OrderSend(
                    Symbol(),OP_SELL,dLots,Bid,3,
                    Ask+iStopLoss*Point,
                    Bid-iTakeProfit*Point,"My First EA",
                    iMagicNumber,0,Red);
        if(iTicket>0) {
            if(OrderSelect(iTicket, SELECT_BY_TICKET,MODE_TRADES)){
                Print("SELL order opened : ",OrderOpenPrice());
            }
        } else {
            Print("Error opening SELL order : ",GetLastError());
        }
    }
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int TrailingStop(int iTotal) {
    int iCount;
    bool bRetVal;

    if(iTrailingStop<1) return(-1); // error

    for(iCount=0;iCount<iTotal;iCount++){
        if(OrderSymbol()==Symbol() && OrderMagicNumber()==iMagicNumber){
            switch(OrderType()){
                case OP_BUY:
                    if(Bid-OrderOpenPrice()>Point*iTrailingStop){
                        if(OrderStopLoss()<Bid-Point*iTrailingStop){
                            bRetVal=OrderModify(
                                OrderTicket(),
                                OrderOpenPrice(),
                                Bid-Point*iTrailingStop,
                                OrderTakeProfit(),0,Green);
                            // check for error
                            if(!bRetVal){
                                Print("Error in OrderModify. Error code=",
                                    GetLastError());
                            } else {
                                Print("Order modified successfully.");
                            }
                        }
                    }
                    break;
                case OP_SELL:
                    if((OrderOpenPrice()-Ask)>(Point*iTrailingStop)){
                        if((OrderStopLoss()>(Ask+Point*iTrailingStop)) || 
                            (OrderStopLoss()==0)) {
                                bRetVal=OrderModify(
                                    OrderTicket(),
                                    OrderOpenPrice(),
                                    Ask+Point*iTrailingStop,
                                    OrderTakeProfit(),0,Red);
                            // check for error
                                if(!bRetVal){
                                    Print("Error in OrderModify. Error code=",
                                    GetLastError());
                                } else {
                                    Print("Order modified successfully.");
                                }
                        }
                        break;
                    }
            }
        }
    }

    return(0);
}
//+------------------------------------------------------------------+

External Variables

  • dLots: holds the number of lots you wish to trade.
  • iTakeProfit: the amount of pips we want the EA to automatically close our order at when reached.
  • iTrailingStop: the amount of pips for the stop to be trailed as the order progresses; in this case it’s set to 35, which means as soon as we are 35 pips in profit, our stoploss will be automatically moved and will continue to be moved as the trade develops.
  • iStopLoss: initial stoploss we will use when the order is automatically placed.
  • iMagicNumber: a unique identifier that all orders placed with this EA will be tagged with, so that our EA will be able to work on its own orders and not interfere with any orders that may have been placed by another EA or manually by you.

Functions

  • This EA has three driving functions, which basically power our EA. These functions are PlaceOrder, TrailingStop and CheckForCross
  • The OnTick function is automatically called when the EA first runs and it will continue to be called for each and every tick of data that is received.
    • It can be thought of as a loop which is triggered every time the price moves and therefore anything in this function will conversely be triggered.
    • It can also be thought of as the Director of the EA.
      • Just like in a movie the Director calls the action and tells the actors and technical staff what it is they should be doing in order for the movie to get made on time and on budget.
      • So the OnTick function contains the setup code and the calls to our other functions.
    • It’s good practice to create the ancillary functions first and then plug them into the OnTick function

CheckForCross

Simply monitors two moving averages and lets us know when a cross has occurred.

PlaceOrder

  • The PlaceOrder function receives a signal.
  • It then checks to see if the signal is equal to 1.
  • If it is, it asks another question and based on the answer it decides to take a certain action or not.
  • Then below, it checks to see if the signal is 2 and repeats the above process but this time with slightly different tasks.