Search code examples
mt4mql5

how do i declare variables, compare them and then use them inside a function


i am developing an ea that requires me to compare the high of previous 2 bars and whichever one is higher, use that as a stop loss value.

same for opposite side trades, i need to compare previous 2 lows and use the lower one as stop loss value.

what i am doing is this:-

void onTick()
{
  static int ticket=0;

  double ab=(//calculation for ab);
  double de=(//calculation for de); 
   if(Low[1]<Low[2])
      double sll=Low[1];
   if(Low[1]>Low[2])
      double sll=Low[2];
  if(buy logic comes here) 
  {
   double entryPrice=////////;
   double stoploss=sll-xyz;
   double takeprofit=entryPrice+((entryPrice-stoploss)*3);
   ticket = OrderSend(Symbol(),...entryPrice,stoploss,takeprofit,.....);
  }
    if(ticket == false)
         {
           Alert("Order Sending Failed");
         }
}

the problem is i am not able to reference the values of sll and get an error message saying "sll undeclared identifier"

i am fairly new to programming and would appreciate if someone can help me out with this. I have added most of the code for you to understand the logic.


Solution

  • you would have to declare them outside the scope of the if statements if you want to use variables anywhere else so instead of doing that take a look at this

    double sll; // declare sll outside the if statements
    if(Low[1]<Low[2])
       sll=Low[1];
    if(Low[1]>Low[2])
       sll=Low[2];
    if(buy logic comes here) 
    {
     bool res = OrderSend(..........);
    } 
    

    Judging by what you wrote, it looks like you may be using res somewhere else too which then you need to define outside of the if statement because scoping.