Learn use of Class in mql5

8 August 2024, 21:00
Rajesh Kumar Nait
0
32

1. What is a Class?

A class in MQL5 is a blueprint for creating objects. It allows you to encapsulate data and methods that operate on that data. In MQL5, a class is defined using the class keyword and can have private, protected, and public sections for its members (variables and functions).

2. Basic Structure of a Class

Here’s a basic structure of a class in MQL5:

class MyClass
{
private:
   int privateVariable;

public:
   // Constructor
   MyClass(int initialValue) {
       privateVariable = initialValue;
   }

   // Method to set the value of privateVariable
   void SetValue(int newValue) {
       privateVariable = newValue;
   }

   // Method to get the value of privateVariable
   int GetValue() {
       return privateVariable;
   }
};

3. Example: Using a Class to Manage Trading Settings

Let's create a class that manages trading settings like lots, stop loss, and take profit.

// Define the class
class TradingSettings
{
private:
   double lots;
   int stopLoss;
   int takeProfit;

public:
   // Constructor to initialize the settings
   TradingSettings(double initialLots, int initialStopLoss, int initialTakeProfit)
   {
       lots = initialLots;
       stopLoss = initialStopLoss;
       takeProfit = initialTakeProfit;
   }

   // Method to set lots
   void SetLots(double newLots)
   {
       lots = newLots;
   }

   // Method to get lots
   double GetLots()
   {
       return lots;
   }

   // Method to set stop loss
   void SetStopLoss(int newStopLoss)
   {
       stopLoss = newStopLoss;
   }

   // Method to get stop loss
   int GetStopLoss()
   {
       return stopLoss;
   }

   // Method to set take profit
   void SetTakeProfit(int newTakeProfit)
   {
       takeProfit = newTakeProfit;
   }

   // Method to get take profit
   int GetTakeProfit()
   {
       return takeProfit;
   }
};

// Example usage in an Expert Advisor (EA)
input double lotSize = 0.1;
input int slippage = 3;
input int stopLoss = 50;
input int takeProfit = 100;

TradingSettings tradingSettings(lotSize, stopLoss, takeProfit);

void OnStart()
{
    // Display initial trading settings
    Print("Initial Lot Size: ", tradingSettings.GetLots());
    Print("Initial Stop Loss: ", tradingSettings.GetStopLoss());
    Print("Initial Take Profit: ", tradingSettings.GetTakeProfit());

    // Update trading settings
    tradingSettings.SetLots(0.2);
    tradingSettings.SetStopLoss(100);
    tradingSettings.SetTakeProfit(200);

    // Display updated trading settings
    Print("Updated Lot Size: ", tradingSettings.GetLots());
    Print("Updated Stop Loss: ", tradingSettings.GetStopLoss());
    Print("Updated Take Profit: ", tradingSettings.GetTakeProfit());
}

Explanation

  1. Class Definition:

    • TradingSettings class has private variables for lots , stopLoss , and takeProfit .
    • Public methods are used to set and get these values.
  2. Constructor:

    • The constructor initializes the class with default values when an object is created.
  3. Methods:

    • Methods like SetLots , GetLots , etc., are used to interact with the private variables.
  4. Usage:

    • In the OnStart() function of an EA, an object of TradingSettings is created and initialized.
    • The methods of the class are used to manipulate and retrieve trading settings.

This is a basic example to illustrate how to use classes in MQL5. Classes are powerful and can be used to manage more complex logic and data in your trading applications.

Now lets code another example for better understanding about creating a class class for candle patterns, hammer and spinning top


class CandlestickPatterns
{
private:
   double open;    // Opening price
   double close;   // Closing price
   double high;    // Highest price
   double low;     // Lowest price

   // Helper function to calculate body size
   double BodySize() {
       return MathAbs(close - open);
   }

   // Helper function to calculate shadow sizes
   double UpperShadowSize() {
       return high - MathMax(open, close);
   }

   double LowerShadowSize() {
       return MathMin(open, close) - low;
   }

public:
   // Constructor to initialize candle data
   CandlestickPatterns(double openPrice, double closePrice, double highPrice, double lowPrice) {
       open = openPrice;
       close = closePrice;
       high = highPrice;
       low = lowPrice;
   }

   // Check if the pattern is a Hammer
   bool IsHammer() {
       double bodySize = BodySize();
       double lowerShadow = LowerShadowSize();
       double upperShadow = UpperShadowSize();

       if (bodySize == 0)
           return false;

       // Hammer conditions
       if (lowerShadow >= 2 * bodySize && upperShadow <= bodySize * 0.1) {
           return true;
       }

       return false;
   }

   // Check if the pattern is a Spinning Top
   bool IsSpinningTop() {
       double bodySize = BodySize();
       double totalLength = high - low;
       double upperShadow = UpperShadowSize();
       double lowerShadow = LowerShadowSize();

       if (bodySize == 0 || totalLength == 0)
           return false;

       // Spinning Top conditions
       if (bodySize <= totalLength * 0.3 && upperShadow >= bodySize * 0.5 && lowerShadow >= bodySize * 0.5) {
           return true;
       }

       return false;
   }
};

// Example usage in an Expert Advisor (EA)
void OnStart()
{
    // Example candle data (open, close, high, low)
    double openPrice = 1.1050;
    double closePrice = 1.1060;
    double highPrice = 1.1080;
    double lowPrice = 1.1040;

    // Create a CandlestickPatterns object
    CandlestickPatterns candle(openPrice, closePrice, highPrice, lowPrice);

    // Check for Hammer pattern
    if (candle.IsHammer()) {
        Print("The candle is a Hammer.");
    } else {
        Print("The candle is not a Hammer.");
    }

    // Check for Spinning Top pattern
    if (candle.IsSpinningTop()) {
        Print("The candle is a Spinning Top.");
    } else {
        Print("The candle is not a Spinning Top.");
    }
}
Now lets take an example of how you would code it without using a class
// Function to calculate body size
double BodySize(double open, double close) {
    return MathAbs(close - open);
}

// Function to calculate upper shadow size
double UpperShadowSize(double high, double open, double close) {
    return high - MathMax(open, close);
}

// Function to calculate lower shadow size
double LowerShadowSize(double low, double open, double close) {
    return MathMin(open, close) - low;
}

// Function to check if the pattern is a Hammer
bool IsHammer(double open, double close, double high, double low) {
    double bodySize = BodySize(open, close);
    double lowerShadow = LowerShadowSize(low, open, close);
    double upperShadow = UpperShadowSize(high, open, close);

    if (bodySize == 0)
        return false;

    // Hammer conditions
    if (lowerShadow >= 2 * bodySize && upperShadow <= bodySize * 0.1) {
        return true;
    }

    return false;
}

// Function to check if the pattern is a Spinning Top
bool IsSpinningTop(double open, double close, double high, double low) {
    double bodySize = BodySize(open, close);
    double totalLength = high - low;
    double upperShadow = UpperShadowSize(high, open, close);
    double lowerShadow = LowerShadowSize(low, open, close);

    if (bodySize == 0 || totalLength == 0)
        return false;

    // Spinning Top conditions
    if (bodySize <= totalLength * 0.3 && upperShadow >= bodySize * 0.5 && lowerShadow >= bodySize * 0.5) {
        return true;
    }

    return false;
}

// Example usage in an Expert Advisor (EA)
void OnStart() {
    // Example candle data (open, close, high, low)
    double openPrice = 1.1050;
    double closePrice = 1.1060;
    double highPrice = 1.1080;
    double lowPrice = 1.1040;

    // Check for Hammer pattern
    if (IsHammer(openPrice, closePrice, highPrice, lowPrice)) {
        Print("The candle is a Hammer.");
    } else {
        Print("The candle is not a Hammer.");
    }

    // Check for Spinning Top pattern
    if (IsSpinningTop(openPrice, closePrice, highPrice, lowPrice)) {
        Print("The candle is a Spinning Top.");
    } else {
        Print("The candle is not a Spinning Top.");
    }
}

Now you got to know about why you should class and why you should not?

I do not use class on my projects, I love using functions and struct only

Comment down for what reason you will use the class or if you avoid using the class like me?