HomeHome  Updated: November 20, 2020  [日本語 / English]

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


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.

For Python, please refer to "Linking MT4(MQL4) and Python - 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 will use C# to write an external program (a console application). It's a simple program that displays the string sent from the pipe to the console.

To work with named pipes in C# (.NetFramework), we can use the NamedPipeServerStream class.

using System;
using System.IO.Pipes;

namespace PipeServer
    class Program
        static void Main(string[] args)
            // Create a named pipe.
            // The "TestPipe" is the name of the pipe and can be given arbitrarily.
            NamedPipeServerStream pipeServer = new NamedPipeServerStream("TestPipe");

            // Waiting for the client to connect to the pipe.

            while (true)
                // Reads a byte from the pipe.
                int c = pipeServer.ReadByte();

                if (c == -1) break;

                // Display on the console.

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);


void OnDeinit(const int reason)
   // Close the 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 Example

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.