Why is my code not generating buy signals even though it should be?

 

Hey, im following this guys tutorial and my code is not generating any buy signals or print statements saying that i should buy or sell even though i can clearly see that criteria is met. why do you think is going on here? I followed the guys code to the letter i believe. 


video: https://www.youtube.com/watch?v=YIqh72BxXik


//+------------------------------------------------------------------+
//| Includes
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>


//+------------------------------------------------------------------+
//| Inputs
//+------------------------------------------------------------------+
input group "==== General ====";
static input long InpMagicNumber = 565656;   //magic number
static input double InpLotSize = 0.01;       //lot size
input group "==== trading ====";
input int InpStopLoss = 200;                 //stop loss (in points, 0 = off)
input int InpTakeProfit = 0;                 //take profit (in points, 0 = off)
input bool InpCloseSignal = false;           //close trades when opposite signal is activated
input group "==== Stochastic Inputs ====";
input int InputKPeriod = 21; //k period (5)
input int InputDPeriod = 21; //k period (3)
input int InputSlowing = 3; //slowing value (3)
input int InpUpperLevel = 80; //upper level


//+------------------------------------------------------------------+
//| gloabal variables
//+------------------------------------------------------------------+
int handle;
double bufferMain[];
double bufferSignal[];
MqlTick cT;  // this is used to store the current tick of the symbol in for comparison
CTrade trade; //trade is object to open and close positions



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   //check user inputs
   if (!CheckInputs()){return INIT_PARAMETERS_INCORRECT;}
   
   
   //set magic number to trade object
   trade.SetExpertMagicNumber(InpMagicNumber);
   
   //create indicator handle 
   handle = iStochastic(_Symbol,PERIOD_CURRENT,InputKPeriod,InputDPeriod,InputSlowing,MODE_SMA,STO_LOWHIGH);
   if (handle ==INVALID_HANDLE){
      Alert("Failed to create stochastic handle.");
      return INIT_FAILED;
   }
   
   //set the buffer as series so it organizes it from newest to oldest
   ArraySetAsSeries(bufferMain,true);
   ArraySetAsSeries(bufferSignal,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()
  {
   // check for bar open tick
   if(!IsNewBar()){return;}
   
   //get current tick
   if(!SymbolInfoTick(_Symbol,cT)){Print("Failed to get current symbol tick"); return;}
   
   //get indicator values
   //get k value
   if(CopyBuffer(handle,0,1,2,bufferMain)!=2){
      Print("Failed to get indicator main values");
      return;
   }
   //get d value
   if(CopyBuffer(handle,1,1,2,bufferSignal)!=2){
      Print("Failed to get indicator signal values");
      return;
   }
   
   Comment("buffer main: ", (bufferMain[0]));
   Comment("buffer signal: ",(bufferSignal[0]));
   
   
   //count open positions
   int cntBuy, cntSell;
   if(!CountOpenPositions(cntBuy,cntSell)){
      Print("Failed to count open positions");
      return;
   }
   
   //check for buy position
   if(cntBuy==0 && bufferMain[0]<=(100-InpUpperLevel) && bufferMain[1] > (100-InpUpperLevel)){
      Print("Open buy position");
   
   }
   //check for sell position
   if(cntSell==0 && bufferMain[0]>=InpUpperLevel && bufferMain[1] < InpUpperLevel){
      Print("Open sell position");
   
   }
   

  }

//+------------------------------------------------------------------+
//| Custom functions
//+------------------------------------------------------------------+

//checks user inputs
bool CheckInputs(){
if (InpMagicNumber <=0){
   Alert("Wrong input for magic number. <=0. ");
   return false;
   } 
if (InpLotSize <=0 || InpLotSize >10){
   Alert("Lot size is <=0 or above >10. ");
   return false;
   } 
if (InpStopLoss <0){
   Alert("Stop loss is <0. ");
   return false;
   } 
if (InpTakeProfit <0){
   Alert("Take Profit is < 0 ");
   return false;
   } 
if (!InpCloseSignal && InpStopLoss == 0){
   Alert("Close Signal is false and no stop loss");
   return false;
   } 
if (InputKPeriod < InputDPeriod || InputKPeriod==0 || InputDPeriod == 0  ){
   Alert("Input k is lower than input d or Input is 0");
   return false;
   } 
if (InpUpperLevel <=50 || InpUpperLevel >=100){
   Alert("upper level is greater than 100 or lower than 50.  ");
   return false;
   }

return true;
}


//check if we have a new bar open tick
bool IsNewBar(){

   static datetime previousTime = 0;
   datetime currentTime = iTime(_Symbol,PERIOD_CURRENT,0);
   if(previousTime != currentTime){
   previousTime = currentTime;
   }
   return false;
}


//count open positions
bool CountOpenPositions(int &cntBuy, int &cntSell){

   cntBuy = 0;
   cntSell = 0;
   
   int total = PositionsTotal();
   for (int i=total - 1; i>=0;i--){
   
   ulong ticket = PositionGetTicket(i);
   if(ticket<=0){
      Print("Failes to get position ticket");
      return false;}
   if(!PositionSelectByTicket(ticket)){
      Print("Failes to select position");
      return false;}
   long magic;
   if(!PositionGetInteger(POSITION_MAGIC,magic)){
      Print("Failes to get position magic number");
      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 when we have opposite signal
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("Failes 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 magic number"); 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;

}
Stochastic trading bot in mql5! | Part 1
Stochastic trading bot in mql5! | Part 1
  • 2023.04.13
  • www.youtube.com
Today I will show you how to code a stochastic trading bot for Metatrader 5. In this video we will create a fully working stochastic Expert Advisor for Metat...
 
thecerealslayer:
bool IsNewBar(){
   static datetime previousTime = 0;
   datetime currentTime = iTime(_Symbol,PERIOD_CURRENT,0);
   if(previousTime != currentTime){
   previousTime = currentTime;
   }
   return false;
}

You don't understand what you are writing. Is it a chatGPT EA ?

 
  1. thecerealslayer: why do you think is going on here? 

    Your code is broken.

    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)

  2.    if(CopyBuffer(handle,0,1,2,bufferMain)!=2){
       if(CopyBuffer(handle,1,1,2,bufferSignal)!=2){
    Don't hard code constants, use the proper symbols. See the example iStochastic - Technical Indicators - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
Icham Aidibe #: You don't understand what you are writing. Is it a chatGPT EA ?

OP said he followed a YouTube video.

 
William Roeder #:

OP said he followed a YouTube video.

Indeed

 
William Roeder #:
  1. Your code is broken.

    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)

  2. Don't hard code constants, use the proper symbols. See the example iStochastic - Technical Indicators - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
Icham Aidibe #:

You don't understand what you are writing. Is it a chatGPT EA ?  No, I followed the video, however i personally dont see whats wrong with it, could you explain deeper? 

 
William Roeder #:
  1. Your code is broken.

    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)

  2. Don't hard code constants, use the proper symbols. See the example iStochastic - Technical Indicators - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5

Hey when you say dont hard code constants do you mean i should be using a variable instead? Also i am using the istochastic function on the oninit area, am i doing that wrong?

Reason: