EN fortrader
29 January, 2026Updated 27 March, 2026

Heads or Tails Trading Strategy: Complete MQL5 Expert Advisor Code

ForTrader.org

Contents

Heads or Tails Strategy Explained

The Heads or Tails trading strategy randomly selects buy or sell directions like flipping a coin, opening positions with fixed stop loss and take profit levels. Traders pick an asset such as stocks or forex pairs, generate a random signal, enter a trade at a set lot size, and manage risk with predefined stop loss and take profit.

  • Asset selection: Choose a financial instrument like stocks or currencies.
  • Coin flip: Randomly decide buy or sell.
  • Position entry: Open the trade with a fixed volume.
  • Risk management: Set stop loss to cap losses and take profit to lock in gains.

This random direction choice simplifies decision-making by eliminating market analysis.

Strategy Pros and Cons

Advantages include:

  1. No need for complex technical or fundamental analysis.
  2. Reduced market monitoring lowers stress.
  3. Easy to automate in trading systems.

Disadvantages include:

  1. 50% win rate, far below professional strategies.
  2. Ignoring economic data and indicators increases loss risks.
  3. Requires substantial capital to withstand drawdowns.

Key implementation tips:

  • Limit position size to 1% of total capital.
  • Strictly follow stop loss and take profit levels.
  • Diversify across multiple assets to reduce portfolio risk.

Test on demo accounts first to assess performance and refine position management.

Expert Advisor Code Breakdown

1. File Structure Overview

The EA file starts with a header comment specifying the filename (VR Heads or Tails.mq5), author, and release year. It includes #property directives for metadata like copyright, version, and links.

2. Libraries and Variables

Standard MQL5 libraries handle trading:

#include <Trade\Trade.mqh>nCTrade trade; // Trade management instancenn#include <Trade\PositionInfo.mqh>nCPositionInfo posit; // Position info instance
  • CTrade sends buy/sell orders.
  • CPositionInfo retrieves open position data.

Input parameters (user-configurable in MT5):

input double iStartLots = 0.01; // Starting lot sizeninput int iTakeProfit = 450; // Take profit (points)ninput int iStopLoss = 390; // Stop loss (points)ninput int iMagicNumber = 227; // Trade identifierninput int iSlippage = 30; // Max slippage
  • iStartLots: Initial trade volume.
  • iTakeProfit/iStopLoss: Profit/loss levels.
  • iMagicNumber: Identifies EA trades.
  • iSlippage: Allowed price deviation.

3. OnInit() Function

Runs once on EA launch to set parameters:

int OnInit() {n trade.SetExpertMagicNumber(iMagicNumber); // Set magic numbern trade.SetDeviationInPoints(iSlippage); // Set slippagen trade.SetTypeFillingBySymbol(_Symbol); // Order fill typen trade.SetMarginMode(); // Hedging moden MathSrand(GetTickCount()); // Seed random generatorn return(INIT_SUCCEEDED);n}

Key actions:

  1. SetExpertMagicNumber(): Assigns unique trade ID.
  2. SetDeviationInPoints(): Defines slippage tolerance.
  3. SetTypeFillingBySymbol(): Sets order execution type.
  4. SetMarginMode(): Enables hedging.
  5. MathSrand(): Initializes random number generator for trade direction.

4. OnTick() Function

Executes on every price tick. Breaks down as follows.

4.1. Market and Position Data

int total = ::PositionsTotal(); // Open positions countndouble Bid = ::SymbolInfoDouble(_Symbol, SYMBOL_BID); // Bid pricendouble Ask = ::SymbolInfoDouble(_Symbol, SYMBOL_ASK); // Ask price

Exits if prices invalid:

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

4.2. Position Analysis

Counts buy (b) and sell (s) positions:

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}

4.3. New Trade Entry

If no positions (b + s == 0), randomly opens trade:

if((b + s) == 0) {n if(MathRand() % 2 == 0) { // 0 = BUYn trade.Buy(iStartLots, _Symbol, Ask, Ask - iStopLoss * _Point, Ask + iTakeProfit * _Point, "");n } else { // 1 = SELLn trade.Sell(iStartLots, _Symbol, Bid, Bid + iStopLoss * _Point, Bid - iTakeProfit * _Point, "");n }n}
  • MathRand() % 2: Random 0 (buy) or 1 (sell).
  • trade.Buy()/Sell(): Opens with TP/SL.

Trade parameters use _Point for pip scaling. Exits after opening to prevent duplicates.

5. OnDeinit() Function

Runs on EA removal:

void OnDeinit(const int reason) {n // Add cleanup code heren}
  • Can save stats, close positions, or log data.

6. How the EA Works Overall

  1. OnInit(): Configures trading settings.
  2. OnTick(): Checks positions; opens random LONG/SHORT with TP/SL if none exist.
  3. OnDeinit(): Handles cleanup.

7. Beginner Tips

  1. Testing: Backtest on demo or MT5 Strategy Tester before live use.
  2. Risks: Random entries are high-risk; add trend filters for real trading.
  3. Parameters: Tune lot size, TP, SL to account and style.
  4. MagicNumber: Ensure unique from other EAs.
  5. Slippage: Match iSlippage to asset liquidity.

8. Improvement Ideas

  • Add indicator filters (RSI, MACD).
  • Dynamic lot sizing by balance.
  • Trade logging.
  • Multiple entry protection.
  • Parameter optimization.

This MQL5 code provides a foundation for custo

FAQ

What is the Heads or Tails trading strategy?

The strategy randomly selects buy or sell directions like flipping a coin, opening positions with fixed stop loss and take profit levels on chosen assets such as forex pairs.

How does the Expert Advisor decide trade direction?

The EA uses MathRand() % 2 in OnTick() to generate a random 0 for buy or 1 for sell when no positions are open.

What are key input parameters for the EA?

Parameters include iStartLots for trade volume, iTakeProfit and iStopLoss in points, iMagicNumber for trade identification, and iSlippage for price deviation tolerance.

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

Recent educational articles

All articles

The editor recommends

All articles
Loading...