Hello, why does this code not work? There is no error

 
//+------------------------------------------------------------------+
//|                                                        rsi14.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| inputs                                                           |
//+------------------------------------------------------------------+
static input long    InpMagicnumber = 546812;   // magic number
static input double  InpLotSize = 0.01;         // lot size
input int            InpRSIPeriod = 21;         // rsi period
input int            InpRSILevel = 70;          // rsi level (upper)
input int            InpStopLoss = 200;         // stop loss in points (0-off)
input int            InpTakeProfit = 100;       // take profit in points (0=off)
input bool           InpCloseSignal = false;    // close trades by opposite signal

//+------------------------------------------------------------------+
//| globalvariable                                                   |
//+------------------------------------------------------------------+

int handle;
double buffer[];
MqlTick currentTick;
CTrade trade;
datetime openTimeBuy = 0;
datetime openTimeSell = 0;

///----------------

int OnInit()
{
   // check user inputs
   if (InpMagicnumber<=0) {
      Alert("Magicnumber <= 0");
      return INIT_PARAMETERS_INCORRECT;
   }
   if (InpLotSize<=0 || InpLotSize>10) {
      Alert("Lot size <= 0 or > 10"); 
      return INIT_PARAMETERS_INCORRECT;
   }
   if (InpRSIPeriod<=1) {
      Alert("RSI period <= 1");
      return INIT_PARAMETERS_INCORRECT;
   }
   if (InpRSILevel>=100 || InpRSILevel<=50) {
      Alert ("RSI level >= 100 or <= 50");
      return INIT_PARAMETERS_INCORRECT;
   }
   if (InpStopLoss<0) {
      Alert ("Stop loss < 0");
      return INIT_PARAMETERS_INCORRECT;
   }
   
   if (InpTakeProfit<0) {
      Alert ("Take profit < 0");
      return INIT_PARAMETERS_INCORRECT;
    }
    
   // set magic number to trade object
   trade.SetExpertMagicNumber (InpMagicnumber);
   
   // create rsi handle
   handle = iRSI (_Symbol, PERIOD_CURRENT, InpRSIPeriod, PRICE_CLOSE);
   if (handle == INVALID_HANDLE) {
      Alert("Failed to create indicator handle"); 
      return INIT_FAILED;
   }
   
   // set buffer as series
   ArraySetAsSeries (buffer, true);

   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // release indicator handle
   if (handle!= INVALID_HANDLE) {IndicatorRelease (handle); }
   
}
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // get current tick
   if (!SymbolInfoTick (_Symbol, currentTick)) {Print ("Failed to get current tick"); return; }
   
   // get rsi values
   int values =CopyBuffer (handle,0,0,2,buffer);
   if (values!=2) {
      Print ("Failed to get indicator values");
      return;
   }
   Comment("buffer[0]:",buffer[0],"\nbuffer[1]:",buffer[1]);
   
   ///--------------------------------
   // count open positions
   int cntBuy, cntsell;
   if (!CountOpenPositions (cntBuy, cntsell)) {return;}
   
   // check for buy position
   if (cntBuy==0 && buffer[1]>= (100-InpRSILevel) && buffer[0]<(100-InpRSILevel) && openTimeBuy!=iTime (_Symbol, PERIOD_CURRENT, 0)) {
      openTimeBuy=iTime (_Symbol, PERIOD_CURRENT, 0);
      if (InpCloseSignal) {if (!ClosePositions (2)) {return;}}
      double sl = InpStopLoss==0 ? 0: currentTick.bid -InpStopLoss * _Point; 
      double tp = InpTakeProfit==0 ? 0: currentTick.bid + InpTakeProfit* _Point;
      if (!NormalizePrice(sl)) {return;}
      if (!NormalizePrice(tp)) {return;}
      
      trade.PositionOpen (_Symbol, ORDER_TYPE_BUY, InpLotSize, currentTick.ask,sl,tp, "RSI EA"); 
   }
   
   // check for sell position
   if (cntsell == 0 && buffer[1] <= InpRSILevel && buffer[0]>InpRSILevel && openTimeSell!=iTime (_Symbol, PERIOD_CURRENT, 0)){
      openTimeSell=iTime (_Symbol, PERIOD_CURRENT, 0);
      if (InpCloseSignal) {if (!ClosePositions (1)) {return;}}
      double sl= InpStopLoss ==0 ? 0: currentTick.ask + InpStopLoss *_Point;
      double tp = InpTakeProfit==0 ? 0: currentTick.ask -InpTakeProfit * _Point;
      
      if (!NormalizePrice (sl)) {return;}
      if (!NormalizePrice (tp)) {return;}
      trade.PositionOpen (_Symbol, ORDER_TYPE_SELL, InpLotSize, currentTick.bid, sl, tp, "RSI EA");
   }
 }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| custom function                                             |
//+------------------------------------------------------------------+

// count open positions
bool CountOpenPositions (int &cntBuy, int &cntSell) {
   cntBuy = 0;
   cntSell = 0;
   int total = PositionsTotal();
   for (int i=total-1; 1>=0; i--) {
      ulong ticket = PositionGetTicket (i);
      if (ticket<=0) {Print ("Failed to get position ticket"); return false;}
      if (!PositionSelectByTicket (ticket)) {Print ("Failed to select position"); return false;}
      long magic;
      if (!PositionGetInteger (POSITION_MAGIC, magic)) {Print ("Failed to get position magicnumber"); return false;}
      if (magic==InpMagicnumber) {
         long type;
         if (!PositionGetInteger (POSITION_TYPE, type)) {Print ("Failed to get position type"); return false;}
         if (type==POSITION_TYPE_BUY) {cntBuy++;}
         if (type==POSITION_TYPE_SELL) {cntSell++; }

      }
   }

   return true;

}

// normalize price
bool NormalizePrice (double &price) {

   double ticksize=0;
   if (!SymbolInfoDouble (_Symbol,SYMBOL_TRADE_TICK_SIZE, ticksize)) { 
      Print ("Failed to get tick size");
      return false;
   }
   price = NormalizeDouble (MathRound (price/ticksize) *ticksize, _Digits);
   return true;
}



// close positions
bool ClosePositions (int all_buy_sell) {

   int total = PositionsTotal();
   for(int i=total-1; i>=0; i--) {
      ulong ticket = PositionGetTicket (i);
      if (ticket<=0) {Print ("Failed to get position ticket"); return false;}
      if (! PositionSelectByTicket (ticket)) {Print ("Failed to select position"); return false;}
      long magic;
      if (!PositionGetInteger (POSITION_MAGIC, magic)) {Print ("Failed to get position magicnumber"); return false;}
      if (magic==InpMagicnumber) {
         long type;
         if (!PositionGetInteger (POSITION_TYPE, type)) {Print ("Failed to get position type"); return false;} 
         if (all_buy_sell==1 && type==POSITION_TYPE_SELL) { continue; }
         if (all_buy_sell==2 && type==POSITION_TYPE_BUY) {continue; }
         trade. PositionClose (ticket); 
         if (trade.ResultRetcode () !=TRADE_RETCODE_DONE) {
             Print ("Failed to close position. ticket: ",
                    (string) ticket," result:", (string) trade. ResultRetcode (), ":", trade. CheckResultRetcodeDescription());
         }

      }
 
   }
   return true;

}


There is no error, but it does not open a buy or sell trade. Why?

Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2023.03.25
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
  1. Please edit your (original) post and use the CODE button (or Alt+S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum #25 (2019)
              Forum rules and recommendations - General - MQL5 programming forum (2023)
              Messages Editor

  2. aref2468: why does this code not work

    “Doesn't work” is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — meaningless.
         How To Ask Questions The Smart Way. (2004)
              When asking about code
              Be precise and informative about your problem

    How can we know what it's doing and what you want it to do?

  3. aref2468: There is no error, but it does not open a buy or sell trade .why ????

    Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)