Undeclared identifier

 

Hey guys,


I have a problem with "telegram undeclared identifier in the attached code.

I've tried every way but I haven't been able to resolve it.

If anyone knows and can solve it I would really appreciate it.

tks


Samuel

Files:
7trader.mq5  13 kb
 
// Create a Telegram object
CTrade trade
CTelegram telegram
No terminating semicolons.
 
William Roder # : Sem ponto-e-vírgula final.

As you can see below on the picture I have created it already




 
Samuel Saar #: s you can see below on the picture I have created it already

You haven't created it. What you posted will not compile.

 
I'm sorry, William, but I'm new to programming and still have some difficulty understanding most of the logic, but I want to learn. You said my file won't compile. Have you seen the complete file I posted? I confess to you that I didn't understand what's missing in my code for it to compile. Could you please detail the step-by-step process for me to resolve the problem? If you prefer, you can correct the file and explain the corrections to me, and then return it to me; I would be very grateful.
 
Samuel Saar # I didn't understand what's missing in my code for it to compile.

I told you what was missing in the first post.

 

Lokk my code below:

As you can see, I have created 

// Create a Telegram object
CTrade trade
CTelegram telegram

Look below

//+------------------------------------------------------------------+
//|                                                Telegram EA     |
//|                                                                |
//+------------------------------------------------------------------+
#property copyright "SAS"
#property link ""
#property version "1.10"
#property strict

// Include the Telegram library
#include <Telegram.mqh>
#include <Trade/Trade.mqh>

// Create a Telegram object
CTrade trade
CTelegram telegram

// Define the input parameters
input string TelegramToken = "";
input string TelegramChatID = "";
input double Lots = 0.1;
input int MaxRetries = 3; // Número máximo de tentativas de conexão com o Telegram

// Define a struct to hold order parameters
struct OrderParameters {
   string symbol;
   double price;
   double stopLoss;
   double takeProfit;
};

// Define the order prefixes
input string BuyOrderPrefix = "🟢 COMPRA ↗️";
input string SellOrderPrefix = "🔴 VENDA ↘️";
input string CloseOrderPrefix = "🚪ATENÇÃO SAIR";

// Define the order types enumeration
enum OrderTypes {
   BUY,
   SELL,
   CLOSE
};

// Define the timer interval
input int TimerIntervalMilissegs = 500; // Intervalo de verificação em milissegundos

//+------------------------------------------------------------------+
//| Expert initialization function                                  |
//+------------------------------------------------------------------+
int OnInit()
{
   // Iniciar o timer para verificar mensagens do Telegram
   EventSetTimer(TimerIntervalMilissegs);

   // Conectar ao Telegram com tratamento de exceções
   int retries = 0;
   while (!telegram.Connect(TelegramToken) && retries < MaxRetries)
   {
      Print("Erro ao conectar ao Telegram. Tentando novamente...");
      retries++;
      Sleep(1000); // Aguardar 1 segundo antes da próxima tentativa
   }

   if (retries == MaxRetries)
   {
      Print("Não foi possível conectar ao Telegram após várias tentativas. Encerrando o Expert Advisor.");
      return INIT_FAILED;
   }

   Print("Conectado ao Telegram com sucesso!");
   return INIT_SUCCEEDED;
}

// Restante do código...

//+------------------------------------------------------------------+
//| Expert deinitialization function                                |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   // Parar o timer
   EventKillTimer();

   // Desconectar do bot do Telegram
   telegram.Disconnect();

   Print("Desconectado do Telegram.");
}

//+------------------------------------------------------------------+
//| Timer event handler                                             |
//+------------------------------------------------------------------+
void OnTimer()
{
   Print("Verificando mensagens do Telegram...");

   // Obter as últimas mensagens do Telegram
   string updates = telegram.GetUpdates();

   // Verificar se há novas mensagens
   int messageCount = telegram.MessageCount(updates);
   for (int i = 0; i < messageCount; i++)
   {
      // Obter o texto da mensagem
      string messageText = telegram.MessageText(updates, i);

      // Verificar se a mensagem é do contato autorizado
      if (StringFind(messageText, TelegramChatID) == 0)
      {
         Print("Mensagem do contato autorizado recebida!");

         // Verificar se a mensagem indica uma operação de compra
         if (StringFind(messageText, BuyOrderPrefix) != -1)
         {
            ExecuteTradeOrder(messageText, OrderTypes::BUY);
         }
         // Verificar se a mensagem indica uma operação de venda
         else if (StringFind(messageText, SellOrderPrefix) != -1)
         {
            ExecuteTradeOrder(messageText, OrderTypes::SELL);
         }
         // Verificar se a mensagem indica fechamento de operação
         else if (StringFind(messageText, CloseOrderPrefix) != -1)
         {
            ExecuteTradeOrder(messageText, OrderTypes::CLOSE);
         }
      }
   }
}

//+------------------------------------------------------------------+
//| Função para executar operações de trading                       |
//+------------------------------------------------------------------+
void ExecuteTradeOrder(string& message, OrderTypes orderType)
{
   Print("Executando ordem de trading...");

   // Extrair o símbolo do ativo da mensagem
   int symbolStart = StringFind(message, "📣📣📣") + 6;
   int symbolEnd = StringFind(message, "📣📣📣", symbolStart);
   string symbol = StringSubstr(message, symbolStart, symbolEnd - symbolStart);

   // Extrair os parâmetros da ordem da mensagem
   OrderParameters orderParams;
   orderParams.symbol = symbol;
   orderParams.price = ExtractParameter(message, "Preço de Abertura:");
   orderParams.stopLoss = ExtractParameter(message, "Stop Loss:");
   orderParams.takeProfit = ExtractParameter(message, "Take Profit:");

   // Executar a operação correspondente
   if (orderType == OrderTypes::BUY)
   {
      // Executar operação de compra
      ExecuteBuyOrder(orderParams);
   }
   else if (orderType == OrderTypes::SELL)
   {
      // Executar operação de venda
      ExecuteSellOrder(orderParams);
   }
   else if (orderType == OrderTypes::CLOSE)
   {
      // Fechar operação
      CloseTrade(orderParams);
   }
}

//+------------------------------------------------------------------+
//| Função para executar uma ordem de compra                        |
//+------------------------------------------------------------------+
void ExecuteBuyOrder(OrderParameters& params)
{
   Print("Executando ordem de compra...");

   // Implementar a lógica para executar a ordem de compra
   if (trade.Buy(Lots, params.symbol, params.price, params.stopLoss, params.takeProfit))
   {
      Print("Ordem de compra executada com sucesso!");
   }
   else
   {
      Print("Erro ao executar a ordem de compra.");
   }
}

//+------------------------------------------------------------------+
//| Função para executar uma ordem de venda                         |
//+------------------------------------------------------------------+
void ExecuteSellOrder(OrderParameters& params)
{
   Print("Executando ordem de venda...");

   // Implementar a lógica para executar a ordem de venda
   if (trade.Sell(Lots, params.symbol, params.price, params.stopLoss, params.takeProfit))
   {
      Print("Ordem de venda executada com sucesso!");
   }
   else
   {
      Print("Erro ao executar a ordem de venda.");
   }
}

//+------------------------------------------------------------------+
//| Função para fechar uma operação de trading                      |
//+------------------------------------------------------------------+
void CloseTrade(OrderParameters& params)
{
   Print("Fechando operação de trading...");

   // Implementar a lógica para fechar a operação
   if (trade.PositionClose(params.symbol))
   {
      Print("Operação fechada com sucesso!");
   }
   else
   {
      Print("Erro ao fechar a operação.");
   }
}

//+------------------------------------------------------------------+
//| Função para extrair um parâmetro da mensagem do Telegram        |
//+------------------------------------------------------------------+
double ExtractParameter(string message, string parameterName)
{
   Print("Extraindo parâmetro da mensagem do Telegram...");

   int start = StringFind(message, parameterName) + StringLen(parameterName);
   int end = StringFind(message, "\n", start);
   string valueStr = StringSubstr(message, start, end - start);
   return StringToDouble(valueStr);
}
 
Samuel Saar #:

Lokk my code below:

As you can see, I have created 

Read William's first post again. You're missing semicolons at the end of those two lines.

Reason: