22.9 C
San Juan
Sunday, March 8, 2026

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 identify is because of the randomness of decision-making, just like flipping a coin (“heads” — purchase an asset, “tails” — promote). This technique is predicated solely on intuitive choices or random indicators and ignores basic 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 selected group or particular person (“Buying and selling-Go”). This info seems within the properties window of the EA/indicator throughout the consumer terminal.

2. Developer Useful resource Hyperlink:

This directive permits setting an internet hyperlink to the developer’s assets. When merchants use this EA or indicator, this hyperlink turns into accessible through its properties menu. It is helpful for builders since they will direct customers to assist 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 immediately on technique logic quite 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 ingredient of the given block of code individually, explaining its objective and position in configuring an computerized professional advisor (Professional Advisor) within the MetaTrader buying and selling platform.

Enter Parameters:

1. Lot Measurement (iLots = 0.10):

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

2. Take Revenue Degree (iTakeProfit = 450):

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

3. Cease Loss Degree (iStopLoss = 390):

This integer parameter establishes the loss-limitation stage (Cease Loss). By default, it is set at 390. Cease Loss robotically closes a place if the market strikes in opposition to 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 novel identification quantity (Magic Quantity) for transactions. Every occasion (place opening, closing, and so forth.) receives a novel Magic Quantity that filters offers related to this explicit EA. The default worth is 227.

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

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

Native Variables:

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

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

2. Level Calculation Step (pt = 0):

A variable of kind double holds the scale of the smallest value 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 Depend (dt = 0):

An integer variable supposed to trace the variety of decimal locations after the decimal level in quotes for the chosen instrument. Understanding 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 setting for an automatic professional advisor in MetaTrader. The enter parameters permit versatile configuration earlier than beginning buying and selling periods.

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

   commerce.SetExpertMagicNumber(iMagicNumber); 

   commerce.SetDeviationInPoints(iSlippage); 

   commerce.SetTypeFillingBySymbol(sy); 

   commerce.SetMarginMode(); 

Every assertion performs a essential position in getting 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 identify of the at present traded instrument retrieved from the built-in fixed _Symbol. Thus, we get hold of entry to the instrument mandatory for subsequent calculations and interplay.

2. Minimal Unit Change Measurement:

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

3. Decimal Digits Depend:

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

Commerce Configuration:

4. Distinctive Deal Quantity Setup:

commerce.SetExpertMagicNumber(iMagicNumber);

Establishes a novel 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 appropriate most deviation in value execution in comparison with the anticipated value. Ensures safety in opposition to important market fluctuations. Decrease tolerance means larger accuracy in executing requests.

6. Order Execution Kind:

commerce.SetTypeFillingBySymbol(sy);

Configures the strategy of filling orders relying on the traits of the instrument itself. Some devices require prompt execution (“Market Execution”), whereas others could settle for delayed executions (“Immediate Execution”). This command robotically selects the suitable mode primarily based on the instrument’s specs.

7. Margin Mode Adjustment:

Adjusts the margin necessities for buying and selling. Completely different strategies of managing collateral fluctuate throughout devices and buying and selling modes. Appropriate setup impacts the free capital wanted to keep up positions and minimizes dangers of pressured closure as a consequence 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 means of 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. As an example, some devices might need a step of 0.01 heaps, that means you can’t commerce fractional quantities smaller than that.

Step 2: Confirm Constructive Step Worth:

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

Step 3: Calculate Adjusted Lot Measurement:

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 outcome 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 Measurement:

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, making certain unpredictability in future randomized processes.

General Goal:

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

   int whole = ::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:

whole = ::PositionsTotal();

Retrieves the entire 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 means of present positions.

Present Market Costs:

3. BID Value Acquisition:

Bid = ::SymbolInfoDouble(sy, SYMBOL_BID);

Fetches one of the best out there promoting value (bid) for the present instrument. Obligatory for evaluating stop-loss and take-profit ranges.

4. ASK Value Acquisition:

Ask = ::SymbolInfoDouble(sy, SYMBOL_ASK);

Obtains one of the best shopping for value (ask) for a similar instrument. Each bid and ask are important for computing lifelike revenue targets and threat administration thresholds.

Making ready Cease-Loss/Take-Revenue Ranges:

5. New/Previous 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 stop defective actions.

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

 for(int i = 0; i < whole; 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);
              }

Rationalization:

Iteration By way of Open Positions:

1. Choice by Index:

if(posit.SelectByIndex(i))

Selects a place primarily based on its index within the record 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 best place.

Updating Cease-Loss and Take-Revenue Ranges:

3. Retrieving Previous 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, making certain 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 value and new take-profit above the ask value, adjusting for the configured stop-loss/take-profit offsets.

5. Updating Brief Positions:

if(posit.PositionType() == POSITION_TYPE_SELL)

Equally handles quick positions, putting stop-loss above the bid value and take-profit beneath the bid value.

6. Making use of Adjustments:

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 bear updating.

Conclusion:

This loop effectively manages a number of open positions, updating protecting measures corresponding to stop-loss and take-profit to boost profitability and scale back threat 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 Energetic Place Exists:

1. Situation Analysis:

Checks if there aren’t any energetic positions (each purchase and promote counters equal zero). If true, proceeds to randomly choose a place route.

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 Test:

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

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

4. Opening Purchase Place:

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

Promote Place Creation:

5. Various Situation:

else

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

In case the random selector selected a promote place, repeats the fund availability verify however now for promoting on the bid value (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 at any time when none exist, emphasizing frequency of trades over deliberate strategic planning.

void OnDeinit(const int purpose) 
  {

  }

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

Abstract:

General, the code demonstrates learn how to configure an Professional Advisor in MetaTrader successfully, dealing with dynamic lot changes, place modifications, and safeguards in opposition to misguided inputs or market anomalies.

Related Articles

Stay Connected

0FansLike
0FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles