Русский 中文 Español Deutsch 日本語 Português
preview
Camel Algorithm (CA)

Camel Algorithm (CA)

MetaTrader 5Trading |
1 926 0
Andrey Dik
Andrey Dik

Contents

  1. Introduction
  2. Implementation of the algorithm
  3. Test results


Introduction

In recent decades, a significant number of optimization algorithms have emerged that are inspired by natural phenomena and animal behavior. These bio-inspired approaches have shown excellent results in many tasks. In this article, we will examine a new optimization algorithm called the Camel Algorithm (CA), based on the survival and movement strategies of camels in extreme desert conditions. The algorithm was developed and presented in 2016 by two scientists: Mohammed Khalid Ibrahim and Ramzy Salim Ali.

Camels have unique physiological characteristics and behavioral adaptations that allow them to effectively navigate and survive in harsh desert environments with limited resources, extreme temperatures, and changing landscapes. The CA algorithm models key aspects of this behavior: the influence of temperature, management of water and food supplies, endurance, the effect of "oases" (promising search areas), as well as group interaction in the caravan.

As usual, we will analyze the original algorithm's internals, modify it, and test both versions on test functions. The results will be included in our optimization algorithm ranking table.


Implementation of the algorithm

Imagine a caravan of camels setting out on a journey across a vast desert. Their goal is to find oases of water and food hidden among the endless sands. It was this journey that inspired the authors to create the Camel Algorithm (CA).

The algorithm simulates how these amazing animals survive and find resources in harsh desert conditions. Each camel in the algorithm is a potential solution that explores the search space (the desert) trying to find the optimal solution (the richest oasis). 

Camel caravans travel together for a reason – it is a survival strategy. In the algorithm, a population of "camels" (potential solutions) exchange information about the best routes they have found, much like how real camels in a caravan follow proven paths to water sources.

Key elements:

Temperature (T) — a random factor influencing the behavior of camels. In the desert, temperatures fluctuate from cool nights to hot days, affecting the camels' speed and direction of travel. Camels' unique ability to adapt to extreme temperatures (from cold nights to hot desert days) inspired the "temperature" parameter in the algorithm. This parameter introduces an element of randomness and adaptability, which helps avoid local optima similar to how camels must adapt their route to changing conditions.

Supply (S) — water and food, which gradually become depleted along the way. Camels have evolved to survive in some of the harshest conditions on the planet. Their ability to efficiently allocate resources (water and food) is directly reflected in the algorithm through the "supply" parameter, which decreases over the course of the "journey" and influences the search strategy. The longer a camel travels without finding an oasis, the less energy it has left. This feature makes the algorithm particularly effective in problems with limited computational resources.

Endurance (E) — the camel's energy, depending on the temperature and duration of the journey. The scorching sun slowly saps the caravan's strength. Camels are renowned for their exceptional endurance and their ability to cover long distances with minimal resources. In the algorithm, the "endurance" parameter affects the agent's ability to explore the solution space, gradually decreasing over time and influencing the balance between exploring new areas and exploiting promising solutions already found.

Oasis effect — when a camel finds a promising location (the best solution), its reserves and endurance are restored, allowing it to continue exploring. In the algorithm, when a solution is found, the "supply" and "endurance" parameters are replenished, allowing it to explore the area more thoroughly just like a camel pauses at an oasis to recover strength. This is one of the algorithm's most interesting features.

Random walk — deviations from the main path that help explore new territories.

As shown in the illustration below, a group of five camels are searching for a rich oasis in the desert. Initially they are in different places and move in different directions:

Camel 1 is heading north, but due to the high temperature its speed is slowed down and it has to make more stops.
Camel 2 finds a small oasis (local optimum) with some food and water supplies. It informs the others of its discovery, but continues searching, suspecting that there is a larger oasis somewhere.
Camel 3 wanders across relatively flat terrain, its supplies gradually diminishing, but it continues to explore new directions.
Camel 4 enters an area with very high temperatures, which significantly reduces its endurance. However, random walk helps it get out of this area.
Camel 5, using information from other camels and the favorable direction of the random walk, finds the richest oasis (global optimum).

    camel-algorithm

    Figure 1. CA algorithm operation

    Let's write pseudocode for the CA algorithm:

    // Initialize parameters
    Initialize:
        popSize = population size (camel caravan)
        Tmin = minimum temperature
        Tmax = maximum temperature
        omega = supply load factor
        dyingRate = camels' "death" rate
        alpha = visibility parameter for the oasis effect
        initialSupply = initial supply of water and food (usually 1.0)
        initialEndurance = initial endurance (usually 1.0)
        totalSteps = total number of steps in the path
        traveledSteps = 0 initial value of steps traveled

    // Initialize the initial population
    Create a starting camel caravan (multiple solutions):
        For each camel i from 1 to popSize:
            Generate a random solution within an acceptable range
            Set initial values:
                temperature [i] = random value between Tmin and Tmax
                supply [i] = initialSupply
                endurance [i] = initialEndurance
        
        Calculate the fitness of each camel in the caravan
        Find the current best solution

    // Main optimization loop
    While (traveledSteps < totalSteps):
        traveledSteps++
        
        // For each camel in the caravan
        For i from 1 to popSize:
            // 1. Update factors (temperature, supply, endurance)
            // Equation (1): Tnow = (Tmax - Tmin) * Rand(0,1) + Tmin
            temperature [i] = CalculateTemperature (i)
            
            // Equation (2): Snow = Spast * (1 - ω * Traveled steps/Total journey steps)
            supply [i] = CalculateSupply (i)
            
            // Equation (4): Enow = Epast * (1 - Tnow/Tmax) * (1 - Traveled steps /Total journey steps)
            endurance [i] = CalculateEndurance (i)
            
            // 2. Check if a camel is "dead"
            If (random_number < dyingRate):
                Generate a new random solution for camel i
                Continue to the next iteration
            
            // 3. Update the camel's position
            delta = random number in the range of [-1, 1]  // random walk factor
            Save the old camel coordinates
            
            // For each coordinate
            For each c coordinate:
                // Calculate factors for the update equation
                enduranceFactor = (1.0 - endurance [i] / initialEndurance)
                supplyFactor = exp(1.0 - supply [i] / initialSupply)

                
                // Update position using the equation (6)
                new_position [c] = old_position [c] + delta * enduranceFactor * supplyFactor * (best_position [c] - old_position [c])
                
                // Check for out-of-bounds and adjust if necessary
                new_position [c] = Clamp to the valid range
            
            // 4. Apply the oasis effect
            If (random_number > (1.0 - alpha) AND fitness_new > fitness_old):
                // Found an oasis, replenish supplies and endurance
                supply [i] = initialSupply
                endurance [i] = initialEndurance
            
        // Rank the camels and find the best solution
        Update the best solution

    // Return the final best solution

    Now we can begin writing the code, which will include both the original version of the authors (some strings will be commented out) and my modification, aimed at improving the logic of the algorithm. Let's write the C_AO_CAm class, which will represent the implementation of the CAm algorithm and will inherit from the C_AO base class.

    The class contains parameters specific to the algorithm, such as population size, minimum and maximum temperature, load factor, camel "death" rate, and visibility parameter. These parameters can be set at initialization and are conveniently configurable via the parameters array.

    The class constructor defines the basic properties of the algorithm, including the name, description, and link to the source of the idea, and initializes the parameter array. In the SetParams method, these parameters can be updated at runtime.

    The class implements methods for initializing the population, moving the camels, revising solutions, updating factors, and applying oasis-related effects - everything that simulates the behavior of camels in the desert and seeks optimal solutions. The main properties of the class are arrays storing the temperature of each camel, their water and food reserves, endurance, as well as counters of steps taken and total steps. There are variables that specify the starting levels of reserves and endurance, which are usually initialized at the beginning of the algorithm.

    In general, this class implements a modified version of the optimization algorithm based on the behavior of a camel caravan, where "temperature" and "supply" model intermediate search states, and the dynamics of camel movement and death help to efficiently find a solution.

    //——————————————————————————————————————————————————————————————————————————————
    class C_AO_CAm : public C_AO
    {
      public: //--------------------------------------------------------------------
      ~C_AO_CAm () { }
      C_AO_CAm ()
      {
        ao_name = "CA";
        ao_desc = "Camel Algorithm M";
        ao_link = "https://www.mql5.com/en/articles/18057";
    
        popSize   = 50;     // population size (camel caravan)
        Tmin      = 50;     // minimum temperature
        Tmax      = 100;    // maximum temperature
        omega     = 0.8;    // load factor for 'supply'
        dyingRate = 0.01;   // camels' "death" rate
        alpha     = 0.9;    // visibility parameter for the oasis effect
    
        ArrayResize (params, 6);
    
        params [0].name = "popSize";    params [0].val = popSize;
        params [1].name = "Tmin";       params [1].val = Tmin;
        params [2].name = "Tmax";       params [2].val = Tmax;
        params [3].name = "omega";      params [3].val = omega;
        params [4].name = "dyingRate";  params [4].val = dyingRate;
        params [5].name = "alpha";      params [5].val = alpha;
      }
    
      void SetParams ()
      {
        popSize   = (int)params [0].val;
        Tmin      = params      [1].val;
        Tmax      = params      [2].val;
        omega     = params      [3].val;
        dyingRate = params      [4].val;
        alpha     = params      [5].val;
      }
    
      bool Init (const double &rangeMinP  [],  // minimum values
                 const double &rangeMaxP  [],  // maximum values
                 const double &rangeStepP [],  // step change
                 const int     epochsP = 0);   // number of epochs
    
      void Moving   ();
      void Revision ();
    
      //----------------------------------------------------------------------------
      double Tmin;         // minimum temperature
      double Tmax;         // maximum temperature
      double omega;        // load factor for 'supply'
      double dyingRate;    // camels' "death" rate
      double alpha;        // visibility parameter for the oasis effect
    
      private: //-------------------------------------------------------------------
      double temperature [];   // current temperature for each camel
      double supply      [];   // current supply of water and food for each camel
      double endurance   [];   // current endurance for each camel
      double initialSupply;    // initial supply (usually 1.0)
      double initialEndurance; // initial endurance (usually 1.0)
      int    traveledSteps;    // number of steps taken
      int    totalSteps;       // total number of steps
    
      // Auxiliary methods
      void   InitializePopulation ();
      void   UpdateFactors        ();
      void   UpdatePositions      ();
      void   ApplyOasisEffect     ();
    };
    //——————————————————————————————————————————————————————————————————————————————
    

    The Init method initializes the CAm algorithm. During the execution of this method, the necessary data structures and parameters are prepared for further work. The main steps of the method include calling the standard initialization, which sets the ranges and steps of changing the search variables. If initialization fails, the method fails as well.

    Next, memory is allocated for arrays storing the parameters of each camel—temperature, water and food supply, endurance — the size of which is equal to the size of the population. These arrays are needed to simulate the behavior of camels during optimization. The initial supply and endurance values are set, as well as the total number of steps corresponding to the number of epochs. The number of steps taken is set to zero.

    //——————————————————————————————————————————————————————————————————————————————
    bool C_AO_CAm::Init (const double &rangeMinP  [],  // minimum values
                         const double &rangeMaxP  [],  // maximum values
                         const double &rangeStepP [],  // step change
                         const int     epochsP = 0)    // number of epochs
    {
      if (!StandardInit (rangeMinP, rangeMaxP, rangeStepP)) return false;
    
      //----------------------------------------------------------------------------
      // Initialize arrays for each camel
      ArrayResize (temperature, popSize);
      ArrayResize (supply,      popSize);
      ArrayResize (endurance,   popSize);
    
      // Set initial values
      initialSupply    = 1.0;
      initialEndurance = 1.0;
      traveledSteps    = 0;
      totalSteps       = epochsP;
      
      return true;
    }
    //——————————————————————————————————————————————————————————————————————————————
    

    The Moving method implements the iterative process of the algorithm, responsible for updating the states and movements of the camels. First, it checks whether the first iteration has been completed; if not, it initializes the initial population of camels and marks the initialization complete.

    At each subsequent step, the counter of steps completed increases, after which the following actions are performed sequentially:

    1. Updating factors such as temperature, supply and the endurance of each camel is important for modeling dynamic behavior and search.
    2. Updating the positions of the camels in the search space, that is moving in a direction that will potentially improve the solution.
    3. The use of the oasis effect, where camels can replenish their supply and restore endurance, helps avoid local minima and encourages more complex exploration of space.

    At the end of each step, the fitness function value for each camel is saved so that the current state can be compared with the previous one and, based on this, further decisions can be made.

    //+----------------------------------------------------------------------------+
    //| Basic optimization method                                                  |
    //+----------------------------------------------------------------------------+
    void C_AO_CAm::Moving ()
    {
      // First iteration - initialization of the initial population
      if (!revision)
      {
        InitializePopulation ();
        revision = true;
        return;
      }
    
      // Increase the steps counter
      traveledSteps++;
    
      // Main optimization
      // 1. Update factors (temperature, supply, endurance)
      UpdateFactors ();
    
      // 2. Update the camel positions
      UpdatePositions ();
    
      // 3. apply the oasis effect (replenishment of supply and endurance)
      ApplyOasisEffect ();
    
      // 4. Save the state of camels
      for (int i = 0; i < popSize; i++) a [i].fP = a [i].f;
    }
    //——————————————————————————————————————————————————————————————————————————————
    

    The Revision method is responsible for updating the best solution found in the current camel population. It goes through all the camels in the population and compares the fitness of each camel with the current best value. If the current camel's fitness value (a[i].f) is better than the current best value (fB), then an update occurs:

    1. "fB" is assigned a new best value (a[i].f).
    2. The position (coordinates, parameters) of the camel that has achieved the best value is copied from the coordinates of the current best camel (a[i].c) to the array of coordinates of the best solution (cB). 

    After completing the loop over all camels in the population, fB and cB will contain the value and coordinates of the best solution found in the current iteration.

    //+----------------------------------------------------------------------------+
    //| Update the best solution                                                   |
    //+----------------------------------------------------------------------------+
    void C_AO_CAm::Revision ()
    {
      // Find the best solution in the current population
      for (int i = 0; i < popSize; i++)
      {
        // Update the best solution
        if (a [i].f > fB)
        {
          fB = a [i].f;
          ArrayCopy (cB, a [i].c, 0, 0, WHOLE_ARRAY);
        }
      }
    }
    //——————————————————————————————————————————————————————————————————————————————
    

    The InitializePopulation method is used to form the initial population of camels in the optimization algorithm. It creates a uniform distribution of initial solutions across the entire feasible search space.

    The basic steps of the method involve going through the entire population, that is, all the camels. For each camel, random coordinates are generated within the allowed ranges for each variable (each coordinate). These coordinates are chosen randomly to cover the entire valid range evenly.

    After generating the coordinates, each of them is rounded to the nearest acceptable step, which ensures that the search complies with the discreteness restrictions. This is done to ensure that the initial solutions accurately match the acceptable ranges and steps. Also, each camel is given initial values for parameters such as water supply and endurance, which are determined by pre-set default values for the entire population.

    As a result of the method execution, a starting population of solutions is created, uniformly distributed throughout the entire search space, which helps ensure an efficient start of the optimization.

    //+----------------------------------------------------------------------------+
    //| Initialize the initial population                                          |
    //+----------------------------------------------------------------------------+
    void C_AO_CAm::InitializePopulation ()
    {
      // Initialize the initial population uniformly throughout the space
      for (int i = 0; i < popSize; i++)
      {
        for (int c = 0; c < coords; c++)
        {
          // Generate random coordinates within acceptable limits
          a [i].c [c] = u.RNDfromCI (rangeMin [c], rangeMax [c]);
          // Round to the nearest acceptable step
          a [i].c [c] = u.SeInDiSp (a [i].c [c], rangeMin [c], rangeMax [c], rangeStep [c]);
        }
    
        // Initialize factors for each camel
        supply    [i] = initialSupply;
        endurance [i] = initialEndurance;
      }
    }
    //——————————————————————————————————————————————————————————————————————————————
    

    The UpdateFactors method in the C_AO_CAm class is responsible for updating the key factors that influence the behavior of each "camel" in the population: temperature, supply and endurance. These factors change dynamically at each iteration of the algorithm and influence the search for the optimal solution.

    First, the journeyRatio is calculated, which is the ratio of the number of traveledSteps traveled steps to the totalSteps total number of steps. This value reflects the progress of the algorithm execution. For each camel (i from 0 to popSize -1) the temperature (temperature[i]) is set randomly within the given range from Tmin to Tmax. A new temperature is generated independently for each camel, which introduces randomness into the process.

    The camel's supply (supply [i]) decreases depending on the distance traveled. It is calculated as the previous supply value multiplied by the ratio (1.0 - omega * journeyRatio). The "omega" parameter controls the supply depletion rate. The larger the "omega" and the larger the "journeyRatio" (i.e., the further the algorithm has gone), the faster the supply depletion.

    The camel's endurance (endurance [i]) decreases depending on both the temperature and the distance traveled. Endurance is calculated as the previous endurance value multiplied by (1.0 - temperatureRatio) * (1.0 - journeyRatio). temperatureRatio is the ratio of the camel's current temperature to the Tmax maximum temperature. The higher the temperature and the further the algorithm goes, the more the endurance decreases.

    Thus, the method dynamically changes the characteristics of each camel using both random variables (temperature) and information about the algorithm's progress (distance traveled). These changes affect how camels explore the search space.

    //+----------------------------------------------------------------------------+
    //| Update factors (temperature, supply, endurance)                            |
    //+----------------------------------------------------------------------------+
    void C_AO_CAm::UpdateFactors ()
    {
      double journeyRatio = (double)traveledSteps / (double)totalSteps;
    
      for (int i = 0; i < popSize; i++)
      {
        // Temperature update - random value in the [Tmin, Tmax] range,
        // equation (1): Tnow = (Tmax - Tmin) * Rand(0,1) + Tmin
        temperature [i] = u.RNDfromCI (Tmin, Tmax);
    
        // Supply update - decreases over time,
        // equation (2): Snow = Spast * (1 - ω * Traveled steps / Total journey steps)
        supply [i] = supply [i] * (1.0 - omega * journeyRatio);
    
        // Endurance update depends on temperature and time,
        // equation (4): Enow = Epast * (1 - Tnow/Tmax) * (1 - Traveled steps / Total journey steps)
        double temperatureRatio = temperature [i] / Tmax;
        endurance [i] = endurance [i] * (1.0 - temperatureRatio) * (1.0 - journeyRatio);
      }
    }
    //——————————————————————————————————————————————————————————————————————————————
    

    The UpdatePositions method is designed to update the positions of the camels at each step of the optimization algorithm. It simulates movements and random events that influence decision updating.

    The main steps of the method involve iteration across the entire camel population. For each camel, the following steps are performed:

    1. With some probability (for example, due to unfavorable conditions such as quicksand, or storms, or high temperatures) the camel is considered dead. In this case, its position in space is randomly generated anew within the acceptable range and adjusted according to the minimum steps.

    2. If the camel does not "die", its new position is determined using a random walk model. For each coordinate dimension, a random "delta" factor in the [-1, 1] range is generated to simulate random variation.

    3. The new coordinate is calculated as the old value with the addition of a modifying term that takes into account the random walk, the camel's current characteristics (endurance and supply), and the difference between the current coordinate and the position of the oasis. In this case, the influence of the "endurance" and reserve "supply" is taken into account.

    4. After calculating a new coordinate, it is checked to see if it is outside the acceptable range.

    As a result of this process, the positions of the camels change dynamically, simulating their movements in the search space while taking into account random factors and internal state (endurance and supply). Such updates help the algorithm explore the solution space more efficiently, avoiding local minima and facilitating the search for the optimal solution. 

    The commented code of the original "death" and position re-creation functionality is not used in the current modified version of the algorithm. 

    Key changes in the modified version: the camel's "death" check is now performed for each coordinate separately, rather than for the entire camel; instead of completely randomly generating a new position, a normal (Gaussian) distribution around the best solution (cB) is used; the GaussDistribution function creates a new position based on a normal distribution centered on the best solution, which allows for more targeted exploration of promising areas.

    //+----------------------------------------------------------------------------+
    //| Update camel positions                                                     |
    //+----------------------------------------------------------------------------+
    void C_AO_CAm::UpdatePositions ()
    {
      for (int i = 0; i < popSize; i++)
      {
        /*
        // Checking for camel "death" (quicksand, storm, etc.)
        if (u.RNDprobab () < dyingRate)
        {
          // Generate a new position randomly
          for (int c = 0; c < coords; c++)
          {
            a [i].c [c] = u.RNDfromCI (rangeMin [c], rangeMax [c]);
            a [i].c [c] = u.SeInDiSp (a [i].c [c], rangeMin [c], rangeMax [c], rangeStep [c]);
          }
          continue;
        }
        */
    
        // Updating position-------------------------------------------------------
        double delta = u.RNDfromCI (-1.0, 1.0); // Random walk factor
    
        // Update each coordinate
        for (int c = 0; c < coords; c++)
        {
          /*
          // Apply the update equation from the article
          double enduranceFactor = (1.0 - endurance [i] / initialEndurance);
          double supplyFactor    = MathExp (1.0 - supply [i] / initialSupply);
    
          // Update position
          a [i].c [c] = a [i].c [c] + delta * enduranceFactor * supplyFactor * (cB [c] - a [i].c [c]);
    
          // Check for out-of-bounds and adjust to acceptable value
          a [i].c [c] = u.SeInDiSp (a [i].c [c], rangeMin [c], rangeMax [c], rangeStep [c]);
          */
    
          // Checking for camel "death" (quicksand, storm, etc.)
          if (u.RNDprobab () < dyingRate)
          {
            // Generate a new position relative to the oasis coordinate using a normal distribution
            a [i].c [c] = u.GaussDistribution (cB [c], rangeMin [c], rangeMax [c], 8);
          }
          else
          {
            // Apply the update equation from the article
            double enduranceFactor = (1.0 - endurance [i] / initialEndurance);
            double supplyFactor    = MathExp (1.0 - supply [i] / initialSupply);
    
            // Update position
            a [i].c [c] = a [i].c [c] + delta * enduranceFactor * supplyFactor * (cB [c] - a [i].c [c]);
          }
    
          // Check for out-of-bounds and adjust to acceptable value
          a [i].c [c] = u.SeInDiSp (a [i].c [c], rangeMin [c], rangeMax [c], rangeStep [c]);
        }
      }
    }
    //——————————————————————————————————————————————————————————————————————————————
    

    The ApplyOasisEffect method simulates the effect of an oasis on the condition of camels during the search. Its main task is to determine whether the camel has discovered an oasis and, in doing so, to improve the condition of its resources.

    As it runs through the entire population, the method tests two conditions for each camel. The first one is the probability of finding an oasis, which is determined by a random number and depends on the "alpha" parameter. The higher the "alpha", the greater the chance of detection. The second is to check that the current value of the fitness function (or the quality of the solution) of the camel is better than it had in the previous iteration. This ensures that the oasis only affects those camels whose performance has actually improved.

    If both conditions are met, the camel is considered to have discovered an oasis. In this case, its supply and endurance are reset to their original values. Thus, the oasis promotes the restoration of the camel's resources and allows it to continue actively exploring the search space with increased efficiency.

    The general idea of the method is to simulate the ability of camels to find oases, which allows them to recover and continue searching, improving their chances of reaching the global optimum.

    //+----------------------------------------------------------------------------+
    //| Apply the oasis effect (refresh supply and endurance)                      |
    //+----------------------------------------------------------------------------+
    void C_AO_CAm::ApplyOasisEffect ()
    {
      for (int i = 0; i < popSize; i++)
      {
        // Oasis detection condition:
        // 1) The camel should "see" the oasis (random probability depending on 'alpha')
        // 2) The current solution should be better than the previous iteration
    
        if (u.RNDprobab () > (1.0 - alpha) && a [i].f > a [i].fP)
        {
          // Oasis discovered, replenish supply and endurance
          supply    [i] = initialSupply;
          endurance [i] = initialEndurance;
        }
      }
    }
    //——————————————————————————————————————————————————————————————————————————————
    


    Test results

    As you can see, when running the original version of the CA algorithm, it scores a maximum of 32.56%.

    CA|Camel Algorithm|50.0|50.0|100.0|0.8|0.1|0.5|
    =============================
    5 Hilly's; Func runs: 10000; result: 0.5872886802671936
    25 Hilly's; Func runs: 10000; result: 0.3896531310299016
    500 Hilly's; Func runs: 10000; result: 0.3412707468979892
    =============================
    5 Forest's; Func runs: 10000; result: 0.5248302942062708
    25 Forest's; Func runs: 10000; result: 0.2760893244414008
    500 Forest's; Func runs: 10000; result: 0.18881523788478266
    =============================
    5 Megacity's; Func runs: 10000; result: 0.3507692307692308
    25 Megacity's; Func runs: 10000; result: 0.16676923076923078
    500 Megacity's; Func runs: 10000; result: 0.10464615384615475
    =============================
    All score: 2.93013 (32.56%)

    The modified algorithm shows better results:

    CAm|Camel Algorithm|50.0|50.0|100.0|0.8|0.01|0.9|
    =============================
    5 Hilly's; Func runs: 10000; result: 0.786842172387197
    25 Hilly's; Func runs: 10000; result: 0.560421361070792
    500 Hilly's; Func runs: 10000; result: 0.3513297097198401
    =============================
    5 Forest's; Func runs: 10000; result: 0.8277193604225209
    25 Forest's; Func runs: 10000; result: 0.5604138230149972
    500 Forest's; Func runs: 10000; result: 0.24335977579892912
    =============================
    5 Megacity's; Func runs: 10000; result: 0.6484615384615386
    25 Megacity's; Func runs: 10000; result: 0.33092307692307693
    500 Megacity's; Func runs: 10000; result: 0.13417692307692433
    =============================
    All score: 4.44365 (49.37%)

    Visualization of the algorithm operation is presented for the CA and CAm versions, for a better understanding of the differences between the two algorithms. Both versions exhibit the "clumping" in the vicinity of potentially good solutions characteristic of the algorithm's logic.

    Hilly

    CA on the Hilly test function

      Hilly

    CAm on the Hilly test function

    Forest

    CA on the Forest test function

        Forest

    CAm on the Forest test function

    Megacity

    CA on the Megacity test function

    Megacity

    CAm on the Megacity test function

    The modified version of the algorithm is ranked 35th in the ranking of population optimization algorithms. The original version is presented for information purposes only and does not have a ranking.

    # AO Description Hilly Hilly
    Final
    Forest Forest
    Final
    Megacity (discrete) Megacity
    Final
    Final
    Result
    % of
    MAX
    10 p (5 F) 50 p (25 F) 1000 p (500 F) 10 p (5 F) 50 p (25 F) 1000 p (500 F) 10 p (5 F) 50 p (25 F) 1000 p (500 F)
    1 ANS across neighbourhood search 0.94948 0.84776 0.43857 2.23581 1.00000 0.92334 0.39988 2.32323 0.70923 0.63477 0.23091 1.57491 6.134 68.15
    2 CLA code lock algorithm (joo) 0.95345 0.87107 0.37590 2.20042 0.98942 0.91709 0.31642 2.22294 0.79692 0.69385 0.19303 1.68380 6.107 67.86
    3 AMOm animal migration ptimization M 0.90358 0.84317 0.46284 2.20959 0.99001 0.92436 0.46598 2.38034 0.56769 0.59132 0.23773 1.39675 5.987 66.52
    4 (P+O)ES (P+O) evolution strategies 0.92256 0.88101 0.40021 2.20379 0.97750 0.87490 0.31945 2.17185 0.67385 0.62985 0.18634 1.49003 5.866 65.17
    5 CTA comet tail algorithm (joo) 0.95346 0.86319 0.27770 2.09435 0.99794 0.85740 0.33949 2.19484 0.88769 0.56431 0.10512 1.55712 5.846 64.96
    6 TETA time evolution travel algorithm (joo) 0.91362 0.82349 0.31990 2.05701 0.97096 0.89532 0.29324 2.15952 0.73462 0.68569 0.16021 1.58052 5.797 64.41
    7 SDSm stochastic diffusion search M 0.93066 0.85445 0.39476 2.17988 0.99983 0.89244 0.19619 2.08846 0.72333 0.61100 0.10670 1.44103 5.709 63.44
    8 BOAm billiards optimization algorithm M 0.95757 0.82599 0.25235 2.03590 1.00000 0.90036 0.30502 2.20538 0.73538 0.52523 0.09563 1.35625 5.598 62.19
    9 AAm archery algorithm M 0.91744 0.70876 0.42160 2.04780 0.92527 0.75802 0.35328 2.03657 0.67385 0.55200 0.23738 1.46323 5.548 61.64
    10 ESG evolution of social groups (joo) 0.99906 0.79654 0.35056 2.14616 1.00000 0.82863 0.13102 1.95965 0.82333 0.55300 0.04725 1.42358 5.529 61.44
    11 SIA simulated isotropic annealing (joo) 0.95784 0.84264 0.41465 2.21513 0.98239 0.79586 0.20507 1.98332 0.68667 0.49300 0.09053 1.27020 5.469 60.76
    12 ACS artificial cooperative search 0.75547 0.74744 0.30407 1.80698 1.00000 0.88861 0.22413 2.11274 0.69077 0.48185 0.13322 1.30583 5.226 58.06
    13 DA dialectical algorithm 0.86183 0.70033 0.33724 1.89940 0.98163 0.72772 0.28718 1.99653 0.70308 0.45292 0.16367 1.31967 5.216 57.95
    14 BHAm black hole algorithm M 0.75236 0.76675 0.34583 1.86493 0.93593 0.80152 0.27177 2.00923 0.65077 0.51646 0.15472 1.32195 5.196 57.73
    15 ASO anarchy society optimization 0.84872 0.74646 0.31465 1.90983 0.96148 0.79150 0.23803 1.99101 0.57077 0.54062 0.16614 1.27752 5.178 57.54
    16 RFO royal flush optimization (joo) 0.83361 0.73742 0.34629 1.91733 0.89424 0.73824 0.24098 1.87346 0.63154 0.50292 0.16421 1.29867 5.089 56.55
    17 AOSm atomic orbital search M 0.80232 0.70449 0.31021 1.81702 0.85660 0.69451 0.21996 1.77107 0.74615 0.52862 0.14358 1.41835 5.006 55.63
    18 TSEA turtle shell evolution algorithm (joo) 0.96798 0.64480 0.29672 1.90949 0.99449 0.61981 0.22708 1.84139 0.69077 0.42646 0.13598 1.25322 5.004 55.60
    19 DE differential evolution 0.95044 0.61674 0.30308 1.87026 0.95317 0.78896 0.16652 1.90865 0.78667 0.36033 0.02953 1.17653 4.955 55.06
    20 SRA successful restaurateur algorithm (joo) 0.96883 0.63455 0.29217 1.89555 0.94637 0.55506 0.19124 1.69267 0.74923 0.44031 0.12526 1.31480 4.903 54.48
    21 CRO chemical reaction optimization 0.94629 0.66112 0.29853 1.90593 0.87906 0.58422 0.21146 1.67473 0.75846 0.42646 0.12686 1.31178 4.892 54.36
    22 BIO blood inheritance optimization (joo) 0.81568 0.65336 0.30877 1.77781 0.89937 0.65319 0.21760 1.77016 0.67846 0.47631 0.13902 1.29378 4.842 53.80
    23 BSA bird swarm algorithm 0.89306 0.64900 0.26250 1.80455 0.92420 0.71121 0.24939 1.88479 0.69385 0.32615 0.10012 1.12012 4.809 53.44
    24 HS harmony search 0.86509 0.68782 0.32527 1.87818 0.99999 0.68002 0.09590 1.77592 0.62000 0.42267 0.05458 1.09725 4.751 52.79
    25 SSG saplings sowing and growing 0.77839 0.64925 0.39543 1.82308 0.85973 0.62467 0.17429 1.65869 0.64667 0.44133 0.10598 1.19398 4.676 51.95
    26 BCOm bacterial chemotaxis optimization M 0.75953 0.62268 0.31483 1.69704 0.89378 0.61339 0.22542 1.73259 0.65385 0.42092 0.14435 1.21912 4.649 51.65
    27 ABO african buffalo optimization 0.83337 0.62247 0.29964 1.75548 0.92170 0.58618 0.19723 1.70511 0.61000 0.43154 0.13225 1.17378 4.634 51.49
    28 (PO)ES (PO) evolution strategies 0.79025 0.62647 0.42935 1.84606 0.87616 0.60943 0.19591 1.68151 0.59000 0.37933 0.11322 1.08255 4.610 51.22
    29 FBA Fractal-Based Algorithm 0.79000 0.65134 0.28965 1.73099 0.87158 0.56823 0.18877 1.62858 0.61077 0.46062 0.12398 1.19537 4.555 50.61
    30 TSm tabu search M 0.87795 0.61431 0.29104 1.78330 0.92885 0.51844 0.19054 1.63783 0.61077 0.38215 0.12157 1.11449 4.536 50.40
    31 BSO brain storm optimization 0.93736 0.57616 0.29688 1.81041 0.93131 0.55866 0.23537 1.72534 0.55231 0.29077 0.11914 0.96222 4.498 49.98
    32 WOAm wale optimization algorithm M 0.84521 0.56298 0.26263 1.67081 0.93100 0.52278 0.16365 1.61743 0.66308 0.41138 0.11357 1.18803 4.476 49.74
    33 AEFA artificial electric field algorithm 0.87700 0.61753 0.25235 1.74688 0.92729 0.72698 0.18064 1.83490 0.66615 0.11631 0.09508 0.87754 4.459 49.55
    34 AEO artificial ecosystem-based optimization algorithm 0.91380 0.46713 0.26470 1.64563 0.90223 0.43705 0.21400 1.55327 0.66154 0.30800 0.28563 1.25517 4.454 49.49
    35 CAm camel algorithm M 0.78684 0.56042 0.35133 1.69859 0.82772 0.56041 0.24336 1.63149 0.64846 0.33092 0.13418 1.11356 4.444 49.37
    36 ACOm ant colony optimization M 0.88190 0.66127 0.30377 1.84693 0.85873 0.58680 0.15051 1.59604 0.59667 0.37333 0.02472 0.99472 4.438 49.31
    37 BFO-GA bacterial foraging optimization - ga 0.89150 0.55111 0.31529 1.75790 0.96982 0.39612 0.06305 1.42899 0.72667 0.27500 0.03525 1.03692 4.224 46.93
    38 SOA simple optimization algorithm 0.91520 0.46976 0.27089 1.65585 0.89675 0.37401 0.16984 1.44060 0.69538 0.28031 0.10852 1.08422 4.181 46.45
    39 ABHA artificial bee hive algorithm 0.84131 0.54227 0.26304 1.64663 0.87858 0.47779 0.17181 1.52818 0.50923 0.33877 0.10397 0.95197 4.127 45.85
    40 ACMO atmospheric cloud model optimization 0.90321 0.48546 0.30403 1.69270 0.80268 0.37857 0.19178 1.37303 0.62308 0.24400 0.10795 0.97503 4.041 44.90
    41 ADAMm adaptive moment estimation M 0.88635 0.44766 0.26613 1.60014 0.84497 0.38493 0.16889 1.39880 0.66154 0.27046 0.10594 1.03794 4.037 44.85
    42 CGO chaos game optimization 0.57256 0.37158 0.32018 1.26432 0.61176 0.61931 0.62161 1.85267 0.37538 0.21923 0.19028 0.78490 3.902 43.35
    43 ATAm artificial tribe algorithm M 0.71771 0.55304 0.25235 1.52310 0.82491 0.55904 0.20473 1.58867 0.44000 0.18615 0.09411 0.72026 3.832 42.58
    44 CROm coral reefs optimization M 0.78512 0.46032 0.25958 1.50502 0.86688 0.35297 0.16267 1.38252 0.63231 0.26738 0.10734 1.00703 3.895 43.27
    45 CFO central force optimization 0.60961 0.54958 0.27831 1.43750 0.63418 0.46833 0.22541 1.32792 0.57231 0.23477 0.09586 0.90294 3.668 40.76
    CA camel algorithm 0.58729 0.38965 0.34127 1.31821 0.52483 0.27609 0.18882 0.98974 0.35077 0.16677 0.10465 0.62219 2.930 32.56
    RW neuroboids optimization algorithm 2(joo) 0.48754 0.32159 0.25781 1.06694 0.37554 0.21944 0.15877 0.75375 0.27969 0.14917 0.09847 0.52734 2.348 26.09


    Summary

    The modified version of the CAm camel algorithm demonstrates significantly higher performance than the original, thanks to a number of key improvements.

    First of all, the camel's "death" mechanism has been fundamentally changed: instead of completely randomly generating new solutions, a Gaussian distribution is used around the best solution found, which ensures a targeted and intensive search in the most promising areas.

    Accurate tracking of solution improvements by storing previous fitness function values for each camel ensures more accurate application of the oasis effect. Increasing the flexibility of the algorithm by adding "Tmin" to the adjustable parameters and using an external parameter to determine the total number of steps makes CAm more adaptive to different types of optimization problems.

    Taken together, these improvements significantly enhance the modified version in terms of convergence speed, solution accuracy, and stability.

    chart

    Figure 2. Color gradation of algorithms according to the corresponding tests

    chart

    Figure 3. Histogram of algorithm testing results (scale from 0 to 100, the higher the better, where 100 is the maximum possible theoretical result, in the archive there is a script for calculating the rating table)

    CAm pros and cons:

    Pros:

    1. Fast.
    2. Simple implementation.
    3. Good results on functions of large and medium dimensions (especially on "smooth" problems).

    Cons:

    1. A large number of external parameters.
    2. Scatter of results on low-dimensional functions.

    The article is accompanied by an archive with the current versions of the algorithm codes. The author of the article is not responsible for the absolute accuracy in the description of canonical algorithms. Changes have been made to many of them to improve search capabilities. The conclusions and judgments presented in the articles are based on the results of the experiments.


    Programs used in the article

    # Name Type Description
    1 #C_AO.mqh
    Include
    Parent class of population optimization algorithms
    2 #C_AO_enum.mqh
    Include
    Enumeration of population optimization algorithms
    3 TestFunctions.mqh
    Include
    Library of test functions
    4
    TestStandFunctions.mqh
    Include
    Test stand function library
    5
    Utilities.mqh
    Include
    Library of auxiliary functions
    6
    CalculationTestResults.mqh
    Include
    Script for calculating results in the comparison table
    7
    Testing AOs.mq5
    Script The unified test stand for all population optimization algorithms
    8
    Simple use of population optimization algorithms.mq5
    Script
    A simple example of using population optimization algorithms without visualization
    9
    Test_AO_CAm.mq5
    Script CAm test stand

    Translated from Russian by MetaQuotes Ltd.
    Original article: https://www.mql5.com/ru/articles/18057

    Attached files |
    CA.zip (213.16 KB)
    Integrating Computer Vision into Trading in MQL5 (Part 2): Extending the Architecture to 2D RGB Image Analysis Integrating Computer Vision into Trading in MQL5 (Part 2): Extending the Architecture to 2D RGB Image Analysis
    Computer vision for trading: how it works and how to develop it step by step. We create an algorithm for recognition of RGB images of price charts using the attention mechanism and a bidirectional LSTM layer. As a result, we obtain a working model for forecasting the EURUSD price with the accuracy of up to 55% in the validation section.
    Hilbert-Schmidt Independence Criterion (HSIC) Hilbert-Schmidt Independence Criterion (HSIC)
    The article discusses the non-parametric HSIC (Hilbert-Schmidt Independence Criterion) statistical test designed to identify linear and non-linear dependencies in data. Implementations of two algorithms for calculating HSIC in the MQL5 language are proposed: the exact permutation test and the gamma approximation. The method efficiency is demonstrated on synthetic data modeling a non-linear relationship between features and the target variable.
    Building a Trade Analytics System (Part 1): Foundation and System Architecture Building a Trade Analytics System (Part 1): Foundation and System Architecture
    We design a simple external trade analytics pipeline for MetaTrader 5 and implement its backend in Python with Flask and SQLite. The article defines the architecture, data model, and versioned API, and shows how to configure the environment, initialize the database, and run the server locally. As a result, you get a clean base to capture closed-trade records from MetaTrader 5 and store them for later analysis.
    Automating Market Entropy Indicator: Trading System Based on Information Theory Automating Market Entropy Indicator: Trading System Based on Information Theory
    This article presents an EA that automates the previously introduced Market Entropy methodology. It computes fast and slow entropy, momentum, and compression states, validates signals, and executes orders with SL/TP and optional position reversal. The result is a practical, configurable tool that applies information-theoretic signals without manual interpretation.