-->

Expert Advisors • Indicators • Scripts • Libraries

MQL.RobotFX.org is the biggest collection of MetaTrader expert advisors (MT5 & MT4), indicators, scripts and libraries that can be used to improve trading results, minimize risks or simply automate trading tasks

Metatrader 5 Expert Advisor | Updated: Trading strategy Heads or Tails | Free MetaTrader Script

Explore the latest free tools from the MQL5 community. Here's a new indicator, expert advisor, or script for MetaTrader.

Image for Trading strategy Heads or Tails

For experienced investors, this strategy represents more of an experimental method for testing hypotheses rather than a stable way to earn money.

Thus, although the strategy is simple and accessible to every beginner, it carries significant risks and has almost no chance of providing stable income in the long term.


Let's examine the main block of the random position opening signal:

if((b + s) == 0) // If there are no active positions

Here, the condition checks for the absence of open positions. Variable b represents the number of long ("buy") positions, and variable s represents the number of short ("sell") positions. If the sum of both is zero (b + s = 0), it means there are no open positions.

if(::MathRand() % 2 == 0) // Randomly choosing the direction of opening a position

Inside the previous block, a random number is checked. The function ::MathRand() generates a pseudo-random number from 0 to 32767 inclusive. This number is then divided by 2 (% 2) — if the remainder is 0, the next block is executed.

{
if(trade.Buy(lt)) // Opening a long position (BUY)
   return; // Terminating function execution
}

If the random number is even (remainder of division by 2 is 0), the trading robot opens a long position (purchase) with a volume of iLots. After successfully opening the position, the function execution is interrupted by the return operator.

else // Otherwise...
    if(trade.Sell(lt)) // Opening a short position (SELL)
      return; // Terminating function execution

If the random number was odd (remainder of division by 2 is not zero), a short position (sale) with a volume of iLots is opened, and further execution of the function is also terminated.

Final logic of the fragment:

  • It checks whether the trader has any open positions.
  • If there are no open positions, a random direction for the trade is chosen: either a purchase (long) or a sale (short).
  • The opened trade automatically stops further execution of the function.

Thus, this code represents the simplest example of an algorithm that makes a decision to open a position on the market randomly.

For a detailed line-by-line analysis of the code, you can visit the blog post: https://www.mql5.com/en/blogs/post/766912

Grid trading done right – try the robust Grid Expert Advisor for controlled risk. Details here.

Build better strategies with RobotFX professional tools – check them out.

11637

Best MetaTrader Indicators + Profitable Expert Advisors