How to Use Constants, Enums, and Structures in MQL5

Watch on YouTube: Constants, Enumerations, and Structures in MQL5

MQL5 offers powerful tools like constants, enumerations (enums), and structures, which help streamline and organize your trading algorithms. These features improve code readability, reduce errors, and allow better management of trading-related data.

Constants and Enumerations

Understanding Constants in MQL5

Constants are immutable values that remain fixed during the script’s execution. They improve code clarity, prevent accidental changes, and ensure consistent behavior across your program. Constants are often predefined in MQL5 for common values like order types, price modes, or trade actions.

Example: Constants for Order Types

void OnStart() {
   int orderType = ORDER_TYPE_BUY; // ORDER_TYPE_BUY is a predefined constant for buy orders (int 0)
   Print("Order Type: ", orderType); // Outputs the constant's value
}

In this example, ORDER_TYPE_BUY represents a buy order. MQL5 also includes constants for chart operations, environment state, objects, indicators, and more, allowing you to standardize various aspects of your code.

Enumerations (Enums) in MQL5

Enums in MQL5 group related values into predefined sets, ensuring consistency and reducing errors. Built-in enums are widely used for trading logic, such as timeframes, price constants, or order types.

Example: Timeframes Using ENUM_TIMEFRAMES

void OnStart() {
   ENUM_TIMEFRAMES selectedTimeFrame = PERIOD_M15; // Predefined 15-minute timeframe
   Print("Selected Timeframe: ", selectedTimeFrame);
}

Example: Order Types with ENUM_ORDER_TYPE

void OnStart() {
   ENUM_ORDER_TYPE orderType = ORDER_TYPE_BUY_STOP; // Buy-stop order constant 
   Print("Order Type: ", orderType);
}

Explanation

  • Timeframes: ENUM_TIMEFRAMES includes constants like PERIOD_M1 (1 minute) or PERIOD_H1 (1 hour).
  • Order Types: ENUM_ORDER_TYPE defines actions like ORDER_TYPE_BUY or ORDER_TYPE_SELL.

These enums ensure code is clear and prevents invalid values from being used in trading logic.

We will encounter and utilize various types of constants and enums throughout our Expert Advisors, where they will be explained in greater depth in relevant contexts.

Structures

Structures (structs) in MQL5 allow you to group related variables into a custom data type. This is useful for storing complex data that belongs together, like trade details or market information.

Example Structure for Trade Details:

// Define a structure to hold trade details
struct TradeDetails {
   int orderID;           // Order ID of the trade
   double price;          // Price at which the trade is executed
   datetime orderTime;    // Time when the order was placed
};
void OnStart() {
   TradeDetails trade;  // Create an instance of the TradeDetails structure
   // Assign values to the structure fields
   trade.orderID = 12345;  // Set the order ID
   trade.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);  // Get the current ask price of the symbol
   trade.orderTime = TimeCurrent();  // Record the current server time as the order time
   // Print the trade details, including Order ID, Price, and Order Time
   Print("Order ID: ", trade.orderID, ", Price: ", trade.price, ", Order Time: ", TimeToString(trade.orderTime));
}

In this example, the TradeDetails structure bundles order ID, price, and order time into a single object, making it easier to manage and manipulate related data.

Predefined Structures in MQL5

MQL5 offers 12 built-in structures for handling common trading data. Some of the key ones include:

  • MqlRates: Stores historical price data like open, high, low, and close.
  • MqlTradeRequest: Used for placing orders.
  • MqlTick: Holds real-time market data such as bid and ask prices.
  • MqlDateTime: Helps with efficient handling of date and time.

Example using MqlRates:

void OnStart() {
   // Declare an array of MqlRates to store price data
   MqlRates rate[];
   // Copy the last 10 one-minute (M1) historical price bars for the chart symbol (_Symbol)
   int copied = CopyRates(_Symbol, PERIOD_M1, 0, 10, rate);
   // Reverse the array to treat the last copied bar as the first element
   ArraySetAsSeries(rate, true);
   // Check if the data retrieval was successful
   if (copied > 0) {
      // Print the open and close price of the most recent period (now at index 0)
      Print("Last period Open: ", rate[0].open, ", Close: ", rate[0].close);
   }
}

The MqlRates structure in MQL5 stores historical price data for a symbol. In the example provided, we use the CopyRates function to retrieve the last 10 one-minute (M1) price bars for the chart symbol (_Symbol).

Here’s how the code works:

  1. MqlRates rate[];: Declares an array of MqlRates to hold price data.
  2. CopyRates(_Symbol, PERIOD_M1, 0, 10, rate);: Copies the last 10 one-minute price bars into the rate array for the symbol specified by _Symbol.
  3. ArraySetAsSeries(rate, true);: Reverse the array as timeseries.
  4. if (copied > 0): Checks if the data retrieval was successful (i.e., at least one data point was copied).
  5. Print(“Last period Open: “, rate[0].open, “, Close: “, rate[0].close);: Prints the open and close prices of the most recent (first) bar in the rate array.

In summary, this code retrieves and prints the open and close prices for the most recent one-minute period of a symbol’s price data.

Conclusion

MQL5 constants, enumerations, and structures significantly enhance code organization and readability. Constants provide standard values, enums group predefined options, and structures bundle related data together. By using these tools effectively, you can reduce errors, simplify your code, and develop more maintainable trading algorithms.

Next: Compilation

Previous: Functions