[EA] [Socket] [Python] - After few hours, the SocketSend() "freeze", stop sending data... without error messages

 

Hi everyone,

  • System:Windows / MT5
  • Environnement:Python Script + Socket Server (Python) + Socket Client (MQL5)
  • Problem:After few hours (around 25-26hrs) the EA stop sending any data through the socket or the Socket Server stop receiving data

I'm a fresh python coder, and for the last few days I'm trying to create an algo that can trade for me.
To do so, I created an Expert Advisor who is the socket client to send the data (Bid / Ask / and if the candle is closed or not) to my socket server in Python and then I have my python script that understand what's going on and make decision about it (e.g Long / Short...)

Even if it work like a charm for 25-26hours, it stop sending anything without error messages.
But the EA still work (still print the data in the Experts tab in MT5) and the Python script still works... The only thing that is not working is the data flow through the socket :/

In my python script I throw multiple try: Except: line, I even write everything in a log file, but nothing popped out on why the data flow stopped.

My first though was MEMORY LEAKS so I monitored my CPU / RAM but nothing shows off (screen below)
To understand better or even to reproduced it, you can find my EA code and my Python Socket below:

[EA Socket]
This EA send the Bid / Ask and detect if the candle is close or not (send 0 or 1)

int My_Socket_Handle = INVALID_HANDLE; 

int OnInit()
{
   My_Socket_Handle = Socket_Connect();    
 
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   Socket_Close(My_Socket_Handle); 
}


void OnTick()
{
   MqlRates priceData[];
   ArraySetAsSeries(priceData, true);
   CopyRates(_Symbol, _Period, 0, 2, priceData);
   
   ArrayPrint(priceData, _Digits, NULL, 0, 1);
   
   MqlTick ask_price;
   SymbolInfoTick(_Symbol, ask_price);
   
   static int candleCounter;   
   static datetime timeStampLastCheck; 
   datetime timeStampCurrentCandle;
 
   timeStampCurrentCandle=priceData[0].time; 
   if (timeStampCurrentCandle != timeStampLastCheck)
   {
      timeStampLastCheck = timeStampCurrentCandle;
      candleCounter = candleCounter+1;
      string tosend;
      {
       tosend+=" " + (string)ask_price.ask;
       tosend+=" " + (string)ask_price.bid;
       tosend+=" " +"1";
       }
       Socket_Send(My_Socket_Handle, tosend);
   }else{
      string tosend;
      {
       tosend+=" " + (string)ask_price.ask;
       tosend+=" " + (string)ask_price.bid;
       tosend+=" " +"0";
       }
       Socket_Send(My_Socket_Handle, tosend);
   }
  
   Comment("Counted Candles since the start: ",candleCounter);
}


int Socket_Connect()
{
  int h_socket = SocketCreate(SOCKET_DEFAULT);
  
  if(h_socket != INVALID_HANDLE)
  {
     if(SocketConnect(h_socket,"127.0.0.1",9090,10000))
     {
      Print("Connected to Socket Server"); 
     }
     else
     {
      Print("Fail connected to Socket Server. error code : ", GetLastError());
     }
  }
  else
  {
   Print("Fail SocketCreate error code : ", GetLastError());
  }
  return h_socket; 
}

void Socket_Close(int socket_handle)
{
   if(socket_handle != INVALID_HANDLE)
   {
      SocketClose(socket_handle);
      My_Socket_Handle = INVALID_HANDLE; 
      Print("Socket Closed");      
   }
}

int Socket_Send(int socket_handle,string str_data)
{
   if(socket_handle == INVALID_HANDLE) return 0; 
   
   uchar bytes[]; 
   int byte_size = StringToCharArray(str_data,bytes)-1;
   Print("Error Code:", GetLastError());
   return SocketSend(socket_handle,bytes,byte_size);  
}


[Python Socket Server]

Create the socket and receive the data...

import socket
import bot

class socketserver:
    def __init__(self, address = '', port = 9090):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.address = address
        self.port = port
        self.sock.bind((self.address, self.port))
        self.cummdata = ''


    def waitforconnection(self):
        try:
            self.sock.listen(1)
            self.conn, self.addr = self.sock.accept()
            print('connected to', self.addr)
            return 1
        except Exception as e:
            bot.log_and_print('Error occurred on socket connection')
            bot.log_and_print(e)


    def recvmsg(self):
        try:
            while True:
                data = self.conn.recv(1000)
                if not data:
                    break
                return data.decode("utf-8")


        except Exception as e:
            bot.log_and_print('Error occurred while receiving data from socket client')
            bot.log_and_print(e)
   

    def __del__(self):
        print('Socket Close')
        self.sock.close()


[Screen Shot the CPU / RAM usage]

Attached below:



I have absolutely no idea on how to find why it stopped after 25hours of running...
If you have any idea, I will be so thanksfull <3

To anyone how is reading this post, I hope you are having a wonderfull day !
Mines are shit until I find a solution to my problem ^^

Cheers,

MetaTrader 5 and Python integration: receiving and sending data
MetaTrader 5 and Python integration: receiving and sending data
  • www.mql5.com
Comprehensive data processing requires extensive tools and is often beyond the sandbox of one single application. Specialized programming languages are used for processing and analyzing data, statistics and machine learning. One of the leading programming languages for data processing is Python. The article provides a description of how to connect MetaTrader 5 and Python using sockets, as well as how to receive quotes via the terminal API.
Files:
 
how can i ue data indicator programming withe mql5 in my programme python pls can you help me
 
TerenceD:

Hi everyone,

  • System:Windows / MT5
  • Environnement:Python Script + Socket Server (Python) + Socket Client (MQL5)
  • Problem:After few hours (around 25-26hrs) the EA stop sending any data through the socket or the Socket Server stop receiving data

I'm a fresh python coder, and for the last few days I'm trying to create an algo that can trade for me.
To do so, I created an Expert Advisor who is the socket client to send the data (Bid / Ask / and if the candle is closed or not) to my socket server in Python and then I have my python script that understand what's going on and make decision about it (e.g Long / Short...)

Even if it work like a charm for 25-26hours, it stop sending anything without error messages.
But the EA still work (still print the data in the Experts tab in MT5) and the Python script still works... The only thing that is not working is the data flow through the socket :/

In my python script I throw multiple try: Except: line, I even write everything in a log file, but nothing popped out on why the data flow stopped.

My first though was MEMORY LEAKS so I monitored my CPU / RAM but nothing shows off (screen below)
To understand better or even to reproduced it, you can find my EA code and my Python Socket below:

[EA Socket]
This EA send the Bid / Ask and detect if the candle is close or not (send 0 or 1)


[Python Socket Server]

Create the socket and receive the data...


[Screen Shot the CPU / RAM usage]

Attached below:



I have absolutely no idea on how to find why it stopped after 25hours of running...
If you have any idea, I will be so thanksfull <3

To anyone how is reading this post, I hope you are having a wonderfull day !
Mines are shit until I find a solution to my problem ^^

Cheers,

By default A broker usually disconnect a connection in 24 hours. You should code for socket client status check and reconnect on disconnection. Also must read about ping pong which keeps connection alive. I dont know which broker you are trying to connect and your server side config at

127.0.0.1

.

 
You solved?
Because I had a similar problem, launching the python socket with CMD after about a day it closed by itself, I solved it by launching the python server socket in powershell
Reason: