Discussão do artigo "Como criar bots para Telegram em MQL5" - página 30

 
Andrey Voytenko:

Gostaria de pedir àqueles que não estão conseguindo executar o Telegram via WebRequest que executem esse script e copiem aqui a linha da guia Experts com o resultado. Isso ajudará a identificar rapidamente o problema.

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:

No Windows 10 pro e no Server 2016, as solicitações são enviadas sem problemas.

 
GedThey MaThey:

Já testei seu script em dois sistemas

Primeiro, no Windows 7 7601 SP1, com erro de execução como o seu erro
Segundo, no Windows 10 pro 64 bit build 18363, funcionando bem, sem erro


Meus scripts funcionam com os mesmos resultados, portanto, posso confirmar isso agora:

- Windows 7: NÃO funciona ❌

- Windows 10: Funciona bem ✅

@Andrey Voytenko

 

Olá, pessoal, preciso de ajuda



Quando faço um pedido, o bot está enviando a mesma mensagem várias vezes,

Aqui está o código!


Obrigado desde já

#include <Telegram.mqh>


input string InpChannelName="@signal";/Nome do canal
input string InpToken="1049045330:AxxxxxxbFxxx0-IxwKXyxxxxxxxx";Token //Bot


CCustomBot bot;

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




//+------------------------------------------------------------------+
//| Função de inicialização especializada|
//+------------------------------------------------------------------+
int OnInit()
  {
   time_signal=0;

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


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

//+------------------------------------------------------------------+
//| Função de desinicialização de especialista|
//+------------------------------------------------------------------+
void OnDeinit(const int reason)

{

}
     
  
//+------------------------------------------------------------------+
//| Função de tique de especialista|
//+------------------------------------------------------------------+
void OnTick()
  {
  

   string message = "";
   int total=OrdersTotal();
  
        
   for(int pos=0;pos<total;pos++){  // Pedidos atuais -----------------------
     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++){  // Pedidos de histórico-----------------------
      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}";
}
   

   
//---
 

Olá, senhor! Obrigado por essa ótima ferramenta!


Gostaria de saber se já tenho minhas predefinições de alertas em diferentes indicadores configurados para alertas por e-mail. Posso saber quais linhas preciso adicionar para receber em meu canal por meio de seu telegrama mql.


Já tenho todos os arquivos na pasta include


Obrigado desde já



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

//--- configurações do indicador
#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";/Nome do canal
input string InpToken="xxxxxxx:AxxxxxxbFxxx0-IxwKXyxxxxxxxx";Token //Bot


CCustomBot bot;

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



//--- buffers de indicadores
double Buffer1[];
double Buffer2[];

datetime time_alert; //usado ao enviar um alerta
bool Send_Email = true;
double myPoint; //inicializado no 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);
     }
  }

//+------------------------------------------------------------------+
//| Função de inicialização do indicador personalizado
//+------------------------------------------------------------------+
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);
   
   
   //inicializar 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);
  }

//+------------------------------------------------------------------+
//| Função de iteração de indicador personalizado|
//+------------------------------------------------------------------+
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;
   //--- contando de 0 a rates_total
   ArraySetAsSeries(Buffer1, true);
   ArraySetAsSeries(Buffer2, true);
   //--- zero inicial
   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);
   //--- loop principal
   for(int i = limit-1; i >= 0; i--)
     {
      if (i >= MathMin(5000-1, rates_total-1-50)) continue; //omitir algumas taxas antigas para evitar "Array out of range" ou cálculo lento 
      
      int barshift_D1 = iBarShift(Symbol(), PERIOD_D1, TimeShift[i]);
      if(barshift_D1 < 0) continue;
      
      //Buffer do indicador 1
      if(MACD_Main[barshift_D1] > MACD_Signal[barshift_D1]
      && MACD_Main[barshift_D1+1] < MACD_Signal[barshift_D1+1] //MACD cruza acima do MACD
      )
        {
         Buffer1[i] = Low[i]; /Definir o valor do indicador em Candlestick Low
         if(i == 0 && Time[0] != time_alert)
         { myAlert("",
        "\n"
        "\n" + ">Direction : " " UP"); time_alert = Time[0]; } //Alerta instantâneo, apenas uma vez por barra
        }
      else
        {
         Buffer1[i] = EMPTY_VALUE;
        }
      //Buffer do indicador 2
      if(MACD_Main[barshift_D1] < MACD_Signal[barshift_D1]
      && MACD_Main[barshift_D1+1] > MACD_Signal[barshift_D1+1] //MACD cruza abaixo do MACD
      )
        {
         Buffer2[i] = High[4+i]; /Definir o valor do indicador em Candlestick High
         if(i == 0 && Time[0] != time_alert) 
         { myAlert(" ",
         "\n"
         "\n" + ">Direction : " " DOWN"); time_alert = Time[0]; } //Alerta instantâneo, apenas uma vez por barra
        }
      else
        {
         Buffer2[i] = EMPTY_VALUE;
        }
     }
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
OrelMely:



A biblioteca funciona em indicadores?
 
Jefferson Metha:
A biblioteca funciona com indicadores?

Sim, ele predefiniu um arquivo de sinal que já funciona com o MACD...


Mas como tenho habilidades limitadas de programação, não posso executá-lo no momento

 

Hi,

O Mt4 exibe um erro quando tento enviar uma foto:


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


Parece que ele acha que estou tentando acessar EURUSD.gif de um servidor enquanto ele está em "MQL4/Files".

Tentei usar um caminho direto dos arquivos do Windows, mas o problema persiste. Estou preso a esse problema há horas. Alguém tem alguma pista?

Aqui está o meu código

      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...
 
Desculpe-me, mas não tenho certeza do que estou fazendo de errado. Você quer dizer que não posso enviar uma foto localmente e que preciso carregá-la em um servidor primeiro?