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

 
Andrey Voytenko:

I would like to ask those who are unable to run Telegram via WebRequest to run this script and copy here the line from the Experts tab with the result. This will help to quickly identify the problem.

2020.06.10 10:16:02.090    TestWebRequest (EURUSD,M15)    Build=2485 
WebRequest=200 GetLastError=0 
strData={"ok":true,"result":{"id":177791741,"is_bot":true,"first_name":"ForexSignal","username":"ForexSignalBot","can_join_groups":true,"can_read_all_group_messages":true,"supports_inline_queries":true}}
 
Ilyas:

From windows 10 pro and server 2016 requests are sent without any problems.

 
GedThey MaThey:

I am already test your script in two system

First in windows 7 7601 SP1, running error like  your error
Second in windows 10 pro 64 bit build 18363 running well no error


I've got my scripts work with the same results so I can confirm this now:

 - Windows 7: Does NOT work ❌

 - Windows 10: Does work well ✅

@Andrey Voytenko

 

Hello guys i need help  



when i place a order the bot is sending the same message multiple times, 

Here is the code !


thanks in advance

#include <Telegram.mqh>


input string InpChannelName="@signal";//Channel Name
input string InpToken="1049045330:AxxxxxxbFxxx0-IxwKXyxxxxxxxx";//Bot Token


CCustomBot bot;

datetime time_signal=0;
//int SendMessage(const string channel_name,
                //const string text);




//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   time_signal=0;

//--- set token
   bot.Token(InpToken);


//--- done
   return(INIT_SUCCEEDED);
  }
 
  datetime _opened_last_time = TimeCurrent() ;
  datetime _closed_last_time = TimeCurrent()  ;
  
 

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)

{

}
     
  
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  

   string message = "";
   int total=OrdersTotal();
  
        
   for(int pos=0;pos<total;pos++){  // Current orders -----------------------
     if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
     if(OrderOpenTime() <= _opened_last_time) continue;
     
     message += StringFormat("Order opened!\r\nType: %s\r\nSymbol: %s\r\nPrice: %s\r\nSL: %s\r\nTP: %s\r\nTime: %s\r\nTicket:.%s ",
     order_type(),
     OrderSymbol(),
     DoubleToStr(OrderOpenPrice(),MarketInfo(OrderSymbol(),MODE_DIGITS)),
     DoubleToStr(OrderStopLoss(),MarketInfo(OrderSymbol(),MODE_DIGITS)),
     DoubleToStr(OrderTakeProfit(),MarketInfo(OrderSymbol(),MODE_DIGITS)),
     TimeToStr(OrderOpenTime(),TIME_MINUTES),
     IntegerToString(OrderTicket())
          
      );
      
     int res=bot.SendMessage(InpChannelName,message);
     if(res!=0)
         Print("Error: ",GetErrorDescription(res));
     
     }
     
      bool is_closed = false;

  
  total = OrdersHistoryTotal();
      
   for(int pos=0;pos<total;pos++){  // History orders-----------------------
      if(OrderSelect(pos,SELECT_BY_POS,MODE_HISTORY)==false) continue;
      if(OrderCloseTime() <= _closed_last_time) continue;
     printf(OrderCloseTime());
     is_closed = true;
     
     message += StringFormat("Order closed!\r\nTicket: %s\r\nSymbol: %s\r\nClosing Price: %s\r\nTime: %s",
     IntegerToString(OrderTicket()),
     OrderSymbol(),
     DoubleToStr(OrderClosePrice(),MarketInfo(OrderSymbol(),MODE_DIGITS)),
     TimeToStr(OrderCloseTime(),TIME_MINUTES),
     DoubleToStr(order_pips(),1)
     
     
     );
      
      int res=bot.SendMessage(InpChannelName,message);
     if(res!=0)
         Print("Error: ",GetErrorDescription(res));
      
     }
 
   }
   
   
double order_pips() {
   double pips;
   
   if(OrderType() == OP_BUY) {
      pips =  (OrderClosePrice()-OrderOpenPrice())/MarketInfo(OrderSymbol(),MODE_POINT);
   } else {
      pips =  (OrderOpenPrice()-OrderClosePrice())/MarketInfo(OrderSymbol(),MODE_POINT);
   }
   return pips/10;
}

string order_type_to_str(int type)
{
   return StringSubstr(EnumToString((ENUM_ORDER_TYPE)type), 11);
}
string order_type () {
   return order_type_to_str(OrderType());
   
   if(OrderType() == OP_BUY)        return "BUY";
   if(OrderType() == OP_SELL)       return "SELL";
   if(OrderType() == OP_BUYLIMIT)   return "BUY LIMIT";
   if(OrderType() == OP_SELLLIMIT)  return "SELL LIMIT";
   if(OrderType() == OP_BUYSTOP)    return "BUYSTOP";
   if(OrderType() == OP_SELLSTOP)   return "SELLSTOP";
   
   return "{err}";
}
   

   
//---
 

Hello Sir !! Thanks for this nice tool!


I am wondering if I have already my alerts presets on different indicators setup for email alerts , Can i know which lines I need to add to receive on my channel via your telegram mql.


I have already all the files at include folder 


Thanks in advance



//+------------------------------------------------------------------+
//|                                              Indicator: Alert.mq5 |
//|                                                                   |
//|                                                                   |
//+------------------------------------------------------------------+
#property copyright ""
#property link      ""
#property version   "1.00"
#property description ""

//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 2

#property indicator_type1 DRAW_ARROW
#property indicator_width1 4
#property indicator_color1 0xFFFFFF
#property indicator_label1 "Buy"

#property indicator_type2 DRAW_ARROW
#property indicator_width2 4
#property indicator_color2 0xC437C4
#property indicator_label2 "Sell"

#include <Telegram.mqh>


input string InpChannelName="@xxxxx";//Channel Name
input string InpToken="xxxxxxx:AxxxxxxbFxxx0-IxwKXyxxxxxxxx";//Bot Token


CCustomBot bot;

datetime time_signal=0;
//int SendMessage(const string channel_name,
                //const string text);



//--- indicator buffers
double Buffer1[];
double Buffer2[];

datetime time_alert; //used when sending alert
bool Send_Email = true;
double myPoint; //initialized in OnInit
int MACD_handle;
double MACD_Main[];
double MACD_Signal[];
double Low[];
double High[];
double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double Last = SymbolInfoDouble(_Symbol, SYMBOL_LAST);

void myAlert(string type, string message)
  {
   if(type == "print")
      Print(message);
   else if(type == "error")
     {
      Print(type+" DAILY ALERT "+Symbol()+message);
     }
   else if(type == "order")
     {
     }
   else if(type == "modify")
     {
     }
   else if(type == "")
     {
      if(Send_Email) SendMail("DAILY ALERT",">Symbol : "+Symbol()+
      "\n"
      "\n" + "Price : "+ DoubleToString(Last) +  
      "\n" + "Date : "+TimeToString(TimeLocal(),TIME_DATE )+
      "\n" + "Time : "+TimeToString(TimeLocal(),TIME_MINUTES)+
      "\n" + "Time Frame : "+EnumToString((ENUM_TIMEFRAMES)Period())+message);
     }
  }

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {   
   SetIndexBuffer(0, Buffer1);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_ARROW, 241);
   SetIndexBuffer(1, Buffer2);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(1, PLOT_ARROW, 242);
   
   
   //initialize myPoint
   myPoint = Point();
   if(Digits() == 5 || Digits() == 3)
     {
      myPoint *= 10;
     }
   MACD_handle = iMACD(NULL, PERIOD_D1, 12, 26, 9, PRICE_CLOSE);
   if(MACD_handle < 0)
     {
      Print("The creation of iMACD has failed: MACD_handle=", INVALID_HANDLE);
      Print("Runtime error = ", GetLastError());
      return(INIT_FAILED);
     }
   
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime& time[],
                const double& open[],
                const double& high[],
                const double& low[],
                const double& close[],
                const long& tick_volume[],
                const long& volume[],
                const int& spread[])
  {
   int limit = rates_total - prev_calculated;
   //--- counting from 0 to rates_total
   ArraySetAsSeries(Buffer1, true);
   ArraySetAsSeries(Buffer2, true);
   //--- initial zero
   if(prev_calculated < 1)
     {
      ArrayInitialize(Buffer1, 0);
      ArrayInitialize(Buffer2, 0);
     }
   else
      limit++;
   datetime TimeShift[];
   datetime Time[];
   
   if(BarsCalculated(MACD_handle) <= 0) 
      return(0);
   if(CopyBuffer(MACD_handle, MAIN_LINE, 0, rates_total, MACD_Main) <= 0) return(rates_total);
   ArraySetAsSeries(MACD_Main, true);
   if(CopyTime(Symbol(), PERIOD_CURRENT, 0, rates_total, TimeShift) <= 0) return(rates_total);
   ArraySetAsSeries(TimeShift, true);
   if(BarsCalculated(MACD_handle) <= 0) 
      return(0);
   if(CopyBuffer(MACD_handle, SIGNAL_LINE, 0, rates_total, MACD_Signal) <= 0) return(rates_total);
   ArraySetAsSeries(MACD_Signal, true);
   if(CopyLow(Symbol(), PERIOD_CURRENT, 0, rates_total, Low) <= 0) return(rates_total);
   ArraySetAsSeries(Low, true);
   if(CopyHigh(Symbol(), PERIOD_CURRENT, 0, rates_total, High) <= 0) return(rates_total);
   ArraySetAsSeries(High, true);
   if(CopyTime(Symbol(), Period(), 0, rates_total, Time) <= 0) return(rates_total);
   ArraySetAsSeries(Time, true);
   //--- main loop
   for(int i = limit-1; i >= 0; i--)
     {
      if (i >= MathMin(5000-1, rates_total-1-50)) continue; //omit some old rates to prevent "Array out of range" or slow calculation   
      
      int barshift_D1 = iBarShift(Symbol(), PERIOD_D1, TimeShift[i]);
      if(barshift_D1 < 0) continue;
      
      //Indicator Buffer 1
      if(MACD_Main[barshift_D1] > MACD_Signal[barshift_D1]
      && MACD_Main[barshift_D1+1] < MACD_Signal[barshift_D1+1] //MACD crosses above MACD
      )
        {
         Buffer1[i] = Low[i]; //Set indicator value at Candlestick Low
         if(i == 0 && Time[0] != time_alert)
         { myAlert("",
        "\n"
        "\n" + ">Direction : " " UP"); time_alert = Time[0]; } //Instant alert, only once per bar
        }
      else
        {
         Buffer1[i] = EMPTY_VALUE;
        }
      //Indicator Buffer 2
      if(MACD_Main[barshift_D1] < MACD_Signal[barshift_D1]
      && MACD_Main[barshift_D1+1] > MACD_Signal[barshift_D1+1] //MACD crosses below MACD
      )
        {
         Buffer2[i] = High[4+i]; //Set indicator value at Candlestick High
         if(i == 0 && Time[0] != time_alert) 
         { myAlert(" ",
         "\n"
         "\n" + ">Direction : " " DOWN"); time_alert = Time[0]; } //Instant alert, only once per bar
        }
      else
        {
         Buffer2[i] = EMPTY_VALUE;
        }
     }
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
OrelMely:



Does the library work in indicators
 
Jefferson Metha:
Does the library work in indicators

Yes, he has preset a signal file working already with MACD... 


But i have limit code skills , so i can not run it atm

 

Hi,

Mt4 display an error when I'm trying to send a photo :


  • EURUSD,H1: {"ok":false,"error_code":400,"description":"Bad Request: wrong HTTP URL specified"}


It seems like he think I'm trying to reach EURUSD.gif from a server while it is on "MQL4/Files".

I tried with a direct path from windows files but the issue remains. I'm stuck on this issue for hours now, does anybody have a clue?

Here's my code

      bot.Token(token);
      
      string photo_id;
      int result=bot.SendPhoto(-1001098781629,"EURUSD.gif",photo_id);
      if(result==0)
         Print("Photo ID: ",photo_id);
      else
         Print("Error: ",GetErrorDescription(result));
 
Telegram Bot API
  • core.telegram.org
The Bot API is an HTTP-based interface created for developers keen on building bots for Telegram. To learn how to create and set up a bot, please consult our Introduction to Bots and Bot FAQ . Recent changes June 4, 2020 Added the new field via_bot to the Message object. You can now know which bot was used to send a message. Supported video...
 
I'm sorry but I'm not sure of what I'm doing wrong. Do you mean that I can't locally send a photo and that I need to upload it to a server first?