Search code examples
mql5

Can objects use global variables declared outside of their class?


I would need that feature for a stop loss-object including a multiplier that increments every time (i.e. at every interval) it's called, but before its first call (i.e. upon opening a position) it must be reset to 0 (resetting it at the end of the SL-object instead is not possible because the object won't be called when the SL is hit). When I tried using a global variable declared outside of the SL-class I got a compilation error ("missing declaration"; the class is placed in an include file in case that info matters).

Is there another way than making my SL-object a function (which can access global variables) instead?

Thanks a lot!


Solution

  • int  stoplossMultiplier,
         lastOpenedTicket;
    
    void OnInit(){
         stoplossMultiplier = 0;
         lastOpenedTicket   = 0;                // also possible to find among open
    }
    
    int  TradeSend(){
      // do what you need here, include ticket = OrderSend(); function
      // compute lot based on stoplossMultiplier
         lastOpenedTicket = ticket;
    }
    
    void OnTick(){
         if ( lastOpenedTicket >  0 ){
              if ( !isTicketExist( lastOpenedTicket() ){
                    if (  isClosedByStopLoss( lastOpenedTicket() ) ){
                          stoplossMultiplier = 0;
                    }else{
                          stoplossMultiplier++;
                    }
              }
         }
    }
    
    bool isTicketExist(      int ticket ){ /* make sure order is open        */ }
    bool isClosedByStopLoss( int ticket ){ /* loop over OrdersHistoryTotal() */ }