Help on program

 
Hi guys, I am working on this program:
int start()
{ 
     
      Alert("Numero Ordini"+CountTrades(MagicID));
      RsiPrec = iRSI(NULL, 0, RsiPeriod, PRICE_CLOSE, 2);//Rsi
      Rsi = iRSI(NULL, 0, RsiPeriod, PRICE_CLOSE, 1);//Rsi
      if(NuovaCandela()==true)
      {
      if(CountTrades(MagicID)==0)
        if((RsiPrec>RsiLevelUp)&&(Rsi<RsiLevelUp))
         {
          OpenBuy(lots, MagicID,3);   // Criterion for opening Buy
         }
         if((RsiPrec>RsiLevelDown)&&(Rsi<RsiLevelDown))
         {     
         OpenSell(lots, MagicID,3);   // Criterion for opening Buy
         }
       }
       if(CountTrades(MagicID)>0)
            TrailingStop(e_TrailingStep,e_TrailingStep);
               
return(0) ;                 
} 

bool NuovaCandela()
{
 
  datetime TempoCandelaAttuale = Time[0]; 
  if (TempoCandelaAttuale != TempoUltimaCandela)
      {
       TempoUltimaCandela = TempoCandelaAttuale;
       return (true); 
      }   
  else
  {
       return (false); 
  }
}
int CountTrades(int MagicNumber) {
   int count = 0;
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
      if (OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))
          continue;
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) 
          continue;
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
         if (OrderType() == OP_SELL || OrderType() == OP_BUY) 
            count++;
   }
   return (count);
}

void OpenBuy(double lotti, int MagicNumber,int slipage)
{

   double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   Print("Minimum Stop Level=",minstoplevel," points");
   double price=Ask;
//--- calculated SL and TP prices must be normalized
   double stoploss=NormalizeDouble(Bid-minstoplevel*Point,Digits);
   double takeprofit=NormalizeDouble(Bid+minstoplevel*Point,Digits);
//--- place market order to buy 1 lot
   int ticket=OrderSend(Symbol(),OP_BUY,lotti,price,slipage,stoploss,takeprofit,"My order",MagicNumber,0,clrGreen);
   if(ticket<0)
     {
      Print("OrderSend failed with error #",GetLastError());
     }
   else
      Print("OrderSend placed successfully");
}

void OpenSell(double lotti, int MagicNumber, int slipage)
{

   double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   Print("Minimum Stop Level=",minstoplevel," points");
   double price=Bid;
//--- calculated SL and TP prices must be normalized
   double stoploss=NormalizeDouble(Ask+minstoplevel*Point,Digits);
   double takeprofit=NormalizeDouble(Ask-minstoplevel*Point,Digits);
//--- place market order to buy 1 lot
   int ticket=OrderSend(Symbol(),OP_SELL,lotti,price,slipage,stoploss,takeprofit,"My order",MagicNumber,0,clrGreen);
   if(ticket<0)
     {
      Print("OrderSend failed with error #",GetLastError());
     }
   else
      Print("OrderSend placed successfully");
}
void TrailingStop(double e_trailingstop,double e_trailingstep)
{
   Alert("Ts");
   if (OrderType() == OP_BUY)
    if ((Bid - OrderOpenPrice()) > (e_trailingstop * Point))
      if (OrderStopLoss() < Bid - (e_trailingstop + e_trailingstep - 1) * Point) {
         if (OrderModify(OrderTicket(), OrderOpenPrice(), Ask - e_trailingstop * Point, OrderTakeProfit(), 0, clrGreen))
         return;
      }
  if (OrderType()==OP_SELL)
    if ((OrderOpenPrice() - Ask) > (e_trailingstop * Point))
      if (OrderStopLoss() > Ask + (e_trailingstop + e_trailingstep - 1) * Point || OrderStopLoss()==0) {
         if (OrderModify(OrderTicket(), OrderOpenPrice(), Ask + e_trailingstop * Point, OrderTakeProfit(), 0, clrGreen))
         return;
      }
}
The program should operate as follows: declared RsiPrec and Rsi which are the values of the Rsi candel "x-1"(a) and the value at the candel "x"(b), respectively, at each new candel.
"if (NuovaCandela ()==true)" and there are no "in machine" orders (if (CountTrades (MagicID)===0) if the value (a) is greater than RsiLevelUp and (b) is lower than RsiLevelUp.
(it means that the value of the Rsi has "crossed down" RsiLevelUP) opens a position in Buy (OpenBuy (lots, MagicID, 3)), conversely if the value (a) is lower than RsiLevelDown and (b) is higher than RsiLevelDown.
(it's to say that the Rsi value has "crossed up" RsiLevelDown) opens a position in Sell (OpenSell (lots, MagicID, 3)); if instead "if (NewCandela ()==true)" and there are "in machine" orders (if (CountTrades (MagicID)>0) 
the program calls the function TrailingStop (e_TrailingStep, e_TrailingStep) that should manage the trailingStop to the order that is "in machine";
Problems:
1)When I turn the backtest of the program it opens and closes positions on the same candel, although there is the function (NewCandel () that should start the controls only if there is a new candel);
2)The CountTrades (MagicID) function always returns 0, so that the TrailingStop function "(e_TrailingStep, e_TrailingStep)" does not change the open position and alert "Alert (" Number of Orders "+CountTrades (MagicID)";". 
 always returns 0 open positions;
 
texoro:
 

1)When I turn the backtest of the program it opens and closes positions on the same candel, although there is the function (NewCandel () that should start the controls only if there is a new candel);


What do you mean by "it opens and closes positions on the same candle"? It opens multiple positions or just opens and closes one position on the same candle?


2)The CountTrades (MagicID) function always returns 0, so that the TrailingStop function "(e_TrailingStep, e_TrailingStep)" does not change the open position and alert "Alert (" Number of Orders "+CountTrades (MagicID)";". 

 always returns 0 open positions;

int CountTrades(int MagicNumber) {
   int count = 0;
   for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
      if (!OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))
          continue;
      if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) 
          continue;
      if (OrderType() == OP_SELL || OrderType() == OP_BUY) 
          count++;
   }
   return (count);
}


 
  1. int start()
    Start using the new Event Handling Functions.
              Event Handling Functions - Functions - Language Basics - MQL4 Reference

  2. if(NuovaCandela()==true)
    You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.

  3. int CountTrades(int MagicNumber) {
       int count = 0;
       for (int trade = OrdersTotal() - 1; trade >= 0; trade--) {
          if (OrderSelect(trade, SELECT_BY_POS, MODE_TRADES))
              continue;
          if (OrderSymbol() != Symbol() || OrderMagicNumber() != MagicNumber) 
              continue;
          if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
             if (OrderType() == OP_SELL || OrderType() == OP_BUY) 
                count++;
       }
       return (count);
    }
    If you select an order, you continue. When can count ever be non-zero?

    If is isn't the symbol or the MN you continue. So what is the point of checking those two a second time?

  4. double stoploss=NormalizeDouble(Bid-minstoplevel*Point,Digits);
    double takeprofit=NormalizeDouble(Bid+minstoplevel*Point,Digits);
    Do NOT use NormalizeDouble, EVER. For ANY Reason. It's a kludge, don't use it. It's use is always wrong

  5.  (e_trailingstop * Point))
    Using Points means code breaks on 4 digit brokers, exotics (e.g. USDZAR where spread is over 500 points,) and metals. Compute what a PIP is and use it, not points.
              How to manage JPY pairs with parameters? - MQL4 and MetaTrader 4 - MQL4 programming forum
              Slippage defined in index points - Currency Pairs - Expert Advisors and Automated Trading - MQL5 programming forum

  6.    if (OrderType() == OP_BUY ...{
          if (OrderModify(OrderTicket(), OrderOpenPrice(), Ask - e_trailingstop * Point, OrderTakeProfit(), 0, clrGreen))
    You buy at the Ask and sell at the Bid.
    • Your buy order's TP/SL are triggered when the Bid reaches it. Not the Ask.
    • Your sell order's TP/SL will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 and MetaTrader 4 - MQL4 programming forum - Page 3
    • The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools -> Options {control-O} -> charts -> Show ask line.)

Reason: