Download MetaTrader 5
To add comments, please log in or register
Do you need private account monitoring? The Signals will provide you one!
S M Jaber Rahman
246
S M Jaber Rahman 2014.03.01 14:05 

I have compiled the code & got 6 warning but no error. I even don't know how to fix those error. Please see the attachment. The code too long to post. Thanks!

Files:
whroeder1
13589
whroeder1 2014.03.01 15:14  
jaber70: I even don't know how to fix those error.
Neither do we. Us humans can't read an ex4 file. Edit you post. Attach the source code and the compiler warnings.
S M Jaber Rahman
246
S M Jaber Rahman 2014.03.01 16:15  



int init()
  {
      if (Digits == 3 || Digits == 5)   {
         Stop        *=    DECIMAL_CONVERSION;
         TakeProfit  *=    DECIMAL_CONVERSION;
         TrailStart  *=    DECIMAL_CONVERSION;
         TrailAmount *=    DECIMAL_CONVERSION;
         
         Slippage    *=    DECIMAL_CONVERSION;
         decimalConv =     DECIMAL_CONVERSION;
      }
      
      trailStart           =     TrailStart  *  Point;
      trailAmount          =     TrailAmount *  Point;
      
      envelopePercentage   =     EnvelopePercentage * PERCENTAGE_CONVERSION;

      // get miniumum stop/take profit distance
      minSLTPdstnc = MarketInfo(Symbol(), MODE_STOPLEVEL);
      
      Print("Broker: " + AccountCompany());

      ObjectCreate(objName,OBJ_LABEL,0,0,0);
      ObjectSet(objName, OBJPROP_XDISTANCE, 10);
      ObjectSet(objName, OBJPROP_YDISTANCE, 10);
      ObjectSet(objName, OBJPROP_CORNER, 2);     
      ObjectSetText(objName,"OneStepRemoved.com",16,"Arial",Red);
      

   return(0);
  }

int deinit()  
{   
   ObjectDelete(objName);
   
   return(0);  

}

int start()
{
   
   double sma = iMA(Symbol(),0,MAPeriod,0,MAType,MAAppliedPrice,LAST_BAR);
   
   double envelopeDistance = sma * envelopePercentage;
   
   double upper = sma + envelopeDistance;
   double lower = sma - envelopeDistance;
   
   // do exits
   
   if( Close[LAST_BAR] > lower )
      ExitAll(LONG);
   
   if( Close[LAST_BAR] < upper )
      ExitAll(SHORT);
   
   TrailStop(MagicNumber, trailStart, trailAmount);
   
   // do entries
   
   bool bullish = Close[LAST_BAR] < lower && Close[LAST_BAR+1] >= lower;
   bool bearish = Close[LAST_BAR] > upper && Close[LAST_BAR+1] <= upper;
   
   if (NoOpenPositionsExist() && lastTradeTime != Time[THIS_BAR] && CheckTime(StartTime,EndTime) )
   {
      if (bullish)
      {
         if (DoTrade(LONG, Lots, Stop, TakeProfit, ORDER_COMMENT))
            lastTradeTime = Time[THIS_BAR];
         else         
            Print("start() - DoTrade(LONG) had problem");
      }
      else if (bearish)
      {
         if (DoTrade(SHORT, Lots, Stop, TakeProfit, ORDER_COMMENT))
            lastTradeTime = Time[THIS_BAR];
         else 
            Print("start() - DoTrade(SHORT) had problem");
      }
   }

   return(0);
}

bool DoTrade(int dir, double volume, int stop, int take, string comment)  {

   double sl, tp;

   bool retVal = false;

   switch(dir)  {
      case LONG:
         if (stop != 0) { sl = (stop*Point); }
         else { sl = 0; }
         if (take != 0) { tp = (take*Point); }
         else { tp = 0; }

         retVal = OpenTrade(LONG, volume, sl, tp, comment);
         break;

      case SHORT:
         if (stop != 0) { sl = (stop*Point); }
         else { sl = 0; }
         if (take != 0) { tp = (take*Point); }
         else { tp = 0; }

         retVal = OpenTrade(SHORT, volume, sl, tp, comment);
         break;

   }

return(retVal);

}

bool OpenTrade(int dir, double volume, double stop, double take, string comment, int t = 0)  
{
    int i, j, ticket, cmd;
    double prc, sl, tp, lots;
    string cmt;
    color clr;

    Print("OpenTrade("+dir+","+DoubleToStr(volume,3)+","+DoubleToStr(stop,Digits)+","+DoubleToStr(take,Digits)+","+t+")");

    lots = CheckLots(volume);
    

    for (i=0; i<RETRYCOUNT; i++) 
    {
        for (j=0; (j<50) && IsTradeContextBusy(); j++)
            Sleep(100);
        RefreshRates();

        if (dir == LONG) 
        {
            cmd = OP_BUY;
            prc = Ask;
            sl = stop;
            tp = take;
         clr = Blue;
        }
        if (dir == SHORT) 
        {
            cmd = OP_SELL;
            prc = Bid;
            sl = stop;
            tp = take;
         clr = Red;
        }
        Print("OpenTrade: prc="+DoubleToStr(prc,Digits)+" sl="+DoubleToStr(sl,Digits)+" tp="+DoubleToStr(tp,Digits));

        cmt = comment;
        if (t > 0)
            cmt = comment + "|" + t;

        ticket = OrderSend(Symbol(), cmd, lots, prc, Slippage, 0, 0, cmt, MagicNumber,0,clr);
        if (ticket != -1)
        {
         if( sl > 0 || tp > 0)
         {
            Print("OpenTrade: opened ticket " + ticket);
            Screenshot("OpenTrade");

            // Assign Stop Loss and Take Profit to order            
            AssignSLTP(ticket, dir, stop, take);

            return (true);
        }
        else
        { 
            if( ticket > 0 ) 
            {
               Screenshot("OpenTrade_SLTP");
               return( true );
            }
         }   // end if( sl > 0 || tp > 0)
        }   // end if (ticket != -1)
        else if (ticket == -1)
        {// look for any open trades that are missing a stop loss and take profit
         if (FindTradesMissingSLTP(dir, stop, take, comment))
         {
             Screenshot("OpenTrade_SLTP");
             return( true );
         }
        }
        
        Print("OpenTrade: error \'"+ErrorDescription(GetLastError())+"\' when entering with "+DoubleToStr(lots,3)+" @"+DoubleToStr(prc,Digits));
        Sleep(RETRYDELAY);
        
    } // end for (i=0; i<RETRYCOUNT; i++) 

    Print("OpenTrade: can\'t enter after "+RETRYCOUNT+" retries");
    return (false);
}

//-----------------------------------------------------------------------------------+
// This routine calculates a Take Profit price and checks it against the minimum stop 
//  loss take profit distance returned by MarketInfo() for the currency pair.
//-----------------------------------------------------------------------------------+
double GetTakeProfit(int dir, double openPrc, double take)
{
   double tp = 0;


   // Calculate Take Profit Price.
   //-----------------------------
   
   if (dir == LONG)
   {
      tp = NormalizeDouble(openPrc + take, Digits);
      
      RefreshRates();
      
      if ((tp - Bid) < minSLTPdstnc*Point)
      {
         tp = NormalizeDouble(Bid + minSLTPdstnc*Point, Digits);
         if (lastAlertTime != Time[0])
         {
            Print("Min. Stop Loss Take Profit distance = ", minSLTPdstnc);
            Alert("GetTakeProfit() - Specified TP is TOO CLOSE to current price!\nMinimum allowed TP distance for this currency of (",tp,") used instead");
            lastAlertTime = Time[0];
         }
      }
   }
   else if (dir == SHORT)
   {
      tp = NormalizeDouble(openPrc - take, Digits);
      
      RefreshRates();
      
      if ((Ask - tp) < minSLTPdstnc*Point)
      {
         tp = NormalizeDouble(Ask - minSLTPdstnc*Point, Digits);
         if (lastAlertTime != Time[0])
         {
            Print("Min. Stop Loss Take Profit distance = ", minSLTPdstnc);
            Alert("GetTakeProfit() - Specified TP is TOO CLOSE to current price!\nMinimum allowed TP distance for this currency of (",tp,") used instead");
            lastAlertTime = Time[0];
         }
      }
   }
   
   return(tp);
}

//-----------------------------------------------------------------------------------+
// This routine calculates a Stop Loss price and checks it against the minimum stop 
//  loss take profit distance returned by MarketInfo() for the currency pair.
//-----------------------------------------------------------------------------------+
double GetStopLoss(int dir, double openPrc, double stop)
{
   double sl = 0;


   // Calculate Take Profit Price.
   //-----------------------------
   
   if (dir == LONG)
   {
      sl = NormalizeDouble(openPrc - stop, Digits);
      
      RefreshRates();
      
      if ((Bid - sl) < minSLTPdstnc*Point)
      {
         sl = NormalizeDouble(Bid - minSLTPdstnc*Point, Digits);
         if (lastAlertTime != Time[0])
         {
            Print("Min. Stop Loss Take Profit distance = ", minSLTPdstnc);
            Alert("GetStopLoss() - Specified SL is TOO CLOSE to current price!\nMinimum allowed SL/TP distance for this currency of (",sl,") used instead");
            lastAlertTime = Time[0];
         }
      }
   }
   else if (dir == SHORT)
   {
      sl = NormalizeDouble(openPrc + stop, Digits);
      
      RefreshRates();
      
      if ((sl - Ask) < minSLTPdstnc*Point)
      {
         sl = NormalizeDouble(Ask + minSLTPdstnc*Point, Digits);
         if (lastAlertTime != Time[0])
         {
            Print("Min. Stop Loss Take Profit distance = ", minSLTPdstnc);
            Alert("GetStopLoss() - Specified SL is TOO CLOSE to current price!\nMinimum allowed SL/TP distance for this currency of (",sl,") used instead");
            lastAlertTime = Time[0];
         }
      }
   }
   
   return(sl);
}

//----------------------------------------------------------------+
// routine makes RETRYCOUNT attempts to "modify" the Stop Loss and 
//  Take Profit for the specified ticket/order
//----------------------------------------------------------------+

bool AssignSLTP(int tkt, int dir, double stop, double take)
{
   int ix, ix2;
   double tp = take;
   double sl = stop;
   bool modified = false;
   

   // Select specified ticket.
   OrderSelect(tkt, SELECT_BY_TICKET, MODE_TRADES);

   // Make several attempts   

   ix = 0;
   while(!modified && ix < RETRYCOUNT)   
   {
      for (ix2 = 0; (ix2 < 50) && IsTradeContextBusy(); ix2++)
         Sleep(100);
      RefreshRates();
      
      if(dir == LONG)   // LONG order
      {
         // set take profit
         if( tp != 0 ) 
            tp = GetTakeProfit(dir, OrderOpenPrice(), take);
              else 
                 tp = 0;
              
              // set stop loss       
         if( sl != 0 ) 
            sl = GetStopLoss(dir, OrderOpenPrice(), stop);
              else 
                 sl = 0;

         // attempt to set stop loss and take profit
         if ( OrderModify(tkt, 0, sl, tp, 0) ) 
         {
            Print("OpenTrade: SL/TP are set LONG");
            Screenshot("OpenTrade_SLTP");
            modified = true;
         }
         else
         {
            Print("AssignSLTP: error \'"+ErrorDescription(GetLastError())+"\' when setting SL/TP");
            Sleep(RETRYDELAY);
         }
      }
      
      else if( dir == SHORT )    // SHORT order
      {
         // set take profit
         if( tp != 0 ) 
            tp = GetTakeProfit(dir, OrderOpenPrice(), take);
              else 
                 tp = 0;
              
              // set stop loss       
         if( sl != 0 ) 
            sl = GetStopLoss(dir, OrderOpenPrice(), stop);
              else 
                 sl = 0;

         // attempt to set stop loss and take profit
         if ( OrderModify(tkt, 0, sl,tp, 0) ) 
         {
            Print("OpenTrade: SL/TP are set SHORT");
            Screenshot("OpenTrade_SLTP");
            modified = true;
         }                
         else
         {
            Print("AssignSLTP: error \'"+ErrorDescription(GetLastError())+"\' when setting SL/TP");
            Sleep(RETRYDELAY);
         }
      }
      
      ix++;    // increment loop counter

   }  // end while(!modified && ix < RETRYCOUNT)   
   
   return(modified);
}

//--------------------------------------------------------------+
// routine checks for open trades placed by the EA this time bar 
//  that have Stop Loss and Take Profit values of zero.  It then
//  reattempts to assign the stop loss or take profit.  If 
//  successful it returns true, otherwise false.
//--------------------------------------------------------------+

bool FindTradesMissingSLTP(int dir, double stop, double take, string comment)
{
   bool result = true;
   
   
   for (int ix = OrdersTotal()-1; ix >= 0; ix--) 
   {
      OrderSelect(ix, SELECT_BY_POS, MODE_TRADES);
      
      // look for one of the EAs trades
      if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber && OrderComment() == comment) 
      {
         // if the trade has neither stop loss or take profit attempt to assign one
         if (OrderStopLoss() <= 0 && OrderTakeProfit() <= 0)
            if (!AssignSLTP(OrderTicket(), dir, stop, take))
               result = false;   // record whether AssignSLTP ever fails
      }
      
   }  // end for (int ix = OrdersTotal()-1; ix >= 0; ix--)
   
   // return result of our attempt
   return (result);
}



double CheckLots(double lots)
{
    double lot, lotmin, lotmax, lotstep, margin;
    
    lotmin = MarketInfo(Symbol(), MODE_MINLOT);
    lotmax = MarketInfo(Symbol(), MODE_MAXLOT);
    lotstep = MarketInfo(Symbol(), MODE_LOTSTEP);
    margin = MarketInfo(Symbol(), MODE_MARGINREQUIRED);

    if (lots*margin > AccountFreeMargin())
        lots = AccountFreeMargin() / margin;

    lot = MathFloor(lots/lotstep + 0.5) * lotstep;

    if (lot < lotmin)
        lot = lotmin;
    if (lot > lotmax)
        lot = lotmax;

    return (lot);
}


void Screenshot(string moment_name)
{
    if ( WriteScreenshots )
        WindowScreenShot(WindowExpertName()+"_"+Symbol()+"_M"+Period()+"_"+
                         Year()+"-"+two_digits(Month())+"-"+two_digits(Day())+"_"+
                         two_digits(Hour())+"-"+two_digits(Minute())+"-"+two_digits(Seconds())+"_"+
                         moment_name+".gif", 1024, 768);
}

string two_digits(int i)
{
    if (i < 10)
        return ("0"+i);
    else
        return (""+i);
}

bool NoOpenPositionsExist()
{
   int total = OrdersTotal();
  
   for(int i = 0; i < total; i++)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol())
      { return (false); }
   }

return (true);
}

bool Exit(int ticket, int dir, double volume, color clr, int t = 0)  {
    int i, j, cmd;
variable 'cmd' not used
    double prc, sl, tp, lots;
variable 'lots' not used
variable 'sl' not used
variable 'tp' not used
    string cmt;     bool closed;     Print("Exit("+dir+","+DoubleToStr(volume,3)+","+t+")");     for (i=0; i<RETRYCOUNT; i++) {         for (j=0; (j<50) && IsTradeContextBusy(); j++)             Sleep(100);         RefreshRates();         if (dir == LONG) {             prc = Bid;         }         if (dir == SHORT) {             prc = Ask;        }         Print("Exit: prc="+DoubleToStr(prc,Digits));         closed = OrderClose(ticket,volume,prc,Slippage,clr);         if (closed) {             Print("Trade closed");             Screenshot("Exit");             return (true);         }         Print("Exit: error \'"+ErrorDescription(GetLastError())+"\' when exiting with "+DoubleToStr(volume,3)+" @"+DoubleToStr(prc,Digits));         Sleep(RETRYDELAY);     }     Print("Exit: can\'t exit after "+RETRYCOUNT+" retries");     return (false); } void ExitAll(int direction) {    for (int i = OrdersTotal()-1; i >= 0; i--) {       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);              if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) {          if (OrderType() == OP_BUY && ( direction == LONG || direction == ALL) ) { Exit(OrderTicket(), LONG, OrderLots(), Blue); }          if (OrderType() == OP_SELL && ( direction == SHORT || direction == ALL) ) { Exit( OrderTicket(), SHORT, OrderLots(), Red); }       }    } } bool CheckTime(string start, string end) {    string today = TimeToStr( iTime(Symbol(),PERIOD_D1, 0 ), TIME_DATE ) + " ";       datetime startTime = StrToTime( today + start);    datetime endTime = StrToTime( today + end);         if(startTime <= endTime) {       if(TimeCurrent() > startTime && TimeCurrent() < endTime) { return(true); }    }       if( startTime >= endTime ) {       if( TimeCurrent() > startTime ) { return(true); }       if( TimeCurrent() < endTime ) { return(true); }    }       if( startTime == endTime) {       Comment("***** The Start Time cannot equal the End Time ******* ");    }       return(false); } bool TrailStop(int magic, double trailStart, double trailAmount)
declaration of 'trailStart' hides global declaration at line 50
declaration of 'trailAmount' hides global declaration at line 50
{    double profitPips, increments, sl;    double chgFromOpen;    for(int i = 0; i < OrdersTotal(); i++)    {       OrderSelect(i,SELECT_BY_POS,MODE_TRADES);       if (OrderMagicNumber() == magic && OrderSymbol() == Symbol())       {          RefreshRates();                         if( OrderType() == OP_BUY ) {             chgFromOpen = NormalizeDouble(Bid - OrderOpenPrice(), Digits);                // move to break even             if(chgFromOpen >= trailStart && chgFromOpen > (minSLTPdstnc * Point) &&                 NormalizeDouble(OrderStopLoss(),Digits) < NormalizeDouble(OrderOpenPrice(), Digits) && trailStart != 0 )             {                Print("Moving stop to breakeven on order " + OrderTicket() + ". Bid is " + DoubleToStr( Bid, Digits ) + ", Trail start is " + DoubleToStr( trailStart, Digits ) );                return( OrderModify( OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, Blue) );             }                      profitPips = Bid - ( trailStart + OrderOpenPrice() ) ;             if( trailAmount != 0)                increments = MathFloor( profitPips / trailAmount );             else                increments = 0;                               if ( increments >= 1 && Bid >= OrderOpenPrice() + trailStart + ( increments * trailAmount ) ) {                sl = NormalizeDouble( OrderOpenPrice() + ( (increments-1)  * trailAmount ), Digits);                             display = "\n\nRequested stop loss: " + DoubleToStr( sl, Digits);                             if( sl > NormalizeDouble(OrderStopLoss(), Digits) ) {                                if( OrderModify( OrderTicket(), OrderOpenPrice(), sl, OrderTakeProfit(), 0, Blue ) ){                      Print("Trailng stop updated. Total increments: " + DoubleToStr(increments, Digits) );                      return(true);                   }                }             }          }                 if( OrderType() == OP_SELL ) {             chgFromOpen = NormalizeDouble(OrderOpenPrice() - Ask, Digits);                          // move to break even             if( chgFromOpen >= trailStart && chgFromOpen > (minSLTPdstnc * Point) &&                NormalizeDouble(OrderStopLoss(),Digits) > NormalizeDouble(OrderOpenPrice(), Digits) && trailStart != 0 ) {                Print("Moving stop to breakeven on order " + OrderTicket() + ". Ask is " + DoubleToStr( Ask, Digits ) + ", Trail start is " + DoubleToStr( trailStart, Digits ) );                return( OrderModify( OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, Red) );             }                      profitPips = ( OrderOpenPrice()- trailStart ) - Ask ;             if( trailAmount != 0) { increments = MathFloor( profitPips / trailAmount ); }             else { increments = 0; }                      if ( increments >= 1 && Ask <= OrderOpenPrice() - trailStart - ( increments * trailAmount ) ) {                sl = NormalizeDouble(OrderOpenPrice() - ( (increments-1) * trailAmount ), Digits);                             if( sl < NormalizeDouble(OrderStopLoss(), Digits) ) {                   if( OrderModify( OrderTicket(), OrderOpenPrice(), sl, OrderTakeProfit(), 0, Red) ) {                      Print("Trailng stop updated. Total increments: " + DoubleToStr(increments, Digits) );                      return(true);                   }                }             }          }                 if( IsStopped() ) { break; }       }              }       return( false ); }


Daniel Petrovai
440
Daniel Petrovai 2014.03.05 06:48  
jaber70:

I have compiled the code & got 6 warning but no error. I even don't know how to fix those error. Please see the attachment. The code too long to post. Thanks!


Can you post the mq4 code without the errors?

qjol
3243
qjol 2014.03.05 07:31  

these warnings means:

variable 'cmd' not used = You declared a variable 'CMD' but it is not used anywhere in your code

variable 'lots' not used = ditto

variable 'sl' not used = ditto

variable 'lots' not used = ditto

declaration of 'trailStart' hides global declaration at line 50 = you have already declared the variable 'trailStart' with that name

declaration of 'trailAmount' hides global declaration at line 50 = you have already declared the variable 'trailAmount' with that name

/
To add comments, please log in or register