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, much like flipping a coin (“heads” — purchase an asset, “tails” — promote). This technique relies solely on intuitive selections 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 shopper terminal.
2. Developer Useful resource Hyperlink:
This directive permits setting an online hyperlink to the developer’s assets. When merchants use this EA or indicator, this hyperlink turns into accessible through its properties menu. It is useful 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 complicated automated buying and selling algorithms, permitting focus instantly on technique logic somewhat 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 look at every aspect of the given block of code individually, explaining its goal and position in configuring an computerized knowledgeable 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 ready at 0.10. The lot measurement determines what number of belongings will probably be purchased or bought per transaction. For instance, if the instrument is EURUSD, then quite a bit measurement of 0.1 corresponds to 10 thousand models of the bottom foreign money (corresponding to euros).
2. Take Revenue Stage (iTakeProfit = 450):
This integer parameter specifies the profit-fixation degree (Take Revenue). The default worth equals 450. Take Revenue robotically closes a place when the market reaches the indicated revenue degree relative to the entry worth. The extent is expressed in pips.
3. Cease Loss Stage (iStopLoss = 390):
This integer parameter establishes the loss-limitation degree (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 singular identification quantity (Magic Quantity) for transactions. Every occasion (place opening, closing, and so forth.) 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 desired quantity, the commerce gained’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 dimensions 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 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 ascertain preliminary configurations and put together the setting 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 vital position in making ready circumstances 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 presently traded instrument retrieved from the built-in fixed _Symbol. Thus, we receive entry to the instrument crucial for subsequent calculations and interplay.
2. Minimal Unit Change Measurement:
Units the variable pt to the minimal change in worth 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 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), figuring out this element is important 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 appropriate most deviation in worth execution in comparison with the anticipated worth. Ensures safety in opposition to vital market fluctuations. Decrease tolerance means greater accuracy in executing requests.
6. Order Execution Sort:
commerce.SetTypeFillingBySymbol(sy);
Configures the tactic of filling orders relying on the traits of the instrument itself. Some devices require immediate execution (“Market Execution”), whereas others could settle for delayed executions (“On the spot 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. Right setup impacts the free capital wanted to keep up positions and minimizes dangers of compelled closure attributable to 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 may need a step of 0.01 tons, that means you can’t commerce fractional quantities smaller than that.
Step 2: Confirm Optimistic Step Worth:
Checks whether or not the step worth is bigger than zero. Damaging 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:
- Divide the specified lot measurement by the step (iLots / stepvol).
- Spherical down the outcome utilizing MathFloor().
- Subtract one step from the rounded-down worth.
- Multiply again by the step to get the ultimate diminished 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 Under 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.
Total Goal:
This block dynamically adjusts lot sizes in response to 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 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 one of the best out there promoting worth (bid) for the present instrument. Needed for evaluating stop-loss and take-profit ranges.
4. ASK Value Acquisition:
Ask = ::SymbolInfoDouble(sy, SYMBOL_ASK);
Obtains one of the best shopping for worth (ask) for a similar instrument. Each bid and ask are important for computing life like revenue targets and threat 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 damaging, 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 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); }
Clarification:
Iteration Via 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 concentrating on of the best 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 Brief Positions:
if(posit.PositionType() == POSITION_TYPE_SELL)
Equally handles brief positions, putting stop-loss above the bid worth and take-profit beneath the bid worth.
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 have been modified. Solely modified positions endure 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 cut 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 Course 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 Examine:
if(commerce.CheckVolume(sy, lt, Ask, ORDER_TYPE_BUY))
Earlier than initiating a purchase place, verifies adequate 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 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 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.
Remaining Final result:
This block implements a easy but efficient mechanism for creating random purchase or promote positions every time 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 quick 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:
Total, the code demonstrates the best way 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.
























