Discusión sobre el artículo "Cómo crear un bot para Telegram en el lenguaje MQL5" - página 30

 
Andrey Voytenko:

Me gustaría pedir a aquellos que no puedan ejecutar Telegram vía WebRequest que ejecuten este script y copien aquí la línea de la pestaña Expertos con el resultado. Esto ayudará a identificar rápidamente el 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:

Desde windows 10 pro y server 2016 las peticiones se envían sin problemas.

 
GedThey MaThey:

Ya estoy probar el script en dos sistemas

En primer lugar en las ventanas 7 7601 SP1, error de ejecución como el error
En segundo lugar en las ventanas 10 pro 64 bits build 18363 funcionando bien sin error


Tengo mi trabajo de secuencias de comandos con los mismos resultados para que pueda confirmar esto ahora:

- Windows 7: NO funciona ❌

- Windows 10: Funciona bien ✅

@Andrey Voytenko

 

Hola chicos necesito ayuda



cuando hago un pedido el bot esta enviando el mismo mensaje varias veces,

¡Aquí está el código!


gracias de antemano

#include <Telegram.mqh>


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


CCustomBot bot;

datetime time_signal=0;
//int SendMessage(const cadena nombre_canal,
                //const cadena texto);




//+------------------------------------------------------------------+
//| Función de inicialización experta|
//+------------------------------------------------------------------+
int OnInit()
  {
   time_signal=0;

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


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

//+------------------------------------------------------------------+
//| Función de desinicialización experta|
//+------------------------------------------------------------------+
void OnDeinit(const int reason)

{

}
     
  
//+------------------------------------------------------------------+
//| Función tick experto|
//+------------------------------------------------------------------+
void OnTick()
  {
  

   string message = "";
   int total=OrdersTotal();
  
        
   for(int pos=0;pos<total;pos++){  // Pedidos actuales -----------------------
     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++){  // Historia pedidos-----------------------
      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}";
}
   

   
//---
 

¡¡Hola Señor !! ¡Gracias por esta buena herramienta!


Me pregunto si ya tengo mis alertas preestablecidas en diferentes indicadores de configuración de alertas de correo electrónico , ¿Puedo saber qué líneas tengo que añadir a recibir en mi canal a través de su mql telegrama.


Ya tengo todos los archivos en la carpeta de incluir


Gracias de antemano



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

//--- configuración del 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";//Nombre del canal
input string InpToken="xxxxxxx:AxxxxxxbFxxx0-IxwKXyxxxxxxxx";//Bot Token


CCustomBot bot;

datetime time_signal=0;
//int SendMessage(const cadena nombre_canal,
                //const cadena texto);



//--- tampones indicadores
double Buffer1[];
double Buffer2[];

datetime time_alert; //utilizado al enviar la alerta
bool Send_Email = true;
double myPoint; //inicializado en 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);
     }
  }

//+------------------------------------------------------------------+
//| Función de inicialización del indicador personalizada |
//+------------------------------------------------------------------+
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 miPunto
   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);
  }

//+------------------------------------------------------------------+
//| Función personalizada de iteración del indicador|
//+------------------------------------------------------------------+
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);
   //--- cero 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);
   //--- bucle principal
   for(int i = limit-1; i >= 0; i--)
     {
      if (i >= MathMin(5000-1, rates_total-1-50)) continue; //omitir algunas tarifas antiguas para evitar "Array fuera de rango" o cálculos lentos 
      
      int barshift_D1 = iBarShift(Symbol(), PERIOD_D1, TimeShift[i]);
      if(barshift_D1 < 0) continue;
      
      //Indicador Buffer 1
      if(MACD_Main[barshift_D1] > MACD_Signal[barshift_D1]
      && MACD_Main[barshift_D1+1] < MACD_Signal[barshift_D1+1] //MACD cruza por encima de MACD
      )
        {
         Buffer1[i] = Low[i]; //Establecer el valor del indicador en el mínimo de la vela
         if(i == 0 && Time[0] != time_alert)
         { myAlert("",
        "\n"
        "\n" + ">Direction : " " UP"); time_alert = Time[0]; } //Alerta instantánea, sólo una vez por barra
        }
      else
        {
         Buffer1[i] = EMPTY_VALUE;
        }
      //Indicador Buffer 2
      if(MACD_Main[barshift_D1] < MACD_Signal[barshift_D1]
      && MACD_Main[barshift_D1+1] > MACD_Signal[barshift_D1+1] //MACD cruza por debajo de MACD
      )
        {
         Buffer2[i] = High[4+i]; //Establecer el valor del indicador en el Candlestick High
         if(i == 0 && Time[0] != time_alert) 
         { myAlert(" ",
         "\n"
         "\n" + ">Direction : " " DOWN"); time_alert = Time[0]; } //Alerta instantánea, sólo una vez por barra
        }
      else
        {
         Buffer2[i] = EMPTY_VALUE;
        }
     }
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
OrelMely:



¿Funciona la biblioteca en indicadores
 
Jefferson Metha:
¿Funciona la biblioteca en los indicadores

Sí, ha preestablecido un archivo de señal de trabajo ya con MACD...


Pero tengo conocimientos limitados de código, así que no puedo ejecutarlo en este momento.

 

Hola,

Mt4 mostrar un error cuando estoy tratando de enviar una foto :


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


Parece que piensa que estoy tratando de llegar a EURUSD.gif desde un servidor mientras que está en "MQL4/Archivos".

He intentado con una ruta directa de archivos de Windows, pero el problema persiste. Estoy atascado en este problema desde hace horas, ¿alguien tiene una pista?

Aquí está mi 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...
 
Lo siento pero no estoy seguro de lo que estoy haciendo mal. ¿Quieres decir que no puedo enviar localmente una foto y que tengo que subirla primero a un servidor?