Sending data from server to mt5 with socket.

 

Hello there. I opened a socket on MT5 and connected it with the server. But I could not send data from server to mt5 with socket. So I want to send a value from the server to the meta. can you help me. I would be very happy if you show a small example.

 
I recommend that you read the docs and follow the example on the SocketRead page
https://www.mql5.com/en/docs/network/socketread

Remembering that you have to make sure that your server is really sending the socket, maybe you have to use another programming language and create PoC.

I had a lot of trouble using it with the Expert Advisor and not as a Script. As described in the documentation.

OnStart is not called from an Expert Advisor but from a Script.
Documentation on MQL5: Network Functions / SocketRead
Documentation on MQL5: Network Functions / SocketRead
  • www.mql5.com
SocketRead - Network Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 
Thomaz Diogo #:
I recommend that you read the docs and follow the example on the SocketRead page
https://www.mql5.com/en/docs/network/socketread

Remembering that you have to make sure that your server is really sending the socket, maybe you have to use another programming language and create PoC.

I had a lot of trouble using it with the Expert Advisor and not as a Script. As described in the documentation.

OnStart is not called from an Expert Advisor but from a Script.

I tried that but it didn't work. I built the server with .net. I also did the socket in meta using the library here: https://www.mql5.com/en/articles/8196 . I have no problem sending data to the server. For example, the price of EURUSD comes. I want to send the price I want to get to the meta again with socket, but it always gives an error when sending data. What I want to do is actually very simple. If I just send data to meta stably, it will be done. Can you please help. It would be great if you could show a small example.

 
hasan188 # :

Eu tentei isso, mas não funcionou. Eu construo o servidor com .net. Também fiz o socket em meta usando a biblioteca aqui: https://www.mql5.com/en/articles/8196 . Não tenho nenhum problema em enviar dados para o servidor. Por exemplo, vem o preço do EURUSD. Quero enviar o preço quero chegar no meta novamente com socket, mas sempre dá erro ao enviar dados. O que eu quero fazer é realmente muito simples. Se eu apenas enviar dados para metaestavelmente, isso será feito. Você pode por favor ajudar. Seria ótimo se você pudesse mostrar um pequeno exemploEU

I'm not using websockets, I'm using TCP.

backend: nodejs

library node: "net"

basically in my nodejs terminal, I give a console.log of everything that goes through the application.


try the link below, the socket reader part works fine.

https://www.mql5.com/en/blogs/post/706665

Socket library for MT4 and MT5
Socket library for MT4 and MT5
  • 2017.09.06
  • www.mql5.com
[Published as a blog entry because submission to the Codebase stalled on the fact that this socket library works with both MT4 and MT5, whereas the Codebase is divided into separate sections for MT4
 
Thomaz Diogo #:

I'm not using websockets, I'm using TCP.

backend: nodejs

library node: "net"

basically in my nodejs terminal, I give a console.log of everything that goes through the application.


try the link below, the socket reader part works fine.

https://www.mql5.com/en/blogs/post/706665

Are tcp and websocket different things? If your method works, I can use your method. You understand what I want to do, right?

 

if some one can verifay this code pls :

//------------------------------------------------------------------
#property indicator_chart_window
#property indicator_buffers  2
#property indicator_plots    1
#property indicator_label1   "SMA"
#property indicator_type1    DRAW_COLOR_LINE
#property indicator_color1   clrDeepSkyBlue,clrCoral
#property indicator_width1   2
//
//
//
// socket _data
#define  PORT 8888
#define  ADDR "localhost"
#define   MAX_BUFF_LEN 1024
#define TIMEOUT 10000
int socket_handle;             // Handle du socket
double sma_values[];           // Tableau des valeurs SMA
// globale variables of sma
input int                inpSmaPeriod = 14;          // SMA period
input int                inpNetPeriod = 5;           // NET period
input ENUM_APPLIED_PRICE inpPrice     = PRICE_CLOSE; // Price
//
//
//
char msg[] = {'E', 'N', 'D', ' ', 'C', 'O', 'N', 'N', 'E', 'C', 'T', 'I', 'O', 'N', '\0'};
int len = ArraySize(msg) - 1; // Taille du message
double val[],valc[];
struct sGlobalStruct
{
   int    periodNet;
   int    periodSma;
   double netDenom;
};
sGlobalStruct global;
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
int OnInit() {
    // Initialisation du socket
    socket_handle = SocketCreate();
    if (socket_handle == INVALID_HANDLE) {
        Print("Erreur - SocketCreate a échoué. Code d'erreur : ", GetLastError());
    } else {
        if (SocketConnect(socket_handle, ADDR, PORT, TIMEOUT)) {
            Print("[INFO]\tConnexion établie.");
        } else {
            Print("Erreur - SocketConnect a échoué. Code d'erreur : ", GetLastError());
        }
    }
    SetIndexBuffer(0,val ,INDICATOR_DATA);
    SetIndexBuffer(1,valc,INDICATOR_COLOR_INDEX);
      //
      //
      //
         global.periodSma = MathMax(inpSmaPeriod,1);
         global.periodNet = MathMax(inpNetPeriod,2);
         global.netDenom  = 0.5 * global.periodNet * (global.periodNet - 1);
      //
      //
      //
   IndicatorSetString(INDICATOR_SHORTNAME,StringFormat("Sma (%i) with (%i) NET",global.periodSma,global.periodNet));            
   return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason) {
    // Fermeture correcte du socket lors de la désinitialisation
    if (socket_handle != INVALID_HANDLE) {
        SocketSend(socket_handle, msg, len);
        SocketClose(socket_handle);
        Print("[INFO]\tSocket fermé.");
    }
}
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
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 = (prev_calculated > 0) ? prev_calculated - 1 : 0;
    struct sWorkStruct {
        double price;
        double sum;
    };   
    static sWorkStruct m_work[];
    static int m_workSize = -1;
    if (m_workSize < rates_total) {
        m_workSize = ArrayResize(m_work, rates_total + 500, 2000);
    }
    for (int i = _limit; i < rates_total; i++) {
        // Votre logique pour calculer la SMA
        // Assurez-vous que les valeurs SMA sont stockées dans le tableau sma_values[i]
        m_work[i].price = iGetPrice(inpPrice, open, high, low, close, i);
        if (i > global.periodSma) {
            m_work[i].sum = m_work[i - 1].sum + m_work[i].price - m_work[i - global.periodSma].price;
        } else {
            m_work[i].sum = m_work[i].price;
            for (int k = 1; k < global.periodSma && i >= k; k++) {
                m_work[i].sum += m_work[i - k].price;
            }
        }
        val[i] = m_work[i].sum / (double)global.periodSma;
        double _netNum = 0;
        for (int k = 1; k < global.periodNet && i > k; k++) {
            for (int j = 0; j < k; j++) {
                double _diff = val[i - k - 1] - val[i - j - 1];
                _netNum -= (_diff > 0) ? 1 : (_diff < 0) ? -1 : 0;
            }
        }
        double net = _netNum / global.netDenom;
        valc[i] = (net > 0) ? 0 : (net < 0) ? 1 : (i > 0) ? valc[i - 1] : 0;
        // Envoi des données SMA via le socket
        string localMsg;
        StringFormat(localMsg, "%.8f", sma_values[i]); // Formatage des données
        char req[];
        int localLen = StringToCharArray(localMsg, req) - 1;
        if (socket_handle != INVALID_HANDLE) {
            SocketSend(socket_handle, req, localLen);
            Print("[INFO]\tEnvoi de la SMA : ", localMsg);
        } else {
            Print("Erreur - Le socket n'est pas valide.");
        }
    }
    return (rates_total);
}
//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
double iGetPrice(ENUM_APPLIED_PRICE price,const double& open[], const double& high[], const double& low[], const double& close[], int i)
{
   switch (price)
   {
      case PRICE_CLOSE:     return(close[i]);
      case PRICE_OPEN:      return(open[i]);
      case PRICE_HIGH:      return(high[i]);
      case PRICE_LOW:       return(low[i]);
      case PRICE_MEDIAN:    return((high[i]+low[i])/2.0);
      case PRICE_TYPICAL:   return((high[i]+low[i]+close[i])/3.0);
      case PRICE_WEIGHTED:  return((high[i]+low[i]+close[i]+close[i])/4.0);
   }
   return(0);
}
 
@FOUAD KACEMI #: if some one can verifay this code pls

You can't use sockets in custom indicators ... Documentation on MQL5: Network Functions / SocketCreate

Notes

To free up computer memory from an unused socket, call SocketClose for it.

You can create a maximum of 128 sockets from one MQL5 program. If the limit is exceeded, the error 5271 (ERR_NETSOCKET_TOO_MANY_OPENED) is written to _LastError.

The function can be called only from Expert Advisors and scripts, as they run in their own execution threads. If calling from an indicator, GetLastError() returns the error 4014 – "Function is not allowed for call".

Documentation on MQL5: Network Functions / SocketCreate
Documentation on MQL5: Network Functions / SocketCreate
  • www.mql5.com
SocketCreate - Network Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5