Help Needed: Take Profit Not Moving Correctly on Live Account with Martingale Strategy

 
can someone help me why when during live account trade, my takeprofit is not moving correctly.. While using the demo account the takeprofit move flawlessly.. Here my code related to the system trade, by the way this using martingale, when more layer are open, the take profit consistently static to the set value of the user, let say if the broker spread is 15, the take profit is 5, when layering, the take profit will keep opening the static tp. which is it stuck at 5, means when hit, the profit is negative.. means loss..

You can DM me for the full source code, but i think this is enough

Part 1

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double AskPrice(string symbol = "")
  {
   if(symbol == "")
      symbol = Symbol();
   return (MarketInfo(symbol, MODE_ASK));
  }
  
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double BidPrice(string symbol = "")
  {
   if(symbol == "")
      symbol = Symbol();
   return (MarketInfo(symbol, MODE_BID));
  }
  
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double StopLevel(string symbol = "")
  {
   if(symbol == "")
      symbol = Symbol();
   return (MarketInfo(symbol, MODE_STOPLEVEL));
  }
  
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
string OrderCmd(int ordertype)
  {
   string label;

   switch(ordertype)
     {
      case 0:
         label = "Buy";
         break;
      case 1:
         label = "Sell";
         break;
      case 2:
         label = "Buy Limit";
         break;
      case 3:
         label = "Sell Limit";
         break;
      case 4:
         label = "Buy Stop";
         break;
      case 5:
         label = "Sell Stop";
         break;
     }

   return (label);
  }
  
//+------------------------------------------------------------------+
//|Order Entry
//+------------------------------------------------------------------+

int Order(int ordertype, string comment)
{
   int    ticket;
   double lot     = SetupLot(ordertype);
   double price   = 0;
   double sl      = 0;
   double tp      = 0;

   if (ordertype == OP_BUY)
   {
      price = AskPrice();

      if (StopLoss > 0)
         sl = NormalizeDouble(price - (StopLoss * POINT), DIGIT);
      if (TakeProfit > 0)
         tp = NormalizeDouble(price + (TakeProfit * POINT), DIGIT);
   }

   if (ordertype == OP_SELL)
   {
      price = BidPrice();

      if (StopLoss > 0)
         sl = NormalizeDouble(price + (StopLoss * POINT), DIGIT);
      if (TakeProfit > 0)
         tp = NormalizeDouble(price - (TakeProfit * POINT), DIGIT);
   }

   ticket = OrderSend(Symbol(), ordertype, lot, price, SlipPage, sl, tp, comment, MagicNumber, 0);
   if (ticket == -1)
      ShowError("Order " + OrderCmd(ordertype));

   return ticket;
}

  
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void CloseOrder(int ordertype = -1)
  {
   for(int i = OrdersTotal()-1; i >= 0; i--)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            if(ordertype == -1)
              {
               if(OrderType() == OP_BUY)
                 {
                  if(!OrderClose(OrderTicket(),OrderLots(),BidPrice(OrderSymbol()),SlipPage,Blue))
                     ShowError("Close " + OrderCmd(OrderType()));
                 }
               else
                  if(OrderType() == OP_SELL)
                    {
                     if(!OrderClose(OrderTicket(),OrderLots(),AskPrice(OrderSymbol()),SlipPage,Red))
                        ShowError("Close " + OrderCmd(OrderType()));
                    }
                  else
                    {
                     if(!OrderDelete(OrderTicket()))
                        ShowError("Delete Pending Order " + OrderCmd(OrderType()));
                    }
              }
            else
              {
               if(OrderType() == ordertype)
                 {
                  if(ordertype == OP_BUY)
                    {
                     if(!OrderClose(OrderTicket(),OrderLots(),BidPrice(OrderSymbol()),SlipPage,Blue))
                        ShowError("Close " + OrderCmd(OrderType()));
                    }
                  else
                     if(ordertype == OP_SELL)
                       {
                        if(!OrderClose(OrderTicket(),OrderLots(),AskPrice(OrderSymbol()),SlipPage,Red))
                           ShowError("Close " + OrderCmd(OrderType()));
                       }
                     else
                       {
                        if(!OrderDelete(OrderTicket()))
                           ShowError("Delete Pending Order " + OrderCmd(OrderType()));
                       }
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double TotalProfit()
  {
   if(TotalOrder() > 0)
     {
      profit = 0;

      for(int i = 0; i < OrdersTotal(); i++)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
               profit += OrderProfit()+OrderSwap()+OrderCommission();
           }
        }
     }

   return(profit);
  }
  
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void ShowError(string label)
  {
   string Error;
   int    error = GetLastError();

   Error        = StringConcatenate("Terminal: ",TerminalName(),"\n",
                                    label," error ",error,"\n",
                                    ErrorDescription(error));
   if(error > 2)
     {
      if(IsTesting())
         Comment(Error);
      else
         Alert(Error);
     }
  }

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void AutoDigit()
  {
   POINT = MarketInfo(Symbol(),MODE_POINT);
   DIGIT = (int)MarketInfo(Symbol(),MODE_DIGITS);

   if(DIGIT == 3 || DIGIT == 5)
     {
      PT              = 10;
      SlipPage       *= 10;
      StopLoss       *= 10;
      TakeProfit     *= 10;
      TrailStartPip  *= 10;
      TrailStepPip   *= 10;
      PipStep        *= 10;
     }
  }
 

Part 2


//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void last_price_buy()
  {
   int i;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)&&OrderType()==OP_BUY)
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            lpb = NormalizeDouble(OrderOpenPrice(),DIGIT);
           }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void last_price_sell()
  {
   int i;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)&&OrderType()==OP_SELL)
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            lps = NormalizeDouble(OrderOpenPrice(),DIGIT);
           }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void last_lot_sell()
  {
   int i;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)&&OrderType()==OP_SELL)
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            lls = OrderLots();
           }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
int last_bar_buy()
  {
   int bar = -1;
   int i;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)&&OrderType()==OP_BUY)
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            bar = iBarShift(Symbol(),Period(),OrderOpenTime());
           }
     }
   return(bar);
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
int last_bar_sell()
  {
   int bar = -1;
   int i;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)&&OrderType()==OP_SELL)
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            bar = iBarShift(Symbol(),Period(),OrderOpenTime());
           }
     }
   return(bar);
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void last_lot_buy()
  {
   int i;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS)&&OrderType()==OP_BUY)
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            llb = OrderLots();
           }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void LotsTotal()
  {
   int r;
   if(OrdersTotal()>0)
     {
      openbuylots = 0;
      openselllots = 0;    //  set the variables to zero
      for(int i=0; i<OrdersTotal(); i++)
        {
         r = OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderCloseTime()==0)
           {
            if(OrderType()==OP_BUY)
               openbuylots += OrderLots();

            if(OrderType()==OP_SELL)
               openselllots += OrderLots();
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void FTPB()
  {
   ftpb = 0;
   datetime EarliestOrder = D'2099/12/31';

   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS))
        {
         if(OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            if(EarliestOrder > OrderOpenTime())
              {
               EarliestOrder = OrderOpenTime();
               ftpb = OrderTakeProfit();
              }
           }
        }
     }
// Returns 0 if no matching orders
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void FTPS()
  {
   ftps = 0;
   datetime EarliestOrder = D'2099/12/31';

   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS))
        {
         if(OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            if(EarliestOrder > OrderOpenTime())
              {
               EarliestOrder = OrderOpenTime();
               ftps = OrderTakeProfit();
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void FSLB()
  {
   fslb = 0;
   datetime EarliestOrder = D'2099/12/31';

   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS))
        {
         if(OrderType() == OP_BUY && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            if(EarliestOrder > OrderOpenTime())
              {
               EarliestOrder = OrderOpenTime();
               fslb = OrderStopLoss();
              }
           }
        }
     }
// Returns 0 if no matching orders
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void FSLS()
  {
   fsls = 0;
   datetime EarliestOrder = D'2099/12/31';

   for(int i = 0; i < OrdersTotal(); i++)
     {
      if(OrderSelect(i, SELECT_BY_POS))
        {
         if(OrderType() == OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            if(EarliestOrder > OrderOpenTime())
              {
               EarliestOrder = OrderOpenTime();
               fsls = OrderStopLoss();
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void Manage_Layer()
  {
   last_price_buy();
   last_price_sell();
   last_lot_buy();
   last_lot_sell();

   int ticket = 0;

   double opencandle = iOpen(Symbol(),Period(),0);
   datetime candleTime   = iTime(Symbol(),Period(),0);

   int TTL_Buy=TotalOrder(OP_BUY);
   int TTL_Sell=TotalOrder(OP_SELL);
   
//===============================================================================================================
// Trend Order Buy
//===============================================================================================================
   if(TTL_Buy>0 && ((TTL_Buy+TTL_Sell) < MaxOrder))
     {

      nextbuy = NormalizeDouble(low_price_buy()-(PipStep*POINT),DIGIT);
      slbuy = 0;

      lotbuy  = SetupLot(OP_BUY);

      buy_state = 1;

      // layer by candle close
      if(Layer_Type==1 && last_bar_buy() == 0)
         buy_state = 0;
      if(buy_state == 1 && opencandle <= nextbuy && Layer_Type==1)
        {
         ticket = OrderSend(Symbol(),OP_BUY,lotbuy,AskPrice(),SlipPage,0,0,NamaEA +" " + (string)(TTL_Buy+1),MagicNumber,0,clrBlue);
        }

      // layer by grid
      if(buy_state == 1 && AskPrice() <= nextbuy && Layer_Type==0)
        {
         ticket = OrderSend(Symbol(),OP_BUY,lotbuy,AskPrice(),SlipPage,0,0,NamaEA +" " + (string)(TTL_Buy+1),MagicNumber,0,clrBlue);
        }
     }

   if((Hedge_Mode)&&(TTL_Sell==0)&&(TTL_Buy>=(Layer_Per_Group*(Hedge_Group_Start-1))) && ((TTL_Buy+TTL_Sell) < MaxOrder))
     {
      nextsell = NormalizeDouble(low_price_buy()-(PipStep*POINT),DIGIT);
      slsell = 0;
      lotsell  = SetupLot(OP_SELL);
      sell_state = 1;

      if(Layer_Type==1 && last_bar_sell() == 0)
         sell_state = 0;
      if(sell_state == 1 && opencandle >= nextsell && Layer_Type==1)
        {
         ticket = OrderSend(Symbol(),OP_SELL,Hedge_LotSize,BidPrice(),SlipPage,0,0,NamaEA +" Hedging 1st",MagicNumber,0,clrRed);

        }

      if(sell_state == 1 && BidPrice() >= nextsell && Layer_Type==0)
        {
         ticket = OrderSend(Symbol(),OP_SELL,Hedge_LotSize,BidPrice(),SlipPage,0,0,NamaEA +" Hedging 1st",MagicNumber,0,clrRed);

        }
     }

//===============================================================================================================
// Trend Order Sell
//===============================================================================================================
   if(TTL_Sell>0 && ((TTL_Buy+TTL_Sell) < MaxOrder))
     {

      nextsell = NormalizeDouble(high_price_sell()+(PipStep*POINT),DIGIT);
      slsell = 0;
      lotsell  = SetupLot(OP_SELL);

      sell_state = 1;

      if(Layer_Type==1 && last_bar_sell() == 0)
         sell_state = 0;
      if(sell_state == 1 && opencandle >= nextsell && Layer_Type==1)
        {
         ticket = OrderSend(Symbol(),OP_SELL,lotsell,BidPrice(),SlipPage,0,0,NamaEA +" " + (string)(TTL_Sell+1),MagicNumber,0,clrRed);

        }

      if(sell_state == 1 && BidPrice() >= nextsell && Layer_Type==0)
        {
         ticket = OrderSend(Symbol(),OP_SELL,lotsell,BidPrice(),SlipPage,0,0,NamaEA +" " + (string)(TTL_Sell+1),MagicNumber,0,clrRed);

        }
     }

   if((Hedge_Mode)&& (TTL_Buy==0) && (TTL_Sell>=(Layer_Per_Group*(Hedge_Group_Start-1)))&&(TTL_Sell>0) && ((TTL_Buy+TTL_Sell) < MaxOrder))
     {
      nextbuy = NormalizeDouble(high_price_sell()+(PipStep*POINT),DIGIT);
      slbuy = 0;

      lotbuy  = SetupLot(OP_BUY);
      buy_state = 1;

      if(Layer_Type==1 && last_bar_buy() == 0)
         buy_state = 0;
      if(buy_state == 1 && opencandle <= nextbuy && Layer_Type==1)
        {
         ticket = OrderSend(Symbol(),OP_BUY,Hedge_LotSize,AskPrice(),SlipPage,0,0,NamaEA +" Hedging 1st",MagicNumber,0,clrBlue);

        }

      if(buy_state == 1 && AskPrice() <= nextbuy && Layer_Type==0)
        {
         ticket = OrderSend(Symbol(),OP_BUY,Hedge_LotSize,AskPrice(),SlipPage,0,0,NamaEA +" Hedging 1st",MagicNumber,0,clrBlue);

        }
     }

  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void TargetProfit()
  {
   if(TotalOrder() > 0)
     {
      profit = 0;

      for(int i = 0; i < OrdersTotal(); i++)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
              {
               profit = profit+(OrderProfit()+OrderSwap()+OrderCommission());
              }
           }
        }

      if(TotalOrder() > 0)
         targetmoney = TakeMoney;

      if(TakeMoney > 0)
        {
         if(profit >= targetmoney)
            CloseAll = true;
           {
            if(CloseAll)
              {
               while(TotalOrder() > 0)
                 {
                  CloseOrder();
                 }
               Print("Close by CutProfit");
              }
           }
        }
     }
   if(TotalOrder() == 0)
     {
      CloseAll = false;

     }
  }

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void TargetProfitPercent()
  {
   if(TotalOrder() > 0)
     {
      profit = 0;

      for(int i = 0; i < OrdersTotal(); i++)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
              {
               profit = profit+(OrderProfit()+OrderSwap()+OrderCommission());
              }
           }
        }

      if(TotalOrder() > 0)
         targetmoney = TakeMoney;

      if(TakeMoney > 0)
        {
         if(profit >= targetmoney*0.01*AccountBalance())
            CloseAll = true;
           {
            if(CloseAll)
              {
               while(TotalOrder() > 0)
                 {
                  CloseOrder();
                 }
               Print("Close by CutProfit");
              }
           }
        }
     }
   if(TotalOrder() == 0)
     {
      CloseAll = false;

     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void TargetLoss()
  {
   if(TotalOrder() > 0)
     {
      if(CutLossMoney > 0)
        {
         double target = -CutLossMoney;
         if(TotalProfit() <= target)
            CutAll = true;
        }

      if(CutAll)
        {
         CloseOrder();
         Print("Close by CutLossMoney");
        }
     }

   if(TotalOrder() == 0)
     {
      CutAll = false;

     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void TargetLossPercent()
  {
   if(TotalOrder() > 0)
     {
      if(CutLossMoneyPercent > 0)
        {
         double target = -CutLossMoneyPercent;
         if(TotalProfit() <= target*0.01*AccountBalance())
            CutAll = true;
        }

      if(CutAll)
        {
         CloseOrder();
         Print("Close by CutLossMoney");
        }
     }

   if(TotalOrder() == 0)
     {
      CutAll = false;

     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double BEP_buy()
  {
   int i;
   double need = 0;
   double lot_total_size = 0;
   last_price_buy();
   LotsTotal();
   double lot_used;
   if(Lots_By_Risk==0)
      lot_used = Lots_Manual;
   else
      lot_used = AccountBalance()*Lots_By_Risk/10000;

   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
           {
            double size_lot = OrderLots()/lot_used;
            need = need+(((OrderOpenPrice()-lpb)/POINT)*size_lot);
           }
        }
     }
   return(MathCeil(need/(openbuylots/lot_used)));
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double BEP_sell()
  {
   int i;
   double need = 0;
   double lot_total_size = 0;
   last_price_sell();
   LotsTotal();

   double lot_used;
   if(Lots_By_Risk==0)
      lot_used = Lots_Manual;
   else
      lot_used = AccountBalance()*Lots_By_Risk/10000;

   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
           {
            double size_lot = OrderLots()/lot_used;
            need = need+(((lps-OrderOpenPrice())/POINT)*size_lot);
           }
        }
     }
   return(MathCeil(need/(openselllots/lot_used)));
  }

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void TPModifBuy()
  {
   bool q;
   int i;
   double tpbuy;

   last_price_buy();
   FTPB();
   tpbuy = 0;

   if(TotalOrder(OP_BUY) >= 1)
     {
      tpbuy = NormalizeDouble(lpb+((BEP_buy()+TakeProfit)*POINT),DIGIT);
     }

   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderTakeProfit()!=tpbuy)
            q = OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),tpbuy,OrderExpiration(),clrWhite);
        }
     }
  }

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void TPModifSell()
  {
   bool q;
   int i;
   double tpsell;

   last_price_sell();
   FTPS();
   tpsell = 0;

   if(TotalOrder(OP_SELL) >= 1)
     {
      tpsell = NormalizeDouble(lps-((BEP_sell()+TakeProfit)*POINT),DIGIT);
     }

   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderTakeProfit()!=tpsell)
            q = OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),tpsell,OrderExpiration(),clrWhite);

        }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void SLModifBuy()
  {
   bool q;
   int i;
   FSLB();
   slbuy = fslb;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_BUY && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderStopLoss()!=slbuy)
            q = OrderModify(OrderTicket(),OrderOpenPrice(),slbuy,OrderTakeProfit(),OrderExpiration(),clrWhite);
        }
     }
  }

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
void SLModifSell()
  {
   bool q;
   int i;
   FSLS();
   slsell = fsls;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderType()==OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderStopLoss()!=slsell)
            q = OrderModify(OrderTicket(),OrderOpenPrice(),slsell,OrderTakeProfit(),OrderExpiration(),clrWhite);

        }
     }
  }
//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
double TotalLot(int orderType)
  {
   double totalLots = 0;

   if(TotalOrder() > 0)
     {
      for(int i = OrdersTotal()-1; i >= 0; i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderSymbol() == Symbol())
              {
               if(OrderType() == orderType)
                  totalLots += OrderLots();
              }
           }
        }
     }

   return(totalLots);
  }
 
  1. Martingale is not a strategy. It's a betting system.

    Hedging, grid trading, same as Martingale.
              Martingale, Hedging and Grid : MHG - General - MQL5 programming forum (2016)

    Martingale, guaranteed to blow your account eventually. If your strategy is not profitable without, it is definitely not profitable with.
              Martingale vs. Non Martingale (Simplified RoR vs Profit and the Illusions) - MQL5 programming forum (2015)

    Why it won't work:
              Calculate Loss from Lot Pips - MQL5 programming forum (2017)
              THIS Trading Strategy is a LIE... I took 100,000 TRADES with the Martingale Strategy - YouTube (2020)

  2.       price = AskPrice();
    
          if (StopLoss > 0)
             sl = NormalizeDouble(price - (StopLoss * POINT), DIGIT);
          if (TakeProfit > 0)
             tp = NormalizeDouble(price + (TakeProfit * POINT), DIGIT);

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  3. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

 
William Roeder #:
  1. Martingale is not a strategy. It's a betting system.

    Hedging, grid trading, same as Martingale.
              Martingale, Hedging and Grid : MHG - General - MQL5 programming forum (2016)

    Martingale, guaranteed to blow your account eventually. If your strategy is not profitable without, it is definitely not profitable with.
              Martingale vs. Non Martingale (Simplified RoR vs Profit and the Illusions) - MQL5 programming forum (2015)

    Why it won't work:
              Calculate Loss from Lot Pips - MQL5 programming forum (2017)
              THIS Trading Strategy is a LIE... I took 100,000 TRADES with the Martingale Strategy - YouTube (2020)

  2. You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

  3. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
              Code debugging - Developing programs - MetaEditor Help
              Error Handling and Logging in MQL5 - MQL5 Articles (2015)
              Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
              Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)

Can you explain this in simple terms, sir?

The real issue is that when using a demo broker, the take profit works well. Just ignore the Martingale part since I haven’t included that code here. I’m not sure what’s causing the problem. Some say it’s the spread, others say it’s slippage… I’m not sure.

 
seems the problem cause by latest build with mathceil problem.. so i have fixed it..