MQL4 ArraySort Explained: Basics to Advanced Uses

※記事内に広告を含む場合があります。
目次

1. Introduction

MQL4 and the Importance of Array Operations

MQL4 is a programming language used to create automated trading programs (EAs) and custom indicators on the MetaTrader 4 (MT4) platform. In MQL4, which enables data analysis and automation of trading strategies in financial markets, the skill of manipulating arrays is extremely important. Arrays are a fundamental data structure for efficiently managing price data and indicator values.

Among them, the ArraySort function is a convenient tool for sorting array elements. By correctly understanding and utilizing this function, you can streamline trading strategies and data analysis.

Purpose of This Article

This article provides a detailed explanation of MQL4’s ArraySort function, covering everything from basic usage to advanced applications. It is presented in an easy-to-understand manner for beginners, incorporating practical examples throughout.

2. What is the ArraySort function?

Overview of the ArraySort function

ArraySort is a built-in function in MQL4 for sorting arrays in ascending or descending order. The sorting process can be used to arrange price data, time data, and even sort based on custom conditions.

Below is the syntax of this function.

int ArraySort(
    void &array[],
    int count=WHOLE_ARRAY,
    int start=0,
    int direction=MODE_ASCEND
);

Explanation of main parameters

  1. array[]:
    Specify the array to be sorted. This array must be one-dimensional.
  2. count:
    Specify the number of elements to sort. By default, the entire array (WHOLE_ARRAY) is targeted.
  3. start:
    Specify the index at which to start sorting. The default is 0 (the beginning of the array).
  4. direction:
    Specify the direction of sorting.
  • MODE_ASCEND: Ascending (smallest first)
  • MODE_DESCEND: Descending (largest first)

Example: Basic sorting

Below is an example of basic ascending sort.

double prices[] = {1.2345, 1.1234, 1.5678, 1.3456};
ArraySort(prices);

// After sorting: {1.1234, 1.2345, 1.3456, 1.5678}

In this code, the ArraySort function is used to sort price data in ascending order.

3. Basic Usage

Simple Array Sorting

The most basic usage is to sort a single array in ascending or descending order. Below is an example.

Ascending Sort

double values[] = {5.5, 2.2, 8.8, 1.1};
ArraySort(values);

// After sorting: {1.1, 2.2, 5.5, 8.8}

Descending Sort

double values[] = {5.5, 2.2, 8.8, 1.1};
ArraySort(values, WHOLE_ARRAY, 0, MODE_DESCEND);

// After sorting: {8.8, 5.5, 2.2, 1.1}

Specify Sort Start Position

The following code demonstrates sorting only a specific portion.

double data[] = {9.9, 7.7, 3.3, 5.5};
ArraySort(data, 2, 1); // Sort 2 elements starting from index 1

// After sorting: {9.9, 3.3, 7.7, 5.5}

In this code, starting from index 1 (7.7), two elements (7.7 and 3.3) are sorted in ascending order.

4. Applications of the ArraySort Function

Examples of Complex Sorting Conditions

The ArraySort function is very effective when sorting according to specific conditions, in addition to basic ascending and descending order. For example, situations where you sort by combining price and time can be considered.

Example of Sorting with Multiple Conditions

The following code demonstrates sorting of date and price data.

// Date data and price data
datetime dates[] = {20221101, 20221103, 20221102};
double prices[] = {1.2345, 1.1234, 1.3456};

// Sort dates
ArraySort(dates); // Sort dates

// Reconstruct price data based on dates
double sorted_prices[ArraySize(prices)];
for (int i = 0; i < ArraySize(prices); i++)
{
    int index = ArrayBsearch(dates, dates[i], 0, WHOLE_ARRAY);
    sorted_prices[i] = prices[index];
}

// After sorting:
// dates: {20221101, 20221102, 20221103}
// sorted_prices: {1.2345, 1.3456, 1.1234}

In this example, ArraySort and ArrayBsearch are combined to perform sorting while maintaining data linkage.

Partial Sorting of Multidimensional Arrays

In MQL4, you cannot directly sort multidimensional arrays. However, it is common to extract the required columns or rows into a one-dimensional array, sort them, and then reconstruct.

Example of Sorting a Multidimensional Array

// Multidimensional array (rows: date, columns: price)
double data[][2] = {{20221101, 1.2345}, {20221103, 1.1234}, {20221102, 1.3456}};

// Sort based on date
double temp[3]; // Temporary one-dimensional array
for (int i = 0; i < ArraySize(data); i++)
    temp[i] = data[i][0]; // Extract date

ArraySort(temp); // Sort dates ascending

// Reconstruct multidimensional array based on sort results
double sorted_data[3][2];
for (int i <= ArraySize(temp); i++)
{
    for (int j = 0; j < ArraySize(data); j++)
    {
        if (temp[i] == data[j][0])
        {
            sorted_data[i][0] = data[j][0];
            sorted_data[i][1] = data[j][1];
            break;
        }
    }
}

// After sorting: {{20221101, 1.2345}, {20221102, 1.3456}, {20221103, 1.1234}}

Sorting with Performance in Mind

When handling large amounts of data, sorting performance is critical. Below are tips for efficiently using the ArraySort function.

  1. Filter out unnecessary data beforehand:
    By removing unwanted elements from the array, you minimize the sorting target.
   ArrayResize(array, count); // Resize to the required size
  1. Limit the sorting range:
    Instead of sorting the entire array, sorting only the necessary portion reduces computational load.
   ArraySort(array, 50, 10); // Sort only 10th to 50th items
  1. Use appropriate data types:
    Selecting the right data type optimizes memory usage (e.g., using float instead of double).

5. Limitations and Cautions of the ArraySort Function

Constraints on Array Types

ArraySort function can only be used with specific data types. Please note the following points.

  1. Supported data types:
  • Numeric types (int, double, float): sortable
  • String type (string): sortable
  • Other types (e.g., bool, datetime): sortable, but be careful about the meaning of order
  1. When sorting is invalid:
    Multi-dimensional arrays cannot be directly sorted with ArraySort. You need to extract specific columns or rows into a one-dimensional array, sort, and reconstruct.

Example: Unsupported multi-dimensional array

double matrix[][2] = {{1.2, 2.3}, {3.4, 4.5}};
// ArraySort(matrix); // Will cause an error

Reliability of Sort Results

When using ArraySort, if the array contains duplicate values, their order is not guaranteed. This is said to not be a stable sort (where the order of equal values is preserved after sorting).

Example: When not a stable sort

double array[] = {2.2, 1.1, 2.2, 3.3};
ArraySort(array);
// Sort result: {1.1, 2.2, 2.2, 3.3} (order is not preserved)

If necessary, you need to implement custom conditions to achieve behavior similar to a stable sort.

Error Handling

The ArraySort function rarely fails, but errors can occur due to array state or parameter misconfiguration. Below are typical errors and their causes.

  1. When the array is empty:
    If the array is empty (ArraySize(array) == 0), sorting will not be performed.
   double emptyArray[];
   ArraySort(emptyArray); // Will not be sorted
  1. Invalid index specification:
    If the sort range (start and count) exceeds the array size, unexpected behavior may occur.
   double array[] = {5.0, 3.0, 1.0};
   ArraySort(array, 5, 2); // Can cause errors or invalid behavior

Example code to prevent errors

double array[] = {1.0, 2.0, 3.0};
int size = ArraySize(array);

if (size > 0) {
   ArraySort(array, size, 0, MODE_ASCEND);
} else {
   Print("Array is empty");
}

Performance Issues

When sorting large amounts of data, be aware of the algorithmic complexity (O(n log n)). The following methods can improve performance.

  1. Partial sorting:
    Reduces computational cost by sorting only the necessary portion.
   ArraySort(array, 50); // Sort only the first 50 elements
  1. Pre-filter data:
    Exclude unnecessary data before sorting.
   ArrayResize(array, newSize);
  1. Use appropriate data types:
    Optimize memory usage by selecting suitable data types (e.g., use float instead of double).

6. Practical Use Cases

Sorting Trade History Data

Below is an example of organizing trade history data using ArraySort.

Actual Code Example

// Trade history data (date and profit amount)
datetime tradeDates[] = {20221102, 20221101, 20221103};
double profits[] = {100.0, 50.0, 150.0};

// Sort dates in ascending order and align profits accordingly
ArraySort(tradeDates);

double sorted_profits[ArraySize(profits)];
for (int i = 0; i < ArraySize(tradeDates); i++) {
   int index = ArrayBsearch(tradeDates, tradeDates[i], 0, WHOLE_ARRAY);
   sorted_profits[i] = profits[index];
}

// After sorting:
// tradeDates: {20221101, 20221102, 20221103}
// sorted_profits: {50.0, 100.0, 150.0}

Using in Custom Indicators

For example, you can also use ArraySort to reorder moving averages based on specific conditions.

7. Frequently Asked Questions (FAQ)

How can I sort only a portion of an array?

By using the start and count parameters of the ArraySort function, you can sort only a portion of an array.

Example: Sorting a portion of an array

double data[] = {9.0, 3.0, 7.0, 1.0, 5.0};
ArraySort(data, 3, 1); // Sort three elements starting from index 1 in ascending order

// After sorting: {9.0, 1.0, 3.0, 7.0, 5.0}

In this example, only three elements starting from index 1 (3.0) are sorted.

Descending sort is not working correctly. What should I do?

When performing a descending sort, you need to specify MODE_DESCEND for the direction parameter. If not specified, it defaults to ascending order.

Correct example of descending sort

double data[] = {2.2, 3.3, 1.1};
ArraySort(data, WHOLE_ARRAY, 0, MODE_DESCEND);

// After sorting: {3.3, 2.2, 1.1}

Note: If MODE_DESCEND is not specified, the result may be in an unintended order.

Is there a way to efficiently process multidimensional arrays?

Since the ArraySort function in MQL4 does not directly support multidimensional arrays, we recommend processing them efficiently using methods such as the following.

Method 1: Convert to a one-dimensional array and sort

Extract specific columns or rows of the multidimensional array as a one-dimensional array and sort it.

Method 2: Reconstruct the array based on the index of the column to be sorted

In the following example, the multidimensional array is sorted based on the second column (price data).

double data[][2] = {{1.0, 3.3}, {2.0, 1.1}, {3.0, 2.2}};
double temp[ArraySize(data)];

// Extract the second column (price data) and sort
for (int i = 0; i < ArraySize(data); i++) {
   temp[i] = data[i][1];
}
ArraySort(temp); // Sort prices in ascending order

// Reconstruct the multidimensional array based on the sorted results
double sorted_data[ArraySize(data)][2];
for (int i = 0; i < ArraySize(temp); i++) {
   for (int j = 0; j < ArraySize(data); j++) {
       if (temp[i] == data[j][1]) {
           sorted_data[i][0] = data[j][0];
           sorted_data[i][1] = data[j][1];
           break;
       }
   }
}

// After sorting:
// sorted_data: {{2.0, 1.1}, {3.0, 2.2}, {1.0, 3.3}}

Is there a way to prevent errors when the array is empty?

The ArraySort function does not work on an empty array. Therefore, you need to check whether the array is empty beforehand.

Example of checking if the array is empty

double data[];

if (ArraySize(data) > 0) {
   ArraySort(data);
} else {
   Print("The array is empty.");
}

Can duplicate values within an array be handled correctly?

The ArraySort function can correctly sort duplicate values within an array, but the order of identical values is not guaranteed (unstable sort). If a stable sort is required, you need to manually adjust it as follows.

Example of manually preserving order

// Record the values in the array and their original indices
double data[] = {2.2, 1.1, 2.2, 3.3};
int indexes[ArraySize(data)];
for (int i = 0; i < ArraySize(data); i++) {
   indexes[i] = i;
}

// Create a helper function for sorting and implement a custom sort
// Reconstruct the original indices after sorting

8. Summary and Next Steps

Reviewing the Key Points of the ArraySort Function

  • Basic Role:
    The ArraySort function is a convenient tool for sorting arrays in ascending or descending order.
  • Main Features:
    It can be used for partial sorting of arrays, sorting based on specific conditions, indirect manipulation of multidimensional arrays, and many other wide-ranging applications.
  • Limitations and Caveats:
    There are several constraints, such as handling of array types and multidimensional arrays, and the fact that stable sorting is not guaranteed.

Next Steps

To deepen your understanding of array operations in MQL4, we recommend studying the following topics.

  1. ArrayResize Function:
    Understand how to change the size of arrays, enabling dynamic data manipulation.
  2. ArrayCopy Function:
    Efficiently copy arrays, expanding the scope of data manipulation.
  3. Implementing Custom Sort Logic:
    Advanced techniques for when complex sorting conditions are required.
  • As a next step, refer to other articles and official documentation, and try using ArraySort practically in your own EA!

Reference Sites

ArraySort - Array Functions - MQL4 Reference…

EXPO blog 投資の翼

配列操作の重要性 MQL4における配列操作は、効率的なプログラム作成の鍵です。配列を使用することで、大量のデータを一元管…

※記事内に広告を含む場合があります。
佐川 直弘: MetaTraderを活用したFX自動売買の開発で15年以上の経験を持つ日本のパイオニア🔧

トレーデンシー大会'15世界1位🥇、EA-1グランプリ準優勝🥈の実績を誇り、ラジオ日経出演経験もあり!
現在は、株式会社トリロジーの役員として活動中。
【財務省近畿財務局長(金商)第372号】に登録
され、厳しい審査を経た信頼性の高い投資助言者です。


【主な活動内容】
・高性能エキスパートアドバイザー(EA)の開発と提供
・最新トレーディング技術と市場分析の共有
・FX取引の効率化と利益最大化を目指すプロの戦略紹介

トレーダー向けに役立つ情報やヒントを発信中!

This website uses cookies.