Discussion of article "How to create bots for Telegram in MQL5" - page 25

 

hello guys,

I have completed the code for sending message from telegram to mt5 but i am having a small error, when sending close command of many close commands at the same time, it can only send one order but not many orders.

Can anyone help me see where I'm going wrong?

//--- now process the list of closed positions
   max_time = 0;
   double day_profit = 0;
   bool is_closed = false;
   int totalhis = hist_position.PositionsTotal();
   for(int i = 0; i < totalhis; i++) {
      //---
      pos_symbol = PositionGetSymbol(i); // Get the symbol name
      digits = (int)SymbolInfoInteger(pos_symbol, SYMBOL_DIGITS); // Get the number of digits in the price
      //--- Select a closed position by its index in the list
      if(hist_position.SelectByIndex(i)) {
         ulong    ticket            = hist_position.Ticket();
         datetime time_open         = hist_position.TimeOpen();
         ulong    time_open_msc     = hist_position.TimeOpenMsc();
         datetime time_close        = hist_position.TimeClose();
         ulong    time_close_msc    = hist_position.TimeCloseMsc();
         long     type              = hist_position.PositionType();
         string   type_desc         = hist_position.TypeDescription();
         long     magic             = hist_position.Magic();
         long     pos_id            = hist_position.Identifier();
         double   volume            = hist_position.Volume();
         double   price_open        = hist_position.PriceOpen();
         double   price_sl          = hist_position.StopLoss();
         double   price_tp          = hist_position.TakeProfit();
         double   price_close       = hist_position.PriceClose();
         double   commission        = hist_position.Commission();
         double   swap              = hist_position.Swap();
         double   profit            = hist_position.Profit();
         string   symbol            = hist_position.Symbol();
         string   open_comment      = hist_position.OpenComment();
         string   close_comment     = hist_position.CloseComment();
         string   open_reason_desc  = hist_position.OpenReasonDescription();
         string   close_reason_desc = hist_position.CloseReasonDescription();
         string   deal_tickets      = hist_position.DealTickets(",");
         //---
         int      deals_count       = HistoryDealsTotal();   // of the selected position
         int      orders_count      = HistoryOrdersTotal();  // of the selected position
         
         if(TimeToString(TimeCurrent(), TIME_DATE) == TimeToString(time_close, TIME_DATE)) {
            day_profit += profit + swap + commission;
         }
         if(time_close <= _closed_last_time) continue;
         //is_closed = true;
         string msg = StringFormat
                      (
                         "ACCOUNT: { #%s } \n" +
                         "------------ { CLOSE } -----------\n" +
                         "CLOSE ORDER - %s %s\n" +
                         "Time (GTM+0): %s\n" +
                         "------------ { CLOSE } -----------\n" +
                         "Volume: %s\n" +
                         "Open Price: %s\n" +
                         "Close Price: %s\n" +
                         "Gain/Loss: %s USD\n" +
                         "---TOTAL PROFIT TODAY---\n" +
                         "%s USD\n",
                         IntegerToString(login),
                         symbol,
                         PositionTypeToString(type),
                         TimeToString(time_close, TIME_DATE | TIME_SECONDS),
                         DoubleToString(volume, 2),
                         DoubleToString(price_open, digits),
                         DoubleToString(price_close, digits),
                         DoubleToString(profit, 2),
                         DoubleToString(day_profit, 2)
                      );
         
         int res = bot.SendMessage(InpChannelName, msg);
         if(res != 0)
            Print("Error: ", GetErrorDescription(res));
         max_time = MathMax(max_time, time_close);
      }
      _closed_last_time = MathMax(max_time, _closed_last_time);
   }
 
Bui Huy Dat #:

hello guys,

I have completed the code for sending message from telegram to mt5 but i am having a small error, when sending close command of many close commands at the same time, it can only send one order but not many orders.

Can anyone help me see where I'm going wrong?

Improperly formatted code removed by moderator. @Bui Huy Dat Please EDIT your post and use the CODE button when you insert code.

If you are serving many users via the bot there is a 30 interactions per second limit i think 

 
Lorentzos Roussos #:

If you are serving many users via the bot there is a 30 interactions per second limit i think 

I only use it personally and only to send each mt5 account to telegram.
but when opening or closing the command at the same time, it can only send one message to telegram

 
Bui Huy Dat #:

I only use it personally and only to send each mt5 account to telegram.
but when opening or closing the command at the same time, it can only send one message to telegram

There was no code when i replied , i see that you can replace the bot.SendMessage with a function that adds the message to a burst list . You could also keep growing the message and send it out of the loop but you would hit character limitations there.

A brief schematic could be like this : 

  1. You have a string array called "Outbox"
  2. A time interval within which you process the Outbox , so "OnTimer()" (you may already be using it if you are reading from telegram too)
  3. You then enforce -yourself- a milliseconds limit between each message not with the Sleep() function but by remembering when the last message was sent
  4. You can use GetTickCount() for polling milliseconds and you would store the last ms that the message left and subtract it from the current ms to get the distance in time.There is a very very very rare occasion here that the end time is < than the start time in which case you do this : (UINT_MAX-start_time+end_time)
  5. If your distance in milliseconds since the last message is bigger than the limit in milliseconds you enforce then you send the next message from the Outbox
  6. Instead of calling bot.SendMessage in the loop you now call Outbox.add_message_for_sending or something.
  7. With a modification that also stores the chat ids you could also store where the message is going and that would be the solution for multiple users.
 
Lorentzos Roussos #:

There was no code when i replied , i see that you can replace the bot.SendMessage with a function that adds the message to a burst list . You could also keep growing the message and send it out of the loop but you would hit character limitations there.

A brief schematic could be like this : 

  1. You have a string array called "Outbox"
  2. A time interval within which you process the Outbox , so "OnTimer()" (you may already be using it if you are reading from telegram too)
  3. You then enforce -yourself- a milliseconds limit between each message not with the Sleep() function but by remembering when the last message was sent
  4. You can use GetTickCount() for polling milliseconds and you would store the last ms that the message left and subtract it from the current ms to get the distance in time.There is a very very very rare occasion here that the end time is < than the start time in which case you do this : (UINT_MAX-start_time+end_time)
  5. If your distance in milliseconds since the last message is bigger than the limit in milliseconds you enforce then you send the next message from the Outbox
  6. Instead of calling bot.SendMessage in the loop you now call Outbox.add_message_for_sending or something.
  7. With a modification that also stores the chat ids you could also store where the message is going and that would be the solution for multiple users.

Thank you for replying. I will try your way

 
Hello mate. Great article. It works well for channels and groups and I have to make the bot an admin. But what if I want to send it to a personal telegram chat, how can I add the bot to a personal chat? Is that possible or must I send the messages to a channel? 
What do you think?
 
Herman Makmur #:

Never mind....

I found the answer by setting AsHTML flag to true...

bot.SendMessage(InpTelegramId,"<b>Balance: $10056.21</b>",true);

Sorry...


Hi, can u share the code on how to do that ? I am also searching for the code to make the Text Bolded and in Italic style and send to telegram server.

 

Hi everyone,

I am trying to send a message from MT5 to Telegram using a bot. However, I could not send the message from MT5 to Telegram due to the error: Error Code 400 Description "Bad request: chat not found"

Has anyone encountered the same problem? Can you give some reasons why this error might have occurred?

I did a lot of research online, but I could not get the right answers.

Forum on trading, automated trading systems and testing trading strategies

MT5 to Telegram Error: Error Code 400 Description "Bad request: chat not found"

Cerilo Cabacoy, 2023.11.21 18:14

Sir, thanks for your reply. Below is the full source code. It is just a simple expert advisor that extracts data from a text file and then attempts to send the data to a Telegram channel. However, it encountered the error mentioned.

#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

#include <Telegram.mqh>
CCustomBot tgbot;

input string TelegramBotToken = "6770842913:AAGcnR666ddL7hCB8HeTNs6HdNe28y3F-ik";
input string TelegramChatID = "-1002063516288";
input string TelegramAPIurl = "https://api.telegram.org";
input string namefile = "WagScores.txt";

datetime h1time = 0;
string channelname = "";
//+------------------------------------------------------------------+
int OnInit() {

   tgbot.Token(TelegramBotToken);
   int res = tgbot.GetMe();      Print("GetMe() results: "+(string)res);
   channelname = tgbot.Name();   Print("bot name: "+channelname);
   
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {

   
}
//+------------------------------------------------------------------+
void OnTick() {

   ChartRedraw();
   if(NewH1Bar()) {
      string data[];
      string output = "";
      GetTxtDataToArray(namefile,data); 
      string message = StringFormat("Time: %s\n",TimeToStr(TimeCurrent()));  
      StringAdd(output,message);   
      for(int i = 0; i < ArraySize(data); i++) {
         string strmsg = StringFormat("%s\n",data[i]);
         StringAdd(output,strmsg);     
      }     
      int res = tgbot.SendMessage(TelegramChatID,output);      Print((string)__LINE__+" "+(string)res);
      SendNotification(output);
   }
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
bool NewH1Bar() { 
     
   datetime newtime = iTime(Symbol(),PERIOD_H1,0);
   if(newtime==h1time) return false;
   h1time = newtime;                                
   return true;
}
//+------------------------------------------------------------------+   
void GetTxtDataToArray(string filename,string &array[]) { 
             
   if(!FileIsExist(filename)) return;
   int handle = FileOpen(filename,FILE_TXT|FILE_READ|FILE_ANSI);
   if(handle==INVALID_HANDLE) { Print(""+__FUNCTION__+" "+(string)__LINE__+" opening file error"); return; }
   FileSeek(handle,0,SEEK_SET);
   while(!FileIsEnding(handle)) {
      string line = FileReadString(handle); 
      ArrayResize(array,ArraySize(array)+1);         
      array[ArraySize(array)-1] = line;
   }
   FileClose(handle);    
}

OOP in MQL5 by Example: Processing Warning and Error Codes
OOP in MQL5 by Example: Processing Warning and Error Codes
  • www.mql5.com
The article describes an example of creating a class for working with the trade server return codes and all the errors that occur during the MQL-program run. Read the article, and you will learn how to work with classes and objects in MQL5. At the same time, this is a convenient tool for handling errors; and you can further change this tool according to your specific needs.
 

Forum on trading, automated trading systems and testing trading strategies

Adding emoji in telegram messages.

Frédéric LEBRE, 2023.12.04 13:56

Hello, 

Please could you help me.

I try to send a message to telegram using emoji.

when emoji unicode is for example : U+2702 i use as string value " \x2702" and if works.

SendTelegramMessage(TelegramApiUrl, TelegramBotToken, ChatId, "\x2702");

But when unicode is like this : U+1F648 nothing works.

I included <Telegram.mqh> as i read in topics, but i do not know how to do more.

Thx for your answers.

Reason: