20.9 C
New York
Saturday, June 7, 2025

Constructing a Martingale Grid Buying and selling Technique in MQL5 (Half 1) – Buying and selling Programs – 6 June 2025


Constructing a Martingale Grid Buying and selling Technique in MQL5

Abstract: This text presents an entire implementation of a Martingale-based grid buying and selling technique in MQL5. We’ll look at the code construction, danger administration options, and potential enhancements for this controversial however highly effective buying and selling method.

1. Introduction to Martingale Grid Buying and selling

The Martingale technique is a widely known (and infrequently controversial) buying and selling method the place place sizes are elevated after losses, with the expectation that eventual wins will get well earlier losses. When utilized as a grid technique, it entails putting orders at progressively higher costs because the market strikes towards your preliminary place.

How Grid Martingale Works:

  • An preliminary place is opened on the present market worth
  • Extra positions are added at predetermined intervals as worth strikes towards you
  • Every subsequent place is bigger than the earlier (sometimes 1.5-2x)
  • All positions are closed when the typical break-even worth is reached

Key Dangers to Contemplate:

  • Margin depletion: Exponential place development can shortly eat obtainable margin
  • No assured restoration: Sturdy developments can proceed past your grid ranges
  • Psychological stress: Requires self-discipline to handle rising losses

2. The MQL5 Implementation

Let’s look at the whole code construction with detailed explanations for every element.

2.1. Consists of and Preliminary Setup

#embody 
CTrade commerce;

#embody 
static CAccountInfo accountInfo;

Clarification:

  • CTrade class gives simplified commerce execution strategies (market orders, place administration)
  • CAccountInfo provides entry to account-related capabilities (margin checks, steadiness info)

2.2. Grid Buying and selling Parameters


double initialLotSize = 0.01;
double lotMultiplier = 1.5;
int gridStepPoints = 300;
double gridStep = gridStepPoints * _Point;
int breakEvenTPPoints = 100;
double breakEvenTP = breakEvenTPPoints * _Point;
int digits_number;


double currentBuyGridStep = 0;

Parameter Breakdown:

Parameter Description Default Worth
initialLotSize Beginning place dimension 0.01 heaps
lotMultiplier Place dimension multiplier for every new grid degree 1.5x
gridStepPoints Distance between grid ranges in factors 300 factors
breakEvenTPPoints Take-profit distance in factors for break-even exit 100 factors

2.3. Initialization Operate

void InitializeVariables() {
    digits_number = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
    
    if (currentBuyGridStep == 0) {
        currentBuyGridStep = gridStep;
    }
}

Key Capabilities:

  • SymbolInfoInteger(_Symbol, SYMBOL_DIGITS) – Will get the variety of decimal locations for the present image
  • Initializes currentBuyGridStep if not already set

3. Core Buying and selling Logic

3.1. Major Execution Move

void OnTick() {
    InitializeVariables();
    RunTradingStrategy();
}

void RunTradingStrategy() {
   int nr_buy_positions = CountBuyPositions();
   double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   
   if (nr_buy_positions == 0) {
      OpenInitialBuyPosition();
   }

   CheckBuyGridLevels();
   SetBreakEvenTP();
}

Course of Move:

  1. Initialize crucial variables on every tick
  2. Depend present purchase positions
  3. Open preliminary place if none exists
  4. Verify if new grid ranges must be triggered
  5. Monitor for break-even exit circumstances

3.2. Place Counting Operate

int CountBuyPositions() {
   int depend = 0;
   for (int i = 0; i PositionsTotal(); i++) {
      ulong ticket = PositionGetTicket(i);
      if (PositionSelectByTicket(ticket) && 
          PositionGetString(POSITION_SYMBOL) == _Symbol &&
          PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
         depend++;
      }
   }
   return depend;
}

Key Factors:

  • Iterates via all open positions
  • Filters positions for present image and purchase kind
  • Returns depend of matching positions

4. Grid Place Administration

4.1. Opening the Preliminary Place

void OpenInitialBuyPosition() {
   double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK); 
   double lotSize = NormalizeLotSize(initialLotSize);
   double requiredMargin = accountInfo.MarginCheck(_Symbol, ORDER_TYPE_BUY, lotSize, askPrice);
   
   if(requiredMargin > accountInfo.FreeMargin()) {
      Print("Not sufficient margin for preliminary purchase! Required: ", requiredMargin, " Free: ", accountInfo.FreeMargin());
      return;
   }

   if (!commerce.Purchase(lotSize, _Symbol, askPrice, 0, 0, "Preliminary Purchase")) {
      Print("Preliminary purchase error: ", GetLastError());
   } else {
      Print("Preliminary purchase place opened at ", askPrice, " with lot dimension ", lotSize);
   }
}

Security Options:

  • Lot dimension normalization to adjust to dealer restrictions
  • Margin examine earlier than opening place
  • Error dealing with and logging

4.2. Grid Degree Monitoring

void CheckBuyGridLevels() {
   double minBuyPrice = DBL_MAX;
   int nr_buy_positions = 0;

   for (int i = 0; i PositionsTotal(); i++) {
      ulong ticket = PositionGetTicket(i);
      if (PositionSelectByTicket(ticket) && PositionGetString(POSITION_SYMBOL) == _Symbol) {
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
            double entryPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            if (entryPrice if (nr_buy_positions > 0) {
      double nextGridBuyPrice = NormalizeDouble(minBuyPrice - currentBuyGridStep, digits_number);
      double currentAsk = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_ASK), digits_number);

      if (currentAsk double newLotSize = NormalizeLotSize(initialLotSize * MathPow(lotMultiplier, nr_buy_positions));
         double requiredMargin = accountInfo.MarginCheck(_Symbol, ORDER_TYPE_BUY, newLotSize, currentAsk);
         
         if(requiredMargin > accountInfo.FreeMargin()) {
            Print("Not sufficient margin for grid purchase!");
            return;
         }

         if (!commerce.Purchase(newLotSize, _Symbol, currentAsk, 0, 0, "Grid Purchase")) {
            Print("Grid purchase error: ", GetLastError());
         }
      }
   }
}

Grid Logic Defined:

  1. Finds the bottom present purchase place worth
  2. Calculates subsequent grid degree worth (present lowest – grid step)
  3. Checks if present ask worth has reached the subsequent grid degree
  4. Calculates new place dimension utilizing exponential development
  5. Performs margin examine earlier than opening new place

5. Break-Even Exit Technique

void SetBreakEvenTP() {
   double totalBuyVolume = 0;
   double totalBuyCost = 0;

   for (int i = 0; i PositionsTotal(); i++) {
      ulong ticket = PositionGetTicket(i);
      if (PositionSelectByTicket(ticket) && PositionGetString(POSITION_SYMBOL) == _Symbol) {
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
            double quantity = PositionGetDouble(POSITION_VOLUME);
            double entryPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            totalBuyVolume += quantity;
            totalBuyCost += entryPrice * quantity;
         }
      }
   }

   if (totalBuyVolume > 0) {
      double breakEvenBuyPrice = NormalizeDouble((totalBuyCost / totalBuyVolume) + breakEvenTP, digits_number);
      double currentBid = NormalizeDouble(SymbolInfoDouble(_Symbol, SYMBOL_BID), digits_number);

      if (currentBid >= breakEvenBuyPrice) {
         CloseAllBuyPositions();
      }
   }
}

Exit Logic:

  • Calculates volume-weighted common entry worth
  • Provides the break-even TP distance to find out exit worth
  • Screens present bid worth towards goal exit worth
  • Closes all positions when goal is reached

6. Danger Administration and Enhancements

6.1. Present Security Options

  • Margin checks earlier than every commerce
  • Lot dimension normalization
  • Break-even exit mechanism

6.2. Potential Enhancements

Enhancement Description Implementation Issue
Dynamic Grid Spacing Alter step dimension primarily based on ATR or volatility Medium
Max Drawdown Restrict Cease buying and selling after sure loss threshold Straightforward
Trailing Cease Defend income throughout favorable strikes Medium
Time-Based mostly Exit Shut positions after sure time interval Straightforward

7. Conclusion

This Martingale grid technique implementation gives a stable basis for automated grid buying and selling in MQL5. Whereas the method will be worthwhile in ranging markets, it carries important danger throughout robust developments. At all times:

  • Completely backtest with historic information
  • Implement strict danger administration guidelines
  • Monitor efficiency in demo accounts earlier than reside buying and selling

In future articles, we’ll discover enhancements like:

  • Promote-side grid implementation
  • Multi-currency assist
  • Superior danger controls

Be aware: The entire supply code for this EA is accessible within the connected .mq5 file. At all times take a look at totally in a demo setting earlier than contemplating reside buying and selling.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles