MQL5 | Unable to create socket even though I allowed "127.0.0.1" for web requests | Attempting to connect to a Python program.

 

Hello everyone! Here is the context: 

I was trying to develop a MQL5 Expert Advisor capable of sending JSON documents to a Python program, but I stumbled across a problem that I couldn't solve not even asking to ChatGPT or Deepseek, as well as I tried to reproduce solutions that I found in the forum, spoiler alert, nothing worked. So I'm using the forum as a last resource, let me show you what the situation is on my computer (maybe this code works just fine in your PC and that would be infuriating for me, just let me know):

1. First of all let's start by showing my terminal settings... (see image attached to this post, I took a screenshot)

2. Here is my MQL5 object which I use to create a socket, when creating an instance I pass host and port to it:

class SocketHandler: public ISocketHandler {

    public:
        SocketHandler() {}

        SocketHandler(string pHost, int pPort) {
            this.host = pHost;
            this.port = pPort;
            this.socketHandle = INVALID_HANDLE;
        }

        ~SocketHandler() { if (this.socketHandle != INVALID_HANDLE) { SocketClose(socketHandle); } }

        bool create() override {
            ResetLastError();
            this.socketHandle = SocketCreate();
            if (socketHandle == INVALID_HANDLE){
                Print(__FUNCSIG__, " ", __LINE__, " Error al crear el socket. Código: ", GetLastError());
                return false;
            }
            return true;
        }

        bool connect() override {
            ResetLastError();
            if (!SocketConnect(socketHandle, host, port, 1000)) {
                Print(__FUNCSIG__, " ", __LINE__, " Error al conectar con el servidor", GetLastError());
                this.socketHandle = INVALID_HANDLE;
                this.close();
                return false;
            }

            Print(__FUNCSIG__, " ", __LINE__, " Conectado al servidor... ", host, " en el puerto ", port);
            return true;
        }
	
	// this is completely irrelevant ...
        bool send(string &document) override {
            uchar conversionResult[];
            StringToCharArray(document, conversionResult, 0, -1, CP_UTF8);
            if (SocketSend(socketHandle, conversionResult, StringLen(document)) == WRONG_VALUE) {
                return false;
            }
            return true;
        }
	
	// also irrelevant ...
        bool receive(string &document) override {
            return false;
        }

        bool isConnected() override { return SocketIsConnected(this.socketHandle); }

        bool close() override {
            if (this.socketHandle != INVALID_HANDLE) { SocketClose(socketHandle); return true; }
            return false;
        }

    private: 
        string host;
        int port;
        int socketHandle;
}


3. Here is a bit of code inside my OnInit() function where I want to execute SocketHandler methods create and connect:

socketHandler = new SocketHandler(host, port);

bool socketCreated = socketHandler.create();
    bool socketConnected = socketHandler.connect();

    if (!(socketCreated && socketConnected)) {
                Print(__FUNCSIG__, " ", __LINE__, " Error. No se pudo conectar el socket al servidor Python, error código: ", GetLastError());
                return INIT_FAILED;
    }

4. Here is the output when executing this code, even if it is an Expert Advisor, I still get a 4014 error which according to the documentation it is thrown only when calling SocketCreate function from an indicator, this is not the case because I made this EA by using the Mql5 wizard, I also placed my MQL5 program under the Experts -> My Expert Advisors folder in my terminal, as well as I have OnInit, OnTick and OnDeInit functions on my program:

2025.03.06 17:44:05.729 2010.01.01 00:00:00   bool SocketHandler::create() 29 Error al crear el socket. Código: 4014

5. This is the Python program that I use as a "server" (Off topic, but if you can figure out why I can't interrupt program execution with Ctrl + C I'll appreciate it very much!):
import socket
import signal
import json

# event handler provisorio

def signal_handler(pSignal: int, frame):
    print("\t[+] Señal recibida: ", pSignal)
    exit(0)

# registro el signal handler
signal.signal(signal.SIGINT, signal_handler)

# Crear un socket
def listen(host: str, port: int):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        server_socket.bind((host, port))
        server_socket.listen()

        print(f"\t[+] Servidor escuchando en {host}:{port}...")
        try:
            while True:
                # Aceptar una conexión
                client_socket, client_address = server_socket.accept()
                with client_socket:
                    print(f"Conexión establecida con {client_address}")

                    # Recibir datos del cliente
                    data = client_socket.recv(1024).decode('utf-8')
                    print(f"Datos recibidos: {data}")

                    # Procesar el mensaje JSON
                    try:
                        message = json.loads(data)
                        print(f"\t[+] Mensaje JSON recibido: {message}")

                    except json.JSONDecodeError:
                        print("Error: Mensaje JSON inválido")
                        response = {"status": "error", "message": "Mensaje JSON inválido"}
                        client_socket.sendall(json.dumps(response).encode('utf-8'))
        except KeyboardInterrupt:
            print("\t[+] Interrupción recibida. Cerrando el servidor... ")
        finally:
            server_socket.close()
            print("\t[+] Servidor cerrado correctamente")

Whatever information you need I'll be at your disposal!