preview
Apache Arrow Flight from MQL5: A Native gRPC Client for Columnar Data Transport

Apache Arrow Flight from MQL5: A Native gRPC Client for Columnar Data Transport

MetaTrader 5 — Integration |
71 0
Adewumi Babatunde Gbadebo
Adewumi Babatunde Gbadebo

Contents

  1. Introduction
  2. Why not just write a CSV
  3. Protocol architecture
  4. Encoding Arrow IPC by hand
  5. The Flight client over raw HTTP/2
  6. Benchmark design and real results
  7. What happens when the network misbehaves
  8. Streaming bars and deals continuously
  9. Limitations
  10. Conclusion


Introduction

Every MQL5 article that moves data off the terminal eventually hits the same wall: there is no native way to speak a binary wire protocol. You can write a CSV to Common Files and have Python watch the folder. Or you can open a raw socket and use a text format the other side understands. Both work. But neither matches a modern data pipeline: CSV and ad-hoc text sockets do not carry a schema, they are not columnar, and parsing cost grows with row count. This article closes that gap for MQL5.

Apache Arrow Flight is Arrow's own RPC framework: gRPC underneath, Arrow's columnar IPC format for the payload. With pyarrow, a Flight endpoint can be implemented in about thirty lines of code. Any compliant client gets fast, schema-carrying access, and pyarrow can read a decoded message zero-copy. (The gRPC/HTTP/2 transport itself still copies bytes through sockets and framing, like any other RPC). The catch, for us, is that "anything that speaks the protocol" has never included MQL5, because MQL5 has no HTTP/2 library, no gRPC stub generator, and no Arrow bindings.

This article builds all three on top of an MQL5 socket: a FlatBuffers encoder/decoder for Arrow IPC, an HTTP/2 client with its own HPACK header compression, and a gRPC framing layer. They are wired into a CFlightClient class that implements DoPut, DoGet and ListFlights against a real pyarrow Flight server. Two programs use it: a one-shot benchmark that pushes real bar history through round trips and checks every value comes back exactly as sent — a bit-exact comparison of the decoded values, not of the raw encoded bytes — and an EA that streams closed bars and account deals to the server continuously, with reconnect and back-off built in. All numbers in this article, including the fault-injection and dropped-connection behaviour, come from runs of this exact code on a real MetaQuotes-Demo account.


Why not just write a CSV

Take the concrete case this article measures: 50,000 closed bars of XAUUSD M15, eight columns (time, OHLC, tick volume, spread, real volume). Written as a lossless CSV with %.17g for the doubles, that file is 4,624,175 bytes. The same data encoded as Arrow IPC — a FlatBuffers schema message plus one or more record-batch messages of flat, typed column buffers — is 3,024,600 bytes, 34.6% smaller, with no text parsing required to read it back: pyarrow maps the buffers straight into typed arrays. That ratio is specific to this dataset — eight non-nullable numeric columns, %.17g-precision doubles, no compression on either side; a schema with utf8 columns, lower-precision floats, or a compressed CSV would land somewhere else.

Size is the smaller win. The real one is that Arrow IPC carries its own schema. A CSV reader has to be told, out of band, that column four is an integer and column three is a double; an Arrow reader asks the stream, because the schema message is the first thing sent. flight_read.py, the independent Python reader this article uses as a cross-check against the lossless CSV baseline, never hardcodes a column type. It reads whatever ArrowEncodeSchema() put on the wire and checks the data against it.

The cost of that is implementation weight. CSV needs FileWriteString(). Arrow Flight needs a FlatBuffers builder, an IPC message framer, a protobuf encoder for the gRPC request bodies, an HTTP/2 connection with frame multiplexing and flow control, and HPACK for the request headers gRPC requires even though this client never needs more than one stream at a time. All of that lives in ArrowFlightCore.mqh, the single include every program in this article pulls in. (Parquet files, SQLite, or a hand-rolled binary socket protocol would each solve the schema problem too, with their own trade-offs; this article picks Arrow Flight specifically because the payoff is a client that talks directly to pyarrow with no intermediate file or format conversion.)


Protocol architecture

End-to-end path from the terminal to the server's tables

1. Both MQL5 programs share one CFlightClient. Both programs share a single, long-lived TCP connection to flight_server.py, opened once and reused for every DoPut/DoGet call ( EnsureConnected() only reopens it if it has actually dropped ). Each call is its own HTTP/2 stream on that one connection, carried over plaintext HTTP/2 (gRPC's "insecure" transport, the only kind a MQL5 socket can speak without a TLS stack). The server merges incoming bars and deals into in-memory Arrow tables, de-duplicated by time or ticket so a resend after a reconnect never creates a second copy of a row.

Four layers sit between FlightBarStreamer_EA.mq5 and the Python process. From the bottom: a byte-oriented socket wrapper (CH2Conn) that frames and parses raw HTTP/2 frames — SETTINGS, HEADERS, DATA, WINDOW_UPDATE — and keeps its own HPACK dynamic table so it can decode the server's compressed response headers. On top of that, a gRPC layer that wraps each Arrow Flight message in the 5-byte length-prefixed frame gRPC expects and reads the trailing grpc-status pseudo-header to know whether a call actually succeeded. On top of that, FlightBuildData() and FlightParseData() speak the three protobuf fields of a Flight FlightData message (descriptor, data_header, data_body) using a hand-rolled varint/wire-type encoder — no protobuf library, just the four wire types this one message type needs. And at the top, ArrowEncodeSchema() / ArrowEncodeBatch() turn a CArrowTable into the two FlatBuffers messages (Schema, RecordBatch) that make up Arrow's streaming IPC format.

flight_server.py is the other half: a pyarrow.flight.FlightServerBase subclass with do_put, do_get and list_flights overridden. Paths beginning bars/ or deals/ are merged against whatever the server already holds, keyed on time or ticket with the newest row winning a collision; every other path, which in practice means the benchmark's bench/... datasets, is replaced wholesale on each DoPut. A --fail-after N flag raises a FlightInternalError after the Nth batch of any upload, which is how this article's fault tests force a mid-stream failure on demand instead of waiting for a real one to show up.


Encoding Arrow IPC by hand

An Arrow IPC stream is two message types. The Schema message, sent once, describes every column's name, type and nullability as a FlatBuffers table. The RecordBatch message, sent once per batch, carries the actual column buffers: for a non-nullable numeric column, that's just the raw bytes, no null bitmap, no offsets. ArrowEncodeSchema() builds the first one:

//+------------------------------------------------------------------+
//| Encode the schema of t as an Arrow IPC Schema message            |
//| (FlatBuffers bytes only, as carried in FlightData.data_header)   |
//+------------------------------------------------------------------+
void ArrowEncodeSchema(const CArrowTable &t,CByteBuf &out)
  {
//--- children are written before the tables that refer to them
   CFbBuilder b;
   int n=t.Columns();
   int field_off[];
   ArrayResize(field_off,AfMaxI(n,1));
//--- one Field table per column; Arrow C++ rejects a missing children vector
   for(int i=0; i<n; i++)
     {
      int name_off=b.CreateString(t.cols[i].name);
      uint type_id=0;
      int type_off=ArrowBuildType(b,t.cols[i].type,type_id);
      b.StartVector(4,0,4);
      int children=b.EndVector(0);
      b.StartTable(7);
      b.AddOffset(0,name_off);              // name
      b.AddOffset(3,type_off);              // type (union value)
      b.AddOffset(5,children);              // children (empty)
      b.AddU8(2,type_id);                   // type (union tag)
      b.AddU8(1,0);                         // nullable: no nulls are written
      field_off[i]=b.EndTable();
     }
//--- vector of fields, then the optional metadata
   b.StartVector(4,n,4);
   for(int i=n-1; i>=0; i--)
      b.PrependOffset(field_off[i]);
   int fields=b.EndVector(n);
   int meta=ArrowBuildMetadata(b,t);
//--- Schema table, then the Message root
   b.StartTable(4);
   b.AddOffset(1,fields);
   if(meta>=0)
      b.AddOffset(2,meta);
   b.AddI16(0,0);                           // endianness: Little
   int schema=b.EndTable();
   int msg=ArrowBuildMessage(b,AF_HDR_SCHEMA,schema,0);
   b.Finish(msg);
   b.CopyTo(out);
  }

The loop writes Arrow's Field table once per column; the two StartVector/EndVector calls around an empty vector are there because Arrow's C++ reader rejects a Field with a missing (rather than empty) children vector. That's a real failure caught during development, not a defensive guess. ArrowBuildType() maps this project's four column types (int64, float64, int32, utf8) to Arrow's type union; ArrowBuildMetadata() attaches the symbol, timeframe, digits and server name as the schema's key-value metadata, which is how flight_read.py recovers that context on the Python side with no separate out-of-band message.

CFbBuilder is the FlatBuffers piece underneath this: a growable byte buffer that places fields back-to-front (the format's own convention, so vtables can be shared across structurally identical tables) and computes each table's vtable by diffing it against the last one built, reusing an existing vtable when the slot layout matches. That sharing is real: the self-test's "decodes a foreign layout (shared vtables, nulls, micro->ms)" check feeds the decoder a FlatBuffers byte string generated by a separate reference encoder with deliberately shared vtables, and the fact that CFbView still walks it correctly is what proves the decoder isn't just reading back its own encoder's habits.

Correctness here is checked two ways before any byte reaches a socket. First, AfRunSelfTest() runs 22 offline checks with no network involved: protobuf varint encode/decode against RFC-style fixed hex strings, three HPACK integer-encoding cases and three HPACK decoder cases from RFC 7541, Appendix C (Huffman decoding, dynamic table insertion and eviction), FlatBuffers 8-byte alignment on both the schema and a record batch, a full encode-then-decode round trip of a sample table checked value-for-value, the foreign-layout decode above, and three checks on FlightData framing including a SHA-256 of the fully assembled message against a golden hash computed once and frozen into the test. Every check funnels through one bookkeeping function:

//+------------------------------------------------------------------+
//| Self-test bookkeeping: print one check and count it              |
//+------------------------------------------------------------------+
void AfCheck(const string name,const bool ok,int &passed,int &total,const bool verbose)
  {
//--- failures are always printed, passes only in verbose mode
   total++;
   if(ok)
      passed++;
   if(verbose || !ok)
      PrintFormat("%s  %s",ok ? "PASS" : "FAIL",name);
  }

Second, once a self-test run passes, FlightRoundTrip_Benchmark.mq5 does the same check against a live server: every dataset it uploads with DoPut it immediately downloads again with DoGet and compares column-by-column, row-by-row, against the table still held in memory (AfTablesEqual()). This article's 325 clean round trips all passed that comparison, run by the MQL5 client against itself; none of them were accepted on faith that the data probably arrived correctly. flight_read.py is a separate, independent check run on top of that, not a re-verification of all 325: it reads a dataset back with no code shared with the client and diffs it against the same CSV baseline, which is what rules out the client and the Python reader sharing a blind spot.


The Flight client over raw HTTP/2

DoPut is a single HTTP/2 stream carrying one gRPC call: open it, send the schema as the first FlightData message, send the table in batches of batch_rows rows as subsequent messages, half-close the stream, then drain whatever PutResult acknowledgements and trailers come back.

//+------------------------------------------------------------------+
//| CFlightClient: DoPut - stream table t to 'path' in batches of    |
//| batch_rows rows. The first message carries the descriptor and    |
//| the schema; every PutResult the server sends back is counted     |
//+------------------------------------------------------------------+
bool CFlightClient::DoPut(const string &path[],const CArrowTable &t,const int batch_rows,SFlightCallStats &st)
  {
//--- statistics are measured from the connection counters
   FlightResetStats(st);
   if(!EnsureConnected())
      return(false);
   ulong t0=GetMicrosecondCount();
   long out0=m_h2.BytesOut();
   long in0=m_h2.BytesIn();
   int waits0=m_h2.WindowWaits();
   bool ok=m_h2.StartCall(AfMethodPath("DoPut"));
//--- message 1: descriptor + schema, no body
   CByteBuf header,body,msg,reply;
   if(ok)
     {
      ArrowEncodeSchema(t,header);
      FlightBuildData(msg,path,true,header,body);
      st.ipc_bytes+=header.len;
      ok=m_h2.SendGrpc(msg,false);
     }
//--- messages 2..n: record batches
   int rows=t.Rows();
   int step=(batch_rows>0) ? batch_rows : AfMaxI(rows,1);
   for(int row0=0; ok && row0<rows; row0+=step)
     {
      int count=AfMinI(step,rows-row0);
      ArrowEncodeBatch(t,row0,count,header,body);
      FlightBuildData(msg,path,false,header,body);
      st.ipc_bytes+=header.len+body.len;
      ok=m_h2.SendGrpc(msg,false);
      if(ok)
        {
         st.rows+=count;
         st.batches++;
        }
      //--- acknowledgements that arrived while sending
      while(ok && m_h2.PopMessage(reply)==1)
         FlightReadAck(reply,st);
     }
//--- half-close, then read PutResults until the trailers arrive
   if(ok)
      ok=m_h2.EndStream();
   while(ok)
     {
      int r=m_h2.NextMessage(reply);
      if(r<=0)
        {
         ok=(r==0);
         break;
        }
      FlightReadAck(reply,st);
     }
//--- a server error during the upload still arrives as trailers
   if(!ok && m_h2.RemoteClosed() && m_h2.GrpcStatus()>=0)
      ok=true;
   st.elapsed_us=GetMicrosecondCount()-t0;
   st.wire_out=m_h2.BytesOut()-out0;
   st.wire_in=m_h2.BytesIn()-in0;
   st.window_waits=m_h2.WindowWaits()-waits0;
   return(Finish("DoPut",ok));
  }

Two details matter for the fault tests later in this article. The acknowledgement-draining loop inside the batch loop ( while(ok && m_h2.PopMessage(reply)==1) ) is non-blocking — it only consumes whatever the server has already pushed back, so a slow server doesn't stall the upload. And the line after EndStream() — if(!ok && m_h2.RemoteClosed() && m_h2.GrpcStatus()>=0) — is what turns a server-side error into a clean, reported failure instead of a hang: when flight_server.py raises inside do_put, gRPC still delivers trailers with a real status code, and this branch treats "the stream closed with a status" as a legitimate outcome to report, not a transport failure to retry blindly.

Setting ok=true here does not turn the error into a reported success, either: Finish() (called at the end of DoPut, not shown as its own snippet) re-derives the outcome from the gRPC status code itself, and a non-zero status such as INTERNAL(13) always comes back as a reported failure regardless of that flag — which is exactly the FAILED log line quoted further down.

DoGet is simpler in shape: one request message (just the ticket string, protobuf field 1), then a stream of FlightData responses, schema first:

//+------------------------------------------------------------------+
//| CFlightClient: DoGet - fetch the stream named by 'ticket' into   |
//| out (the schema message replaces the columns of out)             |
//+------------------------------------------------------------------+
bool CFlightClient::DoGet(const string ticket,CArrowTable &out,SFlightCallStats &st)
  {
//--- the response replaces whatever out held before
   FlightResetStats(st);
   out.ClearAll();
   if(!EnsureConnected())
      return(false);
   ulong t0=GetMicrosecondCount();
   long out0=m_h2.BytesOut();
   long in0=m_h2.BytesIn();
//--- request: Ticket { bytes ticket = 1 }, then half-close
   CByteBuf msg,reply;
   msg.PutU8(0);
   msg.PutU32BE(0);
   PbPutString(msg,1,ticket);
   msg.SetU32BE(1,(uint)(msg.len-5));
   bool ok=m_h2.StartCall(AfMethodPath("DoGet"));
   if(ok)
      ok=m_h2.SendGrpc(msg,true);
//--- response: FlightData messages, schema first
   bool have_schema=false;
   string err="";
   while(ok)
     {
      int r=m_h2.NextMessage(reply);
      if(r<=0)
        {
         ok=(r==0);
         break;
        }
      int hs=0,hl=0,bs=0,bl=0;
      if(!FlightParseData(reply.data,0,reply.len,hs,hl,bs,bl))
        {
         err="malformed FlightData message";
         break;
        }
      if(hl==0)
         continue;
      CFbView view;
      view.Load(reply.data,hs,hl);
      int type=ArrowMessageType(view);
      st.ipc_bytes+=hl+bl;
      //--- schema, record batch, or an unsupported message
      if(type==AF_HDR_SCHEMA)
        {
         if(!ArrowDecodeSchema(view,out,err))
            break;
         have_schema=true;
        }
      else
         if(type==AF_HDR_RECORDBATCH)
           {
            if(!have_schema)
              {
               err="record batch received before the schema";
               break;
              }
            int before=out.Rows();
            if(!ArrowDecodeBatch(view,reply.data,bs,bl,out,err))
               break;
            st.rows+=out.Rows()-before;
            st.batches++;
           }
         else
           {
            err=StringFormat("unsupported IPC message type %d",type);
            break;
           }
     }
   st.elapsed_us=GetMicrosecondCount()-t0;
   st.wire_out=m_h2.BytesOut()-out0;
   st.wire_in=m_h2.BytesIn()-in0;
//--- a decoding error cancels the call; the stream is reset by EndCall
   if(err!="")
     {
      m_h2.EndCall();
      m_h2.Close();
      m_status=-1;
      m_error="DoGet failed: "+err;
      return(false);
     }
   return(Finish("DoGet",ok));
  }

Worth untangling, since the two call sites look inconsistent side by side: SendGrpc() adds no framing itself. Its header comment says the job is just splitting an already-framed message across DATA frames as the flow-control window allows. FlightBuildData() does the actual framing for DoPut: the 5-byte compression flag plus a length patched in once the body is known. DoGet's request is a single protobuf field, too small to justify routing through FlightBuildData(), so it writes that same 5-byte header by hand instead. Either way, SendGrpc() gets a message that's already framed. There's no double-framing here.

The schema-before-batches ordering is enforced, not assumed: a RecordBatch message arriving before a Schema message is treated as an error ( "record batch received before the schema" ), because without a schema ArrowDecodeBatch() has no column types to interpret the raw buffers against. That check only fires once a record batch actually arrives, though: the loop shown above does not separately require a schema before accepting a clean end of stream, so a server that closes the call with trailers but never sends a Schema message returns an empty table rather than an error. Both calls report their outcome through SFlightCallStats — elapsed microseconds, bytes in/out at the connection level, batch and row counts, and for DoPut the number of HTTP/2 flow-control window waits — which is exactly where every timing number in the next section comes from: not a stopwatch around the whole script, but counters taken from inside the actual gRPC call.


Benchmark design and real results

Test machine: Dell Latitude 5400 (i7-8665U @ 1.90 GHz, 16 GB RAM, Windows), running flight_server.py on 127.0.0.1 — ordinary business hardware, not a server. Note: every result below reflects loopback networking, not a real network link. FlightRoundTrip_Benchmark.mq5 pulls real closed-bar history with CopyRates() for three symbols (XAUUSD, EURUSD, GBPUSD) across two timeframes (M15, H1), 50,000 bars each, and for every combination runs three batch sizes (1,000 / 10,000 / 50,000 rows per Arrow record batch) three times each, 54 round trips per full pass. The three batch sizes cover a 50x range on purpose, to see whether the per-message overhead seen at 1,000 rows/batch keeps dropping or flattens out somewhere in between. It keeps dropping all the way to 50,000, which also answers the obvious sensitivity question about whether this conclusion depends on which two points you happened to pick.

50,000 bars felt like a reasonable upper bound: bigger than most single-session backfills, and still quick enough to run the full six-dataset matrix in under a minute. Three symbols and two timeframes were picked for variety in precision (XAUUSD's wider tick size next to EURUSD/GBPUSD's five-digit quotes), not for any statistical reason. Three repeats per cell gives a feel for run-to-run spread without stretching one pass into something that takes hours. Every row of every pass is logged to bench_results.csv, append-only, so the file analysed here holds every pass run during testing, fault injection included.

CopyRates(symbol, tf, 1, 50000) grabs the most recent 50,000 closed bars counting back from whenever the script happens to run, starting at index 1 specifically so the still-forming current bar at index 0 is never pulled in. There's no fixed calendar window baked in, so running this again later won't reproduce the same start date even on identical hardware.

For this particular session (a MetaQuotes-Demo account, everything run inside one UTC day, MetaTrader 5 build 6316), H1 stayed put at 2018.04.10 for XAUUSD and 2018.09.19 for EURUSD/GBPUSD, both ending 2026.10.07. M15 differed by symbol as well as by pass, since each symbol's own session gaps push a fixed-count window back by a different amount: XAUUSD's M15 window started 2024.08.14 to 2024.08.15, GBPUSD's 2024.09.27 to 2024.10.01, and EURUSD's within half an hour of 2024.10.01 00:45, with all three ending within the same session's final trading days, 2026.10.05 to 2026.10.07. bench_results.csv, shipped with this article's files, records the exact first_bar and last_bar for all 432 logged rows, so anyone who needs the precise window behind a given number can look it up instead of guessing.

Across the whole test session that file accumulated 432 logged round trips: 325 completed and matched value-for-value, and all 107 that didn't are accounted for by the three deliberate fault tests in the next section. There are no unexplained failures in the data. Of the 325 clean round trips, 36 ran against a smaller 5,000-bar dataset used by the mid-upload fault test below rather than the 50,000-row dataset the rest of this section measures; the batch-size breakdown that follows uses only the 289 clean round trips against the full 50,000-row dataset, so the comparison never mixes dataset sizes.

Mean DoPut/DoGet time by batch size

2. Blue bars are the mean DoPut (upload) time, orange the mean DoGet (download) time, both in milliseconds, across the 289 clean round trips against the full 50,000-row dataset, grouped by Arrow record batch size. The 50,000-row dataset is sent as 50 batches at 1,000 rows/batch, 5 batches at 10,000, and a single batch at 50,000.

Batch size n Mean PUT, ms Median PUT, ms Mean GET, ms Mean encode, ms Mean throughput, MB/s
1,000 rows/batch 90 729.4 754.6 56.0 7.9 4.2
10,000 rows/batch 90 84.2 87.5 46.1 11.3 36.8
50,000 rows/batch 109 45.5 43.9 34.1 15.3 70.0

Going from 1,000 to 50,000 rows/batch cuts mean upload time by about 16×, for the same 50,000-row dataset over the same loopback connection. That is not an encoding cost: mean encode time actually rises slightly, from 7.9 to 15.3 ms, because a bigger single batch means more FlatBuffers vector-building work per call. Dispersion is real too: individual PUT times at 1,000 rows/batch ranged 467-845 ms across the 90 runs, against 28-86 ms at 50,000 rows/batch across 109 runs, so the batch-size effect holds well beyond just the means.

Put a number on that spread instead of just eyeballing it: the 95% CI below is a normal approximation, mean ± 1.96 × standard error, with standard error computed as the sample standard deviation divided by √n, not Student's t or a bootstrap. Mean PUT time comes out to 729.4 ± 18.6 ms at 1,000 rows/batch (sd 90.0 ms, n=90), 84.2 ± 3.0 ms at 10,000 (sd 14.8 ms, n=90), and 45.5 ± 2.2 ms at 50,000 (sd 11.7 ms, n=109); GET averages 56.0 ± 2.8 ms (sd 13.6 ms), 46.1 ± 3.1 ms (sd 14.9 ms), and 34.1 ± 1.9 ms (sd 10.0 ms) across those same three groups. None of those intervals come close to touching, so this isn't a case of a few slow runs dragging the mean somewhere it doesn't belong.

The cost that collapses is per-message overhead: each batch is its own gRPC message, carrying its own 5-byte length prefix, and at 1,000 rows/batch the 50,000-row upload is 50 of them instead of 1. SendGrpc() still has to split a large message across multiple HTTP/2 DATA frames once it outgrows the peer's advertised max frame size or the flow-control window, so one 50,000-row batch can already be several DATA frames on the wire; what actually scales with batch count is the 5-byte gRPC prefix and the per-message bookkeeping around it, not a fixed one-batch-one-frame mapping. (HPACK itself only runs once per call, in the single HEADERS frame StartCall() sends before any batches go out, so it is not part of this per-batch cost).

Upload throughput vs. batch size

3. Mean DoPut throughput (Arrow IPC bytes sent ÷ elapsed DoPut time) for the same 289 round trips against the full 50,000-row dataset, by batch size. This is loopback throughput on one laptop, not a network benchmark — it is a measurement of this client's own framing and encoding overhead, not of what a real network link would carry.

The ceiling matters more than the absolute MB/s figure, since loopback has no real network latency to hide behind: this specific client implementation, on this specific machine, tops out around 70 MB/s of Arrow IPC payload at the largest batch size tested. That ceiling is not an isolated measurement of the MQL5 client alone — the server is flight_server.py running on the same laptop, so Python/pyarrow processing, the loopback network stack and OS scheduling are all baked into the same number. What it is representative of is the MQL5-side implementation's own overhead — socket writes, the HEADERS/DATA framing bookkeeping, the window-update bookkeeping in CH2Conn::Flush() — relative to that one local server, not a measurement of what the same client would sustain against a real remote Flight server across an actual network, where round-trip latency, not encoding speed, usually dominates.


What happens when the network misbehaves

Three fault scenarios were run against the real server, not simulated in isolation: killing the server before a call, forcing a mid-upload server error, and killing the server mid-stream then restarting it.

Both deliberate scenarios ran off the same two commands, just started at different points. python flight_server.py brings the server up on 127.0.0.1:8815 by default; restarting it as python flight_server.py --fail-after 3 makes do_put throw once three batches of any upload have gone through, no matter which dataset or batch size got it there. The mid-stream kill wasn't scripted at all: the process got killed by hand (Ctrl+C, or just killing the PID) at whatever point the pass happened to be at, which is why 36 failed against 18 completed. That split reflects how far along things were when the kill happened, not a number the test was built to hit. Bringing the server back is just python flight_server.py again; the client reconnects on its own next call, through the same EnsureConnected() logic covered earlier.

Outcome of every benchmark and fault-test execution, in run order

4. Blue is round trips that completed and matched value-for-value; orange is round trips that failed, which is the correct and expected outcome for the three labelled fault tests. All eight executions are real runs from the test session, in the order they happened.

Server not running. With flight_server.py stopped, every DoPut fails immediately on EnsureConnected() with a connect error (53 of 54 round trips in that pass; the single early success was a connection made just before the server was taken down). No hang, no timeout wait. The terminal stayed responsive throughout.

Server-side error mid-upload. Restarting the server with --fail-after 3 makes it raise an exception after the third batch of any upload. With the benchmark's default bars reduced so the 1,000-row batch size needed 5 batches to cover the dataset while the 10,000 and 50,000-row batch sizes needed only 1 each, only the 1,000-row-batch runs ever reached batch 3: 18 of 54 round trips failed, and the other 36 (10,000-row and 50,000-row batches, all single-batch) completed normally. The client's own log for a failed run reads:

FAILED DoPut failed: INTERNAL (13) fail-after 3: simulated server error after 3000 rows. Detail: Internal

That is the if(!ok && m_h2.RemoteClosed() && m_h2.GrpcStatus()>=0) branch in DoPut doing its job: gRPC status 13 (INTERNAL), the server's own message text, and the exact row count at the point of failure, surfaced as a reported error, not a hang. The server process itself stayed alive and kept serving the next call.

Connection dropped mid-stream, then restored. Killing the server while a run was in flight produced 36 failures of 54 (the round trips still executing or queued behind the dead connection) against 18 that had already completed; crucially, the 36 failed fast (the whole pass finished in 6.7 s against a normal ~20 s), because a dead socket fails a DoPut immediately, with no long read timeout to wait out. Restarting the server and re-running the identical matrix produced 54 of 54, 0 mismatches, 21.8-21.9 s — confirmed twice, once immediately after the kill test and once again later in the session — with no leftover corruption from the interrupted run, because every dataset path under bench/... is replaced wholesale on its next successful DoPut; it is never appended to.

One more real failure showed up outside the deliberate tests: the streaming EA's connection, left idle for several minutes between bar closes, was closed out from under it (plain idle-connection behaviour on this machine, not something the code provoked), and the next DoPut failed with socket send failed (error 5273). FlushQueues() caught it, kept the one queued bar row instead of discarding it, and retried on the EA's 1-second timer with exponential back-off; the next attempt reconnected and delivered both the queued bar and two pending deals. No manual intervention, no restart, and nothing lost for this particular gap: the same recovery path the deliberate fault tests exercised, triggered by an ordinary network hiccup instead of a kill switch. That guarantee holds only up to InpMaxQueueRows — a longer outage that fills the queue starts dropping its oldest rows instead, as the next section describes.


Streaming bars and deals continuously

FlightBarStreamer_EA.mq5 is the long-running counterpart to the one-shot benchmark: on OnInit it queues a configurable backfill (default 5,000 bars, 30 days of deals) and from then on queues only what's new. OnTick does nothing on most ticks: it only acts when InpTimeframe's current bar open time has changed from the last one it saw, which is the project's standard new-bar gate (iTime()-based, not every-tick) applied here to decide when there is actually a closed bar worth sending:

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- act once per new bar of InpTimeframe
   if(!g_net)
      return;
   datetime open_time=iTime(_Symbol,InpTimeframe,0);
   if(open_time==0 || open_time==g_bar_open)
      return;
   g_bar_open=open_time;
//--- the previous bar has just closed: queue it and send at once
   QueueClosedBars();
   FlushQueues(false);
   UpdateComment();
  }

Note that this reads InpTimeframe, an EA input, not the chart's own displayed period: a chart left on H1 with InpTimeframe set to M1 still streams every M1 bar close, which is the documented behaviour but also the most common way to misread this EA's logs while testing it.

FlushQueues() is what actually calls DoPut, and it is the piece that makes the recovery behaviour above possible: it is called both from a new bar close and from a 1-second OnTimer, it does nothing when both queues are empty, and after a failure it sets an exponential back-off (g_backoff_sec, capped at InpMaxBackoffSec) instead of retrying immediately:

//+------------------------------------------------------------------+
//| Send both queues, respecting the reconnect back-off              |
//+------------------------------------------------------------------+
void FlushQueues(const bool ignore_backoff)
  {
//--- nothing to do, or still waiting after a failure
   if(!g_net || (g_bars.Rows()==0 && g_deals.Rows()==0))
      return;
   ulong now=GetMicrosecondCount();
   if(!ignore_backoff && now<g_next_try_us)
      return;
//--- descriptor paths: bars/<symbol>/<timeframe> and deals/<login>
   string bar_path[3];
   bar_path[0]="bars";
   bar_path[1]=_Symbol;
   bar_path[2]=AfTimeframeName(InpTimeframe);
   string deal_path[2];
   deal_path[0]="deals";
   deal_path[1]=IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN));
   bool ok=SendQueue(g_bars,bar_path,g_sent_bars);
   if(ok)
      ok=SendQueue(g_deals,deal_path,g_sent_deals);
//--- exponential back-off after a failure, reset after a success
   if(ok)
     {
      g_backoff_sec=1;
      g_next_try_us=0;
      return;
     }
   PrintFormat("FlightBarStreamer: %s - retry in %d s (%d bar rows, %d deal rows queued)",
               g_last_error,g_backoff_sec,g_bars.Rows(),g_deals.Rows());
   g_next_try_us=now+(ulong)g_backoff_sec*1000000;
   g_backoff_sec=AfMinI(g_backoff_sec*2,AfMaxI(InpMaxBackoffSec,1));
  }

Because SendQueue() only calls queue.ClearRows() after a successful DoPut, a failed send leaves the row queued for the next attempt rather than dropping it, confirmed directly by the idle-disconnect incident above, where the one bar queued at the failed attempt was still present and got delivered on the next timer tick. CapQueue() is the other half of that design: if the server stays unreachable long enough for a queue to exceed InpMaxQueueRows (200,000 by default), the oldest rows get dropped so the queue doesn't grow without bound, on the reasoning that the newest data is what a live consumer actually needs once the connection comes back. Deal tracking runs on a separate trigger: OnTradeTransaction only sets a dirty flag (history can be unreliable to read from inside that handler), and the actual HistorySelect call happens on the next timer tick.


Limitations

A deliberately narrow type system. ArrowFlightCore.mqh encodes and decodes exactly four Arrow types — int64, float64, int32, utf8 — built around non-nullable numeric columns, because that is what bars and deals need. This is an application-shaped subset of Arrow IPC/Flight for tables that look like MetaTrader 5 data, not a general-purpose implementation: dictionary encoding, nested types, and most of Arrow's null-handling are out of scope.

Loopback only. Every number in this article was measured against a server on 127.0.0.1. A real network link would add round-trip latency that loopback hides entirely, and the batch-size effect in Fig. 2 would likely shrink as a fraction of the total time once real network RTT dominates over per-frame encoding overhead.

No TLS. This client speaks gRPC's cleartext transport because MQL5's socket API has no way to negotiate TLS for it: SocketTlsHandshake() cannot select the ALPN protocol ("h2") gRPC-over-TLS requires, and there is no way to present a client certificate either. That is fine for a local or trusted-network Flight server reached over localhost, a LAN, or an SSH tunnel; it is not something to point at a public endpoint.

Server state lives in memory only. flight_server.py keeps every table in a Python dict with no disk persistence. That is fine for a benchmark that runs once and exits, but for FlightBarStreamer_EA.mq5's continuous use case it means restarting the server throws away every bar and deal it had accumulated, unless a separate persistence layer is added on the server side.

An empty stream looks the same as a missing schema. DoGet() only flags an error once a record batch shows up before any schema has arrived. If the server just closes the call cleanly without ever sending one, the result is an empty, zero-column table reported as success. That's by design, not an oversight. Flight gives a client no way to distinguish a genuinely empty result from a server that sent nothing useful, so code relying on this needs to check the returned table's column count itself instead of trusting a successful DoGet() call alone.

Self-test scope. The 22 offline checks cover protobuf varints, three HPACK encode cases and three HPACK decoder cases from RFC 7541, FlatBuffers alignment, a round-trip encode/decode of one sample table, one foreign-layout decode, and FlightData framing. They do not exercise HTTP/2 flow control, window updates under backpressure, or any multi-stream behaviour, because this client only ever opens one stream at a time. Those paths are covered only by the live benchmark and fault tests, against one real server implementation (pyarrow's), not a conformance suite.

One server implementation, one machine, one session. All real-network and fault-injection results here are against flight_server.py (pyarrow 25.0.1) on one Windows laptop in one test session. A different Flight server, a loaded machine, or a real network path could behave differently, particularly around the idle-connection drop this article hit by accident rather than by design. Round-tripping cleanly against pyarrow's implementation demonstrates interoperability with it, not conformance with the Arrow Flight specification as a whole. And the three fault tests cover local failure modes — a dead process, a server-side exception, a severed TCP connection — not the broader class of real network misbehaviour: packet loss, high latency, a half-open connection that never resets, or a proxy in between. Those would need a real degraded network to test, not a laptop talking to itself over loopback.


Conclusion

MQL5 has no HTTP/2 stack, no gRPC, no Arrow bindings, and none of that turned out to be a hard stop — it meant writing a FlatBuffers encoder, an HTTP/2 frame layer with its own HPACK table, and a thin gRPC/Flight shim on top, all checked twice: once offline against fixed reference bytes, and once live against a real pyarrow server with a value-for-value, bit-exact comparison of the decoded table on every round trip. 325 of 325 clean round trips matched exactly, the three deliberate fault tests failed in exactly the way the fault they injected should cause and nothing else, and an accidental idle-connection drop was absorbed by the same retry path without losing the bar it was holding.

The practical payoff is a columnar, schema-carrying channel out of MetaTrader 5 that costs about a third less to send than CSV and needs no agreed-upon column order on the receiving end — useful whenever the consumer is already a Python/Arrow data stack, which is most of them. Start with FlightRoundTrip_Benchmark.mq5 and InpSelfTestOnly=true to confirm the encoder matches this article's own 22 checks on your build, then point FlightBarStreamer_EA.mq5 at a flight_server.py you control before trusting it with anything that matters.

File Type Description
MQL5\Include\ArrowFlight\ArrowFlightCore.mqh Include FlatBuffers builder/reader, Arrow IPC schema/batch encode-decode, protobuf varints, HTTP/2 framing with HPACK, gRPC/Flight framing, CFlightClient (DoPut/DoGet/ListFlights), and the 22-check self-test.
MQL5\Experts\ArrowFlight\FlightBarStreamer_EA.mq5 Expert Advisor Streams closed bars and account deals continuously, with queueing, exponential back-off and reconnect.
MQL5\Scripts\ArrowFlight\FlightRoundTrip_Benchmark.mq5 Script Offline self-test, then real-history DoPut/DoGet round trips across symbols, timeframes and batch sizes with a value-for-value, bit-exact comparison and a CSV baseline.
MQL5\Files\ArrowFlight\flight_server.py / flight_read.py Python pyarrow Flight server (with --fail-after fault injection) and an independent reader used to verify every result in this article.
MQL5\Files\ArrowFlight\bench_results.csv Data Every logged round trip from this article's test session (432 rows), including the exact first_bar/last_bar timestamps and per-run timings behind the table and figures above.
Attached files |
MQL5.zip (51.85 KB)
Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open
When an EA trades several symbols, each new lot size must account for the risk already open. CRiskBudget returns the largest volume that five caps allow: risk per trade, open risk budget, free margin share, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_LIMIT, and it names the cap that decided. Unit tests, a tester EA, and a Python consistency check cover these decisions. In the tested runs, the budget did not reduce drawdown.
Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (MDC Module) Neural Networks in Trading: Mesh Approximation of Event Streams as a Tool for Analyzing Price Patterns (MDC Module)
Here is an implementation of the key components of the EEMFlow framework using MQL5. The article demonstrates how multi-scale event processing, spiking FAM modules, and adaptive feature fusion in MDC form a structured representation that is adapted to market density. This enables the strategy to effectively identify significant signals, combine micro-impulses with broader trends, and improve the accuracy of forecasts, providing traders with a reliable tool for analysis and decision-making.
Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary
We implement a direct MT5→ClickHouse pipeline without intermediate services: RowBinary encoding at the byte level and an HTTP client that authenticates and posts inserts. The article details schema and field mapping, VarUInt and Float64 encoding, Nullable rules, and why POST is required for inserts and DDL. An EA streams live ticks and deals, and scripts verify round‑trip correctness and perform historical backfill, enabling consistent storage for downstream queries.
Constructing Renko Bars from MQL5 Tick Streams in Real Time Constructing Renko Bars from MQL5 Tick Streams in Real Time
We build a Renko aggregator that operates on the raw tick stream from OnTick, not M1 OHLC, to preserve the true crossing order. The engine writes each completed brick to a MetaTrader custom symbol, enabling standard indicators on the output chart. Continuation, reversal, and gap scenarios are covered and validated with a compact test script.