Forex



Go Back   Forex Trading > Programming > MetaTrader
Forex Forum Register More recent Blogs Calendar Advertising Others Help






Register
Welcome to Forex-TSD!, one of the largest Forex forums worldwide, where you will be able to find the most complete and reliable Forex information imaginable.

From the list below, select the forum that you want to visit and register to post, as many times you want. It’s absolutely free. Click here for registering on Forex-TSD.

Exclusive Forum
The Exclusive Forum is the only paid section. Once you subscribe, you will get free access to real cutting-edge Trading Systems (automated and not), Indicators, Signals, Articles, etc., that will help and guide you, in ways that you could only imagine, with your Forex trading.
  • Elite Section
    Get access to private discussions, specialized support, indicators and trading systems reported every week.
  • Advanced Elite Section
    For professional traders, trading system developers and any other member who may need to use and/or convert, the most cutting-edge exclusive indicators and trading systems for MT4 and MT5.
See more

Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old 09-20-2009, 03:39 AM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
Question Need Help Spotting Coding Error

I programmed this EA to (close short trade and) buy when price closes above 5 ema and (close long trade and) sell when price closes below 5 ema.

The logic: (From MetaStock)
Close short: CLOSE > Ref(Mov(CLOSE,5,E),-1)
Enter long: CLOSE > Ref(Mov(CLOSE,5,E),-1)

Close long: CLOSE < Ref(Mov(CLOSE,5,E),-1)
Enter short: CLOSE < Ref(Mov(CLOSE,5,E),-1)

And If trend remains the same, do nothing.

There must be some error in the code (Mql 4 for metatrader) because this is how the backtesting went (See Attached Picture).

Anyone familiar with this error ? Can anyone correct the code ? Thanks.


Code:
//+------------------------------------------------------------------+
//|                                                        MA-EA.mq4 |
//|                                         Copyright © 2009, Simran |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Simran"
#property link      "http://www.metaquotes.net"

//---- input parameters
extern int       MA_Method=2;
extern int       MA_Period=5;
extern int       Lots=1;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+

int BarsCount = 0;

//----
   
int start()
{
  if (Bars > BarsCount)
  {
    double MA1 = iMA(NULL,0,MA_Period,0,MA_Method,0,1);
    double MA2 = iMA(NULL,0,MA_Period,0,MA_Method,0,2);
    
    double C1 = iClose(NULL,0,1);
    double C2 = iClose(NULL,0,2);
    
  
  if ((C2<MA2 && C1<MA1)||(C2>MA2 && C1>MA1)) //No trend change
   {
   return; //Do nothing. Just wait for opposing signal.
   }
//---------------------------------------------------------------------  
 
  if (C2<MA2 && C1>MA1) //Trend change from down to up.
   {
      int total = OrdersTotal(); //Script to close all open orders.
      for(int i=total-1;i>=0;i--)
      {
        OrderSelect(i, SELECT_BY_POS);
        int type   = OrderType();
        bool result = false;
    
        switch(type)
        {
          //Close opened long positions
          case OP_BUY       : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
                              break;
          //Close opened short positions
          case OP_SELL      : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
        }
    
        if(result == false)
        {
          Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
          Sleep(3000);
        }  
     }      //End of Script to close all orders.
     
      int ticket; //Place Buy Order
         RefreshRates();
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-1000*Point,Ask+1000*Point,"Buy Order",9999,0,Green);
         if(ticket<0)
           {
            Print("Buy Order failed with error #",GetLastError());
           }
    return;
   }
 
 //---------------------------------------------------------
 
   if(C2>MA2 && C1<MA1) //Trend change from up to down.
    {
      total = OrdersTotal(); //Script to close all open orders.
      for(i=total-1;i>=0;i--)
      {
        OrderSelect(i, SELECT_BY_POS);
        type   = OrderType();
        result = false;
    
        switch(type)
        {
          //Close opened long positions
          case OP_BUY       : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
                              break;
          //Close opened short positions
          case OP_SELL      : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
        }
    
        if(result == false)
        {
          Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
          Sleep(3000);
        }  
     }      //End of Script to close all orders.
     
      //Place Sell Order
         RefreshRates();
         ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+1000*Point,Bid-1000*Point,"Sell Order",9999,0,Green);
         if(ticket<0)
           {
            Print("Sell Order failed with error #",GetLastError());
           }
    return;
    }
       
    BarsCount = Bars;
  }
   return(0);
}
   
  
//+------------------------------------------------------------------+
Capture.PNG
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #2 (permalink)  
Old 09-20-2009, 05:57 AM
Senior Member
 
Join Date: Oct 2008
Location: Vancouver, BC
Posts: 159
Roger09 is on a distinguished road
Why do you close all orders even trand didn't change the direction?
__________________
www.rogersignals.com - Share your strategy with all
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #3 (permalink)  
Old 09-20-2009, 07:48 AM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
Roger09,

I use the close all trades script only if trend change direction.

If a change in trend is detected, all previous open trades are closed and a trade is opened in the direction of the current trend.

What do you mean when you say that "I close all trades even without a change in trend" ? Could you show it from the code ?

Thanks.

Anyway, do you know what is wrong with the code execution (see the attached picture) ?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #4 (permalink)  
Old 09-20-2009, 07:53 AM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
Anyway, I use once per bar condition checking. But why is the EA executing many trades per single bar (see picture) ?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #5 (permalink)  
Old 09-20-2009, 08:16 AM
Senior Member
 
Join Date: Oct 2008
Location: Vancouver, BC
Posts: 159
Roger09 is on a distinguished road
Quote:
Originally Posted by username1 View Post
Anyway, do you know what is wrong with the code execution (see the attached picture) ?
it's just my variant
Code:
int ord;
if (C2<MA2 && C1>MA1) //Trend change from down to up.
   {
      int total = OrdersTotal(); //Script to close all open orders.
     
      for(int i=total-1;i>=0;i--)
      {
        OrderSelect(i, SELECT_BY_POS);
        if(OrderSymbol()==Simbol()&& OrderType()==1)
       {
 result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
            
        if(result == false)
        {
          Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
          Sleep(3000);
        }  
        } 
        if(OrderSymbol()==Simbol()&& OrderType()==0)ord++;
        
        }
      int ticket; //Place Buy Order
         RefreshRates();
         if(ord==0)ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-1000*Point,Ask+1000*Point,"Buy Order",9999,0,Green);
         if(ticket<0)
           {
            Print("Buy Order failed with error #",GetLastError());
           }
    return;
   }
 
 //---------------------------------------------------------
 
   }
__________________
www.rogersignals.com - Share your strategy with all
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #6 (permalink)  
Old 09-20-2009, 09:11 AM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
Quote:
if(OrderSymbol()==Simbol()&& OrderType()==0)ord++;
if(ord==0)...
Could you explain a little on what these new additions do ?

Thank you.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #7 (permalink)  
Old 09-20-2009, 09:27 AM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
Thumbs up

Quote:
Originally Posted by Roger09 View Post
it's just my variant
Code:
int ord;
if (C2<MA2 && C1>MA1) //Trend change from down to up.
   {
      int total = OrdersTotal(); //Script to close all open orders.
     
      for(int i=total-1;i>=0;i--)
      {
        OrderSelect(i, SELECT_BY_POS);
        if(OrderSymbol()==Simbol()&& OrderType()==1)
       {
 result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
            
        if(result == false)
        {
          Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
          Sleep(3000);
        }  
        } 
        if(OrderSymbol()==Simbol()&& OrderType()==0)ord++;
        
        }
      int ticket; //Place Buy Order
         RefreshRates();
         if(ord==0)ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-1000*Point,Ask+1000*Point,"Buy Order",9999,0,Green);
         if(ticket<0)
           {
            Print("Buy Order failed with error #",GetLastError());
           }
    return;
   }
 
 //---------------------------------------------------------
 
   }
Thanks. This version of closing specific trades is more efficient than using script to close all open trades.

Only thing I dont really understand what or how the new variable "ord" does or controls ?

Cheers.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #8 (permalink)  
Old 09-20-2009, 01:33 PM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
Updated Code

I updated my code. Simplified it and added your recommendations.

Code:
extern int       MA_Period=5;
extern int       MA_Method=1;
extern double    Lots=0.1;
int init() {return(0);}
int deinit(){return(0);}
int start()
  {
   int BarOpen = 0;           //Run Once Per Bar
   if (Open[0] != BarOpen)
   {
      BarOpen=Open[0];
      
      if (Close[2]<iMA(NULL,0,MA_Period,0,MA_Method,0,2)&&Close[1]>iMA(NULL,0,MA_Period,0,MA_Method,0,1)) // Uptrend
      {
        int total = OrdersTotal(); //Close Short Positions
        for(int i=total-1;i>=0;i--)
         {
            OrderSelect(i, SELECT_BY_POS);
            if(OrderSymbol()==Symbol()&& OrderType()==1)
            {bool result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );}
         }
        OrderSend (Symbol(),0,Lots,Ask,3,NULL,NULL,NULL,0,0,Green); // Open Long Position
      }
      
      if (Close[2]>iMA(NULL,0,MA_Period,0,MA_Method,0,2)&&Close[1]<iMA(NULL,0,MA_Period,0,MA_Method,0,1)) //Downtrend
      {
        total = OrdersTotal(); //Close Long Positions
        for(i=total-1;i>=0;i--)
         {
            OrderSelect(i, SELECT_BY_POS);
            if(OrderSymbol()==Symbol()&& OrderType()==0)
            {result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );}
         }
         OrderSend (Symbol(),0,Lots,Bid,3,NULL,NULL,NULL,0,0,Green); //Open Short
      }
      
   return(0);
   }
  }
It seems to be working much better, except for the multiple trades per bar issue. Can you help me with that ?

Capture.PNG

Thanks.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #9 (permalink)  
Old 09-20-2009, 06:13 PM
Senior Member
 
Join Date: Oct 2008
Location: Vancouver, BC
Posts: 159
Roger09 is on a distinguished road
Something wrong with your tester. My tester works properly.
Restart your terminal.
PS Variable ord doesn't allow to open more then one order in one direction.
Attached Images
File Type: bmp chart.bmp (977.0 KB, 36 views)
__________________
www.rogersignals.com - Share your strategy with all
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
  #10 (permalink)  
Old 09-21-2009, 10:39 AM
Junior Member
 
Join Date: Jun 2009
Posts: 19
username1 is on a distinguished road
In the updated new code in post #8, where should I put the "ord" controller ?

Because the new code is not quite the same as the code is the first post.

Could you post your test results here ? I cant test it yet.

Thanks.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!StumbleUpon this Post!Reddit this Post!Facebook this Post!BlinkList this Post!Google Bookmarks this Post!Yahoo! My Web this Post!
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Has anyone got this error? wolfe Metatrader 4 7 03-13-2009 10:40 PM
Error in EA BorisM Expert Advisors - Metatrader 4 3 10-24-2007 12:40 AM
Error = 0 1Dave7 Expert Advisors - Metatrader 4 2 09-12-2007 04:17 AM
Help with error message PLEASE! iscuba11 Metatrader 4 mql 4 - Development course 8 07-13-2007 02:34 AM
Error JoZo General Discussion 2 06-28-2006 08:45 PM


All times are GMT. The time now is 11:48 PM.



Search Engine Friendly URLs by vBSEO 3.2.0 ©2008, Crawlability, Inc.