Download MetaTrader 5
To add comments, please log in or register
Do you know that MQL5 has classes?
GergelyB
44
GergelyB 2016.02.03 18:07 

Hello, I try to develope my first ExpertAdvisor, but just as I solve a problem another seems to pop up.

 Now It seems I have a problem with my CopyTime and I just dont understand where and why, in the noon it worked...

code:

input int      StopLoss=15;
input int      TakeProfit=15;
input int      EA_MagicBuy=12345;
input int      EA_MagicSell=54321;
input double   Lot=1;                           //Lots to trade
input string Symbol="EURUSD";
double STP, TKP;
int i = 0; //for array resizing
double p_last[];
double p_high[];
double p_low[];
bool Buy_opened=false;  
bool Sell_opened=false;
bool First_tick=true;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
  // So we can change SL or TP
   STP = StopLoss;
   TKP = TakeProfit;
   //Ezt itt másoltam, és nem értem miért.... Edőcs?
    if(_Digits==5 || _Digits==3)
     {
      STP = STP*10;
      TKP = TKP*10;
     }

//Setting arraysize----------------------------------------------------
//---------no need here, handeld OnTick
//---------------------------------------------------------------------  
//object for receiving symbol settings
   CSymbolInfo symbol_info;
//set the name for the appropriate symbol
   symbol_info.Name(Symbol);
//receive current rates and display
   symbol_info.RefreshRates();
   Print(symbol_info.Name()," (",symbol_info.Description(),")",
         "  Bid=",symbol_info.Bid(),"   Ask=",symbol_info.Ask());
//receive minimum freeze levels for trade operations
   Print("StopsLevel=",symbol_info.StopsLevel()," pips, FreezeLevel=",
         symbol_info.FreezeLevel()," pips");
//receive the number of decimal places and point size
   Print("Digits=",symbol_info.Digits(),
         ", Point=",DoubleToString(symbol_info.Point(),symbol_info.Digits()));
//spread info
   Print("SpreadFloat=",symbol_info.SpreadFloat(),", Spread(current)=",
         symbol_info.Spread()," pips");
//request order execution type for limitations
   Print("Limitations for trade operations: ",EnumToString(symbol_info.TradeMode()),
         " (",symbol_info.TradeModeDescription(),")");
//clarifying trades execution mode
   Print("Trades execution mode: ",EnumToString(symbol_info.TradeExecution()),
         " (",symbol_info.TradeExecutionDescription(),")");
//clarifying contracts price calculation method
   Print("Contract price calculation: ",EnumToString(symbol_info.TradeCalcMode()),
         " (",symbol_info.TradeCalcModeDescription(),")");
//sizes of contracts
   Print("Standard contract size: ",symbol_info.ContractSize(),
         " (",symbol_info.CurrencyBase(),")");
//minimum and maximum volumes in trade operations
   Print("Volume info: LotsMin=",symbol_info.LotsMin(),"  LotsMax=",symbol_info.LotsMax(),
         "  LotsStep=",symbol_info.LotsStep());
   Print("Initialization completed");

   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {

  ArrayResize(p_high,ArraySize(p_high)+1,100);
  ArrayResize(p_low,ArraySize(p_low)+1,100);
  ArrayResize(p_last,ArraySize(p_last)+1,100);
  ArraySetAsSeries(p_high,true);
  ArraySetAsSeries(p_low,true);
  ArraySetAsSeries(p_last,true);
  
  int copiedhigh = CopyHigh(Symbol(),Period(),0,1,p_high);
  int copiedlow = CopyLow(Symbol(),Period(),0,1,p_low);
  int copiedlast = CopyClose(Symbol(),Period(),0,1,p_last);


  //trades open?-----------------------------------------
   
    if(PositionSelect(Symbol)==true) // we have an opened position
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         Buy_opened=true;  //It is a Buy
        }
      else if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
        {
         Sell_opened=true; // It is a Sell
        }
     }
   
  //-----------------------------------------------------

  //watching for new bars--------------------------------
  static datetime Old_Time = TimeCurrent();
  datetime New_Time[1];
  bool IsNewBar=false;
   
  int CopiedTime=CopyTime(Symbol,_Period,0,1,New_Time);
  if(CopiedTime = -1)
   {Print("Copy time fail!");}
  
   if(CopiedTime>0) // ok, the data has been copied successfully
     {
      if(Old_Time!=New_Time[0]) // if old time isn't equal to new bar time. 1970? Nope 
        {
         IsNewBar=true;   // if it isn't a first call, the new bar has appeared
         int copiedhigh = CopyHigh(Symbol(),Period(),1,1,p_high);
         int copiedlow = CopyLow(Symbol(),Period(),1,1,p_low);
         int copiedlast = CopyClose(Symbol(),Period(),1,1,p_last);
         if(MQL5InfoInteger(MQL5_DEBUGGING)) 
         Print("We have new bar here ",New_Time[0]," old time was ",Old_Time," higest price: ",p_high[0]," lowest price: ",p_low[0]," Close price: ",p_last[0]);
         Old_Time=New_Time[0];            // saving bar time
        }
     }
   else
     {
      Alert("Error in copying historical times data, error =",GetLastError());
      ResetLastError();
      return;
     }
     
  ArrayResize(p_high,ArraySize(p_high)+1,100);
  ArrayResize(p_low,ArraySize(p_low)+1,100);
  ArrayResize(p_last,ArraySize(p_last)+1,100);
     
 //---- Ez nem lehetne feljebb? a is newbar kivételével? -------------      
   MqlTradeRequest mrequest;  
   MqlTradeResult mresult;    
   MqlRates mrate[];          // To be used to store the prices, volumes and spread of each bar
   //ZeroMemory(mrequest);      // wiping of mrequest structure, done in the position opening
   //ZeroMemory(mresult);
   
   ArraySetAsSeries(mrate,true);
   ArrayResize(mrate,ArraySize(mrate)+1,1000);
//---------------------------

   
   bool BuyCondition = (p_high[1] = p_last[1]);
   bool SellCondition = (p_low[1] = p_last[1]);
   
   if(1 == 2) //ORDER TIMEEEE!!!  BuyCondition && IsNewBar && !Buy_opened && !First_tick
   {     
         ZeroMemory(mrequest);
         ZeroMemory(mresult);
         mrequest.action = TRADE_ACTION_DEAL;                                  // immediate order execution
         mrequest.price = NormalizeDouble(p_high[1],_Digits);           // latest ask price
         mrequest.sl = NormalizeDouble(p_high[1] - STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(p_high[1] + TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = Symbol;                                            // currency pair
         mrequest.volume = Lot;                                                 // number of lots to trade
         mrequest.magic = EA_MagicBuy;                                             // Order Magic Number
         mrequest.type = ORDER_TYPE_BUY;                                        // Buy Order
         mrequest.type_filling = ORDER_FILLING_FOK;                             // Order execution type
         mrequest.deviation=100;                                                // Deviation from current price
         //--- send order 
         OrderSend(mrequest,mresult); //Check OrderSend Return!!!
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed according to a lovely post
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError()," with trade return code ",mresult.retcode);
            ResetLastError();           
            return;
           }
       
    }
 
   if(1 == 2) //ORDER TIMEEEE!!!  SellCondition && IsNewBar && !Sell_opened && !First_tick
   {
         ZeroMemory(mrequest);
         ZeroMemory(mresult);
         mrequest.action = TRADE_ACTION_DEAL;                                  // immediate order execution
         mrequest.price = NormalizeDouble(p_low[1],_Digits);           // latest ask price
         mrequest.sl = NormalizeDouble(p_low[1] - STP*_Point,_Digits); // Stop Loss
         mrequest.tp = NormalizeDouble(p_low[1] + TKP*_Point,_Digits); // Take Profit
         mrequest.symbol = Symbol;                                            // currency pair
         mrequest.volume = Lot;                                                 // number of lots to trade
         mrequest.magic = EA_MagicSell;                                             // Order Magic Number
         mrequest.type = ORDER_TYPE_SELL;                                        // Sell Order
         mrequest.type_filling = ORDER_FILLING_FOK;                             // Order execution type
         mrequest.deviation=100;                                                // Deviation from current price
         //--- send order
         OrderSend(mrequest,mresult); //Check OrderSend Return!!!
         // get the result code
         if(mresult.retcode==10009 || mresult.retcode==10008) //Request is completed or order placed
           {
            Alert("A Buy order has been successfully placed with Ticket#:",mresult.order,"!!");
           }
         else
           {
            Alert("The Buy order request could not be completed -error:",GetLastError()," with trade return code ",mresult.retcode);
            ResetLastError();           
            return;
           }
    }
  
 if(IsNewBar)
   {
   ZeroMemory(mrate); // do i need this here?
   ZeroMemory(p_last);
   ZeroMemory(p_high);
   ZeroMemory(p_low);
   }
  First_tick=false;
  }

 I get Copy time fail! and an error 

ERR_TRADE_POSITION_NOT_FOUND

4753

Position not found

I'm about to start over my entire codeing because I start to lose myself in what does what (I had problems with arrays before, maybe a clean slate would help, but I just cannot leave it yet..)

Even if the copytime somehow would succed it seems my code would try to buy!! but it shouldn't (1==2) right? In the comment after that you can read my original conditions. My goal was to identify new bars where the p_close is = with p_highest or p_lowest, assuming that if thats the case there is a down or up trend respectively and buy or sell accordingly. I have a feeling that I over cmplicate it a "little"....

 Do you guys have ny idea what do I do wrong? (Im testing in a demo server) 

any help is welcome... sorry for the spagethi code 

Alain Verleyen
Moderator
29633
Alain Verleyen 2016.02.03 18:11  
  if(CopiedTime == -1)
GergelyB
44
GergelyB 2016.02.03 18:57  

Thank you!

 but still it doesn't print this line on new bars:

Print("We have new bar here ",New_Time[0]," old time was ",Old_Time," higest price: ",p_high[0]," lowest price: ",p_low[0]," Close price: ",p_last[0]);

 I assumed that the copiedtime was to blame for it, and wrote a wrong error check...

 

Do you happened to know why isn't it print out the data? 

Alain Verleyen
Moderator
29633
Alain Verleyen 2016.02.03 19:06  
GergelyB:

Thank you!

 but still it doesn't print this line on new bars:

 I assumed that the copiedtime was to blame for it, and wrote a wrong error check...

 

Do you happened to know why isn't it print out the data? 

It's only printed in debug mode :

if(MQL5InfoInteger(MQL5_DEBUGGING)) 

Are you running it in debug mode ?

GergelyB
44
GergelyB 2016.02.03 19:13  

Guess I didn't...

I moved the Print line up, but then it spams the data on every thick, shouldn't it only Print it on new bar?

do i mess it up with this somehow? (TimeCurrent?)

 Edit: sorry I'm a bit tired, I have to do idiotic universitiy burocracy on the side all day + this.

Yes naturally with TimeCurrent it will take every tick as a newbar.... 

 static datetime Old_Time = TimeCurrent();
  datetime New_Time[1];
GergelyB
44
GergelyB 2016.02.03 19:33  

Can you just tell me if you think my  buy and sell conditions should be working? (in my test sometimes it tries to buy while P_high =/= with p_close)

I have no idea why is that, do I gave to many && to the if?

SellCondition && IsNewBar && !Sell_opened && !First_tick

 Same with buy, just with buycondition....

 ps.: first tick was implemented to avoid first tick buys

Alain Verleyen
Moderator
29633
Alain Verleyen 2016.02.03 19:36  
GergelyB:

Can you just tell me if you think my  buy and sell conditions should be working? (in my test sometimes it tries to buy while P_high =/= with p_close)

I have no idea why is that, do I gave to many && to the if?

 Same with buy, just with buycondition....

 ps.: first tick was implemented to avoid first tick buys

Same error...

   bool BuyCondition = (p_high[1] == p_last[1]);
   bool SellCondition = (p_low[1] == p_last[1]);
GergelyB
44
GergelyB 2016.02.03 19:41  
Alain Verleyen:

Same error...

Jesus... thanks, I have the same feeling when I started to learn programing myself, I should never stoped if I know that I forget everything this quickly...

Thank you 

/
To add comments, please log in or register