Bridging External Programs: From 12 Ports to 0 with Shared Memory
Data moving between two programs on the same machine does not need to send a single byte through the network stack. Switching from sending messages to letting both sides access the same block of memory removes every port, but responsibility for data correctness shifts to whoever designs the byte layout.
1-minute summary
- Symptom / problem
- The data bridge from MT5 to an outside program used sockets and opened 12 ports.
- Who should read
- People passing data between MT5 and another program on the same machine.
- Fix in short
- Move to a single 53 MB memory-mapped file written by one DLL, read with a SeqLock so readers take no lock, and open no ports at all.
My real-time data collection system needs to take data out of a MetaTrader 5 terminal and pass it to an external program written in C# for display and storage in an archive for analysis. For the first bridge, I used socket messaging: an EA attached to a chart opened sockets and sent messages out. It worked, but when I counted everything, one machine had 12 listening ports just to move data between two programs sitting a window apart.
So I rebuilt the bridge using a memory-mapped file that both sides read and write directly through the same block of memory. This article covers why I moved, the platform constraints that shaped the design, and the mistakes I made along the way. The EA names, DLL names, memory names, and identifiers in this article are all made up. The command channel example retains only a ping command for health checks. This system collects data for historical analysis.
The first bridge: a socket per chart per direction
The first platform constraint is that one EA attaches to one chart and works with that chart's symbol. To get data for three symbols, I need three EAs on three charts. In the first bridge, each EA opened two sockets of its own. The data channels alone therefore used 3 EAs times 2 sockets, or 6 ports. Including the command channels brought the total to 12 open ports.
The problem with this version was not that it was too slow to use. Latency was around 1 to 5 milliseconds per message. The problem was everything around it. For every port, I had to track who used it, prevent conflicts with other programs, and configure the firewall to allow it through. Clients needed messaging libraries installed in both C# and Python, and the terminal needed that library's DLL in its Libraries folder. Another issue was that the platform had no timeframes shorter than one minute. Each client that wanted second-level bars had to build them from ticks itself, which meant two clients could build different bars.
| Topic | socket messaging | memory-mapped file |
|---|---|---|
| Latency per read/write | 1 to 5 ms | Design target: below 10 us |
| Data channels | 3 EA x 2 socket = 6 | 1 DLL, 1 MMF |
| Listening ports | 12 | 0 |
| Libraries to install | Messaging libraries on both sides | Built into Windows |
| Second-level bars | Each client builds its own | DLL builds them once, all clients share them |
| Multiple clients reading at once | Through publish/subscribe | Open the same block directly |
| Number of timeframes | 8 | 9 |
The 1 to 5 ms figure for the first bridge comes from observations during use. The below 10 us figure for MMF is a target I set during design, based on the fact that a read copies only a few dozen bytes of memory within the same machine. I have no systematic measurements to include here to confirm it. My main reasons for moving were the number of ports and the number of things to maintain, not this figure.
The new design: one DLL writes, everyone reads the same block
MQL can call functions in a DLL, so I had every EA load the same DLL and made that DLL create and write the memory-mapped file. Clients open the memory with the same name and read it directly. No messages pass through an intermediary.
Because several EAs run in the same process and load the same DLL, each calls the function to reserve its own slot at almost the same time during startup. The DLL therefore needs an internal lock specifically for allocating and releasing slots. The normal data write path uses no lock at all. It uses the SeqLock protocol, which I will explain below.
The command channel follows the same principle, but uses a separate MMF of a few kilobytes for each symbol. The reason is the same constraint: one EA per chart. A command for a given symbol must reach the EA on that chart. Separate blocks remove the need for a central command dispatcher.
Letting an EA call a DLL requires enabling DLL imports in the terminal, and the DLL code runs in the same process as the terminal. If the DLL writes beyond a memory boundary, the entire terminal crashes, not just that EA. This design removes ports and messaging libraries, but I still need to put my own DLL in the Libraries folder and maintain it more carefully than an ordinary script.
Platform constraints that dictated the design
Several parts of this design were not my choice. The platform chose them for me.
What the platform lacks or disallows
- No timeframes shorter than one minute
- One EA per chart
- Relying only on tick events misses ticks
- Network interruptions cause ticks to arrive late
What I had to build
- DLL builds 1-second, 5-second, and 15-second bars from ticks
- Data channel divided into slots, separate command block per symbol
- Fetch ticks with CopyTicks on a 50 ms timer
- Gap repair runs every 60 seconds
The timer was something I configured incorrectly on the first attempt. I had the EA send ticks on tick events, with a timer running every 1 second to catch anything missed. With one broker, the result was that not all ticks reached the DLL. I reduced the timer interval to 50 milliseconds and made every timer cycle fetch ticks with CopyTicks() over a time range, without relying on every event being delivered. The same timer cycle handles two other jobs: checking whether bars of one minute or longer have closed and sending closed bars to the DLL, and updating the heartbeat.
Bars therefore come from two sources. The DLL builds bars shorter than a minute from ticks, while the EA reads bars of one minute or longer from the terminal and sends them in. The DLL rejects any attempt to submit second-level bars from outside.
| Timeframe | Built by | Ring buffer capacity |
|---|---|---|
| 1 second | DLL from ticks | 86,400 bars (1 day) |
| 5 seconds | DLL from ticks | 17,280 bars (1 day) |
| 15 seconds | DLL from ticks | 5,760 bars (1 day) |
| 1 minute | EA sends when the bar closes | 1,440 bars (1 day) |
| 1 hour | EA sends when the bar closes | 72 bars (3 days) |
| 4 hours | EA sends when the bar closes | 42 bars (7 days) |
The byte layout of the 53 MB file
With no messages, there is no serializer. What both sides must agree on is byte offsets. I set every struct to use 1-byte packing, with no compiler-inserted gaps. Where alignment is needed, I add explicit padding in the definition.
The numbers in the diagram add up exactly, which is something I make myself check every time I change a struct. Within one slot, 60 + 112 + 64 + 1,600,016 + 144 + 5,369,184 + 16 equals 6,969,596 bytes. Eight slots plus the 64-byte header equals 55,756,832 bytes, or 53.17 MB. The live system uses 3 slots, so the memory actually touched is around 21 MB.
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct FeedTick // 32 ไบต์ ต้องตรงกับฝั่ง DLL ทุกไบต์
{
public double ValueA;
public double ValueB;
public long TimeUs; // ไมโครวินาที UTC
public uint Volume;
public uint Flags;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct FeedBar // 48 ไบต์
{
public long Time; // เวลาเปิดแท่ง วินาที UTC
public double V1, V2, V3, V4;
public uint Count;
public uint Extra;
}
public static class Layout
{
public const int Header = 64;
public const int BlockSize = 6_969_596;
public const int TickSeq = 60 + 112; // identity + spec
public static long TickSeqOffset(int slot) => Header + (long)slot * BlockSize + TickSeq;
}
The 64-byte header starts with a 4-byte identifier and a 4-byte version number. Every client must check these two values before reading anything else, because reading bytes at the wrong offset does not throw an error. It returns numbers that look plausible.
SeqLock: reading without locking the writer
The writer sits on the system's fastest path. I did not want a slow-reading client to hold it up, so I used SeqLock instead of a mutex. The principle is to place a counter before the data. The writer makes it odd before writing, then advances it to the next even number when finished. The reader reads the counter before and after copying. If it is odd or the two values differ, the copy overlapped a write, so the reader discards it and tries again.
ฝั่งเขียน (DLL) ฝั่งอ่าน (client)
odd = seq | 1 วนซ้ำ:
store(sequence, odd) s1 = load(sequence)
เขียนข้อมูลลงช่อง ถ้า s1 เป็นเลขคี่ ให้เริ่มใหม่
store(sequence, seq + 2) คัดลอกข้อมูลออกมาไว้ที่ตัวเอง
s2 = load(sequence)
จนกว่า s1 เท่ากับ s2
The Python reader can be written entirely with standard library modules, with nothing extra to install.
import mmap, struct
NAME = "Local\\Feed_Demo"
HEADER = 64
BLOCK = 6_969_596
TOTAL = HEADER + 8 * BLOCK # 55,756,832 ไบต์
MAGIC = 0x46454544 # ค่าสมมุติของบทความนี้
mm = mmap.mmap(-1, TOTAL, tagname=NAME, access=mmap.ACCESS_READ)
magic, version, n_symbols = struct.unpack_from("<III", mm, 0)
if magic != MAGIC or version != 1:
raise SystemExit("ยังไม่มีผู้เขียน หรือโครงสร้างคนละเวอร์ชัน")
def latest_tick(slot):
base = HEADER + slot * BLOCK + 60 + 112 # ตำแหน่งของ seq
for _ in range(1000):
s1 = struct.unpack_from("<Q", mm, base)[0]
if s1 & 1:
continue # ฝั่งเขียนกำลังเขียนอยู่
raw = bytes(mm[base + 8: base + 40]) # คัดลอก 32 ไบต์ออกมาก่อน
s2 = struct.unpack_from("<Q", mm, base)[0]
if s1 == s2:
a, b, time_us, volume, flags = struct.unpack("<ddqII", raw)
return s1, time_us, a, b
return None # ชนติดกันนานผิดปกติ
print(latest_tick(0))
The identifier check in this example is not a formality. When opening named memory on Windows, if a block with that name does not exist, the system creates a new, zero-filled block. A client that starts before the writer gets an empty block and can keep reading zeros as data without any error.
The C# side uses classes included with .NET. If I do not want to poll frequently, it can wait on a named event that the writer signals when a new tick arrives. This event is optional; a client can keep reading on its own without waiting.
using System.IO.MemoryMappedFiles;
using System.Threading;
using var mmf = MemoryMappedFile.OpenExisting(@"Local\Feed_Demo", MemoryMappedFileRights.Read);
using var view = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
using var wake = EventWaitHandle.OpenExisting(@"Local\Feed_Demo_NewTick");
long seqAt = Layout.TickSeqOffset(0);
var buf = new byte[32];
while (true)
{
wake.WaitOne(50); // ถูกปลุกเมื่อมี tick หรือครบ 50 ms ก็ตื่นมาดูเอง
ulong s1, s2;
do
{
s1 = view.ReadUInt64(seqAt);
if ((s1 & 1) != 0) { Thread.SpinWait(20); s2 = s1 + 1; continue; }
view.ReadArray(seqAt + 8, buf, 0, 32);
s2 = view.ReadUInt64(seqAt);
} while (s1 != s2);
var tick = MemoryMarshal.Read<FeedTick>(buf);
Console.WriteLine($"{tick.TimeUs} {tick.ValueA} {tick.ValueB}");
}
OpenExisting differs from the Python example in that it throws an exception when no block with that name exists. I prefer this because it immediately tells me the writer has not started yet.
The command channel: ping is the only example
The command channel is a small MMF for each symbol, with a command slot written by the client and a response slot written by the EA. Both slots have their own sequence numbers. The EA checks the command slot on its 50-millisecond timer or wakes on a named event, and another event wakes the client when the response is ready.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PingCommand // โครงที่ตัดเหลือเฉพาะคำสั่งตรวจสุขภาพ
{
public ulong CmdSeq; // เพิ่มทีละหนึ่งต่อคำสั่งใหม่
public uint CmdType; // 6 = PING
public uint Pad;
public long ExpireAtUs; // เวลาหมดอายุแบบ UTC จากนาฬิกาของเครื่อง 0 = ไม่หมดอายุ
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PingReply
{
public ulong ReplySeq; // ต้องเท่ากับ CmdSeq ที่ถาม ถึงจะเป็นคำตอบของเรา
public uint Status; // 0 = ปกติ
public uint Pad;
public long ServerTimeUs;
}
I learned two things from this channel. The first is that command expiry must be checked against the same clock on both sides. The client and EA are on the same machine, so I have the EA get the time through a DLL function that reads the machine's clock. It does not use the time of the server the terminal is connected to, which is in a different time zone and varies by broker.
The second is that there is only one response slot. A new response always overwrites the old one. If the first ping times out and the client sends a second, the response to the second overwrites the late response to the first. The client therefore has to compare the response sequence number with the command's every time. The permanent fix is to turn the response slot into a ring buffer, which requires shifting every subsequent byte offset and updating all sides together. I have not done that yet.
Traps during implementation
Three things cost me time, and none had anything to do with SeqLock.
- The client could not see the memory even though the writer reported creating it successfully. Names starting with
Local\are visible only within the same Windows session. The test script I ran from my code editor's integrated terminal was in a different session from the terminal. As soon as I ran it from PowerShell opened through the regular menu, it could read the memory. - The file header was never written because the DLL incorrectly decided that "this block already exists." The value of
GetLastError()must be saved immediately after the call that creates the memory, before calling any other API. Otherwise, the value is overwritten, the flag indicating that we created the block is wrong, and the identifier and version are never written. - My own documentation listed the command struct as 224 bytes. Its actual packed size was 200 bytes. The Python client calculated offsets from the documentation and therefore read 24 bytes off. Sizes must come from
sizeof, not mental arithmetic.
The first issue is easy to check once I know what to look for.
# ทุก process ที่ต้องเห็นหน่วยความจำก้อนเดียวกัน ต้องมี SessionId เท่ากัน
Get-Process terminal64, python, pwsh -ErrorAction SilentlyContinue |
Select-Object Name, Id, SessionId | Sort-Object SessionId
If a client is launched from a service, a scheduled task configured to run without a login, or a tool that creates processes in another session, it cannot open the terminal's memory named Local\. The symptom is simply that the memory cannot be found, with no indication that sessions are the cause. The options are to run everything in the session of the user running the terminal, or switch to the Global namespace, which requires additional privileges when creating the memory. I chose the first option and noted in the installation steps that clients must be launched from the desktop of the same user running the terminal.
Gap repair every 60 seconds
In practice, networks have interruptions, the terminal disconnects and reconnects, and some ticks arrive late. I therefore gave the EA a repair job that runs every 60 seconds. It checks the ring buffer for gaps of more than 5 seconds between ticks over the past 1 to 6 hours. When it finds one, it fetches historical ticks from the start of the gap and sends them to the DLL again, capped at 10,000 ticks per repair, then fetches missing bars of one minute or longer to fill those in too.
The DLL needs no extra work to support repairs because its tick input function already removes duplicates. A tick whose microsecond timestamp and both field values match an existing tick is skipped. The EA can therefore resend ticks without remembering what it has already sent. A repair job that produces the same result no matter how many times it runs is a property I always want from this kind of work.
Checks after deployment with 3 symbols and 9 timeframes showed 16-digit microsecond tick timestamps increasing continuously, complete and continuous bars across all 9 timeframes, and a heartbeat advancing as expected.
The numbers for this project
To sum up, moving from sockets to shared memory removed all the ports and messaging libraries and let clients in every language read the same data without converting messages. In exchange, I have to take responsibility for every byte offset, check the identifier and version, manage sessions, and maintain a DLL running inside the terminal process. For data moving within one machine, I think it is worth it. If the other end is on another machine, sockets are still the right answer, depending on the job. The remaining work is the single response slot and systematic latency measurements. When those are done, I will come back and update this article.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first