Hedge Implementation

 

Could you please help me implement HEDGE in my code? I can't do it at all... I don't mind opening the code, I ask for help from more experienced people, I make the code available... I've already searched in mql5 but nothing that fits my code... please...

Auto-translation applied by moderator

void OnTick()
  {
   if(TimeDay(TimeCurrent()) != LastTradingDay)
     {
      // É um novo dia de negociação, redefina a variável stopTrading para permitir a negociação
      stopTrading = false;
      LastTradingDay = TimeDay(TimeCurrent());
     }
   double BuyPrice = BuyPric();
   double SellPrice = SellPric();
//+------------------------------------------------------------------+
   Lot = NormalizeDouble(AccountBalance() / 100 * Percentual_Risco_de_seu_Capital / (MarketInfo(Symbol(), MODE_TICKVALUE) * 100 * D), 2);
   if(Lot < MarketInfo(Symbol(), MODE_MINLOT))
      Lot = MarketInfo(Symbol(), MODE_MINLOT);
//+------------------------------------------------------------------+
   for(int i = ObjectsTotal() - 1; i >= 0; i--)
     {
      PricBuyLine = ObjectGetDouble(0, "LineBuy", OBJPROP_PRICE);
      PricSellLine = ObjectGetDouble(0, "LineSell", OBJPROP_PRICE);
     }
   if(Ask + Distancia_pontos_Entrada * D * Point < PricBuyLine)
     {HLineMove("LineBuy", Ask + Distancia_pontos_Entrada * D * Point);}
   if(Bid - Distancia_pontos_Entrada * D * Point > PricSellLine)
     {HLineMove("LineSell", Bid - Distancia_pontos_Entrada * D * Point);}
   if(Ask < PricSellLine && Bid - Distancia_pontos_Entrada * D * Point > PricBuyLine)
     {HLineMove("LineBuy", Ask + Distancia_pontos_Entrada * D * Point);}
   if(Bid > PricBuyLine && Ask + Distancia_pontos_Entrada * D * Point < PricSellLine)
     {HLineMove("LineSell", Bid - Distancia_pontos_Entrada * D * Point);}
   if(TimeHour(TimeCurrent()) >= Ligar_Hr_MT4 && TimeHour(TimeCurrent()) < Desligar_Hr_MT4)
{
   if(!stopTrading)
   {
      int negOrders = 0; // Variável para contar ordens negativas
      double negLots = 0; // Variável para somar os lotes das ordens negativas

      for(int i = OrdersTotal()-1; i >= 0 ; i--)
      {
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         {
            if(OrderSymbol() == Symbol() && OrderMagicNumber() == Numero_MAgico)
            {
               if(OrderProfit() < 0) // Se a ordem está perdendo
               {
                  negOrders++;
                  negLots += OrderLots();
               }
            }
         }
      }

       if(AccountBalance() <= InitialBalance * 0.95) // Se o saldo atual é menor que 95% do saldo inicial
      {
         // Abra uma ordem de hedge com lotes iguais às ordens negativas
         //int hedgeOrderType = (LastType() == OP_BUY) ? OP_SELL : OP_BUY; // Se a última ordem foi de COMPRA, a ordem de hedge será de VENDA, e vice-versa
         int hedgeOrderType = (LastType() == OP_BUY) ? OP_SELL : OP_BUY;  // Se a última ordem foi de VENDA, a ordem de hedge será de COMPRA, e vice-versa
         //double hedgeOrderPrice = (hedgeOrderType == OP_BUY) ? Bid : Ask; // Se a ordem de hedge é de COMPRA, use o preço Ask, se é de VENDA, use o preço Bid
          double hedgeOrderPrice = (hedgeOrderType == OP_BUY) ? Ask : Bid; // Se a ordem de hedge é de COMPRA, use o preço Ask, se é de VENDA, use o preço Bid

         r = OrderSend(Symbol(), hedgeOrderType, negLots, hedgeOrderPrice, 10, 0, 0, comment, Numero_MAgico, 0, clrRed);
      }

      if(Open[0] > Close[0] && Ask <= PricSellLine && LastType() != OP_SELL && Count(-1) == 0)
      {
         r = OrderSend(Symbol(), OP_SELL, Lot, Bid, 10, 0, 0, comment, Numero_MAgico, 0, clrRed);
         HLineMove("LineBuy", Ask + Distancia_pontos_Entrada * D * Point);
      }

      if(Open[0] < Close[0] && Bid >= PricBuyLine && LastType() != OP_BUY && Count(-1) == 0)
      {
         r = OrderSend(Symbol(), OP_BUY, Lot, Ask, 10, 0, 0, comment, Numero_MAgico, 0, clrGreen);
         HLineMove("LineSell", Bid - Distancia_pontos_Entrada * D * Point);
      }

      NewLot = Lot * (MathPow(Multiplicador_Lote, Count(-1)));

      if(Open[0] > Close[0] && Ask <= PricSellLine && Count(OP_SELL) > 0 && Bid - Step * D * Point > SellPric())
      {
         r = OrderSend(Symbol(), OP_SELL, NewLot, Bid, 10, 0, 0, comment, Numero_MAgico, 0, clrRed);
         HLineMove("LineBuy", Ask + Distancia_pontos_Entrada * D * Point);
      }

      if(Open[0] < Close[0] && Bid >= PricBuyLine && Count(OP_BUY) > 0 && Ask + Step * D * Point < BuyPric())
      {
         r = OrderSend(Symbol(), OP_BUY, NewLot, Ask, 10 ,0, 0, comment, Numero_MAgico, 0, clrGreen);
         HLineMove("LineSell", Bid - Distancia_pontos_Entrada * D * Point);
      }
   }
}

//---
   NewProfProc = Profit(-1) / (AccountBalance() / 100);
// Calcula a porcentagem de lucro em relação ao saldo inicial
   double currentProfitPercent = (AccountBalance() - InitialBalance) / InitialBalance * 100.0;
   if(currentProfitPercent >= Seu_Lucro_do_Dia && !stopTrading)
     {
      Comment("Meta de lucro atingida. Negociação suspensa até amanhã.");
      stopTrading = true;  // Desabilitar as operações
      LastTradingDay = TimeDay(TimeCurrent());
     }
   if(TimeDay(TimeCurrent()) != LastTradingDay)
     {
      // É um novo dia de negociação, redefina a variável stopTrading para permitir a negociação
      stopTrading = false;
      LastTradingDay = TimeDay(TimeCurrent());
     }
   if(tradingEnabled && NewProfProc >= Percentual_seu_Saldo_Lucro_Por_Entrada)
     {
      CloseMinus(-1);
      ClosePlus(-1);
     }
   if(tradingEnabled)
     {
      for(int i = 0; i < OrdersTotal(); i++)
        {
         if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
           {
            double orderProfit = OrderProfit();
            double orderOpenPrice = OrderOpenPrice();
            double currentPrice = MarketInfo(OrderSymbol(), MODE_BID);
              {
                 {
                    {
                       {
                        Print("Ordem fechada com sucesso!");
                       }
                       {
                       }
                    }
                 }
              }
           }
        }
     }
   string profitText;
   if(currentProfitPercent >= 0)
     {
      profitText = "Neste momento você está " + DoubleToStr(currentProfitPercent, 2) + "% de lucro";
     }
   else
     {
      profitText = "Neste momento você está -" + DoubleToStr(MathAbs(currentProfitPercent), 2) + "% de prejuízo";
     }
   ObjectSetText(ProfitLabel, profitText, 12, "Arial", Lime);
   ObjectSetInteger(0, ProfitLabel, OBJPROP_CORNER, 0);
   ObjectSetInteger(0, ProfitLabel, OBJPROP_XDISTANCE, 990);
   ObjectSetInteger(0, ProfitLabel, OBJPROP_YDISTANCE, 570);
//+------------------------------------------------------------------+
   if(NewProfProc >= Percentual_seu_Saldo_Lucro_Por_Entrada)
     { {CloseMinus(-1); ClosePlus(-1);}}
Files:
FAST_JAPA.mq4  65 kb
 

On the English forum, please write in English. Either use the automatic translation tool, or post in one of the other language forums.

Your topic has been moved to the section: MQL4 and MetaTrader 4
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893

 
  • Usually people who can't code don't receive free help on this forum.
  • If you show your attempts and describe your problem clearly, you will most probably receive an answer from the community. Use the CODE button (Alt-S) when inserting code.
  • To learn MQL4 programming, you can research the many available Articles on the subject, or examples in the Codebase, as well as reference the online Documentation.
  • If you do not want to learn to code, that is not a problem. You can either look at the Codebase if something free already exists, or in the Market for paid products (also sometimes free). However, recommendations or suggestions for Market products are not allowed on the forum, so you will have to do your own research.
  • Finally, you also have the option to hire a programmer in the Freelance section.
Reason: