Wednesday, January 21, 2026
HomeForexBuying and selling technique Heads or Tails evaluation of the buying and...

Buying and selling technique Heads or Tails evaluation of the buying and selling robotic code. – Different – 21 January 2026

The buying and selling technique “Head or Tail” belongs to the class of high-risk short-term buying and selling approaches used primarily on the inventory market and Foreign exchange. Its title is because of the randomness of decision-making, much like flipping a coin (“heads” — purchase an asset, “tails” — promote). This technique relies solely on intuitive selections or random alerts and ignores elementary components of market evaluation.

The supply code of the buying and selling technique has been added to the bottom codes:

MetaTrader 5: https://www.mql5.com/en/code/11637

#property copyright "Copyright 2025, Buying and selling-Go." 
#property hyperlink      "https://www.mql5.com/en/channels/tradingo-go-en"  
#property model   "26.010" 

The offered code consists of compiler directives for a program written as an Professional Advisor (EA) or indicator within the MetaTrader platform utilizing the MQL4/MQL5 language.

Let’s break down every line individually:

1. Copyright Property:

#property copyright “Copyright 2025, Buying and selling-Go.”

This directive units authorized possession rights over the EA’s or indicator’s supply code. It specifies the proprietor of mental property rights and helps mark the product’s affiliation with a particular group or particular person (“Buying and selling-Go”). This info seems within the properties window of the EA/indicator throughout the shopper terminal.

2. Developer Useful resource Hyperlink:

This directive permits setting an internet hyperlink to the developer’s sources. When merchants use this EA or indicator, this hyperlink turns into accessible by way of its properties menu. It is helpful for builders since they’ll direct customers to help pages, documentation, or community-related content material associated to their merchandise.

3. Model Specification:

#property model “26.010”

Right here, the software program model is outlined. Sometimes, builders specify variations in codecs like XX.XX, the place the primary digit represents main model numbers, second minor model updates, and third patch releases. The model assists customers in monitoring updates and sustaining compatibility between instruments.

Thus, these two libraries simplify the event of advanced automated buying and selling algorithms, permitting focus straight on technique logic moderately than low-level interactions with dealer servers.

enter double  iLots         = 0.10; 
enter int     iTakeProfit   = 450;  
enter int     iStopLoss     = 390;  
enter int     iMagicNumber  = 227; 
enter int     iSlippage     = 30; 

string sy = ""; 
double pt = 0; 
int    dt = 0; 

Allow us to study every factor of the given block of code individually, explaining its objective and function in configuring an automated knowledgeable advisor (Professional Advisor) within the MetaTrader buying and selling platform.

Enter Parameters:

1. Lot Dimension (iLots = 0.10):

This enter parameter defines the lot measurement (quantity of commerce). The default worth is ready at 0.10. The lot measurement determines what number of property will likely be purchased or bought per transaction. For instance, if the instrument is EURUSD, then so much measurement of 0.1 corresponds to 10 thousand models of the bottom forex (reminiscent of euros).

2. Take Revenue Stage (iTakeProfit = 450):

This integer parameter specifies the profit-fixation stage (Take Revenue). The default worth equals 450. Take Revenue mechanically closes a place when the market reaches the indicated revenue stage relative to the entry worth. The extent is expressed in pips.

3. Cease Loss Stage (iStopLoss = 390):

This integer parameter establishes the loss-limitation stage (Cease Loss). By default, it is set at 390. Cease Loss mechanically closes a place if the market strikes towards your place and losses attain the predefined threshold. Losses are mounted in pips.

4. Distinctive Deal Quantity (iMagicNumber = 227):

This integer parameter serves as a singular identification quantity (Magic Quantity) for transactions. Every occasion (place opening, closing, and many others.) receives a singular Magic Quantity that filters offers related to this specific EA. The default worth is 227.

5. Most Value Deviation Factors (iSlippage = 30):

This integer parameter restricts the utmost deviation in worth throughout order execution from the requested worth. A default worth of 30 pips ensures that if the precise worth deviates greater than the required quantity, the commerce gained’t execute. This protects towards extreme slippage.

Native Variables:

1. Instrument Image Storage (sy = “”):

A variable of sort string shops the monetary instrument image (e.g., “EURUSD”) being traded. Initially empty (“”).

2. Level Calculation Step (pt = 0):

A variable of sort double holds the scale of the smallest worth change increment for the instrument. Used for calculating Take Revenue and Cease Loss values primarily based on pip counts. Defaulted to zero (0).

3. Decimal Locations Rely (dt = 0):

An integer variable supposed to trace the variety of decimal locations after the decimal level in quotes for the chosen instrument. Figuring out the variety of decimals is essential for correct calculations of earnings, stops, and different metrics. Initialized to zero (0).

This block of code is designed to determine preliminary configurations and put together the atmosphere for an automatic knowledgeable advisor in MetaTrader. The enter parameters enable versatile configuration earlier than beginning buying and selling classes.

   sy = _Symbol; 
   pt = _Point; 
   dt = _Digits; 

   commerce.SetExpertMagicNumber(iMagicNumber); 

   commerce.SetDeviationInPoints(iSlippage); 

   commerce.SetTypeFillingBySymbol(sy); 

   commerce.SetMarginMode(); 

Every assertion performs a essential function in making ready situations for profitable EA operation. Let’s discover them additional:

Environmental Variables:

1. Present Buying and selling Instrument Retrieval:

This assigns the worldwide variable sy the title of the at present traded instrument retrieved from the built-in fixed _Symbol. Thus, we receive entry to the instrument obligatory for subsequent calculations and interplay.

2. Minimal Unit Change Dimension:

Units the variable pt to the minimal change in worth increments (_Point). This primary unit measures adjustments in pricing wanted for correct interpretation of system alerts and adjustment of orders.

3. Decimal Digits Rely:

Assigns the variable dt representing the variety of decimal locations within the worth quote of the present instrument. Since totally different devices have various precision (e.g., USDJPY makes use of two decimal locations whereas EURUSD makes use of 4), realizing this element is crucial for proper rounding and computations.

Commerce Configuration:

4. Distinctive Deal Quantity Setup:

commerce.SetExpertMagicNumber(iMagicNumber);

Establishes a singular magic quantity (Magic Quantity) for all transactions initiated by this EA. The magic quantity identifies offers made particularly by this EA and simplifies filtering by this criterion. Uniqueness ensures no confusion amongst numerous robotic methods.

5. Most Value Deviation:

commerce.SetDeviationInPoints(iSlippage);

Defines the suitable most deviation in worth execution in comparison with the anticipated worth. Ensures safety towards vital market fluctuations. Decrease tolerance means larger accuracy in executing requests.

6. Order Execution Kind:

commerce.SetTypeFillingBySymbol(sy);

Configures the tactic of filling orders relying on the traits of the instrument itself. Some devices require on the spot execution (“Market Execution”), whereas others might settle for delayed executions (“Prompt Execution”). This command mechanically selects the suitable mode primarily based on the instrument’s specs.

7. Margin Mode Adjustment:

Adjusts the margin necessities for buying and selling. Totally different strategies of managing collateral differ throughout devices and buying and selling modes. Appropriate setup impacts the free capital wanted to keep up positions and minimizes dangers of pressured closure because of inadequate funds.

These steps guarantee optimum preparation for environment friendly functioning of the EA within the MetaTrader platform.

   double stepvol = SymbolInfoDouble(sy, SYMBOL_VOLUME_STEP); 
   if(stepvol > 0.0) 
      lt = stepvol * (MathFloor(iLots / stepvol) - 1); 

   double minvol = SymbolInfoDouble(sy, SYMBOL_VOLUME_MIN); 
   if(lt < minvol) 
      lt = 0.0;

   ::MathSrand(GetTickCount()); 

Let’s stroll by every step sequentially:

Step 1: Retrieve Quantity Step Info:

double stepvol = SymbolInfoDouble(sy, SYMBOL_VOLUME_STEP);

This retrieves the minimal step change in lot sizes for the chosen instrument. For example, some devices might need a step of 0.01 heaps, which means you can’t commerce fractional quantities smaller than that.

Step 2: Confirm Optimistic Step Worth:

Checks whether or not the step worth is larger than zero. Detrimental or zero steps would render changes meaningless.

Step 3: Calculate Adjusted Lot Dimension:

lt = stepvol * (MathFloor(iLots / stepvol) – 1);

Reduces the user-defined lot measurement (iLots) by subtracting one full step. This is what occurs internally:

  1. Divide the specified lot measurement by the step (iLots / stepvol).
  2. Spherical down the end result utilizing MathFloor().
  3. Subtract one step from the rounded-down worth.
  4. Multiply again by the step to get the ultimate decreased lot measurement.

Step 4: Fetch Minimal Allowed Lot Dimension:

double minvol = SymbolInfoDouble(sy, SYMBOL_VOLUME_MIN);

Retrieves the minimal permitted lot measurement for the given instrument. Exchanges impose limits on the smallest tradable volumes.

Step 5: Reset Beneath Minimal Values:

if(lt < minvol)

   lt = 0.0;

If the calculated lot measurement falls beneath the exchange-imposed minimal, the lot measurement is reset to zero, stopping invalid orders.

Step 6: Initialize Random Generator Seed:

::MathSrand(GetTickCount());

Seeds the random quantity generator with the present tick rely, guaranteeing unpredictability in future randomized processes.

General Goal:

This block dynamically adjusts lot sizes based on change laws, avoiding errors throughout place openings and enhancing commerce security.

   int complete = ::PositionsTotal(), b = 0, s = 0; 

   double Bid = ::SymbolInfoDouble(sy, SYMBOL_BID); 
   double Ask = ::SymbolInfoDouble(sy, SYMBOL_ASK); 

   double new_sl = 0, new_tp = 0, old_sl = 0, old_tp = 0; 

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

We’ll analyze every a part of this preparatory block:

Initializing Variables:

1. Open Place Counter:

complete = ::PositionsTotal();

Retrieves the whole variety of open positions throughout all symbols and kinds. Helpful for later place administration and optimization.

2. Buy/Sale Counters:

Counters initialized to trace the variety of opened purchase (b) and promote (s) positions respectively. They begin at zero however improve as we iterate by current positions.

Present Market Costs:

3. BID Value Acquisition:

Bid = ::SymbolInfoDouble(sy, SYMBOL_BID);

Fetches the perfect out there promoting worth (bid) for the present instrument. Vital for evaluating stop-loss and take-profit ranges.

4. ASK Value Acquisition:

Ask = ::SymbolInfoDouble(sy, SYMBOL_ASK);

Obtains the perfect shopping for worth (ask) for a similar instrument. Each bid and ask are important for computing real looking revenue targets and danger administration thresholds.

Making ready Cease-Loss/Take-Revenue Ranges:

5. New/Outdated Cease-Loss and Take-Revenue Definitions:

new_sl = 0, new_tp = 0, old_sl = 0, old_tp = 0;

Declares variables to carry each earlier and newly computed stop-loss (SL) and take-profit (TP) ranges. These are initially set to zero till additional processing happens.

Error Dealing with:

6. Invalid Value Safety:

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

   return;

Ensures that solely legitimate bid and ask costs are processed. If both is lacking or detrimental, the script exits instantly to forestall defective actions.

With these preparations full, subsequent blocks proceed to calculate exact ranges for stop-losses and take-profits, thereby enhancing general buying and selling effectivity.

 for(int i = 0; i < complete; i++) 
      if(posit.SelectByIndex(i)) 
         if(posit.Image() == sy) 
            if(posit.Magic() == iMagicNumber) 
              {

               old_sl = ::NormalizeDouble(posit.StopLoss(),   dt); 
               old_tp = ::NormalizeDouble(posit.TakeProfit(), dt); 

               if(posit.PositionType() == POSITION_TYPE_BUY) 
                 {
                  new_sl = ::NormalizeDouble(Ask - iStopLoss   * pt, dt); 
                  new_tp = ::NormalizeDouble(Ask + iTakeProfit * pt, dt); 
                  b++;                                                 
                 }

               if(posit.PositionType() == POSITION_TYPE_SELL) 
                 {
                  new_sl = ::NormalizeDouble(Bid + iStopLoss   * pt, dt); 
                  new_tp = ::NormalizeDouble(Bid - iTakeProfit * pt, dt); 
                  s++; 
                 }

               if(old_sl == 0 || old_tp == 0) 
                  commerce.PositionModify(posit.Ticket(), new_sl, new_tp);
              }

Clarification:

Iteration Via Open Positions:

1. Choice by Index:

if(posit.SelectByIndex(i))

Selects a place primarily based on its index within the listing of open positions. After choice, the place object turns into accessible for modification.

Instrument Matching:

2. Checking Instrument Consistency:

if(posit.Image() == sy && posit.Magic() == iMagicNumber)

Verifies that the place belongs to the related instrument (image matches ‘sy’) and has the matching magic quantity (‘iMagicNumber’). Each checks guarantee exact focusing on of the correct place.

Updating Cease-Loss and Take-Revenue Ranges:

3. Retrieving Outdated Ranges:

old_sl = NormalizeDouble(posit.StopLoss(), dt);

old_tp = NormalizeDouble(posit.TakeProfit(), dt);

Normalizes beforehand saved stop-loss and take-profit ranges to match the instrument’s decimal format, guaranteeing consistency in floating-point representations.

4. Updating Lengthy Positions:

if(posit.PositionType() == POSITION_TYPE_BUY)

For purchase positions, calculates new stop-loss beneath the present ask worth and new take-profit above the ask worth, adjusting for the configured stop-loss/take-profit offsets.

5. Updating Quick Positions:

if(posit.PositionType() == POSITION_TYPE_SELL)

Equally handles brief positions, inserting stop-loss above the bid worth and take-profit beneath the bid worth.

6. Making use of Modifications:

if(old_sl == 0 || old_tp == 0)

   commerce.PositionModify(posit.Ticket(), new_sl, new_tp);

Updates the place with new stop-loss and take-profit ranges if any had been modified. Solely modified positions endure updating.

Conclusion:

This loop effectively manages a number of open positions, updating protecting measures reminiscent of stop-loss and take-profit to boost profitability and scale back danger publicity.

   if((b + s) == 0) 
      if(::MathRand() % 2 == 0) 
        {
         if(commerce.CheckVolume(sy, lt, Ask, ORDER_TYPE_BUY)) 
            if(commerce.Purchase(lt)) 
               return; 
        }
      else
         if(commerce.CheckVolume(sy, lt, Bid, ORDER_TYPE_SELL)) 
            if(commerce.Promote(lt)) 
               return; 

Description:

When No Lively Place Exists:

1. Situation Analysis:

Checks if there are not any lively positions (each purchase and promote counters equal zero). If true, proceeds to randomly choose a place path.

Random Route Choice:

2. Utilizing Random Perform:

if(::MathRand() % 2 == 0)

Makes use of the modulo operator (% 2) to randomly resolve between opening a purchase or promote place. If the rest is zero, a purchase place is taken into account; in any other case, a promote place is tried.

Purchase Place Creation:

3. Fund Availability Verify:

if(commerce.CheckVolume(sy, lt, Ask, ORDER_TYPE_BUY))

Earlier than initiating a purchase place, verifies enough account steadiness to cowl the proposed commerce quantity (lt) on the present asking worth (Ask).

4. Opening Purchase Place:

Makes an attempt to create a purchase place utilizing the required lot measurement (lt). Upon success, terminates additional execution of the perform.

Promote Place Creation:

5. Various State of affairs:

else

   if(commerce.CheckVolume(sy, lt, Bid, ORDER_TYPE_SELL))

In case the random selector selected a promote place, repeats the fund availability test however now for promoting on the bid worth (Bid).

6. Initiating Sale:

Opens a promote place if funding permits, once more halting additional execution upon completion.

Closing Consequence:

This block implements a easy but efficient mechanism for creating random purchase or promote positions each time none exist, emphasizing frequency of trades over deliberate strategic planning.

void OnDeinit(const int cause) 
  {

  }

Whereas the deinitialization block stays clean right here, it is helpful even with out fast performance. An empty block acts as a placeholder reminding builders about potential cleanup duties. Future expansions may embrace cleansing up sources, closing home windows, or ending community connections.

Abstract:

General, the code demonstrates how you can configure an Professional Advisor in MetaTrader successfully, dealing with dynamic lot changes, place modifications, and safeguards towards faulty inputs or market anomalies.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments