Expert Advisors - time scale.

 

I've just opened an account with Smart Live Spreads and am using MetaTrader which they provide. I'd like to gain an understanding of how the Expert Advisors work. Any suggestions of a guide to look at online? I'm familiar with VB.net, but not C unfortunately.

I've started out by looking at the MACD Sample. But I'm puzzled by the fact that this seems to not apply by reference to any particular time scale. Surely the value of MACD depends on the periods over which you look at the price? If I add the EA to a graph on a particular time scale, say one minute, it seems to apply to whichever other time scale I view the price over - it's not just dependent on the timescale of the graph to which I add it. How can this make sense?

Thanks.

 

MT4 tends to do things BY BAR and not BY TIME directly, even though they are related and you can convert from one to the other.

And I don't actually understand your last sentence.

 
brewmanz:

MT4 tends to do things BY BAR and not BY TIME directly, even though they are related and you can convert from one to the other.

And I don't actually understand your last sentence.


What I was saying was that if I apply MACD Sample to a chart and then change the time period for that chart then the MACD Sample still seems to apply (because it still appears in the top right of the chart). It would be very complicated if the advisor were to tell you say to buy on the basis of the one minute bars, and while that was still open tell you to sell on the basis of the one day bars. I'm sure that such a situation would be possible. But what I now understand from the Alerts is that the advisor just operates on the basis of whichever timescale you have selected, and won't give you any signals for other timescales. So that's fine.

The next thing I'm puzzled over is the testing window. I'm running MACD Sample on the ICE BRENT Rolling Future for this month. When I test it, and go to the Results tab all I see is one trade that is closed out shortly thereafter when a stop is hit. When I run it in the Visual Mode it runs until it makes a trade and then I can't get it to carry on any further. Surely in each case what I should see is a number of trades over the course of the whole month. What's going on here?

 

It depends ... it depends ... it depends.

EAs can use whatever timeframe(TF) they want to generate signals, no matter what TF your chart is. The *usual* is chart TF, but don't think that all EAs will be so.

An EA *could* give you conflicting Buy & Sell signals, if it's coded to do say both Short & Long term trades (I understand having both Long & Short positions at the same time is now illegal in the USA).

As to MACD Sample, that's just a demo program to help you on your way - I don't think that anyone expects to make money with it (although someone might prove me wrong).

I would *expect* MACD Sample to give same result whether Visual Mode is used or not (if I'm wrong, someone please let me know). If you're getting different results, I would be suspicious that *something* has changed - TF, MA period, Model, ... something.

As for 'Surely .. a number of trades', ... it depends(!) on whether the trade criteria happened or not.

Sorry if that outburst isn't directly helpful

 

"As for 'Surely .. a number of trades', ... it depends(!) on whether the trade criteria happened or not." Allright, look at it another way. If I run it from 4th Jan to 24th Jan it does a trade early on 4th which it closes out straightaway. It does no further trades for the whole period. If I run it from 5th Jan to 24th Jan it does a trade early on 5th which it closes out straightaway. Why didn't the run from 4th Jan do this trade as well? I don't see anything in the code that should stop this.

 
I'm completely stumped. Every time I run an EA in the tester it opens and initial trade and then closes it at the stop immediately. It happens with MACD Sample, Moving Average and an EA I've written myself. I thought it might be stoploss in OrderSend is set at 0, but changing that seems to have no effect either. What on earth am I doing wrong?
 

you have most likely made an error in the logic.

Show some code or we can't help..

//z

 

you have most likely made an error in the logic.

Show some code or we can't help..

//z

 
I'm just using the MACD Sample that Metatrader comes with:

extern double TakeProfit = 50;
extern double Lots = 0.1;
extern double TrailingStop = 30;
extern double MACDOpenLevel=3;
extern double MACDCloseLevel=2;
extern double MATrendPeriod=26;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double MacdCurrent, MacdPrevious, SignalCurrent;
   double SignalPrevious, MaCurrent, MaPrevious;
   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
   MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
   MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
   MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);
   
   Print(MacdCurrent," ", Point);
    
   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(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious &&
         MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious)
        {
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"macd 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(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious && 
         MacdCurrent>(MACDOpenLevel*Point) && MaCurrent<MaPrevious)
        {
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,"macd 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(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious &&
               MacdCurrent>(MACDCloseLevel*Point))
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
                 return(0); // exit
                }
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                  if(OrderStopLoss()<Bid-Point*TrailingStop)
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
              }
           }
         else // go to short position
           {
            // should it be closed?
            if(MacdCurrent<0 && MacdCurrent>SignalCurrent &&
               MacdPrevious<SignalPrevious && MathAbs(MacdCurrent)>(MACDCloseLevel*Point))
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
               return(0); // exit
              }
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                    {
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                    }
                 }
              }
           }
        }
     }
   return(0);
  }
// the end.
 
  1. You must count down when closing orders. Check the return code for orderSelect. RefreshRates if there could be multiple changes (multiple server calls modify/close.)
    // total=OrdersTotal();
    //   if(total<1) 
    // ^^ Those assume you are running on only one chart, one EA, one pair, no manual trades.
        int total=0;
        for(pos = OrdersTotal()-1; pos >= 0 ; pos--) if (   // Always count down when closing
            OrderSelect(pos, SELECT_BY_POS)                 // Only my orders w/
        &&  OrderMagicNumber() == magic.number              // my magic number, and
        &&  OrderSymbol()      == Symbol() ){               // period and symbol
            RefreshRate(); // Required if there are multiple closes/modifies
            if (want to close) { orderClose(...); continue; }
            if (want to modify){ orderModify(...) }
            total++;
        }
        if(total==0){ // Now we know no open order for this TF and pair...
            RefreshRate(); // Required if there were any closes/modifies
            orderSend(...)
    

  2. Your buy criteria includes MathAbs(MacdCurrent)>(MACDOpenLevel*Point) or curr>3

    Your buy close include MacdCurrent>(MACDCloseLevel*Point)) or curr >2

    Therefor it closes buys on the next tick.

 
Arbu:
I'm just using the MACD Sample that MetaTrader comes with: [...]

There is lots of good information, on this forum and elsewhere, about how to get started with writing EAs. Unfortunately, this doesn't include the "MACD Sample". It's a terrible example, for at least three reasons:

1. The EA assumes that there will be no other trading on the account, whether manual or automated. Standard practice is to isolate one EA's orders from anything else (because lots of people run multiple EAs on the same account). The MACD Sample will not place an order if there are any open positions or pending orders from other EAs or from manual trading, and it will potentially close orders which "belong" to other EAs or to manual trading.

2. Its code for closing orders is buggy if there is more than one order to be closed (WHRoeder's point 1 above). Not a problem in itself given the EA's assumptions that there will only ever be one order open, but it's a latent bug and bad example code.

3. Its default parameters in effect assume 2DP/4DP pricing (or equivalent on non-forex symbols). For example, on a symbol which is quoted to 5DP, its default trailing stop of 30 * Point will equal 0.00030, i.e. what is typically referred to as 3 pips. That's inside the spread on many symbols/brokers. Similarly, the "MACDCloseLevel" is effectively 2 pips. When the MACD Sample was written in 2005 most (all?) brokers quoted symbols to 2DP/4DP, but they have now almost all moved to 3DP/5DP and the MACD Sample hasn't been updated.

Reason: