Pls Help a Beginner, Thanks

 

Hello!

A hello to all with same mind of trading. I'm a beginer of EA. I learnt C by myself, but all about reading a book of C.

Headache, I tried to read a simple EA of Moving Average in my MT4, but can not understand all of the lines. Pls help! I marked those I can not understand in RED. 

I'd like to learn a bit daily, and hope someday I can test my own strategy. 

Thank you a loooot!

  

//+------------------------------------------------------------------+

//|                                               Moving Average.mq4 |

//|                   Copyright 2005-2014, MetaQuotes Software Corp. |

//|                                              https://www.mql4.com |

//+------------------------------------------------------------------+

#property copyright   "2005-2014, MetaQuotes Software Corp."

#property link        "https://www.mql4.com"

#property description "Moving Average sample expert advisor"


#define MAGICMA  20131111

//--- Inputs

input double Lots          =0.1;

input double MaximumRisk   =0.02;

input double DecreaseFactor=3;      // please tell me what's this, all the things about it, I can not understand.

input int    MovingPeriod  =12;

input int    MovingShift   =6;

//+------------------------------------------------------------------+

//| Calculate open positions                                         |

//+------------------------------------------------------------------+

int CalculateCurrentOrders(string symbol)   //this function is used to return number of buy orders or sell orders ?  where it is used?

  {

   int buys=0,sells=0;

//---

   for(int i=0;i<OrdersTotal();i++)              

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;   // if order selet failed, stop this whole for loop ? then go to where ? Ontick ? 

      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)

        {

         if(OrderType()==OP_BUY)  buys++;

         if(OrderType()==OP_SELL) sells++;

        }

     }

//--- return orders volume

   if(buys>0) return(buys);

   else       return(-sells);             // where are they used ?

  }

//+------------------------------------------------------------------+

//| Calculate optimal lot size                                       |// Luckily I can understand all the following.

//+------------------------------------------------------------------+

double LotsOptimized()

  {

   double lot=Lots;

   int    orders=HistoryTotal();     // history orders total

   int    losses=0;                  // number of losses orders without a break   0.0 still can not understand.

//--- select lot size

   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);  // it's trying to give the lot when trading, why do the math like this? really bad at math, also bad at english haha

//--- calcuulate number of losses orders without a break

   if(DecreaseFactor>0)            //here comes the decrease factor, what does it means really, i'm not native english speaker.  The following codes in red gives me super headache.

     {

      for(int i=orders-1;i>=0;i--)

        {

         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)

           {

            Print("Error in history!");

            break;

           }

         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL)

            continue;

         //---

         if(OrderProfit()>0) break;

         if(OrderProfit()<0) losses++;

        }

      if(losses>1)

         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);     // what the math work for ?

     }

//--- return lot size

   if(lot<0.1) lot=0.1;

   return(lot);

  }

//+------------------------------------------------------------------+

//| Check for open order conditions                                  |

//+------------------------------------------------------------------+

void CheckForOpen()

  {

   double ma;

   int    res;

//--- go trading only for first tiks of new bar

   if(Volume[0]>1) return;

//--- get Moving Average 

   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);

//--- sell conditions

   if(Open[1]>ma && Close[1]<ma)

     {

      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);

      return;

     }

//--- buy conditions

   if(Open[1]<ma && Close[1]>ma)

     {

      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);

      return;

     }

//---

  }

//+------------------------------------------------------------------+

//| Check for close order conditions                                 |

//+------------------------------------------------------------------+

void CheckForClose()

  {

   double ma;

//--- go trading only for first tiks of new bar

   if(Volume[0]>1) return;

//--- get Moving Average 

   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);

//---

   for(int i=0;i<OrdersTotal();i++)

     {

      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;

      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;

      //--- check order type 

      if(OrderType()==OP_BUY)

        {

         if(Open[1]>ma && Close[1]<ma)

           {

            if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))

               Print("OrderClose error ",GetLastError());

           }

         break;

        }

      if(OrderType()==OP_SELL)

        {

         if(Open[1]<ma && Close[1]>ma)

           {

            if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))

               Print("OrderClose error ",GetLastError());

           }

         break;

        }

     }

//---

  }

//+------------------------------------------------------------------+

//| OnTick function                                                  |

//+------------------------------------------------------------------+

void OnTick()

  {

//--- check for history and trading

   if(Bars<100 || IsTradeAllowed()==false)

      return;

//--- calculate open orders by current symbol

   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();

   else                                    CheckForClose();

//---

  }

//+------------------------------------------------------------------+ 

 

 //Sorry I'm really new to codes. Thank you a lot.

 

Sorry I know where the "CalculateCurrentOrders" is used by searching the whole txt. This is too long for me, forgot after reading it through. thanks.

Still have problems left. 

 
  1. Don't paste code
    Play video
    Please edit your post.
    For large amounts of code, attach it.

  2. lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);  // it's trying to give the lot when trading, why do the math like this? really bad at math, also bad at english haha
    Bogus calculation
    • You place the stop where it needs to be - where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.
    • Account Balance * percent = RISK = |OrderOpenPrice - OrderStopLoss| * OrderLots * DeltaPerlot (Note OOP-OSL includes the SPREAD)
    • Do NOT use TickValue by itself - DeltaPerlot
    • You must normalize lots properly and check against min and max.
    • You must also check FreeMargin to avoid stop out

  3. res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
    return;
    Check your return codes What are Function return values ? How do I use them ? - MQL4 forum and Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
  4. input double DecreaseFactor=3;      // please tell me what's this, all the things about it, I can not understand.
    :
          for(int i=orders-1;i>=0;i--){
    :
             if(OrderProfit()>0) break;
             if(OrderProfit()<0) losses++;
            }
          if(losses>1)
             lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);     // what the math work for ?
    • The loop assumes that history is ordered. It isn't necessarily. See Could EA Really Live By Order_History Alone? - MQL4 forum
    • It counts the number of consecutive losses.
    • One consecutive loss reduce lot by 1/DecreaseFactor, i.e. 2/3 normal. Two consecutive losses 1/3 normal. More trading stops.

  5. if(lot<0.1) lot=0.1;
    Don't hard code number; use MODE_MINLOT
  6.  if(Volume[0]>1) return;
    Bars is unreliable (a refresh/reconnect can change number of bars on chart) volume is unreliable (miss ticks) Always use time. New candle - MQL4 forum
 

@WHRoeder

Thank you a loooot! 

 
//--- go trading only for first tiks of new bar

   if(Volume[0]>1) return;  

//--- get Moving Average 

   ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);

//--- sell conditions

   if(Open[1]>ma && Close[1]<ma)

     {

      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);

      return;

     }

//--- buy conditions

   if(Open[1]<ma && Close[1]>ma)

     {

      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);

      return;

     }

Thank you a looooot for your help!! 

Could you please teach me about those 3 returns above ? I'm confused by these returns. I read those C grammers again these days.

I read first 7 chapters of C Primer Plus. 

But still confused. Why need return here, and what is the function of these return?

Thank you again! 

Reason: