My journal in learning to code EA autodidact - Page 3
Page 3 of 5 FirstFirst 12345 LastLast
Results 21 to 30 of 50

Thread: My journal in learning to code EA autodidact

  1. #1
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184

    My journal in learning to code EA autodidact

    First of all, thanks to the admin has given me a chance to create this thread. Basically I don't need any automatic robots at all for my trading activities. And I am not a programmer. But I feel that having the ability to coding EA is an interesting thing especially for me personally. That's why I wanted to learn myself about EA coding, I want to create a journal for learning how to code Expert advisors.

    I will learn coding from zero through many sources on the internet, at least I want have an ability to create a simple EA. But I hope to be more than that. That's why I have to keep this journal as a note or diary to remember what I've learned, because I'm easy to forget.

    If you want to learn together with me here, please give a contribution here.
    If you have already a good skill in coding EA, please provide your feedback, suggestions and your knowledge to me here.

    Not allowed!

  2. #21
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    After we learned in the previous part that EA can already did buy and sell orders with adjustable hours and orders are limited to only 1 order per type.
    So the basis of the previous Order EA (triger) is the number of buy order = 0 or the number of sell = 0.
    Well, the basic EA order is what needs to be developed based on the desire.

    To add insight to this triger I will discuss about Indicators

    The simplest indicator in Mt4 is Candlestick

    Consider the following image:
    2018-06-03_092214.jpg

    1. The highest price is called High
    To know this high by custom way as follows
    iHigh(string Symbol ,int time frime , int shit)

    string symbol for attached pair used Symbol()
    for direct pair can be written example "GBPUSD" or "EURUSD"

    int timefreme can be specified, take a look
    sim.JPG

    Well, just choose one that would be used, but if you want to read the candle on the EA which has been attached it can be filled with numbers 0
    int shif to determine the condition of candle,

    example:
    If 0, it means current candle
    If 1, it means 1 previous candle
    If 2, it means 2 previous candle

    Because High is a semicolon, it includes double data type, so to determine make this high variable as follows
    example :
    double high = iHigh(Symbol(),PERIOD_H1, 1);

    means the highest price on 1 candle before now (before) and in H1 and I called it as high variable name

    Time frime can also be written in value in minutes, for example if PERIOD_H1 can be replaced with 60, PERIOD_H4 can be replaced with 240, PERIOD_D1 can be replaced with 1440 etc.
    But if we write 0, does not mean 0 minutes , the time frame followed the chart where the EA has been attached.

    example :
    double high = iHigh(Symbol(),0, 1);

    Then the high value of the candle where the EA has been attached, if in time frime (TF) 30 then will read the high point of 1 candle before, so also if the ea has been attached in TF H4 also candle in H4 that will be in read.

    NOTE :
    double high = iHigh(Symbol(),0, 1);
    sometimes be written as
    double high = High[1];

    So if High[2], it means the highest point in the 2 previous candles in TF where the EA was been attached.

    Not allowed!

  3. #22
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    2. The opening price is called Open

    Similarly with High, in writing the provisions are the same.

    double open = iOpen(Symbol(),PERIOD_H1, 1);
    The explanation is the same as High

    3. Closing Price is called Close

    double close = iClose(Symbol(),PERIOD_H1, 1);
    The explanation is the same as High

    4. The lowest price is called Low

    double low = iLow(Symbol(),PERIOD_H1, 1);
    The explanation is the same as High

    From the above explanation may be a little understandable
    An example in the application of an EA is usually used as a triger

    if(Close[2] < Close[1]) { -----order buy ----- }
    or
    if(iClose(Symbol(),0, 2) < iClose(Symbol(),0, 1)) { -----order buy -----}

    meaning if the previous closing price of candle 2 is smaller than the previous closing of candle 1 then buy order
    Can also be made variable

    double close_1 = iClose(Symbol(),0, 1);
    double close_2 = iClose(Symbol(),0, 2);

    if( close_2< close_1){-----order buy -----}


    Well from the above description then it can be tried in input into the EA that has been created in the previous part

    Not allowed!

  4. #23
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    Once we learn about the most popular indicator, the candlestick, we will now discuss about the standard Custom Indicators of Mt4.

    In making an Ea in general use many indicators as a consideration in making the trigger (the trigger of the order), there are many indicators available in Mt4, for example
    MA (Moving Average), MACD, Stochastic, RSI etc.

    How do I create a custom indicator?

    Well to create custom usually made variable first (although this is not mandatory).
    Because the data variable usually contains a comma then using a double.

    In general mt4 custom indicator usually the name of indicator was added a letter "i" in front of indicator name,

    Examples are MA (Moving Average)
    We make a variable for MA, double MA (I made the name of MA).
    This MA custom indicator is iMA
    Take a look at the following picture:

    ma.JPG

    When we write the iMa (then Mt4 automatically provides direction on this indicator, there are several parameters to be made in the order.
    just like the picture above then iMa (string symbol, int timeframe, int ma_pereod, int ma_shift, int ma_methot, int applied_price, int shit);

    we see the following MA parameters:
    2018-06-05_193618.png

    string symbol (the same explanation as candlestick) can be written as Symbol(), can also NULL.
    int timeframe (the same explanation as candlestick)
    int ma_period This is an integer data (not containing commas) is often called the period, the quantity can be written directly or made declarations so that can be changed the numbers easily, for example:

    extern int Pereode_Ma

    int ma_shift , int ma_methot , int applied_price (can be filled directly or made declaration)
    int shit is MA's position as candlestick if it is filled with 0 meaning in position that MA value on candle is running, if filled 1 mean MA value at time 1 candle before now etc, (can be in direct content or made declaration,)

    Examples of custom MA indicators as follows:
    double MA =iMA(NULL,0,Period_Ma,0,MODE_SMA,PRICE_CLOSE ,1);
    or
    double MA =iMA(Symbol(),0,Period_Ma,0,MODE_SMA,PRICE_CLOSE ,1);

    Well the example above for the period made declaration first
    extern int Period_Ma.=20;

    How do you apply in trigger?
    There are so many ways to create a trigger using this Ma indicator, for example
    1. if the price above Ma then buy and vice versa if under Ma then sell
    if(Ask > MA) { order buy }
    if(Bid < MA) { order sell }

    2. If the opening price of 1 candle before now under Ma and closure above Ma then buy
    if(Open[1] < MA && Close[1]> MA) { order buy }

    Not allowed!

  5. #24
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    This time we will try to continue about making a simple EA that I have previously discussed in the previous post.

    I will try to make a EA with the following rule :
    For BUY
    Open candle 2 below MA 2 and close candle 2 above MA 2
    Open candle1 above MA 1 and close candle 1 above MA 1
    Price is still above MA1

    Vice Versa for SELL

    Another thing to be added is

    Trading hours
    SL and TP can be set to 0
    Trailing that can be set
    TF ANY (not specified)

    Well from the above rule there may be something new in this ea, that is :

    1. TP and SL in order to be filled with 0
    In the previous EA if TP and SL are filled with 0, it will be error this is because there has not been used facility for it. Well in order TP and SL can be filled with 0 then must be made variable to represent at price level of TP and SL.

    For convenience, the price on buy Takeprofit I make ==> double tpb, for sell takeprofit ==> double tps, price on buy stoploss ==> double slb and stoploss sell ==> double sls.

    First made declarations
    double slb,tpb,sls,tps,pt;

    and make its logic
    if(SL==0)slb=0;else slb=Ask-SL*pt;
    if(SL==0)sls=0;else sls=Bid+SL*pt;
    if(TP==0)tpb=0;else tpb=Ask-SL*pt;
    if(TP==0)tps=0;else tps=Bid+SL*pt;
    OrderSend(Symbol(),OP_BUY,NR(Lots),Ask,3,slb, tpb,Nama_EA,Magic,0,Blue);
    OrderSend(Symbol(),OP_SELL,NR(Lots),Bid,3,sls, tps,Nama_EA,Magic,0,Red);


    2. Trailing
    To create a trailing script there are many ways, but in the trailing that we will make on this I created with a function for commands with using void

    Take a look
    void dtrailing()
    {
    for(int i=0; i<OrdersTotal(); i++){
    OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
    if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic ) continue;
    if(OrderType()==OP_BUY) {
    if(Bid-OrderOpenPrice()>pt*TrailingStop) {
    if((OrderStopLoss()<Bid-pt*TrailingStop) || (OrderStopLoss()==0)) {
    OrderModify(OrderTicket(),OrderOpenPrice(),Bid-pt*TrailingStop,OrderTakeProfit(),0,Green);
    return(0);
    }
    }
    }
    if(OrderType()==OP_SELL) {
    if((OrderOpenPrice()-Ask)>(pt*TrailingStop)){
    if(OrderStopLoss()>(Ask+pt*TrailingStop) || (OrderStopLoss()==0)){
    OrderModify(OrderTicket(),OrderOpenPrice(),Ask+pt* TrailingStop,OrderTakeProfit(),0,Red);
    return(0);
    }
    }
    }
    }

    }


    void is used as a trailing function, so dtrailing() must be created under int start()

    3. Buy and sell logic
    In accordance with the above rule then made the following logic:

    double MA2 =iMA(Symbol(),0,Period,0,MODE_SMA,PRICE_CLOSE ,2);
    double MA1 =iMA(Symbol(),0,Period,0,MODE_SMA,PRICE_CLOSE ,1);
    int signal;
    if(Open[2]<MA2 && Close[2]>MA2 && Open[1]>MA1 && Close[1]>MA1 && Ask>MA1) signal=1;// buy rule
    if(Open[2]>MA2 && Close[2]<MA2 && Open[1]<MA1 && Close[1]<MA1 && Bid<MA1) signal=2;// sell rule


    Well logic above made signal =1 means buy order and if signal =2 means sell order

    Now see the results and add insights from the EA rule above

    Code:
    //+------------------------------------------------------------------+
    //|                                                 Buy and Sell.mq4 |
    //|                        Copyright 2018, MetaQuotes Software Corp. |
    //|                                             https://www.mql5.com |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2018, MetaQuotes Software Corp."
    #property link      "https://www.mql5.com"
    #property version   "1.00"
    #property strict
    
    extern string EA_Name = "MA ara";
    extern bool    Trade_buy               = true;
    extern bool    Trade_sell              = true;
    extern int Start_Hour = 6;
    exter int End_Hour = 20;
    extern int     TP                      = 100;
    extern int     SL                      = 100;
    extern double  Lots                    = 0.1;
    extern int     TrailingStop            = 20;
    extern int     Magic                   = 69;
    extern string  Seting_MA               = "ANY";
    extern int     Period                 = 33;
    double slb,tpb,sls,tps,pt;
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    int init()
      {
    //----
    if(Digits==3 || Digits==5) pt=10*Point;   else   pt=Point;
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
       
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {
    dtrailing()
    //----
     double MA2 =iMA(Symbol(),0,Period,0,MODE_SMA,PRICE_CLOSE ,2);
    double MA1 =iMA(Symbol(),0,Period,0,MODE_SMA,PRICE_CLOSE ,1);
    int signal;
    if(Open[2]<MA2 && Close[2]>MA2 && Open[1]>MA1 && Close[1]>MA1 && Ask>MA1) signal=1;// buy rule
    if(Open[2]>MA2 && Close[2]<MA2 && Open[1]<MA1 && Close[1]<MA1 && Bid<MA1) signal=2;// sell rule
    
    if(Trade_hour()==1){
       if(SL==0)slb=0;else slb=Ask-SL*pt;
       if(SL==0)sls=0;else sls=Bid+SL*pt;
       if(TP==0)tpb=0;else tpb=Ask+TP*pt;
       if(TP==0)tps=0;else tps=Bid-TP*pt;
    if(totalorders(0)==0 && Trade_buy  && signal==1) {OrderSend(Symbol(),OP_BUY,NR(Lots),Ask,3,slb, tpb,EA_Name,Magic,0,Blue);}
      if(totalorders(1)==0 && Trade_sell && signal==2) {OrderSend(Symbol(),OP_SELL,NR(Lots),Bid,3,sls, tps,EA_Name,Magic,0,Red);}
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
     
    int Trade_hour()
    {
    bool trade = false;
    if(Start_Hour > End_Hour){
    if (Hour() >= Start_Hour || Hour() < End_Hour) trade = true;
    } else
    if (Hour() >= Start_Hour && Hour() < End_Hour) trade = true;
    return (trade);
    }
    
    int totalorders( int tipe)
    {
    int total=0;
    for(int i=0; i<OrdersTotal(); i++)
      {
          OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
          if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic || OrderType()!=tipe) continue;
         total++;
      }
    
    return(total);
    } 
    double NR(double thelot)
    {
        double maxlots = MarketInfo(Symbol(), MODE_MAXLOT),
        minilot = MarketInfo(Symbol(), MODE_MINLOT), 
        lstep = MarketInfo(Symbol(), MODE_LOTSTEP);
        double lots = lstep * NormalizeDouble(thelot / lstep, 0);
        lots = MathMax(MathMin(maxlots, lots), minilot);
        return (lots);
    }
    
    void dtrailing()
    {
    for(int i=0; i<OrdersTotal(); i++){
          OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
            if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic ) continue;
            if(OrderType()==OP_BUY)  {
             if(Bid-OrderOpenPrice()>pt*TrailingStop)  {
               if((OrderStopLoss()<Bid-pt*TrailingStop) || (OrderStopLoss()==0)) {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Bid-pt*TrailingStop,OrderTakeProfit(),0,Green);
                  return(0);
                  }
                  }
               }
            if(OrderType()==OP_SELL)  {
             if((OrderOpenPrice()-Ask)>(pt*TrailingStop)){
               if(OrderStopLoss()>(Ask+pt*TrailingStop) || (OrderStopLoss()==0)){
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+pt*TrailingStop,OrderTakeProfit(),0,Red);
                  return(0);
                  }
                  }
               }
         }
       
    }
    //+------------------------------------------------------------------+

    Not allowed!

  6. #25
    Trader tfs2012's Avatar
    Join Date
    Apr 2017
    Posts
    2,037
    Thumbs Up
    Received: 198
    Given: 230
    [lang=ar]
    Quote Originally Posted by ara View Post
    int Trade_hour()
    {
    bool trade = false;
    if(Start_Hour > End_Hour){
    if (Hour() >= Start_Hour || Hour() < End_Hour) trade = true;
    } else
    if (Hour() >= Start_Hour && Hour() < End_Hour) trade = true;
    return (trade);
    }
    I think you do not need all this
    try this it will do the same thing..

    int Trade_hour()
    {
    bool trade = false;
    for( Start_Hour > End_Hour ;Hour() >= Start_Hour ;Hour() < End_Hour )
    trade = true;

    return (trade);
    }

    by the way, excellent thread keep up the good work.[/lang]

    Not allowed!
    Last edited by tfs2012; 06-06-2018 at 09:36 AM.

  7. #26
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    Quote Originally Posted by tfs2012 View Post
    I think you do not need all this
    try this it will do the same thing..

    int Trade_hour()
    {
    bool trade = false;
    for( Start_Hour > End_Hour ;Hour() >= Start_Hour ;Hour() < End_Hour )
    trade = true;

    return (trade);
    }

    by the way, excellent thread keep up the good work.
    Thank u very much for your input my friend.

    Not allowed!

  8. #27
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    In this section I will try to discuss about EA from crossing MA as follows:
    "EA from indicator MA4 Open and MA4 Close"

    2018-06-16_231103.png
    2018-06-16_231114.png
    2018-06-16_231228.png

    We make the costum and logic first as follows:

    double MA_1O =iMA(Symbol(),0,Period_1,0,MODE_SMA,PRICE_OPEN ,1);
    double MA_1C =iMA(Symbol(),0,Period_1,0,MODE_SMA,PRICE_CLOSE ,1);
    double MA_2O =iMA(Symbol(),0,Period_2,0,MODE_SMA,PRICE_OPEN ,2);
    double MA_2C =iMA(Symbol(),0,Period_2,0,MODE_SMA,PRICE_CLOSE ,2);


    int signal;
    if(MA_2O >MA_2C && MA_1O < MA_1C) signal=1;
    // buy rule
    if(MA_2O <MA_2C && MA_1O > MA_1C) signal=2;// sell rule

    The above logic is commonly used for crosing MA

    Well on the EA we will make this I will add for TP in money (hidden TP with reference amount of profit in money $)

    we create a function to calculate profit in $

    double money()
    {
    double dp = 0;
    int i;
    for (i = 0; i < OrdersTotal(); i++) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic) continue;
    dp += OrderProfit();
    }
    return(dp);
    }


    The next step is to create a close all function that is to close all orders when TP in money has been reached

    void closeall()
    {
    for (int i = OrdersTotal() - 1; i >= 0; i--) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
    if (OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic ) continue;
    if (OrderType() > 1) OrderDelete(OrderTicket());
    else {
    if (OrderType() == 0) OrderClose(OrderTicket(), OrderLots(), Bid, 3, CLR_NONE);
    else OrderClose(OrderTicket(), OrderLots(), Ask, 3, CLR_NONE);
    }
    }
    }


    So making ea on this time there is addition of TP in money so that in above function can be made command to execute TP in money

    if(tp_in_money<= money()) closeall();

    So when the profit is greater or equal to tp_in_money then all orders in closeall

    on Ea we make this time EA is only 1 direction (not hedge)

    Well from the above functions we combine with EA on previous part, so it becomes as follows:

    Code:
    //+------------------------------------------------------------------+
    //|                                                 Buy and Sell.mq4 |
    //|                        Copyright 2018, MetaQuotes Software Corp. |
    //|                                             https://www.mql5.com |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2018, MetaQuotes Software Corp."
    #property link      "https://www.mql5.com"
    #property version   "1.00"
    #property strict
    
    extern string EA_Name = "MA ara";
    extern bool    Trade_buy               = true;
    extern bool    Trade_sell              = true;
    extern int Start_Hour = 6;
    exter int End_Hour = 20;
    extern bool    Tp_in_Money             = true;
    extern double  TP_in_money             = 2;
    extern int     TP                      = 100;
    extern int     SL                      = 100;
    extern double  Lots                    = 0.1;
    extern int     TrailingStop            = 20;
    extern int     Magic                   = 69;
    extern string  Seting_MA               = "ANY";
    extern int     Pereode_1                 = 4;
    extern int     Pereode_2                 = 4;
    int res,ras,rus;
    double slb,tpb,sls,tps,pt;
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    int init()
      {
    //----
       if(Digits==3 || Digits==5) pt=10*Point;   else   pt=Point;
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
    
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {
    
    dtrailing();
    if(Tp_in_Money && TP_in_money<= money()) closeall();
    //----
    double MA_1O =iMA(Symbol(),0,Pereode_1,0,MODE_SMA,PRICE_OPEN ,1);
    double MA_1C =iMA(Symbol(),0,Pereode_1,0,MODE_SMA,PRICE_CLOSE ,1);
    double MA_2O =iMA(Symbol(),0,Pereode_2,0,MODE_SMA,PRICE_OPEN ,2);
    double MA_2C =iMA(Symbol(),0,Pereode_2,0,MODE_SMA,PRICE_CLOSE ,2);
    
    int signal;
    if(MA_2O >MA_2C && MA_1O < MA_1C) signal=1;// aturan buy
    if(MA_2O <MA_2C && MA_1O > MA_1C) signal=2;//aturan sell
    if(Trade_hour()==1){
       if(SL==0)slb=0;else slb=Ask-SL*pt;
       if(SL==0)sls=0;else sls=Bid+SL*pt;
       if(TP==0)tpb=0;else tpb=Ask+TP*pt;
       if(TP==0)tps=0;else tps=Bid-TP*pt;
    if(totalorders(0)==0 && Trade_buy  && signal==1) {OrderSend(Symbol(),OP_BUY,NR(Lots),Ask,3,slb, tpb,EA_Name,Magic,0,Blue);}
      if(totalorders(1)==0 && Trade_sell && signal==2) {OrderSend(Symbol(),OP_SELL,NR(Lots),Bid,3,sls, tps,EA_Name,Magic,0,Red);}
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    
    int Trade_hour()
    {
    bool trade = false;
    if(Start_Hour > End_Hour){
    if (Hour() >= Start_Hour || Hour() < End_Hour) trade = true;
    } else
    if (Hour() >= Start_Hour && Hour() < End_Hour) trade = true;
    return (trade);
    }
    
    int totalorders( int tipe)
    {
    int total=0;
    for(int i=0; i<OrdersTotal(); i++)
      {
          OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
          if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic || OrderType()!=tipe) continue;
         total++;
      }
    double NR(double thelot)
    {
        double maxlots = MarketInfo(Symbol(), MODE_MAXLOT),
        minilot = MarketInfo(Symbol(), MODE_MINLOT),
        lstep = MarketInfo(Symbol(), MODE_LOTSTEP);
        double lots = lstep * NormalizeDouble(thelot / lstep, 0);
        lots = MathMax(MathMin(maxlots, lots), minilot);
        return (lots);
    }
    
    void dtrailing()
    {
    for(int i=0; i<OrdersTotal(); i++){
          if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))continue;
            if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic ) continue;
            if(OrderType()==OP_BUY)  {
             if(Bid-OrderOpenPrice()>pt*TrailingStop)  {
               if((OrderStopLoss()<Bid-pt*TrailingStop) || (OrderStopLoss()==0)) {
                  ras=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-pt*TrailingStop,OrderTakeProfit(),0,Green);
                  }
                  }
               }
            if(OrderType()==OP_SELL)  {
             if((OrderOpenPrice()-Ask)>(pt*TrailingStop)){
               if(OrderStopLoss()>(Ask+pt*TrailingStop) || (OrderStopLoss()==0)){
                  ras=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+pt*TrailingStop,OrderTakeProfit(),0,Red);
                  }
                  }
               }
         }
      
    }
    void closeall()
    {
     for (int i = OrdersTotal() - 1; i >= 0; i--) {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))continue;
      if (OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic ) continue;
      if (OrderType() > 1) rus=OrderDelete(OrderTicket());
       else {
        if (OrderType() == 0) rus=OrderClose(OrderTicket(), OrderLots(), Bid, 3, CLR_NONE);
        else               rus=OrderClose(OrderTicket(), OrderLots(), Ask, 3, CLR_NONE);
      }
     }
    }
    double money()
    {
     double dp = 0;
     int i;
     for (i = 0; i < OrdersTotal(); i++) {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))continue;
      if (OrderSymbol() != Symbol()  || OrderMagicNumber()!=Magic) continue;
      dp += OrderProfit();
     }
     return(dp);
    }

    Not allowed!

  9. #28
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    Well this time I will modify the EA on my previous post, I will make those EA become averaging EA.

    Rules that I add are: order in turn of candle when happened order continued (average).
    Advanced orders are not based on range or pips but made a per signal order, so that when there is a buy order and cross-buy signal buy it will make an advanced order in turn of candle.

    The important part to be added is the limitation op == Max_order
    Another thing is I add the option trailing = false / true;

    While the important part is the addition of a candle change filter, I add
    if(wt!=Time[0]){ blabla..........................

    if(tiket>0) wt=Time[0];
    }


    this is the filter for order on the turn of the candle

    Well this is the result:

    Code:
    //+------------------------------------------------------------------+
    //|                                                 Buy and Sell.mq4 |
    //|                        Copyright 2018, MetaQuotes Software Corp. |
    //|                                             https://www.mql5.com |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2018, MetaQuotes Software Corp."
    #property link      "https://www.mql5.com"
    #property version   "1.00"
    #property strict
    
    extern string EA_Name = "MA ara";
    extern bool    Trade_buy               = true;
    extern bool    Trade_sell              = true;
    extern int Start_Hour = 6;
    exter int End_Hour = 20;
    extern bool    Tp_in_Money             = true;
    extern double  TP_in_money             = 2;
    extern int     TP                      = 100;
    extern int     SL                      = 100;
    extern int     Max_order               = 10;
    extern double  Lots                    = 0.1;
    extern bool    TrailingStop_           = true;
    extern int     TrailingStop            = 20;
    extern int     Magic                   = 69;
    extern string  Seting_MA               = "ANY";
    extern int     Pereode_1                 = 4;
    extern int     Pereode_2                 = 4;
    double slb,tpb,sls,tps,pt;
    int wt,ticket;
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    int init()
      {
    //----
       if(Digits==3 || Digits==5) pt=10*Point;   else   pt=Point;
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
    
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {
    
    dtrailing();
    if(Tp_in_Money && TP_in_money<= money()) closeall();
    //----
    double MA_1O =iMA(Symbol(),0,Period_1,0,MODE_SMA,PRICE_OPEN ,1);
    double MA_1C =iMA(Symbol(),0,Period_1,0,MODE_SMA,PRICE_CLOSE ,1);
    double MA_2O =iMA(Symbol(),0,Period_2,0,MODE_SMA,PRICE_OPEN ,2);
    double MA_2C =iMA(Symbol(),0,Period_2,0,MODE_SMA,PRICE_CLOSE ,2);
    
    int signal;
    if(MA_2O >MA_2C && MA_1O < MA_1C) signal=1;// buy rule
    if(MA_2O <MA_2C && MA_1O > MA_1C) signal=2;// sell rule
    if(Trade_hour()==1){
       if(SL==0)slb=0;else slb=Ask-SL*pt;
       if(SL==0)sls=0;else sls=Bid+SL*pt;
       if(TP==0)tpb=0;else tpb=Ask+TP*pt;
       if(TP==0)tps=0;else tps=Bid-TP*pt;
     if(wt!=Time[0]){
    if(totalorders(0)<max_order && totalorders(1)==0 && Trade_buy  && signal==1 ) {ticket = OrderSend(Symbol(),OP_BUY,NR(Lots),Ask,3,slb, tpb,Nama_EA,Magic,0,Blue);}
      if(totalorders(0)==0 && totalorders(1)<Max_order && Trade_sell && signal==2 ) {ticket = OrderSend(Symbol(),OP_SELL,NR(Lots),Bid,3,sls, tps,Nama_EA,Magic,0,Red);}
      if(ticket>0) wt=Time[0];
      }
     }
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    
    int Trade_hour()
    {
    bool trade = false;
    if(Start_Hour > End_Hour){
    if (Hour() >= Start_Hour || Hour() < End_Hour) trade = true;
    } else
    if (Hour() >= Start_Hour && Hour() < End_Hour) trade = true;
    return (trade);
    }
    
    int totalorders( int tipe)
    {
    int total=0;
    for(int i=0; i<OrdersTotal(); i++)
      {
          OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
          if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic || OrderType()!=tipe) continue;
         total++;
      }
    double NR(double thelot)
    {
        double maxlots = MarketInfo(Symbol(), MODE_MAXLOT),
        minilot = MarketInfo(Symbol(), MODE_MINLOT),
        lstep = MarketInfo(Symbol(), MODE_LOTSTEP);
        double lots = lstep * NormalizeDouble(thelot / lstep, 0);
        lots = MathMax(MathMin(maxlots, lots), minilot);
        return (lots);
    }
    
    void dtrailing()
    {
    for(int i=0; i<OrdersTotal(); i++){
          if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))continue;
            if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic ) continue;
            if(OrderType()==OP_BUY)  {
             if(Bid-OrderOpenPrice()>pt*TrailingStop)  {
               if((OrderStopLoss()<Bid-pt*TrailingStop) || (OrderStopLoss()==0)) {
                  ras=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-pt*TrailingStop,OrderTakeProfit(),0,Green);
                  }
                  }
               }
            if(OrderType()==OP_SELL)  {
             if((OrderOpenPrice()-Ask)>(pt*TrailingStop)){
               if(OrderStopLoss()>(Ask+pt*TrailingStop) || (OrderStopLoss()==0)){
                  ras=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+pt*TrailingStop,OrderTakeProfit(),0,Red);
                  }
                  }
               }
         }
      
    }
    void closeall()
    {
     for (int i = OrdersTotal() - 1; i >= 0; i--) {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))continue;
      if (OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic ) continue;
      if (OrderType() > 1) rus=OrderDelete(OrderTicket());
       else {
        if (OrderType() == 0) rus=OrderClose(OrderTicket(), OrderLots(), Bid, 3, CLR_NONE);
        else               rus=OrderClose(OrderTicket(), OrderLots(), Ask, 3, CLR_NONE);
      }
     }
    }
    double money()
    {
     double dp = 0;
     int i;
     for (i = 0; i < OrdersTotal(); i++) {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))continue;
      if (OrderSymbol() != Symbol()  || OrderMagicNumber()!=Magic) continue;
      dp += OrderProfit();
     }
     return(dp);
    }

    Not allowed!

  10. #29
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    In this section we will modify the EA on the previous part with a slight addition of hedge average
    As in the previous sections have been discussed also op hedge (buy and sell).

    In order to occur order not one way but order based on signal that happened, hence part which is changed by trigger part by eliminating filter of count of opposite order, as follows:

    if( totalorders(0)<Max_order && Trade_buy && signal==1 && wt!=Time[0] ){ticket = OrderSend(Symbol(),OP_BUY,NR(Lots),Ask,3,slb, tpb,Nama_EA,Magic,0,Blue);
    if(ticket>0) wt=Time[0];
    }
    if( totalorders(1)<Max_order && Trade_sell && signal==2 && wk!=Time[0]) {ticket = OrderSend(Symbol(),OP_SELL,NR(Lots),Bid,3,sls, tps,Nama_EA,Magic,0,Red);
    if(ticket>0) wk=Time[0];
    }


    So when this is inserted into the EA:

    Code:
    //+------------------------------------------------------------------+
    //|                                                 Buy and Sell.mq4 |
    //|                        Copyright 2018, MetaQuotes Software Corp. |
    //|                                             https://www.mql5.com |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2018, MetaQuotes Software Corp."
    #property link      "https://www.mql5.com"
    #property version   "1.00"
    #property strict
    
    extern string EA_Name = "MA ara";
    extern bool    Trade_buy               = true;
    extern bool    Trade_sell              = true;
    extern int Start_Hour = 6;
    exter int End_Hour = 20;
    extern bool    Tp_in_Money             = true;
    extern double  TP_in_money             = 2;
    extern int     TP                      = 100;
    extern int     SL                      = 100;
    extern int     Max_order               = 10;
    extern double  Lots                    = 0.1;
    extern bool    TrailingStop_           = true;
    extern int     TrailingStop            = 20;
    extern int     Magic                   = 69;
    extern string  Seting_MA               = "ANY";
    extern int     Pereode_1                 = 4;
    extern int     Pereode_2                 = 4;
    double slb,tpb,sls,tps,pt;
    int wt,ticket;
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    int init()
      {
    //----
       if(Digits==3 || Digits==5) pt=10*Point;   else   pt=Point;
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
    
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {
    
    dtrailing();
    if(Tp_in_Money && TP_in_money<= money()) closeall();
    //----
    double MA_1O =iMA(Symbol(),0,Period_1,0,MODE_SMA,PRICE_OPEN ,1);
    double MA_1C =iMA(Symbol(),0,Period_1,0,MODE_SMA,PRICE_CLOSE ,1);
    double MA_2O =iMA(Symbol(),0,Period_2,0,MODE_SMA,PRICE_OPEN ,2);
    double MA_2C =iMA(Symbol(),0,Period_2,0,MODE_SMA,PRICE_CLOSE ,2);
    
    int signal;
    if(MA_2O >MA_2C && MA_1O < MA_1C) signal=1;// buy rule
    if(MA_2O <MA_2C && MA_1O > MA_1C) signal=2;// sell rule
    if(Trade_hour()==1){
       if(SL==0)slb=0;else slb=Ask-SL*pt;
       if(SL==0)sls=0;else sls=Bid+SL*pt;
       if(TP==0)tpb=0;else tpb=Ask+TP*pt;
       if(TP==0)tps=0;else tps=Bid-TP*pt;
     if(wt!=Time[0]){
    if( totalorders(0)<Max_order  && Trade_buy  && signal==1  && wt!=Time[0] ){ticket = OrderSend(Symbol(),OP_BUY,NR(Lots),Ask,3,slb, tpb,Nama_EA,Magic,0,Blue);
      if(ticket>0) wt=Time[0];
      }
      if( totalorders(1)<Max_order && Trade_sell && signal==2  && wk!=Time[0]) {ticket = OrderSend(Symbol(),OP_SELL,NR(Lots),Bid,3,sls, tps,Nama_EA,Magic,0,Red);
      if(ticket>0) wk=Time[0];
      }
     }
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    
    int Trade_hour()
    {
    bool trade = false;
    if(Start_Hour > End_Hour){
    if (Hour() >= Start_Hour || Hour() < End_Hour) trade = true;
    } else
    if (Hour() >= Start_Hour && Hour() < End_Hour) trade = true;
    return (trade);
    }
    
    int totalorders( int tipe)
    {
    int total=0;
    for(int i=0; i<OrdersTotal(); i++)
      {
          OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
          if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic || OrderType()!=tipe) continue;
         total++;
      }
    double NR(double thelot)
    {
        double maxlots = MarketInfo(Symbol(), MODE_MAXLOT),
        minilot = MarketInfo(Symbol(), MODE_MINLOT),
        lstep = MarketInfo(Symbol(), MODE_LOTSTEP);
        double lots = lstep * NormalizeDouble(thelot / lstep, 0);
        lots = MathMax(MathMin(maxlots, lots), minilot);
        return (lots);
    }
    
    void dtrailing()
    {
    for(int i=0; i<OrdersTotal(); i++){
          if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))continue;
            if(OrderSymbol()!=Symbol() || OrderMagicNumber()!=Magic ) continue;
            if(OrderType()==OP_BUY)  {
             if(Bid-OrderOpenPrice()>pt*TrailingStop)  {
               if((OrderStopLoss()<Bid-pt*TrailingStop) || (OrderStopLoss()==0)) {
                  ras=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-pt*TrailingStop,OrderTakeProfit(),0,Green);
                  }
                  }
               }
            if(OrderType()==OP_SELL)  {
             if((OrderOpenPrice()-Ask)>(pt*TrailingStop)){
               if(OrderStopLoss()>(Ask+pt*TrailingStop) || (OrderStopLoss()==0)){
                  ras=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+pt*TrailingStop,OrderTakeProfit(),0,Red);
                  }
                  }
               }
         }
      
    }
    void closeall()
    {
     for (int i = OrdersTotal() - 1; i >= 0; i--) {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))continue;
      if (OrderSymbol() != Symbol() || OrderMagicNumber()!=Magic ) continue;
      if (OrderType() > 1) rus=OrderDelete(OrderTicket());
       else {
        if (OrderType() == 0) rus=OrderClose(OrderTicket(), OrderLots(), Bid, 3, CLR_NONE);
        else               rus=OrderClose(OrderTicket(), OrderLots(), Ask, 3, CLR_NONE);
      }
     }
    }
    double money()
    {
     double dp = 0;
     int i;
     for (i = 0; i < OrdersTotal(); i++) {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))continue;
      if (OrderSymbol() != Symbol()  || OrderMagicNumber()!=Magic) continue;
      dp += OrderProfit();
     }
     return(dp);
    }

    Not allowed!

  11. #30
    Trader ara's Avatar
    Join Date
    Dec 2013
    Posts
    1,834
    Thumbs Up
    Received: 106
    Given: 184
    This time I will create an EA with an indicator outside Mt4. I will try to use Donchian Bands. This indicator is well known
    Well, before we try to make this custom indiator, the thing to know is checking the indicator value first :

    attach the indicator to the chart in mt4
    press Ctrl D


    Well now pay attention to the value that is in the window!
    Given the many indicators created by the programmers, of course to read the indicators and determine the value it is necessary to practice and often try and try!

    Attachment 23544

    In the picture above is how to specify an indicator that does not exist in mt4, preceded by iCustom.

    double donci = iCustom(Symbol(), Timeframe, "Indicator name", bufer, mode, shift);

    I name it donci (example only),
    Timeframe can be adjusted, see the discussion in the initial part
    Indicator name is adjusted with " "
    Bufer depends on the indicator, each indicator has a buff varying in a maximum of 8
    example if there are 3 buffers
    double indi_x = iCustom(Symbol(), Timeframe, "Indicator name", bufer1, bufer2, bufer3, mode, shift);
    Mode is the order of values out of the indicator (can be checked on the window Ctrl D), it starts from 0;
    Shift is like in the candel that has been discussed before, the example is filled 0 means the candel is running, filled 1 means the previous candel 2
    Shift is like on the candle that has been discussed before, the example is filled 0 means the candel is running, filled 1 means the previous candel 2

    Okay we continue to make custom with Donchian Bands indicator

    Donchian Bands.ex4

    Attach to Mt4 and then press Ctrl D

    2018-06-26_083353.png

    Pay attention to the data windows
    There are 3 pieces of value, the top is mode 0, while the middle is mode 1, and the bottom is mode 2.

    In the indicator view there are 3 pieces of the top of the red, middle green and red bottom.
    To determine the value of the 3 lines, point the pointer to that line!
    At the top of the line then if the check data windows at the time redirected to the red line then the value will be the same as mode 0,
    In the middle green line the value matches mode 3
    and on the red bottom line its value matches mode 2

    Well, the above value to determine its custom

    Now we see the value of bufer, press Ctrl I and double click on Donchian Bands indicator, it will appear as follows:

    2018-06-26_084230.png

    Then there is one bufer value, namely IPeriod

    Now from the data above we try to make its custom
    Because there are 3 pieces of his mode, so we make 3 pieces of the name, namely da, db and dt (this name just any)

    double da = iCustom(Symbol(), 0,"Donchian Bands",IPeriod, 0,0 ) ;// top line mode 0
    double db = iCustom(Symbol(), 0,"Donchian Bands",IPeriod, 1,0 ) ;// bottom line mode 1
    double dt = iCustom(Symbol(), 0,"Donchian Bands",IPeriod, 2,0 ) ;// middle line mode 2

    on shift, coincidence 0 means the candle is running

    To check whether the custom that we make is managed to read the value then we see by utilizing comments

    I try to make the EA

    Code:
    //+------------------------------------------------------------------+
    //|                                                           in.mq4 |
    //|                        Copyright 2012, MetaQuotes Software Corp. |
    //|                                        http://www.metaquotes.net |
    //+------------------------------------------------------------------+
    #property copyright "Copyright 2012, MetaQuotes Software Corp."
    #property link      "http://www.metaquotes.net"
    
    extern int IPeriod=20;
    
    //+------------------------------------------------------------------+
    //| expert initialization function                                   |
    //+------------------------------------------------------------------+
    
    int init()
      {
    //----
       
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int deinit()
      {
    //----
       
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    //| expert start function                                            |
    //+------------------------------------------------------------------+
    int start()
      {
    //----
    double da = iCustom(Symbol(), 0,"Donchian Bands",IPeriod, 0,0 ) ;// top line mode 0
    double db = iCustom(Symbol(), 0,"Donchian Bands",IPeriod, 1,0 ) ;// bottom line mode 1
    double dt = iCustom(Symbol(), 0,"Donchian Bands",IPeriod, 2,0 ) ;// middle line mode 2
    
    Comment("top line ",da,"middle line ",dt, "bottom line ",db);
    //----
       return(0);
      }
    //+------------------------------------------------------------------+
    From this reader EA, it will look as follows:

    2018-06-26_085319.png

    Okay now we can make the EA by referring to EA in the previous post, I think it's pretty easy!

    Not allowed!

Page 3 of 5 FirstFirst 12345 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •