Help with Algo: Modern Martingale v1.0

 

Hi, I am trying to fix some issues with my martingale algo. 

  1. The lot size isnt doubling after a losing trade
  2. The Total Profit/Loss for the day is not updating 

I have research the forum and Im still looking for the solution for this code, thank you

#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade/Trade.mqh>

// Input parameters
input double       LotSize = 0.1;            // Fixed lot size
input double       LotMultiplier = 2;       // Geometric progression multiplier
input int          TakeProfitPips = 10;       // Take Profit in pips
input int          StopLossPips = 10;         // Stop Loss in pips (same as TP)
input bool         UseTrailingStop = true;    // Enable/Disable trailing stop
input int          TrailingStopPips = 5;      // Trailing stop in pips
input bool         UseTrailingTakeProfit = true;  // Toggle trailing take profit on/off
input double       MaxDailyLoss = 5000;       // Max daily loss allowed
input bool         UseMaxDailyProfit = false; // Toggle max daily profit check
input double       MaxDailyProfit = 5000;     // Max daily profit allowed (if toggle is on)

CTrade trade;                    // Trading object
double currentLotSize;            // Track current lot size
bool isLongTrade = true;          // Alternating between long and short trades
double currentLoss = 0;           // Track daily loss
double currentProfit = 0;         // Track daily profit
bool wasLastTradeLoss = false;    // Track if the last trade was a loss
int expertMagic = 123456;         // Magic number for identifying positions

// Initialize function
int OnInit()
{
   trade.SetExpertMagicNumber(expertMagic);
   currentLotSize = LotSize;      // Initialize lot size
   Print("Initialization complete. Lot size set to: ", currentLotSize);
   return (INIT_SUCCEEDED);
}

void UpdateLotSize(bool wasLoss)
{
   Print("UpdateLotSize called. Previous Lot Size: ", currentLotSize);
   if (wasLoss)
   {
      currentLotSize *= LotMultiplier;  // Increase lot size after a loss
      Print("Lot size increased after loss to: ", currentLotSize);
   }
   else
   {
      currentLotSize = LotSize;  // Reset lot size after a win
      Print("Lot size reset after win to: ", currentLotSize);
   }
}



// Function to place market orders with symmetrical SL and TP
void PlaceMarketOrders()
{
   double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double stopLossValue = StopLossPips * _Point;
   double takeProfitValue = TakeProfitPips * _Point;

   Print("Placing market order with Lot Size: ", currentLotSize);

   // Long trade (market buy)
   if (isLongTrade)
   {
      if (trade.Buy(currentLotSize, _Symbol, bidPrice, bidPrice - stopLossValue, bidPrice + takeProfitValue))
      {
         Print("Placed Buy Market Order with Lot Size: ", currentLotSize, " SL: ", bidPrice - stopLossValue, " TP: ", bidPrice + takeProfitValue);
      }
      else
      {
         Print("Failed to place Buy Market Order.");
      }
   }
   // Short trade (market sell)
   else
   {
      if (trade.Sell(currentLotSize, _Symbol, askPrice, askPrice + stopLossValue, askPrice - takeProfitValue))
      {
         Print("Placed Sell Market Order with Lot Size: ", currentLotSize, " SL: ", askPrice + stopLossValue, " TP: ", askPrice - takeProfitValue);
      }
      else
      {
         Print("Failed to place Sell Market Order.");
      }
   }

   // Alternate between buy and sell trades
   isLongTrade = !isLongTrade;
   Print("Next trade direction is ", isLongTrade ? "Buy" : "Sell");
}

void TrackDailyLossAndProfit()
{
   double totalProfitLoss = 0;
   datetime todayStart = iTime(_Symbol, PERIOD_D1, 0);  // Get the start of today

   for (int i = 0; i < HistoryDealsTotal(); i++)
   {
      ulong dealTicket = HistoryDealGetTicket(i);  // Get the deal ticket
      if (HistoryDealSelect(dealTicket))  // Select the deal by its ticket
      {
         datetime closeTime = (datetime)HistoryDealGetInteger(dealTicket, DEAL_TIME);  // Get deal close time

         // Check if the deal was closed today
         if (closeTime >= todayStart)
         {
            double profit = HistoryDealGetDouble(dealTicket, DEAL_PROFIT);  // Get the profit/loss of the deal
            totalProfitLoss += profit;  // Accumulate profit/loss
         }
      }
   }

   Print("Total Profit/Loss for the day: ", totalProfitLoss);

   // Update current loss and profit values
   if (totalProfitLoss < 0)
   {
      currentLoss = -totalProfitLoss;
   }
   else
   {
      currentProfit = totalProfitLoss;
   }

   // Stop trading if max loss is hit
   if (currentLoss >= MaxDailyLoss)
   {
      Print("Max daily loss reached. Stopping trading for today.");
      ExpertRemove();  // Stop the expert advisor
   }

   // Stop trading if max daily profit is hit (if toggle is enabled)
   if (UseMaxDailyProfit && currentProfit >= MaxDailyProfit)
   {
      Print("Max daily profit reached. Stopping trading for today.");
      ExpertRemove();  // Stop the expert advisor
   }
}

// Function to check if the last trade was a loss
bool WasLastTradeLoss()
{
   if (HistoryDealsTotal() > 0)
   {
      ulong lastDealTicket = HistoryDealGetTicket(HistoryDealsTotal() - 1);  // Get the last deal ticket
      if (HistoryDealSelect(lastDealTicket))
      {
         double lastTradeProfit = HistoryDealGetDouble(lastDealTicket, DEAL_PROFIT);  // Get the profit/loss of the last trade
         Print("Last trade profit: ", lastTradeProfit);
         return (lastTradeProfit < 0);  // Return true if the last trade was a loss
      }
   }
   return false;  // Default return false if no trades found
}



// OnTick function (main execution loop)
void OnTick()
{
   //Print("OnTick called. PositionsTotal: ", PositionsTotal(), ", OrdersTotal: ", OrdersTotal());
   TrackDailyLossAndProfit();  // Monitor daily loss and profit

   if (PositionsTotal() == 0 && OrdersTotal() == 0)  // Only place orders when no trades are open
   {
      bool wasLoss = WasLastTradeLoss();  // Check if the last trade was a loss
      UpdateLotSize(wasLoss);  // Update the lot size based on the last trade result
      PlaceMarketOrders();  // Place market orders if no open positions
   }

   if (UseTrailingStop)
   {
      ApplyTrailingStop();  // Apply trailing stop if enabled
   }

   ApplyTrailingTakeProfit();  // Apply trailing take profit if enabled
}

// Apply trailing stop function (same as before)
void ApplyTrailingStop()
{
   for (int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if (PositionSelect(_Symbol) && PositionGetInteger(POSITION_MAGIC) == expertMagic)
      {
         double priceCurrent = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         double stopLoss = PositionGetDouble(POSITION_SL);

         // Trailing stop for a buy position
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
         {
            double newStop = priceCurrent - TrailingStopPips * _Point;
            if (stopLoss < newStop)
            {
               trade.PositionModify(PositionGetTicket(i), newStop, PositionGetDouble(POSITION_TP));
               Print("Trailing stop adjusted for buy position.");
            }
         }

         // Trailing stop for a sell position
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
         {
            double newStop = priceCurrent + TrailingStopPips * _Point;
            if (stopLoss > newStop)
            {
               trade.PositionModify(PositionGetTicket(i), newStop, PositionGetDouble(POSITION_TP));
               Print("Trailing stop adjusted for sell position.");
            }
         }
      }
   }
}

// Apply trailing take profit function (same as before)
void ApplyTrailingTakeProfit()
{
   if (!UseTrailingTakeProfit) return;  // Exit if trailing take profit is disabled

   for (int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if (PositionSelect(_Symbol) && PositionGetInteger(POSITION_MAGIC) == expertMagic)
      {
         double priceCurrent = SymbolInfoDouble(_Symbol, SYMBOL_BID);
         double takeProfit = PositionGetDouble(POSITION_TP);

         // Trailing take profit for a buy position
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
         {
            double newTP = priceCurrent + TrailingStopPips * _Point;
            if (takeProfit < newTP)
            {
               trade.PositionModify(PositionGetTicket(i), PositionGetDouble(POSITION_SL), newTP);
               Print("Trailing take profit adjusted for buy position.");
            }
         }

         // Trailing take profit for a sell position
         if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
         {
            double newTP = priceCurrent - TrailingStopPips * _Point;
            if (takeProfit > newTP)
            {
               trade.PositionModify(PositionGetTicket(i), PositionGetDouble(POSITION_SL), newTP);
               Print("Trailing take profit adjusted for sell position.");
            }
         }
      }
   }
}
 
musollc94:

Hi, I am trying to fix some issues with my martingale algo. 

  1. The lot size isnt doubling after a losing trade
  2. The Total Profit/Loss for the day is not updating 

I have research the forum and Im still looking for the solution for this code, thank you

Your Position, Order and HistoryDeal management is completely of charts...

You need to do quite some research on how this works. Your code is so incomplete, I can't even start to explain what's all missing.

Read the docs and example codes as a start, then research the mql book for more complete understanding.
 
I did do the research, what exactly is wrong with the code? What is wrong with the position, order and historydeal management? You need to be specific instead of vague condescending comments with no actual substance I can use. 
 
musollc94 #:
I did do the research, what exactly is wrong with the code? What is wrong with the position, order and historydeal management? You need to be specific instead of vague condescending comments with no actual substance I can use. 
Please read the example codes given in the documentation.


 
How do I delete this entire post?
 
musollc94 #:
How do I delete this entire post?
You dont. Why would you want to?
 
Dominik Egert #:
You dont. Why would you want to?
I have solve the problem already
 
I am requesting mods or admins delete this entire thread, thank you