MQL4 Code: An RSI robot (expert advisor) for MetaQuotes Trading Engine (Meta Trader 4); Automated trading with advanced RSI strategy

in hive-185836 •  3 years ago 

coding.jpg

MetaQuotes 4 Code: An RSI robot EA (expert advisor) for MetaQuotes Trading Engine (Meta Trader 4); Automated trading with advanced RSI strategy

Features:

  1. Time Limitation - You can set time limitation; after a certain time this EA will stop working. It prevents from unauthorized access or piracy.
  2. Middle line of RSI enabled for more accuracy.
  3. Flexiable Take Profit (TP) & Stop Loss setting.
  4. Trailing Stop Loss enabled for collecting more pips.
  5. Auto Lots Calculate feature enabled for selecting right lots to get maximum profits.
  6. Risk Level feature allows you to set how much percentage of risk on your principal you can afford.
  7. Max Opened Orders feature allows how many trades will be opened at a single time.
  8. In Slippage settings you can set maximum slippage you can tollerate.
  9. In MaxSpread settings you can set maximum spread you can allow.
  10. useTimer feature allows you to select the best time of trade, you can easily select best trading hours.
  11. Smart Martingale feature allows you to use risky martingale method in less risky way.
  12. Advanced Error Handling feature integrated to find out any errors occured easily.

---------------------------Advanced RSI EA code---------------------------

//+--------------------------------------------START---------------------------------------------+
//|                                       RM RSI EA.mq4                                          |
//|            Copyright 2015, MetaQuotes Software Corp. & Copyright 2019,Royal Macro            |
//|                                  https://royalmacro.store                                      |
//+----------------------------------------------------------------------------------------------+
#property copyright "Copyright © 2019-2021, royalmacro"
#property link      "https://royalmacro.store"
#property version   "1.06"
#property description "This RSI Expert Advisor was developed by Suprokash Sarkar on behalf of Royal Macro."
#property description "Any unauthorized use/sell/re-distribution of this product means infringement of copyright."
#property description "-----------------------------------------------------------------------------------"
#property description "If you need any help contact: [email protected]"
#property description "-----------------------------------------------------------------------------------"
#property description "ALERT! VALID UNTIL 30 MAY 2022"
#property strict

//--Time Limitation
datetime allowed_until = D'2022.05.30 12:50'; 
//--Time trading
datetime CurrentTime;

//--External variables--
input int    RSIperiod=14;
input double BuyLevel=30;
input double SellLevel=70;
input double MidLevel=50;
input bool   BuyEnabled=True;
input bool   SellEnabled=True;
input bool MidLevelEnabled=False;
input bool   TradeCloseBySignal=True;
input double TakeProfit=100;
input double StopLoss=100;
input double TrailingStop=25;
input bool   AutoLotCalculate=False;
input double SetManualLots=0.01;
input double RiskLevel=10;
input int MaxOpenedOrders=5;
input int Slippage=5;
input int MaxSpread=5;
input bool useTimer=False; // Use start & end trading times in Hours
input int StartTime=9; // Start hour of Trading day
input int EndTime=23; // End hour of Trading day
input int MagicNumber=1513;
input bool MartingaleEnabled=False;
input bool SmartMartingale=False;
input int MaxMartingaleTerms=5;
input int MartingaleMultiply=2;
input string Comments="RM RSI EA Version 1.06";
    //---internal variables---
int OrderBuy,OrderSell;
int ticket;
int LotDigits;
double Trail,iTrailingStop;
bool prepare_buy=False;
bool prepare_sell=False;
bool lot_increase=False; //lot increase for martingale
string RSI_value_print;
int  total_closed_history;
double profit_loss=0;
double last_lots;
int MartingaleTerms=0;
int error;
bool trailing_stop=True;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int deinit()
  {
   return(0);
  }
//+------------------------------------------------------------------+
//| initializing...                                                  |
//+------------------------------------------------------------------+
    int start()
  {
   double stoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   OrderBuy=0;
   OrderSell=0;
   for(int cnt=0; cnt<OrdersTotal(); cnt++)
     {
      if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderComment()==Comments)
           {
            if(OrderType()==OP_BUY) OrderBuy++;
            if(OrderType()==OP_SELL) OrderSell++;
            
            //if smartmartingale is true then trailingstop will be automatically disabled
            if (SmartMartingale) //if smartingale is enabled
               {
                if (MartingaleEnabled) //if martingale is enabled
                   {
                    if(profit_loss<0) trailing_stop=False;  //if last order is loss then trailing_stop will be disabled
                   }
               }
            
            if (SmartMartingale==False) trailing_stop=True;  //if smartingale is disabled then trailing_stop will be enabled
            
            //if trailingstop is set & trailing_stop is true
            if(TrailingStop>0 && trailing_stop==True)
              {
               iTrailingStop=TrailingStop;
               if(TrailingStop<stoplevel) iTrailingStop=stoplevel;
               Trail=iTrailingStop*Point;
               double tsbuy=NormalizeDouble(Bid-Trail,Digits);
               double tssell=NormalizeDouble(Ask+Trail,Digits);
               if(OrderType()==OP_BUY && Bid-OrderOpenPrice()>Trail && Bid-OrderStopLoss()>Trail)
                 {
                  ticket=OrderModify(OrderTicket(),OrderOpenPrice(),tsbuy,OrderTakeProfit(),0,Blue);
                  if(ticket<0) error_handling(); //if error occured Error handling   
                 }
               if(OrderType()==OP_SELL && OrderOpenPrice()-Ask>Trail && (OrderStopLoss()-Ask>Trail || OrderStopLoss()==0))
                 {
                  ticket=OrderModify(OrderTicket(),OrderOpenPrice(),tssell,OrderTakeProfit(),0,Blue);
                  if(ticket<0) error_handling(); //if error occured Error handling  
                 }
              }
           }
        } 
        else 
        error_handling(); //Error handling
     }
   double rsi=iRSI(Symbol(),0,RSIperiod,PRICE_CLOSE,0);
   double rsi1=iRSI(Symbol(),0,RSIperiod,PRICE_CLOSE,1);
      //_____________________________________CODE TEST AREA_____________________________________
   
   
   //_____________________________________CODE TEST AREA_____________________________________
   
   // double HTb=iCustom(Symbol(),0,"HalfTrend-1.02",0,0); //buy
   // double HTs=iCustom(Symbol(),0,"HalfTrend-1.02",1,0); //buy

   //------ If MidLevel Enabled Start
   if(MidLevelEnabled==True)
     {
      //--- prepare for single sell
      if(SellEnabled && OrderSell<1 && rsi<SellLevel && rsi1>SellLevel) prepare_sell=True;

      //--- prepare for single buy
      if(BuyEnabled && OrderBuy<1 && rsi>BuyLevel && rsi1<BuyLevel) prepare_buy=True;

      //--- open position
      //--- prform single sell
      if(SellEnabled && OrderSell<1 && rsi<MidLevel && rsi1>MidLevel && prepare_sell==True)
        {
         // Trading hours
         if(useTimer==True)
           {
            CurrentTime = TimeCurrent();
       
            int GetWeekday = TimeDayOfWeek(CurrentTime);
            int GetHour = TimeHour(CurrentTime);
            int GetMinute = TimeMinute(CurrentTime);
       
            if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6)
              {
               //print RSI values if RSI cross buy/sell levels
               RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is SELL");
               Print(RSI_value_print);
               OPSELL();
               prepare_sell=False;
              }
           }
         else
            {
             //print RSI values if RSI cross buy/sell levels
             RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is SELL");
             Print(RSI_value_print);
             OPSELL();
             prepare_sell=False;
            }
        }
      //--- perform single buy 

      if(BuyEnabled && OrderBuy<1 && rsi<MidLevel && rsi1>MidLevel && prepare_buy==True)
        {  
         // Trading hours
         if(useTimer==True)
           {
            CurrentTime = TimeCurrent();
       
            int GetWeekday = TimeDayOfWeek(CurrentTime);
            int GetHour = TimeHour(CurrentTime);
            int GetMinute = TimeMinute(CurrentTime);
       
            if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6)
              {
               //print RSI values if RSI cross buy/sell levels
               RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is BUY");
               Print(RSI_value_print);
               OPBUY();
               prepare_buy=False;
              }
           }
         else
            {
             //print RSI values if RSI cross buy/sell levels
             RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is BUY");
             Print(RSI_value_print);
             OPBUY();
             prepare_buy=False;
            }
        }

     }
   //------ If MidLevel Enabled End
   //------ If MidLevel Disabled Start
   if(MidLevelEnabled==False)
     {
      //--- open position
 
      // Trading hours
      if(useTimer==True)
        {
         CurrentTime = TimeCurrent();
       
         int GetWeekday = TimeDayOfWeek(CurrentTime);
         int GetHour = TimeHour(CurrentTime);
         int GetMinute = TimeMinute(CurrentTime);
       
         if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6)
           {
            //--- prform single sell
            if(SellEnabled && OrderSell<1 && rsi<SellLevel && rsi1>SellLevel) 
              {
               //print RSI values if RSI cross buy/sell levels
               RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is SELL");
               Print(RSI_value_print);
               OPSELL();
              }
           }
        }
      else
         {
          //--- prform single sell
          if(SellEnabled && OrderSell<1 && rsi<SellLevel && rsi1>SellLevel) 
            {
             //print RSI values if RSI cross buy/sell levels
             RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is SELL");
             Print(RSI_value_print);
             OPSELL();
            }
         }
           // Trading hours
      if(useTimer==True)
        {
         CurrentTime = TimeCurrent();
       
         int GetWeekday = TimeDayOfWeek(CurrentTime);
         int GetHour = TimeHour(CurrentTime);
         int GetMinute = TimeMinute(CurrentTime);
       
         if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6)
           {
            //--- perform single buy 
            if(BuyEnabled && OrderBuy<1 && rsi<BuyLevel && rsi1>BuyLevel) 
              {
               //print RSI values if RSI cross buy/sell levels
               RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is BUY");
               Print(RSI_value_print);
               OPBUY();
              }
           }
        }
      else
         {
          //--- perform single buy 
          if(BuyEnabled && OrderBuy<1 && rsi<BuyLevel && rsi1>BuyLevel) 
            {
             //print RSI values if RSI cross buy/sell levels
             RSI_value_print=StringConcatenate("RM_RSI_EA_V_1.06 :: RSI is ", rsi, " & RSI1 is ", rsi1, ". Signal is BUY");
             Print(RSI_value_print);
             OPBUY();
            }
         }
  
     }
   //------ If MidLevel Disabled End
   //--- close position by signal
   if(TradeCloseBySignal)
     {
      if(OrderBuy>0 && rsi<SellLevel && rsi1>SellLevel) CloseBuy();
      if(OrderSell>0 && rsi>BuyLevel && rsi1<BuyLevel) CloseSell();
     }
   //---
   return(0);
  }
//+------------------------------------------------------------------+
//|  OPEN BUY ORDERS                                                 |
//+------------------------------------------------------------------+
void OPBUY()
  {
   double StopLossLevel;
   double TakeProfitLevel;
   if(StopLoss>0) StopLossLevel=Bid-StopLoss*Point; else StopLossLevel=0.0;
   if(TakeProfit>0) TakeProfitLevel=Ask+TakeProfit*Point; else TakeProfitLevel=0.0;
   
   //--- if time limitation applied
   if (TimeCurrent() < allowed_until) 
    { 
     double SymSpread = MarketInfo(Symbol(), MODE_SPREAD); // This will Obtain broker Spread for current pair

     if(MaxSpread > 0 && MaxSpread >= SymSpread) // This part compares broker spread with maximum allowed spread, and refuse trade if maxspread is exceeded
       {
        int total = OrdersTotal();
        if (MaxOpenedOrders > total)
           {
            ticket=OrderSend(Symbol(),OP_BUY,LOT(),Ask,Slippage,StopLossLevel,TakeProfitLevel,Comments,MagicNumber,0,DodgerBlue);
            if(ticket<0) error_handling(); //if error occured Error handling  
           }
        else
           {
            Print("Error: Can't open BUY order. Number of Maxium Opened Orders exceeds.");
            return;
           }       
       }  
     else
       {
        Print("Error: Can't open BUY order. Spread is greater than Maximum allowed Spread.");
        return;
       }     
    }
   else Print("Error: RM RSI EA has been expired. Contact [email protected]"); 
   
  }
//+------------------------------------------------------------------+
//|   OPEN SELL ORDERS                                               |
//+------------------------------------------------------------------+
void OPSELL()
  {
   double StopLossLevel;
   double TakeProfitLevel;
   if(StopLoss>0) StopLossLevel=Ask+StopLoss*Point; else StopLossLevel=0.0;
   if(TakeProfit>0) TakeProfitLevel=Bid-TakeProfit*Point; else TakeProfitLevel=0.0;
   
   //--- if time limitation applied
   if (TimeCurrent() < allowed_until) 
   {
    double SymSpread = MarketInfo(Symbol(), MODE_SPREAD); // This will Obtain broker Spread for current pair
    
    if(MaxSpread > 0 && MaxSpread >= SymSpread) // This part compares broker spread with maximum allowed spread, and refuse trade if maxspread is exceeded
    {
     int total = OrdersTotal();
     if (MaxOpenedOrders > total)
           {
            ticket=OrderSend(Symbol(),OP_SELL,LOT(),Bid,Slippage,StopLossLevel,TakeProfitLevel,Comments,MagicNumber,0,DeepPink);
            if(ticket<0) error_handling(); //if error occured Error handling  
           } 
     else
           {
            Print("Error: Can't open SELL order. Number of Maxium Opened Orders exceeds.");
            return;
           }               
    }
    else
       {
        Print("Error: Can't open SELL order. Spread is greater than Maximum allowed Spread");
        return;
       }
    }
   else Print("Error: RM RSI EA has been expired. Contact [email protected]"); 
   
  }
//+------------------------------------------------------------------+
//|   CLOSE SELL ORDERS                                              |
//+------------------------------------------------------------------+
void CloseSell()
  {
   int  total=OrdersTotal();
   for(int y=OrdersTotal()-1; y>=0; y--)
     {
      if(OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL && OrderMagicNumber()==MagicNumber)
           {
            ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,Black);
            if(ticket<0) error_handling(); //if error occured Error handling
           }
         }
         else
         error_handling(); //Error handling
     }
  }
//+------------------------------------------------------------------+
//|   CLOSE BUY ORDERS                                               |
//+------------------------------------------------------------------+
void CloseBuy()
  {
   int  total=OrdersTotal();
   for(int y=OrdersTotal()-1; y>=0; y--)
     {
      if(OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY && OrderMagicNumber()==MagicNumber)
           {
            ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage,Black);
            if(ticket<0) error_handling(); //if error occured Error handling
           }
         }
         else
         error_handling(); //Error handling
     }
  }
//+------------------------------------------------------------------+
//|   CALCULATING AND SETTING LOTS                                   |
//+------------------------------------------------------------------+
double LOT()
  {
   double lotsi;
   double ilot_max =MarketInfo(Symbol(),MODE_MAXLOT);
   double ilot_min =MarketInfo(Symbol(),MODE_MINLOT);
   double tick=MarketInfo(Symbol(),MODE_TICKVALUE);
   
   double  LastOrder_swap;
   double LastOrder_commission;
   //---
   double  myAccount=AccountBalance();
   //---
   if(ilot_min==0.01) LotDigits=2;
   if(ilot_min==0.1) LotDigits=1;
   if(ilot_min==1) LotDigits=0;
   

   //if martingale enabled
   if(MartingaleEnabled==True)
     {
      //--calculate profit/loss
      total_closed_history=OrdersHistoryTotal();
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         if(OrderSelect(total_closed_history-1,SELECT_BY_POS,MODE_HISTORY)) //get last closed order
           {
            profit_loss = OrderProfit(); //get last order profitability
            LastOrder_swap = OrderSwap(); // get last order swap value
            LastOrder_commission = OrderCommission(); // get last order commission value
            last_lots = OrderLots(); //get last closed lot
            profit_loss = profit_loss + LastOrder_swap + LastOrder_commission;
            if(profit_loss<0) lot_increase=True;
            else
              {
               lot_increase=False;
               MartingaleTerms=0;
              }
           }
           else
           error_handling(); //Error handling
        }
     } else
     {
      lot_increase=False;
      MartingaleTerms=0;
     }   
   //---
   if(AutoLotCalculate)
     {
      lotsi=NormalizeDouble((myAccount*RiskLevel)/100000,LotDigits);
      if(lot_increase==True) 
      {
       if(MaxMartingaleTerms > MartingaleTerms)
         {
          //lot increase by n times if last order is loss, n is detrmined by value of MartingaleMultiply
          lotsi=last_lots*MartingaleMultiply;
          lot_increase=False;
          MartingaleTerms=MartingaleTerms+1;
         }        
      }
     } else 
     { 
      lotsi=SetManualLots;
      if(lot_increase==True)
      {
       if(MaxMartingaleTerms > MartingaleTerms)
         {
          //lot increase by n times if last order is loss, n is detrmined by value of MartingaleMultiply
          lotsi=last_lots*MartingaleMultiply; 
          lot_increase=False;
          MartingaleTerms=MartingaleTerms+1;
         }        
      }
     }
   //---
   if(lotsi>=ilot_max) { lotsi=ilot_max; }
   //---
   return(lotsi);
  }
//+------------------------------------------------------------------+
//|   ERROR HANDLING                                                 |
//+------------------------------------------------------------------+
void error_handling()
  {
   error=GetLastError(); 
   Print("order execution/modification has failed with error #",error); 
   //Error handling
   switch(error)
     {
      case 4: //Trade server is busy
      case 8: //Too frequent requests
      case 128: //Trade timeout
      case 137: //Broker is busy
      case 141: //Too many requests
      case 146: //Trade context is busy
        Sleep(10000); // Sleep 10 sec
        RefreshRates(); // refresh price data 
        break;    
      
      case 9: //Malfunctional trade operation
      case 129: // Invalid price
      case 130: // Invalid stops
      case 135: // Price changed
      case 138: //Requote
         RefreshRates(); // refresh price data
         break;     
      
      case 6: //No connection with trade server  
      case 136: // Off quotes 
         while(RefreshRates()==false) // Waiting for the tick to come... before new tick
            Sleep(1); // Delay in the cycle  
         break;                    
     }
   
   ResetLastError();
  }
 
//+-----------------------------END----------------------------------+

Enjoy :)

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

image.png

How fix it?

Spread is greater than your setting value. How much spread in your pair?

plz, increase the value in spread settings in your RSI EA

input int MaxSpread=5; //it's default value you can increase the value & try again

//for example
input int MaxSpread=20;