newbie's question: what's wrong with my code?

 
Hi,
I'm learning MQL, it's so difficult due to lack of tutorial and examples, and I'm not good at english...
Could anybody help me with a few questions, please? Any response would be appreciatate.

1, what's the meaning of "tick", "symbol" here?

2, what's the difference between expert and indicator? is it: expert can control trading , indicator can draw lines on chart?

3, with history tester, how can I have the trading operations shown on the chart, like with Arrow Up, Arrow Down, Stop Sign ?

4, I coded a simple strategy: buy when ma5 up_cross ma125, close it when down_cross; sell when ma5 down_cross ma125, close it when up_cross.
But after history test, the result is continuous lose, which is definately not true. So there must be something wrong with my code. Please point it out for me:
//+------------------------------------------------------------------+
//|                                                        5-125.mq4 |
//|                                                             yjfh |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "yjfh"
#property link      "http://www.metaquotes.net"
extern double TakeProfit = 1000;
extern double Lots = 0.1;
extern double TrailingStop = 30;
extern double MA1TrendPeriod=5;
extern double MA2TrendPeriod=125;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double Ma1C, Ma1P;
   double Ma2C, Ma2P;
   int cnt, ticket, total;
// initial data checks
// it is important to make sure that the expert works with a normal
// chart and the user did not make any mistakes setting external 
// variables (Lots, StopLoss, TakeProfit, 
// TrailingStop) in our case, we check TakeProfit
// on a chart of less than 100 bars
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }
// to simplify the coding and speed up access
// data are put into internal variables
   Ma1C=iMA(NULL,0,MA1TrendPeriod,0,MODE_SMA,PRICE_CLOSE,0);
   Ma1P=iMA(NULL,0,MA1TrendPeriod,0,MODE_SMA,PRICE_CLOSE,1);
   Ma2C=iMA(NULL,0,MA2TrendPeriod,0,MODE_SMA,PRICE_CLOSE,0);
   Ma2P=iMA(NULL,0,MA2TrendPeriod,0,MODE_SMA,PRICE_CLOSE,1);

   total=OrdersTotal();
   if(total<1) 
     {
      // no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // check for long position (BUY) possibility
      if(Ma1C>Ma2C && Ma1P<=Ma2P)
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,
                          "ma sample",16384,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("BUY order opened : ",OrderOpenPrice());
           }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
      // check for short position (SELL) possibility
      if(Ma1C<Ma2C && Ma1P>=Ma2P)
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,
                          "ma sample",16384,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               Print("SELL order opened : ",OrderOpenPrice());
           }
         else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
      return(0);
     }
   // it is important to enter the market correctly, 
   // but it is more important to exit it correctly...   
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==Symbol())  // check for symbol
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {
            // should it be closed?
            if(Ma1C<Ma2C && Ma1P>=Ma2P)
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
                 return(0); // exit
                }
            // check for trailing stop
            
           }
         else // go to short position
           {
            // should it be closed?
            if(Ma1C>Ma2C && Ma1P<=Ma2P)
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
               return(0); // exit
              }
            // check for trailing stop
            
           }
        }
     }
   return(0);
  }
// the end.

 
I would double-check your logic by looking at the charts. Moving averages are good trend indicators but they constantly lag behind the action and I have not seen a winning strategy based on Moving Averages alone. When you go from one bar to the next, by the time you take a trade you already will have missed some of the trend. By the time the Moving Averages cross again, you usually will be so late closing your trades that you will have an end price that is not much different - and often worse - than your open price.
 
Yes, but I still believe I've written wrong code.
 
I believe this code works, you can change the ma to suit..

extern double TakeProfit = 0;
extern double Lots = 1;
extern double TrailingStop = 0;
extern double Stoploss = 100;
extern double Perc =10;
extern int ma1 = 5;
extern int ma2 = 20;

//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+

int start()
{
  double Levv,  equity, Lotss, trd,maa1,maa2 ;
  int cnt=0, total ;
         
   maa1= iMA(NULL,0,ma1,0,MODE_EMA,PRICE_CLOSE,0);
   maa2= iMA(NULL,0,ma2,0,MODE_EMA,PRICE_CLOSE,0);
      
 //======================================================================
           
  if(Bars<2)
  {
    Print("bars less than 100");
    return(0); }
  //======================================================================   
  total=OrdersTotal();
   trd =0 ;
   
   for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol()==Symbol()) trd++;
}
  
 //======================================================================
  {
    if(AccountFreeMargin()<(1*Lots))
    {
      Print("We have no money");
      return(0);}
      
   equity =AccountEquity();
   
  Lotss = MathAbs((equity*Perc/100/100)/10);
   
  Levv=NormalizeDouble(Lotss,1);
          
 //======================================================================
  
    // (BUY)
    
    if (trd != 1 && maa1 > maa2  )
    {
      OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-Stoploss*Point,0,0,0,0,Blue);
      
      return(0);
    }
    
    
    // (SELL)
    if ( trd != 1 && maa1 < maa2) 
    {
      OrderSend(Symbol(),OP_SELL,Lots,Bid,3, Ask+Stoploss*Point,0,0,0,0,Red);
     
      
      return(0);
    } 
   }
          
 //======================================================================     
      
  //CLOSE
  
    for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol()==Symbol()) trd++;
      
      if(OrderType()<=OP_SELL && 
         OrderSymbol()==Symbol())   
        {
         if(OrderType()==OP_BUY)   
           {
            
            if( maa1 < maa2  )
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); 
                 return(0); 
                }
                }
                }
               
   for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if (OrderSymbol()==Symbol()) trd++;
      
      if(OrderType()<=OP_SELL && 
         OrderSymbol()==Symbol())   
        {
         if(OrderType()==OP_SELL)   
           {
            
            if( maa1 > maa2  )
                {
                 OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); 
                 return(0); 
                }
                }
                }
 //================================================================================
  
}}}   



 
Thanks a lot ! I'm studying it.....
 
Your questions:

1) what exactly do you mean? (Symbol() normally refers to the currency pair which you are trading, eg. "EURUSD").

2) Yes, Indicators are used to paint indicators on charts, Experts are designed to run and trade.

3) After you ran a history test, click the "show chart" button. It should contain markers for opening and closing deals. With that chart open you can switch to the Results tab and double click a trade and it will then jump to that place in the chart.

4) I have not studied your code, but EMA crossers usually lose money in backtests (and in real trading also), except for very limited periods in the market. When you look at the sell/buy points in your chart for the EMA you will see why.


Btw, for crossers it's better to compare the current ema value with the period 2 bars away. There are crosses where the cross lies exactly on the bar so that a ema>emaprev1 will not catch it. A ema>emaprev2 usually does (and does not delay the signal).



Markus
Reason: