EN fortrader
29 January, 2026

Analysis of the ‘Heads or Tails’ Trading Strategy — MQL5 Source Code

ForTrader.org

Contents

Essence of the Trading Strategy

The main idea is as follows:

  • Asset Selection: The trader selects a financial instrument for trading (e.g., stocks, currencies).
  • Coin Flip: A random selection of trade direction (“buy” or “sell”).
  • Position Opening: After choosing the side, a trade is opened for a predefined volume.
  • Risk Management: Stop-loss and take-profit levels are set to limit losses and fix profits respectively.

Thus, all trading activity boils down to a random selection of price movement direction, which greatly simplifies decision-making.

Advantages and Disadvantages of the Strategy

Advantages of the tactic:

  1. No need to conduct complex technical or fundamental market analysis.
  2. No need for constant market analysis — this reduces stress levels.
  3. The strategy is easily automated and can be used in automated trading systems.

Disadvantages:

  1. Success probability is only 50%, significantly lower than most professional strategies.
  2. Ignoring important economic indicators and technical indicators increases loss risks.
  3. To minimize risks, substantial trading capital is recommended to withstand potential losses.

For successful strategy implementation, consider the following:

  • Optimal position size is no more than 1% of total trading capital.
  • Strict adherence to stop-loss and take-profit levels.
  • Asset diversification: Using different financial instruments reduces overall portfolio risk.

Beginner traders should first test the ‘Heads or Tails’ strategy on demo accounts to assess its potential and develop their own position management approaches.

Expert Advisor Code

1. Overall File Structure

The expert file starts with a header (comment) indicating:

  • File name (VR Heads or Tails.mq5);
  • Author information and release year;
  • Developer’s website.

Followed by #property directives setting expert metadata: copyrights, version, and required links.

2. Library Includes and Variable Declarations

For trading operations, standard MQL5 libraries are included:

#include <Trade\Trade.mqh>nCTrade trade; // Instance for trade managementnn#include <Trade\PositionInfo.mqh>nCPositionInfo posit; // Instance for position information
  • CTrade — class for sending trade orders (buys, sells);
  • CPositionInfo — class for getting data on open positions.

Then, input parameters of the expert are declared (configurable by user in MT5 interface):

input double iStartLots = 0.01; // Initial lotninput int iTakeProfit = 450; // Take-profit (in points)ninput int iStopLoss = 390; // Stop-loss (in points)ninput int iMagicNumber = 227; // Unique trade identifierninput int iSlippage = 30; // Maximum allowable slippage
  • iStartLots — volume of the first trade;
  • iTakeProfit and iStopLoss — profit and loss levels;
  • iMagicNumber — number to identify robot trades (to avoid confusion with manual ones);
  • iSlippage — allowable price deviation on order execution.

3. OnInit() Function — Robot Initialization

This function executes once on expert launch. Its task is to set trading parameters:

int OnInit() {n trade.SetExpertMagicNumber(iMagicNumber); // Set MagicNumbern trade.SetDeviationInPoints(iSlippage); // Set slippagen trade.SetTypeFillingBySymbol(_Symbol); // Execution type by symboln trade.SetMarginMode(); // Margin mode (hedging)n MathSrand(GetTickCount()); // Initialize random number generatorn return(INIT_SUCCEEDED); // Report successful launchn}

Key actions:

  1. SetExpertMagicNumber() — assigns unique identifier to trades.
  2. SetDeviationInPoints() — sets maximum allowable slippage.
  3. SetTypeFillingBySymbol() — configures order execution type (e.g., “market”).
  4. SetMarginMode() — activates hedging mode (separate positions per instrument).
  5. MathSrand() — initializes random number generator (used later for random trade direction selection).

4. OnTick() Function — New Quote Processing

This function is called on every new tick (price change). Let’s break it down.

4.1. Getting Market and Position Data

int total = ::PositionsTotal(); // Number of open positionsndouble Bid = ::SymbolInfoDouble(_Symbol, SYMBOL_BID); // BID pricendouble Ask = ::SymbolInfoDouble(_Symbol, SYMBOL_ASK); // ASK price
  • PositionsTotal() — returns number of open positions;
  • SymbolInfoDouble() — gets current BID (sell) and ASK (buy) prices.

If prices are invalid (≤ 0), the function exits:

if(Bid <= 0 || Ask <= 0)n return;

4.2. Analysis of Open Positions

The loop iterates through all positions and counts long (BUY) and short (SELL) trades:

for(int i = 0; i < total; i++) {n if(posit.SelectByIndex(i)) {n if(posit.Symbol() == _Symbol && posit.Magic() == iMagicNumber) {n if(posit.PositionType() == POSITION_TYPE_BUY) b++;n if(posit.PositionType() == POSITION_TYPE_SELL) s++;n }n }n}
  • SelectByIndex() — selects position by index;
  • Symbol() and Magic() — check if position belongs to current instrument and robot;
  • PositionType() — determines position type (BUY/SELL).

4.3. Opening a New Trade

If no positions (b + s == 0), the robot randomly selects trade direction:

if((b + s) == 0) {n if(MathRand() % 2 == 0) { // Random choice: 0 — BUY, 1 — SELLn trade.Buy(iStartLots, _Symbol, Ask, Ask - iStopLoss * _Point, Ask + iTakeProfit * _Point, "");n } else {n trade.Sell(iStartLots, _Symbol, Bid, Bid + iStopLoss * _Point, Bid - iTakeProfit * _Point, "");n }n}
  • MathRand() % 2 — generates random number (0 or 1);
  • trade.Buy() — opens long position with specified TP and SL;
  • trade.Sell() — opens short position.

Trade Function Parameters:<

ForTrader.org

ForTrader.org

Author

Subscribe to us on Facebook

Fortrader contentUrl Suite 11, Second Floor, Sound & Vision House, Francis Rachel Str. Victoria Victoria, Mahe, Seychelles +7 10 248 2640568

More from this category

All articles

Test on Understanding Forex Market Basics

Test your knowledge of the currency market. Check yourself to identify gaps still affecting your trading.

How Forex Brokers Work Under the Agency Model

In the previous article, we described that the agency model of a Forex broker involves routing ALL client trades to the interbank market. This process is quite complex, involving numerous participants and stages. It encompasses both a technical process for selecting the best prices and executing trades, and a financial one that converts figures into […]

How to Create a Trading Robot If You’re Not a Programmer: 8 Steps from Idea to Implementation

A trader’s brain doesn’t function quite like an ordinary person’s. Someone far from financial markets acts rationally and predictably. But when a person obsessed with candlestick patterns gets involved, the outcomes become much harder to foresee. Common trader flaws include skewed life priorities and heightened impulsiveness. Trading itself becomes the ultimate goal, and the biological […]

The Best Way to Lock Positions: 3 Expert Opinions on Forex Locks

,alignnone size-new-theme-post-size wp-image-233121" src="https://files.fortraders.org/uploads/2017/08/locking-forex-730x379.jpg" alt="Position locking and locks in forex" width="730" height="379" />In order to close a lock, in addition to market analysis and a clear forecast for the currency pair, you need the broker to have suitable conditions for this. For example, some companies do not have the ability to partially close an opposing position, which greatly complicates opening a lock, especially if an equal lock is used.A very common mistake is when a trader opens a locking order of a larger volume than the initial positions in order to reduce losses when the price moves against the initial orders. Such a lock is extremely dangerous: if the price direction changes, the situation will immediately worsen, and losses will grow faster.Also, many traders make a psychological mistake. As soon as any lock trade shows a profit, and there is a possibility that the price will not go further, most traders' nerves fail, and they quickly close the profitable lock position, thereby undermining the structure. When using locking in your trading, you need to know well how to exit it correctly.As market analysis shows, non-retracement (or with minor corrections) price movement in one direction of more than 500 pips occurs only 1-2 times per year. To set a lock at this level, the account drawdown should be no more than 45%, otherwise there will not be enough free funds to open an opposing order. Statistically, the probability of a pullback at this level is several times higher. Therefore, it is better to "sit out" such moments than to set a lock. Of course, you can set a lock without waiting for a non-retracement trend of 500 pips. But in this case, you will constantly be in a suspended state and deal with locks. In most cases, when you are mentally ready to set a lock, the price will be on the verge of a reversal.The expediency of using position locking in Forex is absent. Whatever the situation with the currency pair, the alternative to a lock will always be a stop-loss or simply "sitting out" losses with averaging at important levels.Furthermore, do not forget that if swaps are negative, such a lock will only increase losses, and on some currency pairs, the size is very significant. Yes, one of the swaps may be positive, but even in this case, the size of the negative will be larger, and losses will still increase.The only acceptable option for a reasonable trader to use a lock is to set it not on a losing trade, but on a profitable one. When an open position is generating good profit but a correction is approaching, instead of closing the trade, you can set a lock, thereby fixing the profit. At the moment when the price resumes movement in your favor, the opposing order is closed, and the profit on the previously opened trade continues to grow. It is psychologically much easier to work with such a lock than with a losing one.

Recent educational articles

All articles

The editor recommends

All articles
Loading...