HomeHome  [日本語 / English]

Linking MT4(MQL4) and Python - Passing Data through Named Pipe

Introduction

Sometimes you may want to pass data from MT4 (MQL4) to an external program for processing. This is relatively easy to achieve with the Windows Named Pipes. You can use any programming language to create an external program, as long as it supports named pipes, but in this article I have tried to write it in Python.

If you want to communicate in both directions, see "Linking MT4(MQL4) and Python - Passing Data through Named Pipe, Bidirectional"

For C#, please refer to "Linking MT4(MQL4) and C# - Passing Data through Named Pipe"

Named Pipe

Tested Environment

Program Flow

The program works as follows.

  1. Create a named pipe in the external program and wait for it to be connected.
  2. Connect to the named pipe from MT4 (MQL4).
  3. Write data from MT4 (MQL4) to the named pipe.
  4. The external program reads data from the named pipe.

External Program

In this article, we'll use Python to write an external program. It's a simple program that displays the string sent from the pipe to the console.

To work with Windows named pipes in Python, we can use the win32pipe module.

import win32pipe
import win32file

# Create a named pipe
pipe = win32pipe.CreateNamedPipe(
    r'\\.\pipe\TestPipe', 
    win32pipe.PIPE_ACCESS_DUPLEX,
    win32pipe. PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE | win32pipe.PIPE_WAIT,
    1, 256, 256, 0, None)

# Waiting for the client to connect
win32pipe.ConnectNamedPipe(pipe, None)

# Infinite Loop
while True:
    # Read one byte from the pipe.
    hr, c = win32file.ReadFile(pipe, 1)
    
    # Display it
    print(c.decode(), end='')

MT4(MQL4) Program

An MT4 (MQL4) program is written as an EA (Expert Advisor). This program converts the Bid price to a string for each tick and writes it to the pipe.

To connect to an existing pipe from MT4 (MQL4), we can use the FileOpen function.

#property strict

const string pipeName = "TestPipe";     // Pipe name. Matches the name created by an external program.
int pipe = INVALID_HANDLE;

int OnInit()
{
   // Open the named pipe (connect it).
   pipe = FileOpen("\\\\.\\pipe\\" + pipeName, FILE_WRITE | FILE_BIN | FILE_ANSI);

   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   // Close the pipe.
   FileClose(pipe);
}

void OnTick()
{
   // Convert the Bid price to a string.
   string s = DoubleToString(Bid);

   // Write the string into the pipe.
   FileWriteString(pipe, s + "\r\n");
}

Display Exanple

When you run the above program, start the external program and put it in the waiting state, and then apply the EA to the chart on the MT4 side. Hopefully the external program will display the Bid price as shown below.

104.61700000
104.61800000
104.61900000
104.61800000
104.61900000