Русский Español Português
preview
Forex Arbitrage Trading: A Matrix Trading System for Return to Fair Value with Risk Control

Forex Arbitrage Trading: A Matrix Trading System for Return to Fair Value with Risk Control

MetaTrader 5Trading systems |
744 4
Yevgeniy Koshtenko
Yevgeniy Koshtenko

Introduction

There are countless strategies in the world of algorithmic trading, but only a few possess the mathematical elegance and fundamental logic that underpins financial markets. Today I want to introduce you to a system that embodies exactly these qualities – matrix arbitrage in the Forex market, based on the concept of fair value of currencies.

Imagine a market where the eight major world currencies form a complex web of relationships, in which each currency pair must be in perfect balance with all the others. In theory, this network should be perfectly balanced, but in practice, we observe constant microscopic imperfections — temporary deviations from fair value that create unique opportunities for profit.

These deviations are not just random noise. They represent imbalances that the market sooner or later corrects, returning to a state of equilibrium. It is this mathematical inevitability that we will learn to utilize in our trading system, without relying on technical indicators or subjective analysis, but based solely on the inexorable logic of numbers and probabilities.

What is particularly attractive about this strategy is its versatility and independence from market regimes. While most systems only work in certain conditions: trending, flat, or high volatility, our matrix system functions in any market environment because it relies on fundamental mathematical laws rather than fleeting market sentiment.

In this article, we will not only present the theoretical concept but also demonstrate a fully automated trading system, implemented in MQL5, that brings this idea to life, featuring intelligent risk management, adaptive position sizing, and a visual imbalance matrix for monitoring market opportunities in real time. We will delve into a world where mathematical precision meets financial markets, creating an elegant approach to profiting from the imperfections of the global monetary system.



Matrix arbitrage system operation principle

Our matrix system is based on a concept that can be called "triangular arbitrage on steroids." Traditional triangular arbitrage involves looking for imbalances between three currency pairs. Our system takes this approach to a whole new level by creating a multidimensional matrix of relationships between all the major currencies of the Forex market.

Mathematical foundation of strategy

Each currency in our system is represented as a vertex in a multidimensional graph, where the edges are the exchange rates between currencies. An ideal balanced system should have the property of transitivity: if we know the EURUSD and USDJPY rates, then the EURJPY rate should be their product. However, in reality, the Forex market is a living organism, where temporary inefficiencies constantly arise.

Our system tracks these inefficiencies by calculating a "fair value" for each currency pair based on all other currency pairs. When the current market price deviates significantly from this calculated fair value, this creates a potential market entry opportunity.

Trading system architecture

The EA creates and continuously updates the 8x8 matrix representing the relationships between the major currencies: EUR, USD, GBP, JPY, CHF, CAD, AUD and NZD. Each cell of the matrix contains not just the current rate, but the "fair" rate, calculated taking into account all possible cross rates.

// Exchange rate matrix (fair values)
// Use a one-dimensional array to implement a two-dimensional matrix
double g_currency_matrix[];

Important technical point: in the code, we use a one-dimensional array to efficiently implement a two-dimensional matrix, which ensures more efficient use of memory and improves the performance of the EA when working with a large number of currency pairs.

Fair value calculation

Determining fair value begins with initializing the matrix, where the diagonal elements are filled with ones. After all, the exchange rate of a currency to itself is always equal to 1 - this is an axiom of our system. Then, the matrix is filled with current market rates – the same prices we see in the terminal.

But the real magic begins in the next step – iteratively refining all the values in the matrix. Here, all possible cross rates are calculated when the system analyzes currency relationships through third currencies. Think of it as exploring "workarounds" - if we can get a better EURJPY rate via USD, the system will detect it.

The algorithm for calculating cross rates is particularly elegant:

void CalculateCrossRatesArbitrage()
{
   // Several iterations to refine the matrix
   for(int iterations = 0; iterations < 3; iterations++)
   {
      for(int i = 0; i < g_currencies_count; i++)
      {
         for(int j = 0; j < g_currencies_count; j++)
         {
            if(i == j) continue;
            
            for(int k = 0; k < g_currencies_count; k++)
            {
               if(k == i || k == j) continue;
               
               double ik_value = GetMatrixValue(i, k);
               double kj_value = GetMatrixValue(k, j);
               
               if(ik_value != 0 && kj_value != 0)
               {
                  double triangleRate = ik_value * kj_value;
                  double current_value = GetMatrixValue(i, j);
                  
                  if(current_value == 0)
                     SetMatrixValue(i, j, triangleRate);
                  else
                     SetMatrixValue(i, j, (current_value * 0.7 + triangleRate * 0.3));
                  
                  current_value = GetMatrixValue(i, j);
                  if(current_value != 0)
                     SetMatrixValue(j, i, 1.0 / current_value);
               }
            }
         }
      }
   }
}

Note the fine-tuning in the form of weighting factors of 0.7 and 0.3. These are not random numbers, but the result of numerous tests. We give more weight to direct quotes, but at the same time we do not ignore information obtained through cross rates. This proportion creates an ideal balance between stability and the system's sensitivity to market inefficiencies.

Trading logic and risk management

Once the fair value matrix has been created, it is time to make trading decisions. The system calculates the percentage deviation of the current market price from the fair value for each currency pair. This is expressed by an elegant equation:

g_market_rates[i].discrepancy = (g_market_rates[i].median / g_market_rates[i].fair_value - 1.0) * 100.0;

When the deviation exceeds a user-defined threshold, the system sees a potential profit opportunity. A negative deviation means that the market is undervaluing the currency relative to its fair value – it is a buy signal. A positive deviation indicates overvaluation – a sell signal.

Intelligent risk management is not just an add-on feature, but an integral part of our system. The position size calculation function takes into account not only the user-specified risk level, but also the specifics of a particular currency pair: pip value, volatility, and minimum and maximum lot sizes. This allows the system to adapt to different market conditions and maintain the same level of risk, regardless of the instrument being traded.

Visualization and monitoring

One of the main treasures of our system is the visualization of the currency imbalance matrix directly on the chart. This is not just a set of abstract numbers, but an interactive map of opportunities that updates in real time with every market move:

=== CURRENCY IMBALANCE MATRIX ===
Total profit: $120.35 / $500.00
       EUR     USD     GBP     JPY     CHF     CAD     AUD     NZD   
    +-------+-------+-------+-------+-------+-------+-------+-------+
 EUR |   X   |+0.15% |-0.31% | ~ | ~ |-0.52% | ~ |
    +-------+-------+-------+-------+-------+-------+-------+-------+
 USD |-0.15% |   X   |+0.24% | ~ |-0.11% | ~ |+0.42% | ~ |
    +-------+-------+-------+-------+-------+-------+-------+-------+
...

This visualization acts as a high-precision radar, instantly identifying arbitrage opportunities in the Forex market. Positive values are highlighted in green, signaling that the currency pair is overvalued creating a potential selling opportunity. Negative values are colored red, indicating undervaluation and a favorable buying opportunity. The "~" symbol denotes currency pairs in a state of relative equilibrium that are currently of no interest to our trading strategy.

Automatic completion of trading

Trading psychology is one of the most complex areas of financial markets. Our system addresses this aspect by offering a mechanism to automatically close a trade when a specified target profit is reached. The trader sets the desired profit level, and when it is reached, the system closes all positions and stops trading until the next launch.

This mechanism is a real guard against greed, one of the most dangerous enemies of a trader. When the system reaches its goal, it is not tempted by the opportunity to earn "a little more", but rather locks in profits in a disciplined manner.

The essence of our matrix system can be expressed in one phrase: "Mathematical elegance in the service of financial efficiency." We do not attempt to predict market movements or analyze news. Instead, we create a mathematical model of fair relationships between currencies and profit from temporary market deviations from that model. It is an approach that works regardless of market conditions because it is based on fundamental mathematical principles rather than on transient market trends.

In the next part of the article, we will delve into the practical aspects of setting up the system, consider the optimal parameters for various market conditions, and analyze the results of backtesting on historical data covering various market modes.



Optimal configuration of system parameters

The art of creating a truly efficient trading system lies not so much in inventing new indicators or analysis methods, but in fine-tuning the parameters. In our matrix arbitrage system, the key settings are: the minimum deviation for entering the market, the risk level, and the approach to calculating the position size.

The MinDiscrepancy parameter requires special attention. Too low a value will result in frequent market entries on small deviations, which may just be random noise. Too high a value means the system will miss many opportunities. Based on extensive testing, we recommend starting with this parameter set in the range of 0.05-0.1%. For pairs involving JPY, a higher value of around 0.15% may be optimal, given their traditionally high volatility.

Risk management through the MaxRisk parameter is your protective shield in the world of forex trading. We recommend never exceeding 0.02 (2% of balance) even for the most aggressive strategies. Conservative traders may lower this value to 0.01 or even 0.005, sacrificing potential profit for greater stability.

Lot size auto calculation (AutoLots) is a powerful tool for adapting the system to various market conditions. When this option is enabled, the system automatically determines the optimal position size taking into account the current volatility and the pip value for a specific currency pair. This allows maintaining the same level of risk for all trades, regardless of the instrument being traded.

Matrix and trading signals update timing

The update frequency of the fair value matrix has a significant impact on the system performance. Updating too frequently can introduce unnecessary "noise" into calculations, while updating too infrequently can result in missed opportunities. In our implementation, we use a timer with the interval of 5 seconds:

EventSetTimer(5); // Update every 5 seconds

This interval was chosen for a reason: it ensures a balance between data relevance and computing load. When working with fast CPUs, you can experiment with reducing this interval to 2-3 seconds for an even faster response to market imbalances.

Interestingly, during periods of high market volatility, such as during important economic news releases, the system can show particularly impressive results. Sharp price movements often create temporary imbalances between currency pairs, and our system effectively detects them. However, be careful when trading during periods of extreme volatility — increased spreads can significantly impact the strategy profitability.

Fine-tuning matrix calculations

One of the most interesting features of our system is the mechanism for iterative refinement of the fair value matrix. In the current implementation, we use three iterations:

for(int iterations = 0; iterations < 3; iterations++)
{
   // Calculate cross rates...
}

Increasing the number of iterations can potentially improve the accuracy of calculations at the cost of increasing the computational load. Our tests show that three iterations provide the optimal balance between accuracy and performance.

Another fine-tuning parameter is the weighting ratios when averaging the direct rate and the rate calculated using cross rates:

SetMatrixValue(i, j, (current_value * 0.7 + triangleRate * 0.3));

Increasing the weight for triangleRate will make the system more sensitive to arbitrage opportunities, but may also increase the number of false signals. Decreasing this ratio, on the contrary, will result in a more conservative strategy with fewer trades, but a potentially higher percentage of successful entries.

The TotalProfitTarget target profit parameter deserves special attention. Setting it is a kind of disciplinary contract traders make with themselves. Once the target is reached, the system closes all positions and stops trading until the next launch. This protects the trader from the temptation to "improve the result a little," which often leads to the loss of already earned profits.

Adapting the system to changing market conditions

The Forex market is a living organism that is constantly evolving. Approaches that worked yesterday may not work tomorrow. How does our matrix system adapt to changing conditions?

First, the very concept of searching for deviations from fair value makes the system relatively resilient to changes in market regimes. It does not rely on long-term trends or stable patterns of price action, but profits from short-term imbalances that exist independently of the overall market direction.

Second, a systematic approach to parameter optimization allows the strategy to be adapted to current market conditions. It is recommended to periodically (for example, once a quarter) re-optimize the parameters using the latest historical data so that the system is "tuned" to the current market conditions.

In the next part of the article, we will look at the advanced capabilities of our matrix system, including adaptive entries and exits, integration with other analysis methods, and the ability to scale the strategy to more currency pairs and instruments.



Expanded capabilities of the matrix arbitrage system

The true power of our matrix system is fully revealed when we begin to explore its expanded capabilities. From adaptive entry-exit algorithms to integration with additional sources of market information. The potential for creative development of the basic concept is virtually limitless.

Adaptive entry and exit algorithms

The standard implementation of our system uses a fixed minimum deviation value for market entry. However, the Forex market is dynamic, and the volatility of individual currency pairs is constantly changing. Imagine how much more efficient the system could be if the entry threshold automatically adapted to current market volatility.

We can modify our system by adding the calculation of the moving standard deviation of imbalances for each currency pair. Then, the MinDiscrepancy value will automatically adjust - increasing during periods of high volatility and decreasing during calmer times. This adaptability significantly increases the efficiency of the system, especially during transition periods when the nature of the market changes dramatically.

A similar approach can be applied to the algorithm for exiting positions. Instead of simply closing a position on an opposite signal, the system can use an adaptive trailing stop that follows the price at a distance proportional to the current volatility. This allows maximizing your profit if the price continues to move in a favorable direction.

Integration with currency correlation

Our matrix system already implicitly takes into account correlations between currency pairs through the calculation of fair values. However, we can go further and add explicit correlation analysis, which will help optimize the structure of opened positions.

Imagine a situation where the system simultaneously issues signals to buy EURUSD and sell GBPUSD. These pairs often have a high positive correlation, making such contrarian trades particularly attractive from a risk/reward perspective. In effect, we are creating a hedge that protects us from broad market movements and allows us to profit from relative currency movements.

On the other hand, if the system produces signals in the same direction on highly correlated pairs (for example, buy EURUSD and buy AUDUSD), such a combination increases the concentration of risk. In this case, it is possible to implement an algorithm that selects only one of the pairs with the highest expected risk/reward ratio.

Optimizing computational efficiency

As the system expands to cover more currency pairs, computational efficiency becomes critical. Our current implementation uses a simple but effective approach with a one-dimensional array to store a two-dimensional matrix. This solution significantly saves memory and increases computing speed.

However, we can go even further. For very large systems (e.g., covering all major, minor, and exotic currency pairs), sparse matrices can be implemented that store only non-zero elements. This is particularly effective because at the start of the system, most of the cells in the fair value matrix are empty.

Another optimization opportunity is parallel computing. Modern CPUs have multiple cores, and the iterative matrix refinement algorithm can be parallelized, significantly speeding up calculations for large systems.

Dynamic selection of currency pairs

In the current implementation, the system works with a fixed set of eight major currencies. However, it is possible to develop an algorithm that dynamically selects currency pairs for analysis based on their liquidity, volatility, and the historical performance of the system on those pairs.

// Dynamic selection of currency pairs
void SelectOptimalCurrencyPairs()
{
   CArrayString potential_pairs; // All available pairs
   
   // Fill the list of all available pairs
   // ...
   
   // Evaluation of each pair according to several criteria
   for(int i = 0; i < potential_pairs.Total(); i++)
   {
      double liquidity = EstimateLiquidity(potential_pairs.At(i));
      double volatility = EstimateVolatility(potential_pairs.At(i));
      double historical_performance = EstimateHistoricalPerformance(potential_pairs.At(i));
      
      // Combined assessment
      double score = CalculateCombinedScore(liquidity, volatility, historical_performance);
      
      // Save the score
      // ...
   }
   
   // Selecting the best pairs for the current trading loop
   // ...
}

This approach allows the system to adapt to changing market conditions, focusing on the most promising currency pairs at the current moment in time.

Derivatives trading

The principles of our matrix system apply not only to the spot Forex market, but also to derivatives such as currency futures and options. A particularly interesting area is the use of the system for options trading, where temporary imbalances in pricing can create additional arbitrage opportunities.

The system can be modified to calculate "fair" volatility for various expirations and option strikes, identifying situations where market premiums deviate significantly from theoretically fair values. This approach opens up a whole new world of possibilities for experienced traders.

Scaling to other asset classes

Although our system was developed for the Forex market, its concept is universal and can be adapted to other related financial instruments. Consider applying the matrix approach to cryptocurrency pairs, where pricing inefficiencies are often more pronounced than in traditional markets.

Another interesting area is intermarket arbitrage, where the system analyzes the relationships between different asset classes: currencies, interest rates, commodities, and indices. For example, there are well-known historical correlations between AUD and Gold, or between CAD and oil prices. Temporary deviations in these correlations can present interesting trading opportunities.



Conclusion

The matrix arbitrage system embodies a profound philosophical idea: markets strive for equilibrium, but never fully achieve it. It is in this constant oscillation between chaos and order that opportunities for profit lie hidden.

Our system does not attempt to predict future price movements based on historical patterns or fundamental factors. Instead, it creates a mathematical model of a "perfect" market and profits from temporary deviations of the real market from this model. This approach makes the system resilient to changes in market regimes and trends — it works not with trends or reversals, but with the relative imbalances that exist in any market environment.

In an era where machine learning and neural networks are becoming increasingly popular in algorithmic trading, our matrix system reminds us of the power of classical mathematical methods. It proves that sometimes an elegant application of simple principles can be more effective than complex models that require training on large amounts of data.

We put into your hands a powerful tool that, when used correctly, can become a valuable addition to your trading arsenal. Remember that the key to success in algorithmic trading is not only the quality of the algorithm itself, but also the discipline and precision in its application. Start with conservative settings, thoroughly test the system in different market conditions, and gradually adapt it to your own trading style and goals.

The matrix arbitrage system is more than just a trading robot; it is a new way of looking at the market that allows you to see structure and order where others see only chaos and random price movements. Welcome to the world of mathematical trading! 

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

Attached files |
ArbyCross.mq5 (42 KB)
Last comments | Go to discussion (4)
Evgen Khenkin
Evgen Khenkin | 6 May 2025 at 08:41
Been waiting for something like this for a long time. Thanks for the material!
hdhyxiaobin
hdhyxiaobin | 6 May 2025 at 09:44
EA laod and showing error:zero divide, check divider to avoid this error in 'ArbyCross.mq5' (482,34)
pleas modify . thankyou

Roman Shiredchenko
Roman Shiredchenko | 6 May 2025 at 14:22

thank you. INteresting article. I will reread it in detail....

on RUSSIA on shares - futures on it or sber - sber is previligated - can this approach be used?

pivomoe
pivomoe | 8 May 2025 at 08:47
Judging by the picture at the beginning of the article EURUSD and USDEUR are both in arbitrage in the same direction. Where is the logic ? They should be in the opposite arbitrage. It is a bit confusing that almost all pairs are in arbitrage. I always thought that forex is a very efficient market, but judging by the screenshot, trading takes place in a mental hospital.
MetaTrader 5 Machine Learning Blueprint (Part 12): Probability Calibration for Financial Machine Learning MetaTrader 5 Machine Learning Blueprint (Part 12): Probability Calibration for Financial Machine Learning
Tree-based classifiers are typically overconfident: true win rates near 0.55 appear as 0.65–0.80 and inflate position sizes and Kelly fractions. This article presents afml.calibration and CalibratorCV, which generate out-of-fold predictions via PurgedKFold and fit isotonic regression or Platt scaling. We define Brier score, ECE, and MCE, and show diagnostics that trace miscalibration into position sizes, realized P&L, and CPCV path Sharpe distributions to support leakage-free, correctly sized trading.
Chaos optimization algorithm (COA): Continued Chaos optimization algorithm (COA): Continued
We continue studying the chaotic optimization algorithm. The second part of the article deals with the practical aspects of the algorithm implementation, its testing and conclusions.
Formulating Dynamic Multi-Pair EA (Part 8): Time-of-Day Capital Rotation Approach Formulating Dynamic Multi-Pair EA (Part 8): Time-of-Day Capital Rotation Approach
This article presents a Time-of-Day capital rotation engine for MQL5 that allocates risk by trading session instead of using uniform exposure. We detail session budgets within a daily risk cap, dynamic lot sizing from remaining session risk, and automatic daily resets. Execution uses session-specific breakout and fade logic with ATR-based volatility confirmation. Readers gain a practical template to deploy capital where session conditions are statistically strongest while keeping exposure controlled throughout the day.
Chaos optimization algorithm (COA) Chaos optimization algorithm (COA)
This is an improved chaotic optimization algorithm (COA) that combines the effects of chaos with adaptive search mechanisms. The algorithm uses a set of chaotic maps and inertial components to explore the search space. The article reveals the theoretical foundations of chaotic methods of financial optimization.