Reading Parquet Natively in MQL5: Thrift, Snappy and Dictionary Decoding into matrix Without CSV
Introduction
The usual way to get Parquet data into MQL5 is a conversion step: a Python script writes a CSV, and an MQL5 script or EA reads it back with FileReadString(). That works, but it costs a second process before the terminal sees fresh data, a round trip through text for every number, and the file's own schema — which column is nullable, which is an integer — since once everything is text, null handling becomes a convention you invent and keep in sync yourself.
This article builds a native Parquet reader that skips that step: a hand-written Thrift Compact Protocol decoder, a Snappy decompressor, and a hybrid RLE/bit-packing decoder, assembled by one orchestrator into a native matrix — no DLL, no external process. The matrix holds doubles, so an INT64 beyond 2^53 is rounded and flagged, and the file is treated as untrusted input throughout: a file that fails a check is refused rather than half-read.
Scope. Flat numeric schemas (INT32/INT64/FLOAT/DOUBLE), UNCOMPRESSED/SNAPPY, DataPageV1 with PLAIN or dictionary encoding and RLE definition levels, first row group only. Anything else is refused with a Journal message, not decoded. See Testing for what the self-tests cover and Limitations for the rest.
Architecture
A Parquet file reads back to front: a 4-byte PAR1 magic, the column data, a Thrift-encoded footer, the footer's own length as a 4-byte little-endian integer, then PAR1 again. The last eight bytes are enough to locate the footer — jump there, read the length, and step backward by that many bytes.
The footer is a Thrift Compact Protocol-encoded FileMetaData struct; MQL5's standard library has no Thrift support, so ThriftCompactReader.mqh implements exactly the subset Parquet uses: unsigned and zigzag-signed varints, delta-encoded field headers, and list/struct/map framing. Everything downstream — the schema, the row group list, every column chunk's byte offsets — comes out of walking that struct.
Once a column chunk's offsets are known, its pages are read directly from the loaded file bytes. Each page starts with its own small Thrift-encoded PageHeader, followed by a payload that is Snappy-compressed when the chunk's codec says so. SnappyDecoder.mqh handles that. A page's decompressed payload is either a dictionary page (a flat list of the column's distinct values) or a data page (the actual row values, referencing the dictionary by index when the column is dictionary-encoded, or storing literal values directly otherwise). Both the dictionary indices and, on a nullable column, the definition-level null-tracking stream are packed with Parquet's hybrid RLE/bit-packing scheme, decoded by RLEBitPackedDecoder.mqh. ParquetReader.mqh ties all three together into one orchestrator that a script calls with a filename and gets a populated matrix back.
Native Parquet Reader Pipeline
Fig. 1. From raw file bytes to a native matrix, through Thrift footer parsing, Snappy decompression, and RLE/bit-packing decode.
ThriftCompactReader.mqh: Decoding the Wire Format Without a Thrift Library
Compact Protocol packs a lot of information into very few bytes, which is exactly why Parquet uses it for the footer - a file with thousands of row groups and columns would otherwise carry a bulky footer. The type identifiers below are the 4-bit nibble values the protocol packs into field headers; they are fixed by the Thrift spec, not a design choice made here.
//+------------------------------------------------------------------+ //| Thrift Compact Protocol type identifiers | //| Nibble values the Thrift compact protocol reserves for field | //| types — fixed by the Apache Thrift spec, not a choice made here.| //+------------------------------------------------------------------+ #define THRIFT_TYPE_STOP 0x00 #define THRIFT_TYPE_BOOLEAN_TRUE 0x01 #define THRIFT_TYPE_BOOLEAN_FALSE 0x02 #define THRIFT_TYPE_BYTE 0x03 #define THRIFT_TYPE_I16 0x04 #define THRIFT_TYPE_I32 0x05 #define THRIFT_TYPE_I64 0x06 #define THRIFT_TYPE_DOUBLE 0x07 #define THRIFT_TYPE_BINARY 0x08 #define THRIFT_TYPE_LIST 0x09 #define THRIFT_TYPE_SET 0x0A #define THRIFT_TYPE_MAP 0x0B #define THRIFT_TYPE_STRUCT 0x0C
The reader is a thin cursor over a copied slice of the file. Attach() copies only the requested byte range (the footer or one page header), which prevents parsing outside that region. All other methods advance m_pos as they consume bytes. It deliberately doesn't attempt the full Thrift spec (no RPC/service types, no write support) - only the read-side primitives a FileMetaData or PageHeader struct actually needs. Every read is bounds-checked: the first read past the end of the slice, an over-long varint, an impossible length or an unknown type id sets an error flag that callers test with HasError().
//+------------------------------------------------------------------+ //| CThriftCompactReader | //| Read-only cursor over Thrift Compact Protocol bytes — only what | //| a Parquet FileMetaData/PageHeader needs (no write/RPC support). | //| Every read is bounds-checked; HasError() reports a malformed | //| stream. | //+------------------------------------------------------------------+ class CThriftCompactReader { private: uchar m_buf[]; // slice of the file currently being parsed int m_pos; // read cursor, relative to the slice start int m_size; // length of the slice in bytes int m_depth; // current SkipValue() nesting depth bool m_error; // latched on the first malformed read void SkipCollectionElement(const uchar elem_type); public: void Attach(const uchar &src[], const int start_offset, const int end_offset); int Position(void) const { return(m_pos); } bool Eof(void) const { return(m_pos >= m_size); } bool HasError(void) const { return(m_error); } uchar ReadByte(void); ulong ReadVarUInt(void); long ReadZigZagVarInt(void); string ReadBinaryString(void); void ReadBinaryBytes(uchar &out[]); bool ReadFieldHeader(int &last_field_id, uchar &field_type); void ReadListHeader(uchar &elem_type, int &list_size); void SkipValue(const uchar field_type); };
Attach and ReadByte - bounds first. Attach() validates its range and copies only that slice, and ReadByte() is the single place every other primitive gets its bytes from: reading past the end sets the error flag and returns 0, so every loop built on top of it terminates, and every parse can end with one HasError() test.
//+------------------------------------------------------------------+ //| CThriftCompactReader::Attach | //| Point the cursor at [start_offset, end_offset) of src, copying | //| only that slice so parsing can't wander outside it. An invalid | //| range latches the error flag. | //+------------------------------------------------------------------+ void CThriftCompactReader::Attach(const uchar &src[], const int start_offset, const int end_offset) { m_pos = 0; m_size = 0; m_depth = 0; m_error = false; ArrayResize(m_buf, 0); //--- reject a range that is empty, inverted or outside the source array if(start_offset < 0 || end_offset <= start_offset || end_offset > ArraySize(src)) { m_error = true; return; } int n = end_offset - start_offset; if(ArrayResize(m_buf, n) != n) { m_error = true; return; } ArrayCopy(m_buf, src, 0, start_offset, n); m_size = n; } //+------------------------------------------------------------------+ //| CThriftCompactReader::ReadByte | //| Return the next byte and advance the cursor; past the end latches| //| the error flag and returns 0. | //+------------------------------------------------------------------+ uchar CThriftCompactReader::ReadByte(void) { if(m_pos >= m_size) { m_error = true; return(0); } return(m_buf[m_pos++]); }
ReadVarUInt - the base integer encoding. Every integer Thrift Compact Protocol sends - field ids, list sizes, string lengths, and the payload of every zigzag-signed value - rides on top of one unsigned varint scheme: 7 payload bits per byte, low byte first, with the top bit of each byte marking whether another byte follows. A value under 128 costs one byte; Parquet's small metadata integers (row counts in the tens of thousands, byte offsets in the low millions) mostly cost two to four. A 64-bit value never needs more than 10 bytes, so a longer run of continuation bytes is treated as corruption and sets the error flag instead of shifting forever.
//+------------------------------------------------------------------+ //| CThriftCompactReader::ReadVarUInt | //| Decode an unsigned LEB128 varint (7 bits/byte, continuation bit | //| high). More than 10 bytes is not a valid 64-bit varint and | //| latches the error flag. | //+------------------------------------------------------------------+ ulong CThriftCompactReader::ReadVarUInt(void) { ulong result = 0; int shift = 0; //--- accumulate 7 bits per byte, low byte first, until the continuation bit clears while(!m_error) { uchar b = ReadByte(); result |= ((ulong)(b & 0x7F)) << shift; // low 7 bits of this byte //--- top bit clear means this was the last byte of the varint if((b & 0x80) == 0) break; shift += 7; //--- more than 10 bytes cannot be a valid 64-bit varint if(shift > 63) { m_error = true; break; } } return(result); }
ReadZigZagVarInt - recovering the sign. The unsigned scheme above has no way to represent a negative number efficiently, so Compact Protocol zigzag-maps signed integers onto unsigned ones before varint-encoding them: 0, -1, 1, -2, 2, ... map to 0, 1, 2, 3, 4, ... Decoding reverses that mapping with one shift and one xor once the raw unsigned varint is read. Every i16, i32 and i64 field in FileMetaData and PageHeader - version numbers, row counts, byte offsets - goes through this path.
//+------------------------------------------------------------------+ //| CThriftCompactReader::ReadZigZagVarInt | //| Decode a zigzag-signed varint: reverse (n << 1) ^ (n >> 63) after| //| reading the raw unsigned varint. | //+------------------------------------------------------------------+ long CThriftCompactReader::ReadZigZagVarInt(void) { ulong raw = ReadVarUInt(); return((long)(raw >> 1) ^ -(long)(raw & 1)); }
ReadFieldHeader - the delta trick that makes the format compact. A Thrift struct is a sequence of (field id, type, value) triples, and Compact Protocol avoids spending a full field id on every one of them. The high nibble of the header byte is normally just the difference between this field's id and the previous field id read in the same struct - 1 through 15 covers the overwhelmingly common case of sequential or near-sequential field ids. A delta of 0 is the escape hatch: it means the real id didn't fit in a nibble, and a full zigzag-encoded id follows separately.
A header byte of 0x00 (THRIFT_TYPE_STOP) means the struct has no more fields - there is no explicit field count anywhere in the format. The caller is responsible for resetting last_field_id to 0 every time it starts parsing a new nested struct, since the delta convention restarts there; every nested-struct loop in ParquetReader.mqh declares its own fresh last_field_id for exactly this reason. Running off the end of the slice also makes it return false, with the error flag set so a truncated struct can be told apart from a finished one.
//+------------------------------------------------------------------+ //| CThriftCompactReader::ReadFieldHeader | //| Read one field header: the high nibble is the id delta from the | //| struct's last field id (0 means a full id follows); | //| THRIFT_TYPE_STOP ends the struct. Caller resets last_field_id per| //| nested struct. | //+------------------------------------------------------------------+ bool CThriftCompactReader::ReadFieldHeader(int &last_field_id, uchar &field_type) { uchar header = ReadByte(); //--- a stop byte means this struct has no more fields to read if(header == THRIFT_TYPE_STOP) { field_type = THRIFT_TYPE_STOP; return(false); } uchar type_bits = header & 0x0F; uchar delta_bits = (header >> 4) & 0x0F; //--- delta 0 is the escape hatch: the real id did not fit the 4-bit delta, so a //--- full zigzag id follows; any other delta just advances from the last field id if(delta_bits == 0) last_field_id = (int)ReadZigZagVarInt(); // long form: explicit field id follows else last_field_id += (int)delta_bits; // short form: id is last id + delta field_type = type_bits; return(!m_error); }
SkipValue - staying correctly positioned through fields nobody asked for. A real FileMetaData carries far more than this reader keeps: per-column statistics (min/max/null counts), bloom filter offsets, key-value metadata, a created_by string, sort orders. None of it is used here, but every one of those fields still has to be walked byte for byte to keep the cursor synchronized for the fields that do matter downstream - skipping a field by guessing its length would silently misalign every field read after it. This is the one function in the class that recurses: a struct can contain a list of structs, a map can have struct values, and each case calls back into the same dispatch.
The walk is defensive about hostile input too: nesting deeper than 32 levels, a truncated value or an unknown type id sets the error flag, a collection's declared size is checked against the bytes remaining before the loop starts, and a boolean inside a list or map is skipped as the full byte it occupies there (a boolean struct field, by contrast, lives entirely in the header nibble).
//+------------------------------------------------------------------+ //| CThriftCompactReader::SkipValue | //| Consume one value of field_type without decoding it, recursing | //| for lists/sets/maps/structs, to keep the cursor synced past | //| fields this reader ignores. Nesting past THRIFT_MAX_DEPTH or an | //| unknown type latches the error flag. | //+------------------------------------------------------------------+ void CThriftCompactReader::SkipValue(const uchar field_type) { if(m_error) return; //--- a corrupt file can nest structs arbitrarily deep; stop before the stack does if(m_depth >= THRIFT_MAX_DEPTH) { m_error = true; return; } m_depth++; //--- dispatch purely on the compact-protocol type nibble; every branch below //--- must consume exactly the bytes that value occupies, no more and no less switch(field_type) { case THRIFT_TYPE_BOOLEAN_TRUE: case THRIFT_TYPE_BOOLEAN_FALSE: break; // value is carried in the type nibble itself case THRIFT_TYPE_BYTE: ReadByte(); break; case THRIFT_TYPE_I16: case THRIFT_TYPE_I32: case THRIFT_TYPE_I64: ReadZigZagVarInt(); break; case THRIFT_TYPE_DOUBLE: { for(int i = 0; i < 8; i++) ReadByte(); break; } case THRIFT_TYPE_BINARY: { uchar tmp[]; ReadBinaryBytes(tmp); break; } case THRIFT_TYPE_LIST: case THRIFT_TYPE_SET: { uchar elem_type; int count; ReadListHeader(elem_type, count); for(int i = 0; i < count && !m_error; i++) SkipCollectionElement(elem_type); break; } case THRIFT_TYPE_MAP: { ulong map_size = ReadVarUInt(); //--- a size of 0 has no key/value-type byte at all — nothing further to read if(!m_error && map_size > 0) { //--- each pair needs at least two bytes, so an oversized count is corrupt if(map_size > (ulong)(m_size - m_pos)) { m_error = true; break; } uchar kv_types = ReadByte(); uchar key_type = (kv_types >> 4) & 0x0F; uchar val_type = kv_types & 0x0F; //--- keys and values can be different types; skip each pair in turn for(ulong i = 0; i < map_size && !m_error; i++) { SkipCollectionElement(key_type); SkipCollectionElement(val_type); } } break; } case THRIFT_TYPE_STRUCT: { int nested_last_id = 0; uchar nested_type; //--- recurse: a struct field can itself be a struct, so this reuses //--- ReadFieldHeader/SkipValue exactly as the top-level caller does while(ReadFieldHeader(nested_last_id, nested_type)) SkipValue(nested_type); break; } default: m_error = true; // unknown type id: the stream is corrupt break; } m_depth--; }
SnappyDecoder.mqh: Native Block Decompression
Snappy is the codec many Parquet writers apply by default - pyarrow's writer, for one, uses it unless told otherwise - so a native decoder for it is what makes this reader useful against typical files rather than only specially prepared uncompressed ones. (The Parquet specification itself doesn't name a default codec; that is a property of each writer.) Snappy is an LZ77-family scheme: the compressed stream is a sequence of tagged elements, each either a literal byte run or a back-reference copy from earlier in the output that has already been produced.
//+------------------------------------------------------------------+ //| CSnappyDecoder | //| Native Snappy block decompressor: a varint length prefix, then | //| literal runs and back-reference copies. Untrusted input — | //| Decompress() returns false on anything malformed. | //+------------------------------------------------------------------+ class CSnappyDecoder { private: static bool ReadVarUInt(const uchar &src[], int &pos, ulong &value); public: bool Decompress(const uchar &src[], uchar &dst[]); };
Decompress - literal runs and three copy forms. After a varint uncompressed-length prefix, every element's tag byte is read one at a time. The low 2 bits pick the element kind: 00 is a literal run, with its length in the top 6 bits of the tag (or, for a run of 60 bytes or more, an escape that reads 1-4 extra little-endian length bytes). The other three values are copy elements with progressively larger offset fields - 1, 2, or 4 bytes - since a short back-reference (repeating the last few bytes) is far more common than a reference thousands of bytes back, and the format spends fewer bits on the common case.
One detail matters: a copy's source region may legally overlap the destination when the offset is smaller than the copy length (a run of the same byte repeated many times compresses to a single 1-byte-offset copy with a long length). The copy loop below therefore reads and writes dst[] one byte at a time instead of using ArrayCopy(), which would read stale bytes in the overlapping case. (Literal runs can't overlap anything, so those do use ArrayCopy().)
Everything the decoder reads is untrusted. The decoder caps output at 256 MB and validates input bounds, output bounds, copy offsets, and complete block consumption. Any failed check makes Decompress() return false.
//+------------------------------------------------------------------+ //| CSnappyDecoder::Decompress | //| Decompress one block: the tag's low bits pick a literal run or | //| one of three copy forms. A copy's source may overlap its | //| destination, so the copy loop runs byte-by-byte. Returns false on| //| any malformed bound, offset, or leftover bytes. | //+------------------------------------------------------------------+ bool CSnappyDecoder::Decompress(const uchar &src[], uchar &dst[]) { int pos = 0; int src_size = ArraySize(src); ulong out_len = 0; ArrayResize(dst, 0); //--- the declared length comes from untrusted bytes: bound it before allocating if(!ReadVarUInt(src, pos, out_len) || out_len > SNAPPY_MAX_OUTPUT) return(false); int n_out = (int)out_len; if(ArrayResize(dst, n_out) != n_out) return(false); int out_pos = 0; //--- walk the tagged-element stream until the declared uncompressed length is produced while(out_pos < n_out) { //--- the stream must not end before the declared output is complete if(pos >= src_size) return(false); uchar tag = src[pos++]; uchar el_type = tag & 0x03; //--- element kind 0: a literal byte run, copied straight from the input if(el_type == 0) { long lit_len = (tag >> 2) & 0x3F; //--- runs of 60+ bytes don't fit the 6-bit inline length, so the tag //--- instead names how many extra little-endian length bytes follow if(lit_len >= 60) { int extra_bytes = (int)lit_len - 59; if(pos + extra_bytes > src_size) return(false); lit_len = 0; for(int i = 0; i < extra_bytes; i++) lit_len |= ((long)src[pos++]) << (8 * i); } lit_len++; // tag stores length-1 //--- the literal must fit both the remaining input and the remaining output if(lit_len > (long)(src_size - pos) || lit_len > (long)(n_out - out_pos)) return(false); ArrayCopy(dst, src, out_pos, pos, (int)lit_len); pos += (int)lit_len; out_pos += (int)lit_len; } //--- element kinds 1/2/3: a back-reference copy, offset width grows with the kind else { long copy_len = 0; long offset = 0; //--- 1-byte offset: the short, most common case (length 4-11, offset 0-2047) if(el_type == 1) { if(pos + 1 > src_size) return(false); copy_len = ((tag >> 2) & 0x07) + 4; offset = (((long)tag >> 5) << 8) | (long)src[pos++]; } //--- 2-byte offset, little-endian: mid-range back-references else if(el_type == 2) { if(pos + 2 > src_size) return(false); copy_len = (tag >> 2) + 1; offset = (long)src[pos] | ((long)src[pos + 1] << 8); pos += 2; } //--- 4-byte offset, little-endian: for references far back in a large block else { if(pos + 4 > src_size) return(false); copy_len = (tag >> 2) + 1; offset = (long)src[pos] | ((long)src[pos + 1] << 8) | ((long)src[pos + 2] << 16) | ((long)src[pos + 3] << 24); pos += 4; } //--- offset 0 is invalid, and a copy cannot reach back before the first //--- output byte or write past the declared output length if(offset <= 0 || offset > out_pos || copy_len > (long)(n_out - out_pos)) return(false); //--- byte-by-byte, not ArrayCopy: when offset < copy_len the source region //--- overlaps bytes this same loop is still writing, so each destination //--- byte must become visible to dst[] before the next iteration reads it int copy_src = out_pos - (int)offset; for(int i = 0; i < (int)copy_len; i++) { dst[out_pos] = dst[copy_src + i]; out_pos++; } } } //--- a well-formed block ends exactly where its declared output ends return(pos == src_size); }
RLEBitPackedDecoder.mqh: Hybrid RLE/Bit-Packing for Dictionary Indices and Nulls
Parquet uses one run-encoding scheme in two different places inside a data page: to pack the stream of dictionary indices when a column is dictionary-encoded, and to pack the definition-level stream that marks which rows are null on any OPTIONAL (nullable) column. Same wire format both times, only the bit width and the meaning of the decoded integers differ - a definition-level stream on a column with max_definition_level 1 uses a 1-bit width (0 = null, 1 = present); a dictionary-index stream uses whatever width the dictionary's size requires.
//+------------------------------------------------------------------+ //| CRLEBitPackedDecoder | //| Decodes Parquet's hybrid RLE/bit-packing stream, used for both | //| definition levels and dictionary indices. Every read is checked | //| against an explicit end offset. | //+------------------------------------------------------------------+ class CRLEBitPackedDecoder { private: static bool ReadVarUInt(const uchar &src[], int &pos, const int end_offset, ulong &value); static void UnpackGroup(const uchar &src[], int &pos, const int bit_width, int &out[], int &out_idx); public: bool Decode(const uchar &src[], const int start_offset, const int end_offset, const int bit_width, const int value_count, int &out_values[]); };
A run stream is a sequence of runs, and the encoder picks per run whichever of two representations is smaller: an RLE run (one repeated value, for long stretches of identical values - overwhelmingly common for definition levels when nulls are rare or absent) or a bit-packed run (a tightly packed sequence of distinct values, for stretches with real variety - the usual case for dictionary indices over a column with several distinct values in quick succession). UnpackGroup is the bit-packed side: it pulls exactly 8 values of bit_width bits each out of a byte stream, LSB-first, using a small rolling bit buffer so a value that straddles a byte boundary needs no special-casing - the buffer is simply topped up a byte at a time until enough bits are available.
//+------------------------------------------------------------------+ //| CRLEBitPackedDecoder::UnpackGroup | //| Unpack 8 bit_width-bit values LSB-first via a small bit buffer. | //| Caller has already checked a full group remains in the stream. | //+------------------------------------------------------------------+ void CRLEBitPackedDecoder::UnpackGroup(const uchar &src[], int &pos, const int bit_width, int &out[], int &out_idx) { ulong bit_buffer = 0; int bits_in_buffer = 0; //--- extract exactly 8 values, refilling the bit buffer a byte at a time as needed for(int i = 0; i < 8; i++) { //--- pull in whole bytes until the buffer holds at least one full value -- //--- this is what lets a value straddle a byte boundary with no special case while(bits_in_buffer < bit_width) { bit_buffer |= ((ulong)src[pos++]) << bits_in_buffer; bits_in_buffer += 8; } out[out_idx++] = (int)(bit_buffer & ((1UL << bit_width) - 1)); bit_buffer >>= bit_width; bits_in_buffer -= bit_width; } }
Decode is the run dispatcher. Each run starts with a varint header whose low bit selects the kind: bit clear is an RLE run, where the remaining bits are a repeat count followed by one fixed-width little-endian value; bit set is a bit-packed run, where the remaining bits count groups of 8 values, each group consuming exactly bit_width bytes.
The stream itself carries no overall value count - only per-run counts - so the caller has to already know how many values to stop at (the page's declared row count, or the non-null count computed from a previously decoded definition-level stream); the loop below stops exactly at value_count even if that cuts an RLE run's repeat count short, which happens whenever the encoder padded the last run past the true end of the page.
The stream's end offset is an explicit argument, so a definition-level stream can't read into the values that follow it. If the stream ends before value_count values exist, a run header is longer than a 32-bit count needs, or bit_width falls outside 0 to 32, Decode() returns false instead of reading on.
//+------------------------------------------------------------------+ //| CRLEBitPackedDecoder::Decode | //| Decode value_count integers from [start_offset, end_offset): each| //| run's varint header picks RLE (one value, repeated) or bit-packed| //| (groups of 8). Returns false if the stream runs out first or | //| bit_width is outside 0..32. | //+------------------------------------------------------------------+ bool CRLEBitPackedDecoder::Decode(const uchar &src[], const int start_offset, const int end_offset, const int bit_width, const int value_count, int &out_values[]) { ArrayResize(out_values, 0); //--- the stream must lie inside src, and values must fit the int output if(start_offset < 0 || end_offset > ArraySize(src) || start_offset > end_offset || bit_width < 0 || bit_width > 32 || value_count < 0) return(false); if(ArrayResize(out_values, value_count) != value_count) return(false); int pos = start_offset; int produced = 0; //--- bit_width 0 means every value the encoder saw was 0 — the degenerate //--- case of a definition-level stream where every row on the page is null if(bit_width == 0) { for(int i = 0; i < value_count; i++) out_values[i] = 0; return(true); } //--- consume runs until value_count values have been produced; the stream //--- itself has no overall count, only per-run counts, so this loop — not //--- the data — is what knows when to stop while(produced < value_count) { ulong header = 0; if(!ReadVarUInt(src, pos, end_offset, header)) return(false); bool is_packed = ((header & 1) == 1); //--- RLE run: a single value repeated run_len times, read once and replayed if(!is_packed) { ulong run_len = header >> 1; int byte_len = (bit_width + 7) / 8; ulong value = 0; //--- the repeated value's bytes must still be inside the stream if(pos + byte_len > end_offset) return(false); for(int i = 0; i < byte_len; i++) value |= ((ulong)src[pos++]) << (8 * i); for(ulong i = 0; i < run_len && produced < value_count; i++) out_values[produced++] = (int)value; } //--- bit-packed run: num_groups groups of 8 tightly packed values each else { ulong num_groups = header >> 1; for(ulong g = 0; g < num_groups && produced < value_count; g++) { //--- a full group is exactly bit_width bytes; it must fit in the stream if(pos + bit_width > end_offset) return(false); int tmp[8]; int idx = 0; UnpackGroup(src, pos, bit_width, tmp, idx); for(int i = 0; i < 8 && produced < value_count; i++) out_values[produced++] = tmp[i]; } } } return(true); }
ParquetReader.mqh: From Footer Bytes to a Native Matrix
This is the orchestrator that turns the three codecs above into something a script can actually call. It works from the whole file loaded into memory rather than seeking a file handle back and forth - Parquet is a random-access format by design (the footer points anywhere in the file), so a full in-memory copy is a far simpler correctness story for the file sizes a trading-data extract realistically produces, at the cost of not scaling to multi-gigabyte files without a streaming redesign. The physical type, codec, and encoding identifiers below are fixed by the public Parquet format spec. Every number it reads from the file - footer length, offsets, sizes, counts, dictionary indices - is treated as untrusted and checked before it is used, and a file over 2 GB is refused because an MQL5 array index is an int.
//+------------------------------------------------------------------+ //| Parquet wire-format enum values | //| Subset of parquet.thrift's Type / ConvertedType / | //| CompressionCodec / Encoding / PageType / FieldRepetitionType | //| enums this reader uses — fixed by the format spec. | //+------------------------------------------------------------------+ #define PARQUET_TYPE_BOOLEAN 0 #define PARQUET_TYPE_INT32 1 #define PARQUET_TYPE_INT64 2 #define PARQUET_TYPE_INT96 3 #define PARQUET_TYPE_FLOAT 4 #define PARQUET_TYPE_DOUBLE 5 #define PARQUET_TYPE_BYTE_ARRAY 6 #define PARQUET_TYPE_FIXED_LEN 7 #define PARQUET_CONVERTED_DECIMAL 5 #define PARQUET_CONVERTED_UINT_32 13 #define PARQUET_CONVERTED_UINT_64 14 #define PARQUET_CODEC_UNCOMPRESSED 0 #define PARQUET_CODEC_SNAPPY 1 #define PARQUET_ENC_PLAIN 0 #define PARQUET_ENC_PLAIN_DICTIONARY 2 #define PARQUET_ENC_RLE 3 #define PARQUET_ENC_RLE_DICTIONARY 8 #define PARQUET_PAGE_DATA 0 #define PARQUET_PAGE_INDEX 1 #define PARQUET_PAGE_DICTIONARY 2 #define PARQUET_PAGE_DATA_V2 3 #define PARQUET_REP_REQUIRED 0 #define PARQUET_REP_OPTIONAL 1 #define PARQUET_REP_REPEATED 2 //+------------------------------------------------------------------+ //| Reader limits | //| 2^53 is IEEE754's exact-double boundary for INT64. | //| PARQUET_MAX_PAGE_HEADER (1 MB) is a generous safety cap, not a | //| measurement of typical headers or an MQL5 limit, so a hostile | //| length field is refused outright. | //+------------------------------------------------------------------+ #define PARQUET_MAX_EXACT_INT64 9007199254740992 #define PARQUET_MAX_PAGE_HEADER 1048576
Parquet's PLAIN encoding stores FLOAT and DOUBLE values as raw little-endian IEEE754 bytes on disk - exactly the in-memory representation a CPU already uses for a float or double, just without any language-level way in MQL5 to reinterpret a byte buffer as one directly. A union does the job: writing bytes into as_bytes and reading back as_float / as_double reinterprets the same 4 or 8 bytes as the other type, no bit-shifting arithmetic required.
//+------------------------------------------------------------------+ //| Byte <-> IEEE754 reinterpretation helpers | //| MQL5 has no byte-buffer-to-float/double reinterpret cast, so a | //| union does it: raw little-endian bytes in, IEEE754 FLOAT/DOUBLE | //| out — matching Parquet's PLAIN encoding. | //+------------------------------------------------------------------+ union UFloatBytes { float as_float; uchar as_bytes[4]; }; union UDoubleBytes { double as_double; uchar as_bytes[8]; };
Three small structs carry exactly what this reader keeps from Parquet's much larger schema and metadata structures - everything else (column statistics, bloom filter offsets, sort orders) is walked past by SkipValue() and discarded on purpose, not by oversight.
//+------------------------------------------------------------------+ //| SParquetColumn / SColumnChunkMeta / SPageHeader | //| Three plain-data structs holding only what this reader keeps from| //| Parquet's larger FileMetaData/PageHeader — everything else is | //| skipped on purpose via SkipValue(). | //+------------------------------------------------------------------+ struct SParquetColumn { string name; // leaf column name from the schema int type; // PARQUET_TYPE_* physical type int converted_type; // legacy logical-type id, -1 when absent int max_def_level; // 1 if OPTIONAL (nullable), 0 if REQUIRED }; struct SColumnChunkMeta { int type; // PARQUET_TYPE_*, duplicated from schema int codec; // PARQUET_CODEC_* long num_values; // row count for this column chunk long total_compressed_size; // bytes spanned by the chunk's pages on disk long data_page_offset; // absolute file offset of the first data page long dictionary_page_offset; // absolute file offset of the dictionary page bool has_dictionary_page; // true if the chunk carries a dictionary page bool has_meta; // true once ColumnMetaData has been parsed string path; // first element of path_in_schema int path_depth; // length of path_in_schema (1 for a flat column) }; struct SPageHeader { int page_type; // PARQUET_PAGE_* int uncompressed_size; int compressed_size; int num_values; // rows (data page) or entries (dictionary page) int encoding; // PARQUET_ENC_* for the values stream int def_level_encoding; // PARQUET_ENC_* for definition levels, -1 if absent int header_bytes; // size of the Thrift-encoded header itself };
The class declaration lists every parsing stage as its own private method - one method per Thrift struct being walked - plus the public entry points a script actually calls: Open(), ReadColumn() and ReadToMatrix(), each with an overload that adds an exact null mask, and read-only accessors for what the file says about itself (ColumnName(), ColumnType(), ColumnTypeName(), ColumnNullable(), ColumnConvertedType()), its row-group count and the INT64 precision flag.
//+------------------------------------------------------------------+ //| CParquetReader | //| Top-level orchestrator: loads a .parquet file, parses its footer,| //| and decodes columns into MQL5 arrays or a matrix — no CSV, no | //| external library. Scope: flat numeric schemas, | //| UNCOMPRESSED/SNAPPY, DataPageV1, PLAIN/dictionary encoding with | //| RLE definition levels, first row group only. All input is | //| untrusted; a failed check returns false. INT64 beyond 2^53 is | //| flagged via Int64PrecisionLoss(); nulls carry both EMPTY_VALUE | //| and an exact null mask. | //+------------------------------------------------------------------+ class CParquetReader { private: uchar m_file[]; // entire file loaded into memory int m_file_size; int m_data_end; // file offset where the footer starts SParquetColumn m_columns[]; // flat leaf-column schema, in file order SColumnChunkMeta m_chunks[]; // one entry per column, first row group only CThriftCompactReader m_thrift; // reusable Thrift Compact Protocol cursor long m_file_num_rows; // FileMetaData.num_rows, -1 if absent long m_first_rg_rows; // first RowGroup.num_rows, -1 if absent int m_row_group_count; // row groups declared in the footer int m_int64_hits; // INT64 values beyond 2^53 converted to double so far //--- private parsing/decoding methods (ReadWholeFile, ParseFileMetaData, ParseSchemaList, //--- ParseRowGroup, ParsePageHeader, DecompressPage, DecodeDataPage and others) are declared //--- in full in ParquetReader.mqh — each is covered in its own section below public: bool Open(const string filename); int ColumnCount(void) const { return(ArraySize(m_columns)); } string ColumnName(const int idx) const { return(idx >= 0 && idx < ArraySize(m_columns) ? m_columns[idx].name : ""); } int ColumnType(const int idx) const { return(idx >= 0 && idx < ArraySize(m_columns) ? m_columns[idx].type : -1); } int ColumnConvertedType(const int idx) const { return(idx >= 0 && idx < ArraySize(m_columns) ? m_columns[idx].converted_type : -1); } bool ColumnNullable(const int idx) const { return(idx >= 0 && idx < ArraySize(m_columns) && m_columns[idx].max_def_level > 0); } string ColumnTypeName(const int idx) const; long RowCount(const int idx) const { return(idx >= 0 && idx < ArraySize(m_chunks) ? m_chunks[idx].num_values : 0); } int RowGroupCount(void) const { return(m_row_group_count); } long FileRowCount(void) const { return(m_file_num_rows); } bool Int64PrecisionLoss(void) const { return(m_int64_hits > 0); } bool ReadColumn(const int idx, double &out_values[], bool &out_null[]); bool ReadColumn(const int idx, double &out_values[]); bool ReadToMatrix(matrix &out, string &column_names[], matrix &out_null_mask); bool ReadToMatrix(matrix &out, string &column_names[]); };
Open - validating the envelope, then jumping to the footer. The very first and very last 4 bytes of a real Parquet file are always the PAR1 magic; checking both catches a non-Parquet file immediately rather than producing a confusing parse failure several calls later. The footer length sits in the 4 bytes just before the trailing magic, and it comes from the file, so it is validated before it is trusted: it's assembled in a long so a value with the top bit set can't turn negative, it must be positive, and the footer it implies has to begin after the leading magic. Only then is the offset handed to the metadata parser, together with the footer's end, so parsing can't wander outside the footer bytes.
//+------------------------------------------------------------------+ //| CParquetReader::Open | //| Load the file, validate the PAR1 magic at both ends, then parse | //| the footer (its untrusted length must be positive and point past | //| the leading magic). | //+------------------------------------------------------------------+ bool CParquetReader::Open(const string filename) { ArrayResize(m_columns, 0); ArrayResize(m_chunks, 0); m_file_num_rows = -1; m_first_rg_rows = -1; m_row_group_count = 0; m_int64_hits = 0; m_data_end = 0; if(!ReadWholeFile(filename)) return(false); //--- a file shorter than magic+length+magic cannot possibly be well-formed if(m_file_size < 12) { Print("ParquetReader: file too small to be a valid Parquet file"); return(false); } bool head_ok = (m_file[0] == 'P' && m_file[1] == 'A' && m_file[2] == 'R' && m_file[3] == '1'); bool tail_ok = (m_file[m_file_size - 4] == 'P' && m_file[m_file_size - 3] == 'A' && m_file[m_file_size - 2] == 'R' && m_file[m_file_size - 1] == '1'); //--- catching a non-Parquet file here, by its magic, beats a confusing //--- parse failure several calls later once footer parsing has begun if(!head_ok || !tail_ok) { Print("ParquetReader: PAR1 magic missing at head or tail — not a Parquet file"); return(false); } //--- the footer length sits in the 4 bytes right before the trailing magic; //--- assembled in a long so a length with the top bit set cannot go negative long footer_len = (long)m_file[m_file_size - 8] | ((long)m_file[m_file_size - 7] << 8) | ((long)m_file[m_file_size - 6] << 16) | ((long)m_file[m_file_size - 5] << 24); long footer_offset = (long)m_file_size - 8 - footer_len; //--- the footer must be non-empty and begin after the 4-byte leading magic if(footer_len <= 0 || footer_offset < 4) { Print("ParquetReader: footer length ", footer_len, " is invalid for a ", m_file_size, "-byte file"); return(false); } m_data_end = (int)footer_offset; return(ParseFileMetaData((int)footer_offset, m_file_size - 8)); }
ParseFileMetaData - walking the top-level struct, scoped to what matters. Field 2 (schema) goes to ParseSchemaList(). Field 3 (num_rows) and the row-group count are kept so a multi-row-group file is reported rather than silently truncated, and field 4 (row_groups) is decoded for its first entry only. Parsing stops right there: nothing after row_groups is used, so the remaining row groups aren't walked at all. The other top-level fields (version, key_value_metadata, created_by) are walked past with SkipValue(). A truncated or malformed footer returns false, and so does one that fails the cross-checks in ValidateChunks().
//+------------------------------------------------------------------+ //| CParquetReader::ParseFileMetaData | //| Walk FileMetaData: field 2 to ParseSchemaList(), field 3's | //| row/row-group counts kept so a multi-row-group file is reported | //| rather than truncated silently, field 4 decoded for its first | //| entry only. Everything else is skipped; a malformed footer or a | //| failed ValidateChunks() returns false. | //+------------------------------------------------------------------+ bool CParquetReader::ParseFileMetaData(const int footer_offset, const int footer_end) { m_thrift.Attach(m_file, footer_offset, footer_end); int last_field_id = 0; uchar field_type; bool got_schema = false; bool got_rowgroups = false; //--- fields other than 2, 3 and 4 are skipped outright; version, key_value_ //--- metadata and created_by are never read by anything downstream while(m_thrift.ReadFieldHeader(last_field_id, field_type)) { //--- field 2: the schema element list, validated as a flat leaf-column list if(last_field_id == 2 && field_type == THRIFT_TYPE_LIST) { if(!ParseSchemaList()) return(false); got_schema = true; } //--- field 3: total row count across all row groups else if(last_field_id == 3 && field_type == THRIFT_TYPE_I64) m_file_num_rows = m_thrift.ReadZigZagVarInt(); //--- field 4: row groups — scope is the first row group only, see class comment else if(last_field_id == 4 && field_type == THRIFT_TYPE_LIST) { uchar elem_type; int list_size; m_thrift.ReadListHeader(elem_type, list_size); m_row_group_count = list_size; if(list_size > 0) ParseRowGroup(); got_rowgroups = true; break; // nothing after row_groups is needed } else m_thrift.SkipValue(field_type); } if(m_thrift.HasError()) { Print("ParquetReader: footer is truncated or malformed"); return(false); } if(!got_schema || !got_rowgroups || m_row_group_count < 1) { Print("ParquetReader: footer has no schema or no row groups"); return(false); } return(ValidateChunks()); }
ParseSchemaList - flat means flat. The schema is a list of elements in depth-first order; the first is the implicit root group, which only supplies the number of columns it claims. Every other element has to be a typed leaf that is OPTIONAL or REQUIRED and has no children. A group (num_children above 0), a REPEATED field, or a leaf missing its type or repetition_type means the file is nested or malformed, and Open() fails with a Journal message naming the element - the reader doesn't try to guess a hierarchy. Finally the leaf count has to equal the root's child count, which is what a flat schema is.
//+------------------------------------------------------------------+ //| CParquetReader::ParseSchemaList | //| Read the schema list: element 0 is the implicit root (column | //| count only); every other element must be a typed, childless | //| OPTIONAL/REQUIRED leaf, or the file is refused as | //| nested/malformed rather than guessed at. Leaf count must match | //| the root's child count. | //+------------------------------------------------------------------+ bool CParquetReader::ParseSchemaList(void) { uchar elem_type; int list_size; m_thrift.ReadListHeader(elem_type, list_size); //--- the root plus at least one column if(m_thrift.HasError() || list_size < 2) { Print("ParquetReader: schema list is empty or malformed"); return(false); } int root_children = 0; for(int i = 0; i < list_size; i++) { string name; int type, converted, repetition, num_children; bool is_leaf; ParseSchemaElement(name, type, converted, repetition, num_children, is_leaf); if(m_thrift.HasError()) { Print("ParquetReader: schema element ", i, " is truncated or malformed"); return(false); } //--- element 0 is the implicit root group; keep only its declared child count if(i == 0) { root_children = num_children; continue; } //--- below the root, a group, a REPEATED field, or a leaf missing its type or //--- repetition_type is nested or malformed data this reader does not support if(!is_leaf || num_children > 0 || repetition < 0 || repetition == PARQUET_REP_REPEATED) { Print("ParquetReader: schema element '", name, "' is not a flat typed leaf column ", "(nested group, repeated field, or missing type/repetition) — unsupported"); return(false); } int n = ArraySize(m_columns); ArrayResize(m_columns, n + 1); m_columns[n].name = name; m_columns[n].type = type; m_columns[n].converted_type = converted; m_columns[n].max_def_level = (repetition == PARQUET_REP_OPTIONAL) ? 1 : 0; } //--- a flat schema has exactly as many leaves as the root has children if(ArraySize(m_columns) != root_children) { Print("ParquetReader: schema declares ", root_children, " root children but has ", ArraySize(m_columns), " leaf columns — not a flat schema"); return(false); } return(true); }
ParseSchemaElement - the fields one element contributes. Five fields are kept: type (1), repetition_type (3), name (4), num_children (5) and converted_type (6). repetition_type 0 is REQUIRED, 1 is OPTIONAL - a nullable column, which sets max_definition_level to 1 and tells DecodeDataPage whether to expect a definition-level stream on that column's pages - and 2 is REPEATED, which this reader refuses. A group has no type field of its own, so is_leaf only reports whether one was present; ParseSchemaList() decides what each element is from its position and its num_children. converted_type is the legacy logical-type id (DECIMAL, unsigned integers, timestamps and so on); it is recorded and exposed but not applied.
//+------------------------------------------------------------------+ //| CParquetReader::ParseSchemaElement | //| Parse one SchemaElement's type, repetition_type, name, | //| num_children and converted_type. repetition_type: 0 REQUIRED, 1 | //| OPTIONAL, 2 REPEATED (unsupported); absent fields report -1. | //+------------------------------------------------------------------+ void CParquetReader::ParseSchemaElement(string &out_name, int &out_type, int &out_converted, int &out_repetition, int &out_num_children, bool &is_leaf) { int last_field_id = 0; uchar field_type; bool has_type = false; out_name = ""; out_type = -1; out_converted = -1; out_repetition = -1; out_num_children = 0; //--- only fields 1, 3, 4, 5 and 6 are kept; everything else is skipped in step while(m_thrift.ReadFieldHeader(last_field_id, field_type)) { if(last_field_id == 1 && field_type == THRIFT_TYPE_I32) { out_type = (int)m_thrift.ReadZigZagVarInt(); has_type = true; } else if(last_field_id == 3 && field_type == THRIFT_TYPE_I32) out_repetition = (int)m_thrift.ReadZigZagVarInt(); else if(last_field_id == 4 && field_type == THRIFT_TYPE_BINARY) out_name = m_thrift.ReadBinaryString(); else if(last_field_id == 5 && field_type == THRIFT_TYPE_I32) out_num_children = (int)m_thrift.ReadZigZagVarInt(); else if(last_field_id == 6 && field_type == THRIFT_TYPE_I32) out_converted = (int)m_thrift.ReadZigZagVarInt(); else m_thrift.SkipValue(field_type); } is_leaf = has_type; }
ParseColumnMetaData - the fields that actually matter. A real ColumnMetaData struct carries statistics, an encodings summary list, and a bloom filter offset among other things; only the physical type, path_in_schema, codec, value count, on-disk size, and the data-page and dictionary-page start offsets are kept. The path is what lets ValidateChunks() tie a chunk to its schema column by name instead of by position alone. The encoding a page actually uses is read from that page's own PageHeader later, rather than trusted from this struct's summary field - more precise, and one less place for the two to silently disagree.
//+------------------------------------------------------------------+ //| CParquetReader::ParseColumnMetaData | //| Keep only what locates and decodes this column's pages and ties | //| it to its schema leaf (type, path, codec, value count, size, page| //| offsets). Statistics and the encodings list are skipped — actual| //| encoding is read per-page instead. | //+------------------------------------------------------------------+ void CParquetReader::ParseColumnMetaData(SColumnChunkMeta &chunk) { int last_field_id = 0; uchar field_type; while(m_thrift.ReadFieldHeader(last_field_id, field_type)) { switch(last_field_id) { case 1: chunk.type = (int)m_thrift.ReadZigZagVarInt(); break; case 3: { //--- path_in_schema: list<string>; for a flat column exactly [column name] if(field_type != THRIFT_TYPE_LIST) { m_thrift.SkipValue(field_type); break; } uchar elem_type; int list_size; m_thrift.ReadListHeader(elem_type, list_size); chunk.path_depth = list_size; for(int i = 0; i < list_size && !m_thrift.HasError(); i++) { string part = m_thrift.ReadBinaryString(); if(i == 0) chunk.path = part; } break; } case 4: chunk.codec = (int)m_thrift.ReadZigZagVarInt(); break; case 5: chunk.num_values = m_thrift.ReadZigZagVarInt(); break; case 7: chunk.total_compressed_size = m_thrift.ReadZigZagVarInt(); break; case 9: chunk.data_page_offset = m_thrift.ReadZigZagVarInt(); break; case 11: //--- presence of this field is the only signal that a dictionary //--- page exists at all — there is no separate boolean flag for it chunk.dictionary_page_offset = m_thrift.ReadZigZagVarInt(); chunk.has_dictionary_page = true; break; default: m_thrift.SkipValue(field_type); break; } } }
ValidateChunks - cross-checking the schema against the row group. Before any value is decoded, the first row group is checked against the schema: one chunk per schema column, each chunk's physical type and path_in_schema matching the column at the same position, one shared non-negative row count, and every chunk's byte span lying after the leading magic and before the footer. A file that fails any of these doesn't open. A file with several row groups does open - its first row group is valid - but the Journal states how many rows are being left out, and RowGroupCount() and FileRowCount() let a caller check for themselves.
//+------------------------------------------------------------------+ //| CParquetReader::ValidateChunks | //| Cross-check the row group against the schema before decoding | //| anything: one chunk per leaf, matching type/path/order, one | //| shared row count, every chunk inside the data area. Extra row | //| groups still open; the Journal reports how many rows are left | //| out. | //+------------------------------------------------------------------+ bool CParquetReader::ValidateChunks(void) { int cols = ArraySize(m_columns); if(cols == 0 || ArraySize(m_chunks) != cols) { Print("ParquetReader: first row group has ", ArraySize(m_chunks), " column chunks but the schema has ", cols, " columns"); return(false); } long rows = m_chunks[0].num_values; for(int c = 0; c < cols; c++) { //--- the chunk must be fully parsed and describe the same leaf as schema column c if(!m_chunks[c].has_meta || m_chunks[c].type != m_columns[c].type || m_chunks[c].path_depth != 1 || m_chunks[c].path != m_columns[c].name) { Print("ParquetReader: column chunk ", c, " does not match schema column '", m_columns[c].name, "' (type or path_in_schema differs)"); return(false); } //--- every column of a flat row group holds one value per row, nulls included if(m_chunks[c].num_values < 0 || m_chunks[c].num_values > INT_MAX || m_chunks[c].num_values != rows) { Print("ParquetReader: column '", m_columns[c].name, "' has an invalid or ", "inconsistent value count"); return(false); } long start = (m_chunks[c].has_dictionary_page ? m_chunks[c].dictionary_page_offset : m_chunks[c].data_page_offset); //--- the chunk's pages must lie after the leading magic and before the footer if(start < 4 || m_chunks[c].total_compressed_size <= 0 || start + m_chunks[c].total_compressed_size > m_data_end) { Print("ParquetReader: column '", m_columns[c].name, "' has a byte range outside ", "the file's data area"); return(false); } } if(m_first_rg_rows >= 0 && m_first_rg_rows != rows) { Print("ParquetReader: row group row count ", m_first_rg_rows, " disagrees with its column chunks (", rows, ")"); return(false); } //--- scope is the first row group: say so loudly when the file has more if(m_row_group_count > 1) Print("ParquetReader: WARNING file has ", m_row_group_count, " row groups; only the first (", rows, " of ", m_file_num_rows, " rows) is read"); return(true); }
ParsePageHeader - both page kinds share one field layout. A DataPageHeader (field 5) and a DictionaryPageHeader (field 7) both carry num_values and encoding at the same nested field ids, 1 and 2, so one branch of the switch reads both the same way. A DataPageHeader also carries definition_level_encoding at field 3, which DecodeDataPage() later requires to be RLE. header_bytes records exactly how far the Thrift-encoded header extended into the page's bytes, since the compressed payload starts immediately after it, not at a fixed offset from the page's start - a header's size varies with how many bytes its own varints happened to need.
The parse is confined to the chunk's end and to 1 MB - a generous safety margin bounding how much of the file one header parse may copy, not a measurement of typical header sizes (a real PageHeader is at most a few hundred bytes) or an MQL5 runtime limit - and it returns false for a truncated header or one missing its page type or sizes.
//+------------------------------------------------------------------+ //| CParquetReader::ParsePageHeader | //| Parse one PageHeader, bounded by the chunk end and | //| PARQUET_MAX_PAGE_HEADER. DataPageHeader and DictionaryPageHeader | //| share field ids 1/2; header_bytes records where the compressed | //| payload actually starts. A truncated or type/size-less header | //| returns false. | //+------------------------------------------------------------------+ bool CParquetReader::ParsePageHeader(const int offset, const int limit, SPageHeader &hdr) { int end = (int)MathMin((long)limit, (long)offset + PARQUET_MAX_PAGE_HEADER); m_thrift.Attach(m_file, offset, end); int last_field_id = 0; uchar field_type; hdr.page_type = -1; hdr.uncompressed_size = -1; hdr.compressed_size = -1; hdr.num_values = 0; hdr.encoding = -1; hdr.def_level_encoding = -1; hdr.header_bytes = 0; //--- fields 5 (DataPageHeader) and 7 (DictionaryPageHeader) share the same //--- nested num_values/encoding layout, so one branch below handles both while(m_thrift.ReadFieldHeader(last_field_id, field_type)) { switch(last_field_id) { case 1: hdr.page_type = (int)m_thrift.ReadZigZagVarInt(); break; case 2: hdr.uncompressed_size = (int)m_thrift.ReadZigZagVarInt(); break; case 3: hdr.compressed_size = (int)m_thrift.ReadZigZagVarInt(); break; case 5: // DataPageHeader case 7: // DictionaryPageHeader { int outer_field = last_field_id; int nested_last = 0; uchar nested_type; //--- walk the nested struct exactly like any other Thrift struct while(m_thrift.ReadFieldHeader(nested_last, nested_type)) { if(nested_last == 1) hdr.num_values = (int)m_thrift.ReadZigZagVarInt(); else if(nested_last == 2) hdr.encoding = (int)m_thrift.ReadZigZagVarInt(); else if(outer_field == 5 && nested_last == 3 && nested_type == THRIFT_TYPE_I32) hdr.def_level_encoding = (int)m_thrift.ReadZigZagVarInt(); else m_thrift.SkipValue(nested_type); } break; } default: m_thrift.SkipValue(field_type); break; } } if(m_thrift.HasError()) return(false); //--- the compressed payload starts immediately after however many bytes //--- this header's own varints happened to need — never a fixed offset hdr.header_bytes = m_thrift.Position(); return(hdr.page_type >= 0 && hdr.uncompressed_size >= 0 && hdr.compressed_size >= 0); }
DecompressPage. The payload slice has to lie inside the file's data area, and for both supported codecs the result has to be exactly the size the page header declares - an UNCOMPRESSED page whose compressed and uncompressed sizes disagree is an error, not something to copy and hope. A codec other than UNCOMPRESSED or SNAPPY is reported and refused outright rather than silently misread as raw bytes: a GZIP- or ZSTD-compressed page handed to this function would otherwise produce garbage values with no error at all, which is a far worse failure mode than stopping cleanly.
//+------------------------------------------------------------------+ //| CParquetReader::DecompressPage | //| Slice compressed_size bytes at offset and, for SNAPPY, decompress| //| them (UNCOMPRESSED is used as-is); the result must be exactly | //| uncompressed_size bytes. Any other codec id is refused, not | //| misread — see Limitations. | //+------------------------------------------------------------------+ bool CParquetReader::DecompressPage(const int offset, const int compressed_size, const int uncompressed_size, const int codec, uchar &out[]) { ArrayResize(out, 0); //--- the page payload must lie entirely inside the data area of the file if(offset < 0 || compressed_size < 0 || (long)offset + compressed_size > m_data_end) { Print("ParquetReader: page payload extends beyond the file's data area"); return(false); } uchar raw[]; ArrayResize(raw, compressed_size); ArrayCopy(raw, m_file, 0, offset, compressed_size); //--- UNCOMPRESSED: the slice already IS the page payload, once its size checks out if(codec == PARQUET_CODEC_UNCOMPRESSED) { if(compressed_size != uncompressed_size) { Print("ParquetReader: UNCOMPRESSED page declares ", uncompressed_size, " bytes but occupies ", compressed_size); return(false); } ArrayCopy(out, raw); return(true); } //--- SNAPPY: hand off to the dedicated block decompressor, then check the size if(codec == PARQUET_CODEC_SNAPPY) { CSnappyDecoder snappy; if(!snappy.Decompress(raw, out)) { Print("ParquetReader: Snappy block is malformed"); return(false); } if(ArraySize(out) != uncompressed_size) { Print("ParquetReader: Snappy page decoded to ", ArraySize(out), " bytes, header declares ", uncompressed_size); return(false); } return(true); } //--- any other codec id is refused outright rather than silently misread as //--- raw bytes — a wrong-data failure with no error is worse than stopping here Print("ParquetReader: unsupported codec id ", codec, " (only UNCOMPRESSED/SNAPPY are implemented)"); return(false); }
DecodeDataPage - where the null-tracking stream and the value stream meet. A DataPageV1 payload lays out as: an optional definition-level stream (present only on OPTIONAL columns, prefixed by a 4-byte length), then the values themselves. Parquet does not store a placeholder for a null value - a null row simply contributes nothing to the values stream at all - so the definition-level pass has to run first and produce a non-null count before the value stream can even be located.
The 4-byte length is checked against the page before the stream is decoded, and decoding is confined to exactly those bytes. Every decoded level is also range-checked against 0..max_def_level before anything downstream trusts it - a corrupted or malicious stream can still land on an in-range bit pattern that is simply the wrong one for this column (a 3 on a column whose max_def_level is 1, say), and folding anything that isn't exactly max_def_level into "null" would silently mask precisely that kind of corruption, so an out-of-range level refuses the whole page instead of guessing at it.
Dictionary-Encoded Data Page Layout
Fig. 2. A RLE_DICTIONARY/PLAIN_DICTIONARY data page: definition levels, then a one-byte index width, then the packed dictionary indices.
PLAIN-Encoded Data Page Layout
Fig. 3. A PLAIN-encoded data page on a required column: literal values back to back, no level stream, no index bit-width byte.
Dictionary Page Layout
Fig. 4. The dictionary page itself: every distinct value for the column, PLAIN-encoded once, read before any data page that references it.
After decoding the definition levels (or defaulting them to "every row present" on a REQUIRED column with no null stream), the function validates the value encoding - only PLAIN, PLAIN_DICTIONARY and RLE_DICTIONARY are decoded, anything else is refused. It then branches between dictionary-encoded and PLAIN decoding. For the dictionary encodings, a single bit-width byte precedes the packed index stream, every index is range-checked against the dictionary, and a dictionary-encoded page in a chunk with no dictionary page is an error.
For PLAIN encoding, the value stream must be long enough to hold one fixed-width value per non-null row before any value is read. A null row is flagged in a separate null array and also written as MQL5's EMPTY_VALUE, the convention an indicator buffer uses for "no data". Be clear about what that sentinel is: a marker, not a null type. EMPTY_VALUE is DBL_MAX, nothing stops a real value from being equal to it, and a matrix has no nullable mask of its own, so the null array - not the sentinel - is the authoritative record of which rows are null.
//+------------------------------------------------------------------+ //| CParquetReader::DecodeDataPage | //| Decode one DataPageV1 payload into out_values/out_null from | //| row_cursor. Optional RLE definition-level stream first, then | //| PLAIN or dictionary-encoded values; nulls carry no value entry, | //| so the values cursor and row index advance independently via | //| non_null_count. Every level is range-checked against | //| 0..max_def_level before being trusted; out-of-range refuses the | //| page rather than becoming a silent null. | //+------------------------------------------------------------------+ bool CParquetReader::DecodeDataPage(const uchar &page[], const int column_type, const int max_def_level, const SPageHeader &hdr, const double &dict_values[], const bool has_dictionary, double &out_values[], bool &out_null[], int &row_cursor) { int page_size = ArraySize(page); int page_num_values = hdr.num_values; int cursor = 0; //--- the page must not claim more rows than the column chunk has room for if(page_num_values < 0 || (long)row_cursor + page_num_values > ArraySize(out_values)) { Print("ParquetReader: data page declares more rows than its column chunk holds"); return(false); } //--- only the value encodings implemented below are accepted; DELTA_*, BYTE_STREAM_SPLIT //--- and the rest are refused rather than decoded as if they were PLAIN bool dict_encoded = (hdr.encoding == PARQUET_ENC_PLAIN_DICTIONARY || hdr.encoding == PARQUET_ENC_RLE_DICTIONARY); if(!dict_encoded && hdr.encoding != PARQUET_ENC_PLAIN) { Print("ParquetReader: unsupported value encoding id ", hdr.encoding, " (only PLAIN and dictionary encodings are implemented)"); return(false); } if(dict_encoded && !has_dictionary) { Print("ParquetReader: dictionary-encoded data page but the chunk has no dictionary page"); return(false); } //--- Step 1: definition levels (null tracking) — absent entirely on REQUIRED //--- columns, which is why def_levels defaults to "every row present" first int def_levels[]; ArrayResize(def_levels, page_num_values); for(int i = 0; i < page_num_values; i++) def_levels[i] = max_def_level; //--- OPTIONAL column: an explicit RLE stream overrides the all-present default if(max_def_level > 0) { if(hdr.def_level_encoding != PARQUET_ENC_RLE) { Print("ParquetReader: unsupported definition-level encoding id ", hdr.def_level_encoding, " (only RLE is implemented)"); return(false); } //--- the 4-byte length prefix must exist and describe bytes that are really there if(page_size < 4) { Print("ParquetReader: data page too short for its definition-level length"); return(false); } long level_byte_len = (long)page[0] | ((long)page[1] << 8) | ((long)page[2] << 16) | ((long)page[3] << 24); cursor = 4; if(level_byte_len > page_size - cursor) { Print("ParquetReader: definition-level stream of ", level_byte_len, " bytes overruns the page"); return(false); } int bit_width = BitWidthFor(max_def_level); CRLEBitPackedDecoder rle; if(!rle.Decode(page, cursor, cursor + (int)level_byte_len, bit_width, page_num_values, def_levels)) { Print("ParquetReader: definition-level stream is truncated or malformed"); return(false); } cursor += (int)level_byte_len; //--- the only legal definition levels for this column are 0..max_def_level; //--- a corrupted or malicious RLE/bit-packing stream can hand back anything //--- that fits in the bit width, and an out-of-range value must never be //--- silently folded into "null" — refuse the page instead of masking it for(int i = 0; i < page_num_values; i++) { if(def_levels[i] < 0 || def_levels[i] > max_def_level) { Print("ParquetReader: definition level ", def_levels[i], " at row ", i, " is out of range 0..", max_def_level, " — refusing page"); return(false); } } } //--- a null row contributes nothing to the values stream at all, so the value //--- decode below needs to know in advance how many non-null rows to expect int non_null_count = 0; for(int i = 0; i < page_num_values; i++) if(def_levels[i] == max_def_level) non_null_count++; //--- Step 2: the values stream itself, dictionary-indexed or literal PLAIN //--- dictionary-encoded: resolve each non-null row's index against dict_values[] if(dict_encoded) { int indices[]; //--- a page with no non-null rows may carry no index stream at all if(non_null_count > 0) { if(cursor >= page_size) { Print("ParquetReader: dictionary page index stream is missing"); return(false); } int bit_width = page[cursor]; // one-byte index bit-width prefix cursor++; CRLEBitPackedDecoder rle; if(!rle.Decode(page, cursor, page_size, bit_width, non_null_count, indices)) { Print("ParquetReader: dictionary index stream is truncated or malformed"); return(false); } } int idx_cursor = 0; int dict_size = ArraySize(dict_values); for(int i = 0; i < page_num_values; i++) { if(def_levels[i] == max_def_level) { //--- an index outside the dictionary means a corrupt or mismatched file int d = indices[idx_cursor++]; if(d < 0 || d >= dict_size) { Print("ParquetReader: dictionary index ", d, " is outside a dictionary of ", dict_size, " entries"); return(false); } out_values[row_cursor] = dict_values[d]; out_null[row_cursor] = false; } else { out_values[row_cursor] = EMPTY_VALUE; // null row out_null[row_cursor] = true; } row_cursor++; } } //--- PLAIN: no dictionary — literal values, read one per non-null row else { //--- the values stream must hold one fixed-width value per non-null row int width = PlainWidth(column_type); if(width == 0 || (long)non_null_count * width > page_size - cursor) { Print("ParquetReader: PLAIN value stream is shorter than its ", non_null_count, " non-null rows require"); return(false); } for(int i = 0; i < page_num_values; i++) { //--- a null row consumes nothing from the values stream; skip without advancing cursor if(def_levels[i] != max_def_level) { out_values[row_cursor] = EMPTY_VALUE; out_null[row_cursor] = true; row_cursor++; continue; } out_values[row_cursor] = ReadPlainValue(page, cursor, column_type, cursor); out_null[row_cursor] = false; row_cursor++; } } return(true); }
ReadColumn - refuse an unsupported type loudly, then walk the chunk's pages in file order. Before decoding anything, the column's physical type is checked against the four types this reader supports; see Limitations for why that check exists. With that guard cleared, a column chunk is an optional dictionary page (read once, cached for every data page that follows) and then one or more data pages, read until either the chunk's declared byte span or its declared row count is exhausted - whichever bounds the loop stops a truncated or malformed chunk from reading into the next column's bytes.
The loop doesn't take a clean exit for granted: a page whose payload runs past its chunk is an error, DataPageV2 and unknown page types are refused before decompression, and the function returns true only if exactly the declared number of rows was decoded. A chunk that runs out of pages early is reported as truncated, not returned as a short column. The out_null array carries the exact null flag for every row.
//+------------------------------------------------------------------+ //| CParquetReader::ReadColumn | //| Decode one column chunk end to end: optional dictionary page, | //| then data pages in order, bounded by total_compressed_size. | //| Succeeds only if exactly num_values rows were decoded; | //| DataPageV2/unknown types are refused and INT64 overflow is | //| flagged via Int64PrecisionLoss(). | //+------------------------------------------------------------------+ bool CParquetReader::ReadColumn(const int idx, double &out_values[], bool &out_null[]) { ArrayResize(out_values, 0); ArrayResize(out_null, 0); if(idx < 0 || idx >= ArraySize(m_chunks)) return(false); //--- plain locals instead of a struct copy: the chunk holds a string (its path) int chunk_type = m_chunks[idx].type; int chunk_codec = m_chunks[idx].codec; long chunk_rows = m_chunks[idx].num_values; long chunk_bytes = m_chunks[idx].total_compressed_size; int max_def_level = m_columns[idx].max_def_level; //--- refuse a physical type this reader cannot decode values for, rather than //--- letting ReadPlainValue silently return 0.0 for every row of that column -- //--- a column of real zeros and an unsupported-type column must never look the same if(chunk_type != PARQUET_TYPE_INT32 && chunk_type != PARQUET_TYPE_INT64 && chunk_type != PARQUET_TYPE_FLOAT && chunk_type != PARQUET_TYPE_DOUBLE) { Print("ParquetReader: column '", m_columns[idx].name, "' has unsupported physical type id ", chunk_type, " (only INT32/INT64/FLOAT/DOUBLE are decoded)"); return(false); } //--- logical annotations are not applied: DECIMAL and unsigned columns come back //--- as their raw signed physical numbers, which the caller has to know about int ctype = m_columns[idx].converted_type; if(ctype == PARQUET_CONVERTED_DECIMAL || ctype == PARQUET_CONVERTED_UINT_32 || ctype == PARQUET_CONVERTED_UINT_64) Print("ParquetReader: WARNING column '", m_columns[idx].name, "' has converted type ", ctype, "; values are returned as raw physical numbers, not rescaled or made unsigned"); int n_rows = (int)chunk_rows; // range-checked in ValidateChunks() ArrayResize(out_values, n_rows); ArrayResize(out_null, n_rows); int file_cursor = (int)(m_chunks[idx].has_dictionary_page ? m_chunks[idx].dictionary_page_offset : m_chunks[idx].data_page_offset); int chunk_end = file_cursor + (int)chunk_bytes; double dict_values[]; bool have_dict = false; int rows_written = 0; //--- remember the running count so this column's own INT64 precision loss can be told apart int hits_before = m_int64_hits; //--- walk pages in file order: an optional dictionary page first, then one or //--- more data pages, bounded by the chunk's declared size AND its row count //--- so a malformed chunk cannot read into the next column's bytes while(file_cursor < chunk_end && rows_written < n_rows) { SPageHeader hdr; if(!ParsePageHeader(file_cursor, chunk_end, hdr)) { Print("ParquetReader: column '", m_columns[idx].name, "' has a malformed page header at byte ", file_cursor); return(false); } //--- the payload must end inside this column chunk long payload_offset = (long)file_cursor + hdr.header_bytes; if(payload_offset + hdr.compressed_size > chunk_end) { Print("ParquetReader: column '", m_columns[idx].name, "' has a page that overruns its chunk"); return(false); } //--- page types are screened before decompression: a DataPageV2 payload is only //--- partly compressed, so decompressing it whole would fail with a misleading error if(hdr.page_type == PARQUET_PAGE_DATA_V2) { Print("ParquetReader: DataPageV2 pages are not supported (only DataPageV1)"); return(false); } if(hdr.page_type != PARQUET_PAGE_DATA && hdr.page_type != PARQUET_PAGE_DICTIONARY && hdr.page_type != PARQUET_PAGE_INDEX) { Print("ParquetReader: unknown page type ", hdr.page_type); return(false); } uchar page[]; if(!DecompressPage((int)payload_offset, hdr.compressed_size, hdr.uncompressed_size, chunk_codec, page)) return(false); //--- dictionary page: cache the distinct values for every data page that follows if(hdr.page_type == PARQUET_PAGE_DICTIONARY) { if(hdr.encoding != PARQUET_ENC_PLAIN && hdr.encoding != PARQUET_ENC_PLAIN_DICTIONARY) { Print("ParquetReader: unsupported dictionary page encoding id ", hdr.encoding); return(false); } if(!DecodeDictionaryPage(page, chunk_type, hdr.num_values, dict_values)) return(false); have_dict = true; } //--- data page: decode rows, accumulating into the same out_values array else if(hdr.page_type == PARQUET_PAGE_DATA) { if(!DecodeDataPage(page, chunk_type, max_def_level, hdr, dict_values, have_dict, out_values, out_null, rows_written)) return(false); } //--- an index page (the only type left after the screen above) carries no rows //--- and is simply stepped over file_cursor = (int)payload_offset + hdr.compressed_size; } //--- running out of pages before the declared row count is a truncated chunk, //--- not a short but valid column if(rows_written != n_rows) { Print("ParquetReader: column '", m_columns[idx].name, "' decoded ", rows_written, " of ", n_rows, " rows"); return(false); } if(m_int64_hits > hits_before) Print("ParquetReader: WARNING column '", m_columns[idx].name, "' has INT64 values beyond 2^53; ", "the double result is rounded for those rows"); return(true); }
ReadToMatrix - the "no CSV" finish line. Every column in the schema is decoded in turn and written column by column into one native matrix. ValidateChunks() has already proved that every column in the row group shares one row count, so the first column's chunk sizes the whole matrix up front. The matrix holds doubles - that's the price of one numeric container - so each column's physical type, nullability and converted type are not part of the result; they stay available from the reader through ColumnType(), ColumnNullable() and ColumnConvertedType(). The three-argument overload also fills a second matrix with 1.0 for null cells and 0.0 for present ones.
//+------------------------------------------------------------------+ //| CParquetReader::ReadToMatrix | //| Decode every column and assemble them into one matrix, row count | //| taken from the first column (already proven equal by | //| ValidateChunks()). out_null_mask carries the authoritative | //| 1.0/0.0 null record; the data matrix holds EMPTY_VALUE in null | //| cells. This is the no-CSV path the article is built around. | //+------------------------------------------------------------------+ bool CParquetReader::ReadToMatrix(matrix &out, string &column_names[], matrix &out_null_mask) { int cols = ArraySize(m_columns); if(cols == 0 || ArraySize(m_chunks) != cols) return(false); //--- every column in one row group shares the same row count (checked at Open), //--- so the first column's chunk metadata is enough to size the whole matrix long rows = m_chunks[0].num_values; if(!out.Resize((ulong)rows, (ulong)cols) || !out_null_mask.Resize((ulong)rows, (ulong)cols)) return(false); ArrayResize(column_names, cols); //--- decode one column at a time and write it straight into its matrix column for(int c = 0; c < cols; c++) { double col_values[]; bool col_null[]; if(!ReadColumn(c, col_values, col_null)) return(false); column_names[c] = m_columns[c].name; for(int r = 0; r < rows; r++) { out[r, c] = col_values[r]; out_null_mask[r, c] = (col_null[r] ? 1.0 : 0.0); } } return(true); }
ParquetToMatrix_Script.mq5 is the thin script wrapper around all of this: point it at a file under MQL5\Files\, and it opens, decodes, and prints a row/column summary plus a short row preview to the Journal. The full listing (schema printout, 5-row preview loop, null-mask formatting) is in the archive; here are the three calls that matter:
//+------------------------------------------------------------------+ //| OnStart | //| Open, decode into a matrix, and print the result. | //+------------------------------------------------------------------+ void OnStart(void) { CParquetReader reader; if(!reader.Open(InpFileName)) { Print("ParquetToMatrix: failed to open/parse '", InpFileName, "'"); return; } matrix data; matrix null_mask; string column_names[]; //--- one call walks every column's pages and assembles the whole result -- //--- see ParquetReader.mqh for what happens underneath it if(!reader.ReadToMatrix(data, column_names, null_mask)) { Print("ParquetToMatrix: failed to decode column data"); return; } PrintFormat("ParquetToMatrix: %s -> %d rows x %d columns", InpFileName, (int)data.Rows(), (int)data.Cols()); }
Testing: A Deterministic Self-Test Against Real pyarrow Output
This is a script/tool piece, not a trading system, so there's no Strategy Tester run here — the equivalent of a backtest for a parser is checking it decodes a real file correctly, value by value, against known contents. Python/make_test_parquet.py uses pyarrow to write a 30-row file: bar_id as PLAIN-encoded INT32, close as dictionary-encoded DOUBLE cycling through 5 prices, rows 7 and 19 forced to null.
The expected values are written from one formula on both sides (Python and MQL5), so a formula mistake would sit on both; the generator closes that gap itself by reading the file back with pyarrow and asserting it matches the formula. This was run with Python 3.14.7 and pyarrow 24.0.0: generate the file first, then compile and run Parquet_SelfTest.mq5 against a MetaTrader 5 terminal at build 6314 — the script expects the file already sitting in MQL5\Files\ParquetReader\.
The script compares every decoded value against that ground truth, not just row/column counts: bar_id as an exact integer, close within a small epsilon (it round-trips through IEEE754 double storage), and a null row must be flagged in the mask and carry exactly EMPTY_VALUE, not 0.0:
//--- a null row must be flagged in the mask AND carry EMPTY_VALUE; every //--- other row compares with a small epsilon since it round-tripped through IEEE754 bool close_ok; if(expected_close[i] == EMPTY_VALUE) close_ok = (close_null[i] && close_col[i] == EMPTY_VALUE); else close_ok = (!close_null[i] && MathAbs(close_col[i] - expected_close[i]) < 0.0000001);
The full schema check, value loop and first-mismatch reporting are in Parquet_SelfTest.mq5 in the archive.
Running Parquet_SelfTest.mq5 against a file generated by make_test_parquet.py on a live MetaTrader 5 terminal produced, in the terminal's Experts tab:
Parquet_SelfTest: 30/30 rows PASS, 0 FAIL
Parquet_SelfTest: RESULT = PASS
All 30 rows matched — both decode paths (PLAIN and dictionary), both null rows. It's evidence about this one pyarrow-written file and no more: a 30-row file with a 5-value cycle may never exercise long literal runs or multi-byte varints, and it leaves INT64, FLOAT, UNCOMPRESSED, multi-page, multi-row-group, nullable-PLAIN and damaged-file paths completely untested. Parquet_ExtendedTest.mq5 closes exactly those gaps, against eight fixtures from Python/make_extended_fixtures.py:
| Path tested | Fixture | Result |
|---|---|---|
| UNCOMPRESSED codec | fixture_uncompressed.parquet | PASS — 20/20 rows |
| INT64 at the 2^53 boundary | fixture_int64_bounds.parquet | PASS — 8/8 rows, Int64PrecisionLoss() correctly flagged |
| FLOAT column | fixture_float.parquet | PASS — 8/8 values |
| Nullable PLAIN (not dictionary) | fixture_nullable_plain.parquet | PASS — 20/20 rows |
| Multiple data pages | fixture_multipage.parquet | PASS — 20000/20000 rows |
| Multiple row groups | fixture_multirowgroup.parquet | PASS — 3 groups / 60 rows, first group's 20 read |
| Truncated + footer-flip corruption | fixture_corrupt_truncated.parquet, fixture_corrupt_flipped.parquet | PASS — both refused by Open(), neither crashed nor half-read |
Running Parquet_ExtendedTest.mq5 against these eight fixtures on a live MetaTrader 5 terminal (build 6314) produced, in the terminal's Experts tab:
Parquet_ExtendedTest: 7/7 sub-tests PASS
Parquet_ExtendedTest: RESULT = PASS
Both tests were written by one library, pyarrow, with one corruption shape per failure mode; DataPageV2, ZSTD, nested schemas and BOOLEAN/BYTE_ARRAY files stay untested for the reasons given in Limitations.
Limitations and Practical Considerations
| Constraint | Reader behavior | User impact |
|---|---|---|
| First row group only | ParseFileMetaData decodes only the first row group's chunks; Open() warns with the row-group count and rows left out. | A multi-row-group file (several write_table() calls, or a very large export) reads back partial unless ReadColumn is extended to concatenate across groups. |
| UNCOMPRESSED / SNAPPY only | Any other codec id (GZIP/ZSTD/LZ4/Brotli) is refused with a printed error, not misread. | SNAPPY is pyarrow's default, not the format's — a file written with another codec won't open. |
| DataPageV1 only | DecodeDataPage assumes V1's layout: PLAIN, PLAIN_DICTIONARY or RLE_DICTIONARY values with RLE definition levels. | A writer defaulting to DataPageV2, or another value encoding (DELTA_BINARY_PACKED, BYTE_STREAM_SPLIT), is refused rather than misread. |
| Flat schemas only | ParseSchemaList requires every leaf to be typed, childless, OPTIONAL or REQUIRED. | A nested group or REPEATED field (a list, a struct) fails Open() by name — no hierarchy is approximated. |
| Logical types aren't applied | converted_type is exposed via ColumnConvertedType(), but values stay raw physical numbers. | DECIMAL returns unscaled integers, UINT_32/64 can show negative, timestamps are raw ticks — scale/sign/unit is on the caller. |
| Whole-file loading | ReadWholeFile loads the entire file into memory and refuses anything above 2 GB. | Fine for the thousands-to-low-millions-of-rows a trading extract realistically produces; a multi-GB file needs a seek-based redesign. |
| BOOLEAN / BYTE_ARRAY unsupported | Schema metadata is captured correctly, but ReadColumn refuses to decode these physical types. | Avoids a silent 0.0-for-every-row failure; real support needs its own value-decode branch. |
| INT64 beyond 2^53 | Values convert through a double matrix; out-of-range values raise Int64PrecisionLoss() and a Journal warning. | Ordinary bar indices, timestamps and tick volumes stay well inside the limit; raw nanosecond epochs or large counters need a genuine long-typed path. |
| No CRC / statistics cross-check | Offsets, sizes, counts and indices are all validated; the extended self-test confirms two damaged files are refused. | Protection against damaged files isn't the same as verified decoding — a malformed file can still request memory up to the stated caps (256 MB per Snappy page, 2 GB for the file). |
Conclusion
Reading a Snappy-compressed, dictionary-encoded Parquet file in native MQL5 comes down to three wire formats stacked on top of each other: Thrift Compact Protocol for the footer and page headers, Snappy for decompression, and hybrid RLE/bit-packing for null tracking and dictionary indices — assembled by one orchestrator into a matrix, no CSV step in between.
The two self-tests — 30/30 rows on the original file, 7/7 sub-tests across eight extended fixtures — show the mechanism works on pyarrow's own output across the paths tested; that isn't proof of correctness for Parquet files in general, since motivation isn't verification. Before using this with files from another writer, compare a decoded sample to that writer's own output, and add a fixture for any path you depend on that isn't already covered.
Programs used in the article
| # | Name | Type | Description |
|---|---|---|---|
| 1 | ThriftCompactReader.mqh | Include | Native Thrift Compact Protocol cursor: varint/zigzag integers, delta-encoded field headers, list/struct/map framing and skipping. |
| 2 | SnappyDecoder.mqh | Include | Native Snappy block decompressor: literal runs and the three back-reference copy forms. |
| 3 | RLEBitPackedDecoder.mqh | Include | Hybrid RLE/bit-packing decoder used for both definition levels (null tracking) and dictionary indices. |
| 4 | ParquetReader.mqh | Include | Orchestrator: footer parsing and validation, schema/row-group/column-chunk walking, page decompression and decode, assembly into a native matrix with an optional null mask. |
| 5 | ParquetToMatrix_Script.mq5 | Script | Opens a .parquet file and prints a row/column summary, each column's type and nullability, and a row preview to the Journal. |
| 6 | Parquet_SelfTest.mq5 | Script | Checks the schema and every value of a known pyarrow-written test file against expected values rebuilt from the generator's formula. |
| 7 | Python/make_test_parquet.py | Python | pyarrow generator for the deterministic 30-row test file used by Parquet_SelfTest.mq5; reads the file back to assert it matches the formula. |
| 8 | Parquet_ExtendedTest.mq5 | Script | Runs eight fixtures covering UNCOMPRESSED, INT64 bounds, FLOAT, nullable PLAIN, multi-page, multi-row-group and two corrupted-file cases against the reader. |
| 9 | Python/make_extended_fixtures.py | Python | pyarrow generator for the eight fixture files used by Parquet_ExtendedTest.mq5, including the two deliberately corrupted files. |
| 10 | MQL5.zip | Archive | Archive with all files listed above. Unpack it into the terminal data folder and every file lands in its required place. |
MQL5.zip bundles everything in the table above under its own MQL5\Include\ParquetReader, MQL5\Scripts\ParquetReader, and MQL5\Files\ParquetReader\Python subfolders, so unpacking it into the terminal's data folder puts every file where the reader and the test scripts already expect to find it.
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.



