Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary
Contents
- Introduction
- Why HTTP and RowBinary
- Database schema and column mapping
- Encoding the wire format by hand
- Nullable columns and the NULL byte
- Authenticating and routing requests over HTTP
- Recording live ticks and deals
- Edge cases and pitfalls
- Testing
- Conclusion
Introduction
MetaTrader 5 is excellent at generating ticks and deals; it is not a place to keep years of them. The moment you want to run your own analysis across weeks of tick data — spread behavior by hour, slippage by broker, fill quality around news releases — you need that data somewhere a real analytical engine can chew through it. ClickHouse is built for exactly this: columnar storage, brutal compression, and analytical queries that stay fast over far more rows than a single MetaTrader history file is built to scan.
The obvious way to get MetaTrader 5 data into ClickHouse is a message queue and a separate ingestion service sitting between the terminal and the database. That's a reasonable architecture for a team running dozens of accounts, and also more infrastructure than most retail setups need for one or two. ClickHouse happens to expose a plain HTTP interface on port 8123, and MQL5's WebRequest() can talk to it directly — no broker process, no intermediate service, just the terminal pushing rows straight into the database over HTTP. This article builds the path end to end: a byte-level RowBinary encoder in pure MQL5, an HTTP client that wraps WebRequest(), and an Expert Advisor that streams ticks and records each deal as it is added to the terminal history.
Three files do the real work. The article focuses on their code rather than an external description, because the key engineering decisions are in the internal logic: buffer growth, the NULL flag byte, and why GET and POST are not interchangeable here. ClickHouseRowBinary.mqh turns typed MQL5 values into the exact byte layout ClickHouse expects. ClickHouseHttpClient.mqh gets those bytes to the server and back. TickRecorder_EA.mq5 wires both into MetaTrader's event loop. Two scripts, ClickHouse_SelfTest.mq5 and ClickHouse_HistoryBackfill.mq5, exist purely to prove the first three are correct and fast before any of it touches a live account.
Scope: this is a tick/deal recorder, not a trading strategy — the EA places no orders of its own. What's covered here is the wire format, the HTTP plumbing, and the testing needed to trust both before you point them at a production account. Every number quoted below came from one machine, one local Docker container, and one broker's XAUUSD feed; treat the throughput figures as a demonstration of the approach, not a guarantee for your own network.
Why HTTP and RowBinary
Getting MetaTrader 5 data into ClickHouse isn't a choice between exactly two architectures. A message queue with a separate ingestion service is one path; so are a local gateway process, a named pipe or socket into a small local agent, a REST proxy, or a DLL that calls out to a client library directly. Each trades off differently against complexity, latency, and how much infrastructure you're willing to run alongside the terminal. This article picks the path with the least moving parts: ClickHouse's own HTTP interface, exposed on port 8123 among its several supported protocols and interfaces, reached directly from MQL5's built-in WebRequest() against an allow-listed URL — no broker process, no intermediate service, no DLL. MQL5 does have socket functions of its own, so a hand-rolled client over ClickHouse's native TCP protocol isn't off the table either; it's simply more wiring than this article needs when WebRequest() already speaks HTTP out of the box. The HTTP interface is a capable fit on its own terms regardless: stateless request/response, no connection to keep alive between ticks, and a request body in whatever format the query string asks for.
That's where RowBinary comes in. Asking ClickHouse for FORMAT RowBinary on an insert gets you a dense row-oriented encoding: no column names repeated per row the way JSONEachRow would cost, no text parsing overhead the way plain CSV or TSV would cost on the server side, just the column values back to back in the exact order the table defines them — fixed-width little-endian integers, IEEE-754 doubles bit for bit, and a length-prefixed scheme for strings. This article doesn't benchmark RowBinary against ClickHouse's Native format or against compressed variants, so no claim is made about it being the most compact option overall — what matters here is narrower: it's the format most forgiving to encode by hand, because every field follows one mechanical rule with no schema negotiation, no framing handshake, and no compression step required before the bytes are valid.
The trade-off is that RowBinary has zero tolerance for a mistake. There's no field delimiter to resynchronize on and no column name to tell the server which value just arrived wrong — a single miscounted byte anywhere in a row desyncs every column after it for the rest of that row, and usually for every row after it in the same batch. That's precisely why this article leans so heavily on reading the actual encoder code rather than describing the format in the abstract: the correctness of the whole pipeline comes down to a handful of loops in CRowBinaryWriter getting the byte count exactly right, every time.

Fig. 1. The recorder's path from a tick to a stored row.
Four pieces, four responsibilities. MetaTrader fires OnTick() and OnTradeTransaction(); CRowBinaryWriter turns each event into raw RowBinary bytes; CClickHouseHttpClient wraps those bytes in an HTTP POST; and ClickHouse parses and stores the row. Nothing here is asynchronous — a flush blocks the calling event handler until the HTTP response comes back, which is a deliberate trade-off discussed later in the edge cases section, not an oversight.
Database schema and column mapping
Before any code makes sense, the tables it writes to need to exist. setup.sql creates one database and two tables — ticks and deals — both using the MergeTree engine ordered by symbol and timestamp, which is what lets ClickHouse answer a time-range query over one symbol without scanning the whole table:
-- setup.sql -- Run once against ClickHouse to create the database and the two tables -- TickRecorder_EA.mq5 and the backfill/self-test scripts write to. -- Example: docker exec -it clickhouse clickhouse-client --user default --password clickhouse123 --multiquery < setup.sql -- -- Both tables are intentionally a reduced schema for this article: symbol, -- timestamp, price fields, and the one Nullable column the encoder article -- is built around. Tick volume, real volume, and a broker/account label are -- not captured here -- they're a straightforward extension of the same -- RowBinary row (one more Write*() call per column, in the same order on -- both the encoder and the CREATE TABLE side), not a schema this recorder -- already produces. -- -- PARTITION BY splits each table into monthly parts so a retention policy -- (DROP PARTITION, TTL) can discard old tick data without rewriting -- everything still worth keeping -- useful once this holds months or years -- of ticks rather than one week's backfill. CREATE DATABASE IF NOT EXISTS mt5; CREATE TABLE IF NOT EXISTS mt5.ticks ( symbol String, ts DateTime64(3), bid Float64, ask Float64, last Nullable(Float64), flags UInt32 ) ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (symbol, ts); CREATE TABLE IF NOT EXISTS mt5.deals ( deal_ticket UInt64, symbol String, ts DateTime64(3), price Float64, volume Float64, profit Float64 ) ENGINE = MergeTree PARTITION BY toYYYYMM(ts) ORDER BY (symbol, ts);
Every column here has a direct counterpart in the encoder calls you'll see in the next few sections, and the order matters as much as the names: RowBinary has no column labels on the wire, so the writer's calls and the table's CREATE TABLE column list have to agree on sequence or the insert will silently land values in the wrong columns rather than fail outright. ticks.last is Nullable(Float64) specifically because not every tick carries a last-trade price — many symbols only ever quote bid/ask — and that single nullable column is what section 6 below is really about.
Both tables are a deliberately reduced schema, not a complete record of everything MetaTrader 5 exposes. Tick volume, real volume, the tick's original source flag, and a broker or account label aren't captured here, even though the recording section below touches on spread analysis, fill quality, and broker comparison as motivating use cases. Adding any of those fields is a straightforward extension: add one more Write*() call and one more column, keeping the order consistent on both the encoder and the CREATE TABLE side. Because both tables use PARTITION BY toYYYYMM(ts), you can still drop old partitions for retention later.
Encoding the wire format by hand
Every encoder in CRowBinaryWriter reduces to the same handful of primitives: append a fixed number of little-endian bytes, or append a length-prefixed string. The class itself gets a single header describing the whole approach; individual methods get a short //--- note rather than their own boxed header, since repeating the same boilerplate across fourteen near-identical methods would say less than the class header already does:
//+------------------------------------------------------------------+ //| CRowBinaryWriter | //| A minimal byte-buffer writer for ClickHouse's RowBinary insert | //| format. Every public method appends one more field to the | //| current row in the exact little-endian, positional layout | //| RowBinary expects; nothing here talks to the network — | //| GetBytes() hands the finished buffer to the HTTP client once a | //| full row (or a batch of rows) has been written. Methods are | //| documented with a short //--- note each; see the class header | //| above for the format this writer implements. | //+------------------------------------------------------------------+ class CRowBinaryWriter { private: uchar m_buf[]; // growable byte buffer for the current batch int m_len; // number of valid bytes currently in m_buf public: CRowBinaryWriter(void); void Clear(void); void EnsureCapacity(const int extra); void GetBytes(uchar &dst[]) const; void WriteUInt8(const uchar value); void WriteUInt32(const uint value); void WriteUInt64(const ulong value); void WriteInt64(const long value); void WriteFloat64(const double value); void WriteDateTime64Ms(const long epoch_ms); void WriteVarUInt(const ulong value); void WriteString(const string &text); void WriteNullableFloat64(const bool is_null,const double value); void WriteNullableString(const bool is_null,const string &text); };
The internal state is deliberately minimal: a growable uchar array and a write cursor. The constructor reserves 4 KB up front as a starting point rather than a guarantee — a single tick row (symbol, timestamp, bid, ask, a Nullable price, and flags) runs on the order of a few dozen bytes, so at the default InpBatchSize of 500 the buffer will typically grow past 4 KB via EnsureCapacity()'s doubling before a flush. That's expected, not a sign anything is misconfigured; the reservation only avoids a resize on the very first few writes of a batch:
//--- Constructor — starts with an empty buffer; EnsureCapacity() grows it on demand as fields // are written. CRowBinaryWriter::CRowBinaryWriter(void) { m_len=0; ArrayResize(m_buf,4096); }
EnsureCapacity() is the only place that ever calls ArrayResize() on the buffer, and every other method routes through it before writing a single byte. It doubles rather than growing by a fixed increment, which keeps the number of resizes logarithmic in the final size instead of linear — for a batch that ends up ten times larger than the initial reservation, that's roughly four resizes instead of thousands:
//--- Grows m_buf (doubling) whenever the next write would overrun it. Called internally before // every append. void CRowBinaryWriter::EnsureCapacity(const int extra) { int need=m_len+extra; int have=ArraySize(m_buf); if(need<=have) return; int new_size=MathMax(have*2,need); ArrayResize(m_buf,new_size); }
And GetBytes() is the handoff point to the HTTP client: it copies out exactly m_len bytes, trimming away whatever spare capacity EnsureCapacity() over-allocated, so the caller never sends uninitialized tail bytes to the server:
//--- Copies the valid prefix of the internal buffer out to the caller, trimming away any spare // capacity reserved by EnsureCapacity(). void CRowBinaryWriter::GetBytes(uchar &dst[]) const { ArrayResize(dst,m_len); if(m_len>0) ArrayCopy(dst,m_buf,0,0,m_len); }
Everything above this line is plumbing. The methods that actually encode a value build on one primitive, WriteUInt8(), which appends a single raw byte and is the building block every wider Write*() method is ultimately expressed in terms of:
//--- Appends a single raw byte — the building block every other Write*() method is ultimately // expressed in terms of. void CRowBinaryWriter::WriteUInt8(const uchar value) { EnsureCapacity(1); m_buf[m_len]=value; m_len++; }
Widening to four bytes is the same idea repeated: shift, mask, write, one byte at a time, low-order byte first — that's what "little-endian" means in practice, and writing it as an explicit loop rather than a cast makes the byte order impossible to get backwards by accident:
//--- Appends a 4-byte little-endian unsigned integer, matching ClickHouse's UInt32 column // layout. void CRowBinaryWriter::WriteUInt32(const uint value) { EnsureCapacity(4); for(int i=0;i<4;i++) m_buf[m_len+i]=(uchar)((value>>(8*i))&0xFF); m_len+=4; }
UInt64 widens the same little-endian loop to eight bytes, and Int64 reuses it instead of duplicating the logic — MQL5's long and ulong share the same bit width, so a plain cast preserves the pattern needed for an Int64 column such as a deal ticket or a DateTime64(3) timestamp:
//--- Appends an 8-byte little-endian unsigned integer (UInt64). void CRowBinaryWriter::WriteUInt64(const ulong value) { EnsureCapacity(8); for(int i=0;i<8;i++) m_buf[m_len+i]=(uchar)((value>>(8*i))&0xFF); m_len+=8; }
//--- Appends a signed 8-byte little-endian integer (Int64) by reinterpreting the bit pattern of // a ulong — MQL5's ulong and long share the same width, so a plain cast preserves the bits. void CRowBinaryWriter::WriteInt64(const long value) { WriteUInt64((ulong)value); }
Two of the remaining methods are worth reading closely because they encode something more than a fixed-width integer. The length prefix ahead of every string field is a VarUInt — ClickHouse's LEB128-style variable-length integer, seven bits of value per byte with the top bit marking whether another byte follows. Rather than flatten this into a single comment, the nesting below mirrors the logic exactly: a flush-left comment introduces the loop as a whole, and each conditional branch inside it gets its own comment indented to the code it describes:
//--- Appends a length as ClickHouse's VarUInt (LEB128-style): 7 bits per byte, low-order first, // continuation flag in the top bit. Used ahead of every String field's raw bytes. void CRowBinaryWriter::WriteVarUInt(const ulong value) { //--- walk the value 7 bits at a time, low-order first, until nothing remains ulong v=value; while(true) { uchar b=(uchar)(v&0x7F); v>>=7; //--- more bits remain after this one — set the continuation flag and loop again if(v!=0) WriteUInt8((uchar)(b|0x80)); else { //--- nothing left after this byte — no continuation flag, and the loop ends here WriteUInt8(b); break; } } }
And doubles need a bit-cast MQL5 doesn't provide natively. StructToCharArray() does a raw memory copy of a value's bytes into a uchar array, which is exactly what's needed here — not a numeric conversion that could round or rescale the value, the actual IEEE-754 bit pattern a C client or ClickHouse itself would produce for the same double:
//--- Appends an IEEE-754 double (Float64). MQL5 has no built-in bit-cast from double to its raw // 8 bytes, so a struct overlay via StructToCharArray() is used to pull out the exact bit // pattern — this is a verified memory copy, not a numeric conversion, which matters because // RowBinary needs the bits, not a rounded re-encoding of the value. void CRowBinaryWriter::WriteFloat64(const double value) { uchar bytes[8]; StructToCharArray(value,bytes); EnsureCapacity(8); for(int i=0;i<8;i++) m_buf[m_len+i]=bytes[i]; m_len+=8; }
Timestamps get their own method because ClickHouse's DateTime64(3) wants milliseconds since the Unix epoch as a signed Int64. MQL5 already hands this over as one combined value — MqlTick.time_msc and DEAL_TIME_MSC both report the full epoch-millisecond figure directly, not just a sub-second remainder — so the method takes that single value as-is rather than reconstructing it from a whole-seconds field and a separate millisecond part kept in sync by the caller:
//--- Appends a DateTime64(3) value: milliseconds since the Unix epoch, as a signed Int64. The // caller passes the full already-combined epoch-millisecond value (MQL5's own // MqlTick.time_msc and DEAL_TIME_MSC both report this directly), rather than this method // reconstructing it from a separate whole-seconds field and a sub-second remainder — one // field to get right instead of two kept in sync. void CRowBinaryWriter::WriteDateTime64Ms(const long epoch_ms) { WriteInt64(epoch_ms); }
Strings are the one field type with a genuine two-step internal procedure, so WriteString() is where the first-level block comment convention actually earns its keep — one comment for converting to UTF-8 bytes, a second for writing the length prefix and the bytes themselves, each flush left against the function body because both steps sit at the same nesting level:
//--- Appends a String field: a VarUInt byte length followed by the raw UTF-8 bytes, with no // terminator — the length prefix is what tells the reader where the field ends. void CRowBinaryWriter::WriteString(const string &text) { //--- convert to UTF-8 bytes first so the byte count (not the // character count) is what gets written as the VarUInt length uchar utf8[]; int raw_len=StringToCharArray(text,utf8,0,WHOLE_ARRAY,CP_UTF8); int byte_len=raw_len>0 ? raw_len-1 : 0; // drop the trailing null StringToCharArray appends //--- write the length prefix, then the bytes themselves WriteVarUInt((ulong)byte_len); EnsureCapacity(byte_len); for(int i=0;i<byte_len;i++) m_buf[m_len+i]=utf8[i]; m_len+=byte_len; }
Nullable columns and the NULL byte
ClickHouse's Nullable(T) wraps any type with a one-byte flag: 1 means NULL, 0 means a real value follows. That flag byte is written either way — a NULL still costs one byte, it's never free. What's easy to get wrong is what happens after the flag. In ClickHouse's Native (columnar) format, a NULL row still gets a placeholder value written after the flag, to keep every column's stride constant across a whole column block. In RowBinary, there is no such placeholder — when the flag is 1, the value costs zero further bytes; nothing else is written for that field at all. Write a placeholder value anyway, matching Native's convention out of habit, and every column after it is off by that many bytes for the rest of the row; the server reports this as a byte-count mismatch rather than a wrong value, because by the time it notices, the row no longer parses as the schema it expects:
//--- Appends a Nullable(Float64) field: a one-byte flag (1 = NULL, 0 = present) followed by the // value — but only when the flag is 0. RowBinary writes nothing at all for the value when // the flag says NULL; there is no placeholder byte to skip over. void CRowBinaryWriter::WriteNullableFloat64(const bool is_null,const double value) { WriteUInt8(is_null ? (uchar)1 : (uchar)0); if(!is_null) WriteFloat64(value); }
The string version follows the identical rule, and shares the same consequence for getting it wrong — an extra VarUInt-and-bytes sequence written after a NULL flag desyncs every remaining column exactly like the float case does:
//--- Appends a Nullable(String) field using the same flag-then-value convention as // WriteNullableFloat64() — nothing is written for the string at all when the flag says // NULL. void CRowBinaryWriter::WriteNullableString(const bool is_null,const string &text) { WriteUInt8(is_null ? (uchar)1 : (uchar)0); if(!is_null) WriteString(text); }
This is also why the self-test script later sends an explicit NULL as one of its four rows rather than only testing the happy path — a live insert against a running server is the only way this particular mismatch surfaces, since nothing about the encoder itself throws a compile-time or even a runtime error when it writes the extra byte. The bytes are perfectly well-formed on their own; they're only wrong in the context of what the next column expects to find at that offset, which only the receiving server can catch.
Authenticating and routing requests over HTTP
ClickHouse's HTTP interface has one important rule: GET is strictly read-only. Send anything that modifies data or schema over GET — even a statement that reads like a harmless setup step — and the server answers with a read-only mode exception regardless of how the SQL is phrased. POST is required for an INSERT (the RowBinary bytes go in the body) and for any DDL or other modifying statement. CClickHouseHttpClient therefore exposes separate methods rather than one generic "send a request" method: Query() uses GET, while Insert() and Execute() use POST, so the GET/POST choice is made by what the statement does, not left to whoever's calling it that day to remember:
//+------------------------------------------------------------------+ //| CClickHouseHttpClient | //| A thin wrapper around WebRequest() for ClickHouse's HTTP | //| interface. ClickHouse's HTTP server treats GET as strictly read- | //| only — it rejects any statement that modifies data or schema | //| with a read-only mode exception — while POST carries the | //| request body (RowBinary bytes for an insert, or raw SQL text for | //| anything else) and is required for INSERT, CREATE, and every | //| other statement that changes state. Query() therefore only ever | //| issues GET, Insert() and Execute() only ever issue POST, and | //| callers pick the method by what the statement does, not by | //| habit. Credentials are sent as an HTTP Basic Authorization | //| header rather than in the URL, so they never show up in a | //| proxy's or ClickHouse's own query log. | //+------------------------------------------------------------------+ class CClickHouseHttpClient { private: string m_base_url; // e.g. "http://127.0.0.1:8123" string m_user; // ClickHouse user name string m_password; // ClickHouse user password int m_timeout_ms; // WebRequest() timeout public: CClickHouseHttpClient(void); bool Init(const string base_url,const string user,const string password,const int timeout_ms); string BuildAuthHeader(void) const; string UrlEncode(const string &text) const; bool IsValidIdentifier(const string &name) const; bool Insert(const string &database,const string &table,const uchar &rowbinary[],string &error_out) const; bool Query(const string &database,const string &sql,string &response_out,string &error_out) const; bool Execute(const string &database,const string &sql,string &error_out) const; };
Init() just stores the connection settings — it deliberately does not try a real connection, since the first actual request will surface a connectivity problem with a more useful error than a synthetic health check would:
//--- Stores connection settings for later requests. Returns false only on an obviously // malformed base_url, since the real connectivity check happens on the first actual request. bool CClickHouseHttpClient::Init(const string base_url,const string user,const string password,const int timeout_ms) { if(StringLen(base_url)==0) return(false); m_base_url=base_url; m_user=user; m_password=password; m_timeout_ms=timeout_ms; return(true); }
ClickHouse's HTTP interface accepts credentials more than one way — a user/password query-string pair, an X-ClickHouse-User/ X-ClickHouse-Key header pair, or standard HTTP Basic Auth — and the query-string option is the one worth avoiding: a password sitting in the URL is a password sitting in every access log, proxy history, and ClickHouse query log that URL passes through. BuildAuthHeader() takes the Basic Auth route instead, base64-encoding user:password via MQL5's own CryptEncode() into a standard Authorization header, the same way any other HTTP Basic client would send it:
//--- Builds the Authorization header ClickHouse's HTTP interface accepts for HTTP Basic Auth: // "user:password" encoded as base64 via CryptEncode(), the same way any other HTTP Basic // client would send it. Keeping credentials out of the URL means they never land in a web // server's access log, a proxy's history, or ClickHouse's own query log the way a query- // string user/password pair would. string CClickHouseHttpClient::BuildAuthHeader(void) const { string cred=m_user+":"+m_password; uchar cred_bytes[]; int raw_len=StringToCharArray(cred,cred_bytes,0,WHOLE_ARRAY,CP_UTF8); int byte_len=raw_len>0 ? raw_len-1 : 0; ArrayResize(cred_bytes,byte_len); uchar key[]; // CRYPT_BASE64 ignores the key, an empty array is correct here uchar encoded[]; CryptEncode(CRYPT_BASE64,cred_bytes,key,encoded); return("Authorization: Basic "+CharArrayToString(encoded)+"\r\n"); }
The database name and the SQL text still have to survive being embedded in a URL, so UrlEncode() percent-encodes everything outside the small set of characters that are always safe unencoded — letters, digits, and a handful of punctuation marks:
//--- Percent-encodes the handful of characters that are unsafe in a URL query string (space, &, // =, %, plus any non-ASCII byte); used on the SQL text and the database name, neither of // which carries credentials now that those travel in a header instead. string CClickHouseHttpClient::UrlEncode(const string &text) const { uchar bytes[]; int raw_len=StringToCharArray(text,bytes,0,WHOLE_ARRAY,CP_UTF8); int byte_len=raw_len>0 ? raw_len-1 : 0; string out=""; for(int i=0;i<byte_len;i++) { uchar b=bytes[i]; bool safe=(b>='A'&&b<='Z')||(b>='a'&&b<='z')||(b>='0'&&b<='9')||b=='-'||b=='_'||b=='.'||b=='~'; if(safe) out+=CharToString((uchar)b); else out+=StringFormat("%%%02X",b); } return(out); }
Insert() splices a database and table name directly into the URL rather than passing them as bound query parameters, so it validates both through IsValidIdentifier() before either one is ever allowed near a request. Execute() only ever sees a database name and an already-assembled SQL string — it has no separate table parameter to check, so it validates just the database the same way. Any other identifier the caller has spliced into that SQL text is the caller's own responsibility to validate first; EnsureTestTable() below does exactly that for InpSelfTestTable before it ever reaches the SQL string. IsValidIdentifier() itself rejects anything outside letters, digits, and underscore, and anything starting with a digit:
//--- Accepts only plain identifiers (letters, digits, underscore, not starting with a digit) // for a database or table name. Insert() and Execute() both route their database/table // arguments through this before building SQL text out of them, since those two methods // splice the names directly into a statement string rather than passing them as bound query // parameters — rejecting anything outside this charset is what keeps an unexpected name // from being interpreted as SQL. bool CClickHouseHttpClient::IsValidIdentifier(const string &name) const { int len=StringLen(name); if(len==0 || len>64) return(false); for(int i=0;i<len;i++) { ushort c=StringGetCharacter(name,i); bool alpha=(c>='A'&&c<='Z')||(c>='a'&&c<='z'); bool digit=(c>='0'&&c<='9'); bool is_valid_char=alpha||digit||c=='_'; if(!is_valid_char) return(false); if(i==0 && digit) return(false); } return(true); }
With encoding and validation in place, the three request methods differ only in HTTP verb and where the payload goes. Insert() issues POST with the RowBinary bytes as the body and the target table named in the query string; a WebRequest() result of -1 means the request never reached the server at all — DNS, TLS, a timeout, the URL allow-list, or a missing WebRequest permission — which is why that case is reported through GetLastError() rather than folded into the same message as a genuine HTTP error response from the server:
//--- Sends a RowBinary-encoded batch as an INSERT via POST. The query string names the target // table and the FORMAT, and the request body is the raw encoded bytes CRowBinaryWriter // produced — nothing in the body is SQL text. database and table are checked with // IsValidIdentifier() before they're spliced into the statement. WebRequest() takes char[], // not uchar[], for its body and result parameters, so rowbinary is copied into a local char // array first — ArrayCopy() between the two types preserves every byte, it just changes how // the compiler labels its sign. A WebRequest() failure (res==-1, meaning the request never // reached the server at all) is reported with GetLastError() rather than a bare HTTP -1. bool CClickHouseHttpClient::Insert(const string &database,const string &table,const uchar &rowbinary[],string &error_out) const { if(!IsValidIdentifier(database) || !IsValidIdentifier(table)) { error_out="rejected: database/table name is not a plain identifier"; return(false); } string sql="INSERT INTO "+database+"."+table+" FORMAT RowBinary"; string url=m_base_url+"/?query="+UrlEncode(sql); string headers=BuildAuthHeader(); char body[]; ArrayCopy(body,rowbinary); char result[]; string result_headers; int res=WebRequest("POST",url,headers,m_timeout_ms,body,result,result_headers); if(res==-1) { error_out="WebRequest failed, GetLastError()="+IntegerToString(GetLastError()); return(false); } if(res!=200) { error_out="HTTP "+IntegerToString(res)+": "+CharArrayToString(result); return(false); } return(true); }
Query() always issues GET. It's built for SELECT, but nothing inside the method itself checks that the SQL passed in actually is one — send it a modifying statement and it still goes out over GET, where ClickHouse's own read-only mode exception is what stops it, not this method. The caller is responsible for only ever pointing Query() at read-only SQL; Insert() and Execute() exist precisely so that anything else goes out over POST instead. Query() shares the same -1-versus-HTTP-error distinction as Insert():
//--- Runs a read-only SELECT via GET — ClickHouse's HTTP server rejects anything else sent // this way with a read-only mode exception, so this method must never be used for DDL or // INSERT. Like Insert(), body and result are char[] because that's what WebRequest() itself // requires, and a transport-level failure (res==-1) is reported through GetLastError() rather // than folded into the same message as a server-side HTTP error. ClickHouse answers in UTF-8, // so the response is decoded with CP_UTF8 explicitly rather than left to the system's default // code page — the self-test's multi-byte row depends on this, not just on the encoder. bool CClickHouseHttpClient::Query(const string &database,const string &sql,string &response_out,string &error_out) const { string url=m_base_url+"/?database="+UrlEncode(database)+"&query="+UrlEncode(sql); string headers=BuildAuthHeader(); char body[]; char result[]; string result_headers; int res=WebRequest("GET",url,headers,m_timeout_ms,body,result,result_headers); if(res==-1) { error_out="WebRequest failed, GetLastError()="+IntegerToString(GetLastError()); return(false); } if(res!=200) { error_out="HTTP "+IntegerToString(res)+": "+CharArrayToString(result,0,ArraySize(result),CP_UTF8); return(false); } response_out=CharArrayToString(result,0,ArraySize(result),CP_UTF8); return(true); }
And Execute() issues POST with the SQL text as the body — no query= parameter — which is what makes CREATE TABLE and similar statements possible. That's an implementation choice made here so Insert()'s RowBinary body and Execute()'s SQL body follow the same shape, not a requirement ClickHouse imposes: ClickHouse accepts DDL through query= over POST just as well. One detail that matters more than the choice of body shape: StringToCharArray() appends a trailing null byte when it converts the SQL string, and that byte has no place in an HTTP body, so it's trimmed off before the request goes out:
//--- Runs a statement that changes state (CREATE TABLE and the like) via POST, with the SQL // text as the request body and no query= parameter — a choice made so the body for // Insert()'s RowBinary and Execute()'s SQL follow the same shape, not because ClickHouse // requires it; ClickHouse accepts DDL through query= just as well. StringToCharArray() // writes into a uchar buffer and appends a trailing null byte that has no place in an HTTP // body, so that byte is trimmed off first; the bytes are then copied into a char array, // since that's the type WebRequest() itself takes for body and result, not uchar. bool CClickHouseHttpClient::Execute(const string &database,const string &sql,string &error_out) const { if(!IsValidIdentifier(database)) { error_out="rejected: database name is not a plain identifier"; return(false); } string url=m_base_url+"/?database="+UrlEncode(database); string headers=BuildAuthHeader(); uchar sql_bytes[]; int raw_len=StringToCharArray(sql,sql_bytes,0,WHOLE_ARRAY,CP_UTF8); ArrayResize(sql_bytes,raw_len>0 ? raw_len-1 : 0); // drop the trailing null byte char body[]; ArrayCopy(body,sql_bytes); char result[]; string result_headers; int res=WebRequest("POST",url,headers,m_timeout_ms,body,result,result_headers); if(res==-1) { error_out="WebRequest failed, GetLastError()="+IntegerToString(GetLastError()); return(false); } if(res!=200) { error_out="HTTP "+IntegerToString(res)+": "+CharArrayToString(result); return(false); } return(true); }
Recording live ticks and deals
TickRecorder_EA.mq5 is where the two includes above actually get used. Its inputs and globals are small and mostly self-explanatory from the aligned trailing comments, but two globals carry real behavior: g_last_tick is what OnTick() compares a new quote against before deciding whether there's anything new to record, and the two row counters are what decide when a batch is full enough to flush without waiting for the timer:
//+------------------------------------------------------------------+ //| Inputs | //| Connection settings and batching thresholds — everything here | //| is safe to change from the Inputs tab without touching the code. | //+------------------------------------------------------------------+ input string InpBaseUrl = "http://127.0.0.1:8123"; // ClickHouse HTTP endpoint input string InpUser = "default"; // ClickHouse user input string InpPassword = "clickhouse123"; // ClickHouse password input string InpDatabase = "mt5"; // target database input int InpBatchSize = 500; // ticks buffered before a flush input int InpFlushSeconds = 2; // max seconds a partial batch waits //+------------------------------------------------------------------+ //| Globals | //| The recorder's working state: one writer and one HTTP client | //| shared across OnTick(), OnTimer() and OnDeinit(), plus counters | //| the buffers are compared against before a flush. | //+------------------------------------------------------------------+ CRowBinaryWriter g_tick_writer; // encodes the pending tick batch CRowBinaryWriter g_deal_writer; // encodes the pending deal batch CClickHouseHttpClient g_client; // shared HTTP connection settings int g_tick_count; // rows currently buffered in g_tick_writer int g_deal_count; // rows currently buffered in g_deal_writer MqlTick g_last_tick; // last tick actually recorded (dedup check)
InpBatchSize = 500 and InpFlushSeconds = 2 are demonstration starting values, not settings this setup claims are universally correct. The right numbers for your own deployment depend on how fast ticks actually arrive for the symbols you're recording, how much write latency you can tolerate before a batch feels stale, how quickly your ClickHouse instance responds to an insert, and how reliable the network path between the terminal and the server is — a busy symbol on a fast local network can run a larger batch size without the flush timer ever kicking in, while a slow or flaky connection argues for smaller, more frequent flushes so a failed batch loses less.
OnInit() checks that InpBatchSize and InpFlushSeconds are both positive before doing anything else, then wires the HTTP client from the Inputs tab and arms a recurring timer — it returns INIT_PARAMETERS_INCORRECT or INIT_FAILED rather than limping along on a bad input or an empty base_url. That's as far as OnInit() itself can check: g_client.Init() only validates that the string isn't empty — it doesn't parse the URL or check that ClickHouse is actually reachable, so a malformed URL or an unreachable server only becomes visible once the first real request goes out. Still, rejecting the one failure it can detect up front is better than an EA that silently never connects or never flushes:
//+------------------------------------------------------------------+ //| OnInit | //| Expert initialization handler. Validates the batching inputs, | //| wires up the HTTP client from the Inputs, and arms the flush | //| timer; returns INIT_PARAMETERS_INCORRECT or INIT_FAILED on a | //| bad input or an empty base_url — Init() only checks it isn't | //| empty, not that it's well-formed; ClickHouse's actual | //| availability is only checked once the first real request goes | //| out, not here. | //+------------------------------------------------------------------+ int OnInit(void) { if(InpBatchSize<=0 || InpFlushSeconds<=0) { Print("InpBatchSize and InpFlushSeconds must both be positive"); return(INIT_PARAMETERS_INCORRECT); } if(!g_client.Init(InpBaseUrl,InpUser,InpPassword,5000)) { Print("ClickHouse client Init() failed — check InpBaseUrl"); return(INIT_FAILED); } g_tick_count=0; g_deal_count=0; EventSetTimer(InpFlushSeconds); return(INIT_SUCCEEDED); }
On the way out, OnDeinit() flushes whatever is still buffered rather than discarding it, so a deliberate stop from the Experts tab doesn't drop the last partial batch on top of the terminal's own shutdown. That's a best-effort safeguard rather than a guarantee — if that final flush's WebRequest() itself fails, the batch is logged and dropped like any other failed flush, not retried on the way out:
//+------------------------------------------------------------------+ //| OnDeinit | //| Expert deinitialization handler. Stops the timer and flushes | //| whatever is still buffered so a deliberate stop never silently | //| drops the last partial batch. | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { EventKillTimer(); if(g_tick_count>0) FlushTicks(); if(g_deal_count>0) FlushDeals(); }
OnTick() is the hot path, called on every new quote. The skip check compares time_msc, bid, ask, last and flags against the last recorded tick — all five, not just price — so a tick that only updates the last-trade price or only flips a flag bit still gets recorded rather than silently dropped as an apparent duplicate. Whether last is even present is read from TICK_FLAG_LAST in tick.flags rather than from tick.last==0, since a real last-trade price of exactly 0.0 is possible for some instruments and a bare zero check can't tell that apart from "no last price at all". Worth flagging here too: because FlushTicks() runs synchronously inside this same handler, a tick that arrives while an earlier flush is still waiting on WebRequest() never gets its own OnTick() call at all, so this recorder does not guarantee that every market tick is captured — more on that under edge cases below:
//+------------------------------------------------------------------+ //| OnTick | //| Called on every new price quote. Encodes one RowBinary row for | //| any tick that carries information not already in g_last_tick and | //| buffers it; a size-triggered flush covers the busy case, while | //| OnTimer() below covers the quiet case where ticks never reach | //| InpBatchSize on their own. | //+------------------------------------------------------------------+ void OnTick(void) { //--- pull the latest tick; nothing to record if the symbol has none yet MqlTick tick; if(!SymbolInfoTick(_Symbol,tick)) return; //--- skip only an exact repeat of the last recorded tick — bid, ask, last and flags // are all compared, not just bid/ask, so a last-price or flags-only update still records if(tick.time_msc==g_last_tick.time_msc && tick.bid==g_last_tick.bid && tick.ask==g_last_tick.ask && tick.last==g_last_tick.last && tick.flags==g_last_tick.flags) return; g_last_tick=tick; //--- a tick carries a last-trade price only when TICK_FLAG_LAST is set in tick.flags — // tick.last itself can legitimately be 0.0 for an instrument that trades at that price, // so the flag, not a zero check on the value, is what decides whether this field is NULL bool has_last=(tick.flags & TICK_FLAG_LAST)!=0; //--- encode one RowBinary row matching the ticks table's column order exactly g_tick_writer.WriteString(_Symbol); g_tick_writer.WriteDateTime64Ms((long)tick.time_msc); g_tick_writer.WriteFloat64(tick.bid); g_tick_writer.WriteFloat64(tick.ask); g_tick_writer.WriteNullableFloat64(!has_last,tick.last); g_tick_writer.WriteUInt32((uint)tick.flags); g_tick_count++; //--- size-triggered flush; the timer below covers the size-not-reached case if(g_tick_count>=InpBatchSize) FlushTicks(); }
A second trigger on a timer covers the case a size threshold alone can't: a quiet market where ticks never arrive fast enough to fill a batch on their own, so a partial batch would otherwise sit unflushed indefinitely:
//+------------------------------------------------------------------+ //| OnTimer | //| Fires every InpFlushSeconds. Flushes whatever is currently | //| buffered, even a single row, so a batch never waits longer than | //| this interval to reach ClickHouse regardless of tick volume. | //+------------------------------------------------------------------+ void OnTimer(void) { if(g_tick_count>0) FlushTicks(); if(g_deal_count>0) FlushDeals(); }
Deals are recorded from a different event entirely. OnTradeTransaction() fires for several transaction types, and TRADE_TRANSACTION_DEAL_ADD is the one this handler filters on — it fires once for every deal MetaTrader 5 adds to history, whether that deal opens a position, adds to one, or closes it, not only when a position closes. Filtering on it records every such deal-add event rather than every intermediate state a trade request passes through on its way to one:
//+------------------------------------------------------------------+ //| OnTradeTransaction | //| Trade-event handler. Records one row per deal the terminal adds | //| to history — TRADE_TRANSACTION_DEAL_ADD fires once for every | //| such deal, whether it opens, adds to, or closes a position, not | //| only on a close — the moment the terminal confirms it, | //| independent of OnTick()'s own buffering. | //+------------------------------------------------------------------+ void OnTradeTransaction(const MqlTradeTransaction &trans,const MqlTradeRequest &request,const MqlTradeResult &result) { if(trans.type!=TRADE_TRANSACTION_DEAL_ADD) return; ulong deal_ticket=trans.deal; if(!HistoryDealSelect(deal_ticket)) return; //--- encode one RowBinary row matching the deals table's column order exactly g_deal_writer.WriteUInt64(deal_ticket); g_deal_writer.WriteString(HistoryDealGetString(deal_ticket,DEAL_SYMBOL)); g_deal_writer.WriteDateTime64Ms((long)HistoryDealGetInteger(deal_ticket,DEAL_TIME_MSC)); g_deal_writer.WriteFloat64(HistoryDealGetDouble(deal_ticket,DEAL_PRICE)); g_deal_writer.WriteFloat64(HistoryDealGetDouble(deal_ticket,DEAL_VOLUME)); g_deal_writer.WriteFloat64(HistoryDealGetDouble(deal_ticket,DEAL_PROFIT)); g_deal_count++; if(g_deal_count>=InpBatchSize) FlushDeals(); }
Both event paths end the same way: hand the writer's bytes to the HTTP client and clear the buffer regardless of whether the insert succeeded, so one failed batch can't back up every tick or deal behind it.
//--- forward declarations void FlushTicks(void); void FlushDeals(void);
//+------------------------------------------------------------------+ //| FlushTicks | //| Sends the buffered tick batch to ClickHouse via a single POST | //| insert and clears the writer either way — a row that fails to | //| insert is logged and dropped rather than retried, so one bad | //| batch can't block every tick behind it. | //+------------------------------------------------------------------+ void FlushTicks(void) { uchar payload[]; g_tick_writer.GetBytes(payload); string error_text; if(!g_client.Insert(InpDatabase,"ticks",payload,error_text)) Print("ClickHouse ticks insert failed: ",error_text); g_tick_writer.Clear(); g_tick_count=0; }
FlushDeals() mirrors it exactly, writing to the deals table instead:
//+------------------------------------------------------------------+ //| FlushDeals | //| Sends the buffered deal batch to ClickHouse via a single POST | //| insert, mirroring FlushTicks()'s clear-either-way behavior. | //+------------------------------------------------------------------+ void FlushDeals(void) { uchar payload[]; g_deal_writer.GetBytes(payload); string error_text; if(!g_client.Insert(InpDatabase,"deals",payload,error_text)) Print("ClickHouse deals insert failed: ",error_text); g_deal_writer.Clear(); g_deal_count=0; }
Edge cases and pitfalls
A few things cost real debugging time while this was being built, and are worth knowing up front rather than rediscovering the hard way:
A ternary can't bind to a const string& reference parameter. MQL5's compiler wants an addressable lvalue for a reference parameter, and a ternary expression isn't one — assign it to a named local first, then pass that local instead of the inline expression.
GET is read-only, full stop. It doesn't matter how the SQL is phrased; any modifying statement sent over GET gets a read-only mode exception. Route CREATE TABLE and anything else that changes state through Execute(), not Query().
Always qualify the database name. A CREATE TABLE or SELECT without database.table silently targets whatever database the connection's default points at — usually default — rather than erroring, which makes the mistake easy to miss until a later query can't find the table it expects.
Recent ClickHouse images disable the default user's network access by default. Starting the official Docker image without CLICKHOUSE_PASSWORD (or CLICKHOUSE_USER) set leaves HTTP requests failing authentication even though the container itself reports healthy — set one of those two environment variables at container creation, not after the fact.
Flushing is synchronous. WebRequest() blocks the calling event handler until ClickHouse responds, so a slow network round-trip delays whatever OnTick()/OnTimer() would otherwise do next. For the batch sizes and local-network latency this recorder is built for, that's a reasonable trade-off — but it's worth sizing InpBatchSize with that cost in mind rather than pushing it arbitrarily high on the assumption that bigger batches are always better.
This recorder does not guarantee lossless capture of every market tick. MQL5 does not queue intermediate NewTick events while OnTick() is still busy with an earlier one, so while a flush is blocked on WebRequest(), any ticks that arrive in that window simply never trigger their own OnTick() call — nothing is dropped from a buffer, because that tick never reached the handler to be buffered in the first place. This is separate from a failed insert being logged and dropped: here the insert that does go out succeeds, but a handful of quotes in between two flushes can go unrecorded on a fast-moving symbol. Nothing in this architecture changes to fix that; it's a property of a synchronous single-threaded event handler, worth knowing about rather than working around.
A failed insert is logged and dropped, not retried. This is a deliberate choice, not an oversight: retrying inline would risk blocking the event loop even longer on a server that's already struggling, and a retry queue is exactly the kind of addition that belongs in its own article rather than bolted onto this one as an afterthought (see the conclusion).
The symbol name itself needs no special handling here, but a broker-suffixed symbol would. Some brokers append a suffix to the standard symbol name (XAUUSD.m, XAUUSDpro, and similar), and this recorder stores whatever _Symbol returns verbatim. That's correct for a single-broker setup, but if you ever consolidate data from more than one broker into the same ClickHouse tables, normalizing the symbol name before it reaches WriteString() is worth doing at that point — otherwise the same underlying instrument shows up as several distinct symbol values in your queries.
Testing
Two scripts do the testing, and they test different things. ClickHouse_SelfTest.mq5 checks the encoding against four edge-case rows, writing them and reading them straight back: a negative float, a multi-byte UTF-8 string, an explicit NULL, and an empty string — each a case the ordinary tick path alone wouldn't reliably exercise on a quiet demo account. Its entry point runs a full round trip under a marker that combines the current time with a microsecond component. This reduces the chance of two runs landing on the same marker compared with wall-clock time alone (TimeLocal(), one-second resolution), although collisions are still possible:
//+------------------------------------------------------------------+ //| OnStart | //| Script entry point. Creates the scratch table if needed, inserts | //| four edge-case rows under a marker that combines the current | //| time with the microsecond counter, then reads them back and | //| checks every value — a full round trip through the real server | //| rather than just inspecting the encoder in isolation. | //+------------------------------------------------------------------+ void OnStart(void) { CClickHouseHttpClient client; if(!client.Init(InpBaseUrl,InpUser,InpPassword,5000)) { Print("Init() failed"); return; } string marker="selftest_"+IntegerToString((int)TimeLocal())+"_"+IntegerToString((int)(GetMicrosecondCount()%1000000)); if(!EnsureTestTable(client,marker)) return; if(!InsertTestRows(client,marker)) return; VerifyTestRows(client,marker); }
It creates its scratch table through Execute(), since CREATE TABLE is a modifying statement and would otherwise hit the read-only mode exception described above:
//--- forward declarations bool EnsureTestTable(CClickHouseHttpClient &client,const string &marker); bool InsertTestRows(CClickHouseHttpClient &client,const string &marker); bool VerifyTestRows(CClickHouseHttpClient &client,const string &marker);
//+------------------------------------------------------------------+ //| EnsureTestTable | //| Creates the scratch table if it doesn't already exist. Validates | //| InpSelfTestTable with IsValidIdentifier() first, since Execute() | //| itself only checks the database argument, not a table name | //| already spliced into the SQL text passed to it. Uses Execute() | //| (POST) rather than Query() (GET), since CREATE TABLE is a | //| modifying statement and ClickHouse's HTTP server rejects any | //| modifying statement sent over GET with a read-only mode | //| exception, regardless of how the SQL itself is phrased. | //+------------------------------------------------------------------+ bool EnsureTestTable(CClickHouseHttpClient &client,const string &marker) { if(!client.IsValidIdentifier(InpSelfTestTable)) { Print("EnsureTestTable: InpSelfTestTable is not a plain identifier"); return(false); } string sql="CREATE TABLE IF NOT EXISTS "+InpDatabase+"."+InpSelfTestTable+" (" +"run_marker String, row_id UInt32, val_float Float64, " +"val_nullable Nullable(Float64), val_string String" +") ENGINE = MergeTree ORDER BY (run_marker, row_id)"; string error_text; if(!client.Execute(InpDatabase,sql,error_text)) { Print("EnsureTestTable failed: ",error_text); return(false); } return(true); }
The four rows themselves are written in one batch, each one chosen for a specific reason rather than arbitrarily: row 0 is an ordinary negative float, to catch a sign-handling mistake; row 1 carries a multi-byte UTF-8 string, to catch a byte-count-versus-character-count mistake; row 2 sends an explicit NULL, to catch the exact placeholder-byte mismatch the Nullable encoding rule described in the previous section has to avoid; and row 3 sends an empty string, a degenerate but entirely legal VarUInt length of zero:
//+------------------------------------------------------------------+ //| InsertTestRows | //| Writes four rows chosen to exercise the encoder's edge cases | //| in one batch: a negative float, a multi-byte UTF-8 string, an | //| explicit NULL in the Nullable column, and an empty string — | //| each a case the happy path alone would never touch. | //+------------------------------------------------------------------+ bool InsertTestRows(CClickHouseHttpClient &client,const string &marker) { CRowBinaryWriter w; //--- row 0: an ordinary negative float, nothing unusual w.WriteString(marker); w.WriteUInt32(0); w.WriteFloat64(-123.456); w.WriteNullableFloat64(false,-123.456); w.WriteString("row0"); //--- row 1: a multi-byte UTF-8 string, to catch any byte-count mistake w.WriteString(marker); w.WriteUInt32(1); w.WriteFloat64(1.0); w.WriteNullableFloat64(false,1.0); w.WriteString("XAUUSD тест €"); //--- row 2: an explicit NULL — the case a placeholder-byte mistake would miss w.WriteString(marker); w.WriteUInt32(2); w.WriteFloat64(2.0); w.WriteNullableFloat64(true,0.0); w.WriteString("row2"); //--- row 3: an empty string, a degenerate but legal VarUInt length of zero w.WriteString(marker); w.WriteUInt32(3); w.WriteFloat64(3.0); w.WriteNullableFloat64(false,3.0); w.WriteString(""); uchar payload[]; w.GetBytes(payload); string error_text; if(!client.Insert(InpDatabase,InpSelfTestTable,payload,error_text)) { Print("InsertTestRows failed: ",error_text); return(false); } return(true); }
Verification reads the rows back as TSV and checks row_id, val_float (with a small numeric tolerance), val_nullable, and val_string against what InsertTestRows() sent for that row_id. The Nullable column is checked against ClickHouse's own TSV rendering of NULL — the literal text \N, not an empty string and not a zero — for row 2, and against its own val_float for every other row. A row_id outside the expected 0-3 range, a duplicate row_id, or a missing row_id fails the overall check even if every value it did see matched, and a blank trailing TSV line is never counted as a row:
//+------------------------------------------------------------------+ //| VerifyTestRows | //| Reads the four rows for this run's marker back as tab-separated | //| text and checks row_id, val_float, val_nullable, and val_string | //| against what InsertTestRows() sent for that row_id. ClickHouse | //| renders a NULL as the literal text '\\N' in TSV output, which is | //| what row 2's val_nullable is checked against; every other row's | //| val_nullable must equal its own val_float instead. A row_id | //| outside 0-3, a duplicate, or a missing row_id fails the overall | //| check even if every value it did see matched. | //+------------------------------------------------------------------+ bool VerifyTestRows(CClickHouseHttpClient &client,const string &marker) { string sql="SELECT row_id, val_float, val_nullable, val_string FROM " +InpDatabase+"."+InpSelfTestTable+" WHERE run_marker = '"+marker+"' " +"ORDER BY row_id FORMAT TSV"; string response, error_text; if(!client.Query(InpDatabase,sql,response,error_text)) { Print("VerifyTestRows query failed: ",error_text); return(false); } //--- the exact values InsertTestRows() sent for each row_id, indexed by row_id double expected_float[4]={-123.456,1.0,2.0,3.0}; string expected_string[4]={"row0","XAUUSD тест €","row2",""}; bool seen[4]={false,false,false,false}; int pass_count=0, data_rows=0; string rows[]; int row_count=StringSplit(response,'\n',rows); //--- walk every non-empty TSV line and score it against the row_id it claims to be for(int i=0;i<row_count;i++) { if(StringLen(rows[i])==0) continue; // a trailing blank line after the final \n is not a data row data_rows++; string cols[]; if(StringSplit(rows[i],'\t',cols)<4) continue; int row_id=(int)StringToInteger(cols[0]); if(row_id<0 || row_id>3 || seen[row_id]) continue; // an unexpected or duplicate row_id can't pass; the count check below catches it seen[row_id]=true; bool float_ok=MathAbs(StringToDouble(cols[1])-expected_float[row_id])<0.0001; bool nullable_ok=(row_id==2) ? (cols[2]=="\\N") : (cols[2]!="\\N" && MathAbs(StringToDouble(cols[2])-expected_float[row_id])<0.0001); bool string_ok=(cols[3]==expected_string[row_id]); if(float_ok && nullable_ok && string_ok) pass_count++; } bool all_four_seen=(seen[0] && seen[1] && seen[2] && seen[3]); Print("VerifyTestRows: ",pass_count," of 4 expected rows matched, ",data_rows," data rows returned"); return(pass_count==4 && all_four_seen && data_rows==4); }
Running it against a local ClickHouse container (started with docker run and the password environment variable set at creation time) printed every row matching expectations, including the NULL row — confirming the Nullable encoding rule holds under an actual server round trip, not just on inspection of the encoder.
The second script, ClickHouse_HistoryBackfill.mq5, measures throughput. It pulls local tick history via CopyTicksRange() in 24-hour chunks — measured from range_start, not aligned to calendar-day midnight boundaries — to keep each request and batch size predictable and to give a natural progress point; not to dodge a tick-count cap: a single busy trading day for an instrument like XAUUSD can easily hold well over a hundred thousand ticks, far more than any per-call limit some MetaTrader 5 history functions are documented to have:
//+------------------------------------------------------------------+ //| OnStart | //| Script entry point. Walks the requested day range in | //| 24-hour chunks from range_start — not calendar-day | //| boundaries — and reports wall-clock throughput at the end. | //| Chunking bounds each CopyTicksRange() call and RowBinary | //| batch to a predictable size regardless of how many ticks a | //| chunk actually holds, and gives a natural progress point. | //| If any chunk fails outright, the run stops and reports what | //| it committed rather than claiming the backfill finished. | //+------------------------------------------------------------------+ void OnStart(void) { CClickHouseHttpClient client; if(!client.Init(InpBaseUrl,InpUser,InpPassword,10000)) { Print("Init() failed"); return; } datetime range_end=TimeCurrent(); datetime range_start=range_end-InpDaysBack*86400; ulong t0=GetTickCount64(); int total_rows=0; bool backfill_ok=true; datetime day_start=range_start; while(day_start<range_end) { datetime day_end=(day_start+86400<range_end) ? day_start+86400 : range_end; bool chunk_ok=true; int rows=BackfillDay(client,day_start,day_end,chunk_ok); total_rows+=rows; Print(TimeToString(day_start,TIME_DATE|TIME_SECONDS)," to ",TimeToString(day_end,TIME_DATE|TIME_SECONDS),": ",rows," ticks"); if(!chunk_ok) { backfill_ok=false; break; // stop at the first chunk that didn't complete; don't claim later chunks are fine } day_start=day_end; } double elapsed_sec=(GetTickCount64()-t0)/1000.0; if(!backfill_ok) { Print("Backfill INCOMPLETE: stopped after ",total_rows," rows, ",DoubleToString(elapsed_sec,1),"s — see the error above and re-run to retry"); return; } Print("Backfill done: ",total_rows," rows in ",DoubleToString(elapsed_sec,1), "s (",DoubleToString(total_rows/MathMax(elapsed_sec,0.001),0)," rows/sec)"); }
Each chunk's worth of ticks is pulled, encoded, and flushed in InpBatchSize pieces by BackfillDay(), which returns only the ticks actually committed to ClickHouse — not merely fetched — and signals failure through its own ok parameter rather than folding it into the row count: a CopyTicksRange() error and a failed flush both set ok to false and stop the chunk, while a chunk the market was simply closed for returns zero with ok left true:
//--- forward declarations int BackfillDay(CClickHouseHttpClient &client,const datetime day_start,const datetime day_end,bool &ok); bool FlushBatch(CClickHouseHttpClient &client,CRowBinaryWriter &writer);
//+------------------------------------------------------------------+ //| BackfillDay | //| Pulls every tick for one 24-hour chunk via CopyTicksRange(), | //| encodes and flushes it in InpBatchSize chunks, and returns | //| the ticks actually committed to ClickHouse, not merely fetched. | //| ok is set false on two distinct failures: CopyTicksRange() | //| itself erroring (count<0), or a flush failing mid-chunk — both | //| are reported to the caller instead of being folded into a plain | //| zero. A chunk with the market legitimately closed still returns | //| zero ticks with ok left true; that is not an error. | //+------------------------------------------------------------------+ int BackfillDay(CClickHouseHttpClient &client,const datetime day_start,const datetime day_end,bool &ok) { ok=true; MqlTick ticks[]; long from_msc=(long)day_start*1000; long to_msc=(long)day_end*1000-1; // CopyTicksRange() includes both endpoints; -1ms keeps adjacent chunks from double-counting the shared boundary tick int count=CopyTicksRange(InpSymbol,ticks,COPY_TICKS_ALL,from_msc,to_msc); if(count<0) { Print("CopyTicksRange failed, GetLastError()=",IntegerToString(GetLastError())); ok=false; return(0); } if(count==0) return(0); // the market was simply closed for this chunk; not an error CRowBinaryWriter writer; int buffered=0; int committed=0; for(int i=0;i<count;i++) { bool has_last=(ticks[i].flags & TICK_FLAG_LAST)!=0; writer.WriteString(InpSymbol); writer.WriteDateTime64Ms((long)ticks[i].time_msc); writer.WriteFloat64(ticks[i].bid); writer.WriteFloat64(ticks[i].ask); writer.WriteNullableFloat64(!has_last,ticks[i].last); writer.WriteUInt32((uint)ticks[i].flags); buffered++; if(buffered>=InpBatchSize) { if(!FlushBatch(client,writer)) { ok=false; return(committed); // a failed batch is not counted, and the chunk stops here } committed+=buffered; buffered=0; } } if(buffered>0) { if(FlushBatch(client,writer)) committed+=buffered; else ok=false; } return(committed); }
Its flush step is the same shape as the EA's own FlushTicks(), which matters because it means both the live path and the backfill path write the ticks table in exactly the same row layout — there's only one encoding to get right, used by two scripts:
//+------------------------------------------------------------------+ //| FlushBatch | //| Sends whatever the writer currently holds as one insert and | //| clears it, mirroring the EA's FlushTicks() so both paths write | //| the ticks table in exactly the same row layout. | //+------------------------------------------------------------------+ bool FlushBatch(CClickHouseHttpClient &client,CRowBinaryWriter &writer) { uchar payload[]; writer.GetBytes(payload); string error_text; bool ok=client.Insert(InpDatabase,"ticks",payload,error_text); if(!ok) Print("Backfill insert failed: ",error_text); writer.Clear(); return(ok); }
A 7-day XAUUSD backfill on this setup moved 1,181,045 rows in 195.8 seconds — a little over 6,000 rows/sec on this one machine, this one Docker container, and this one network path, not a general bound on the encoder or on ClickHouse itself. It's a single measured run on one environment, not a number this setup is claimed to reproduce on different hardware, a different broker feed, or a different ClickHouse version. The day-by-day breakdown below shows why the total isn't evenly split across the week: Friday's session ends early and Saturday has no ticks at all, both expected for a symbol that follows the regular forex week rather than a gap in the backfill logic.
The exact figure above is tied to one machine, one container, and one tick source, so rather than listing specs that would still only describe that single run, the honest path is to run ClickHouse_HistoryBackfill.mq5 yourself: point InpSymbol and InpDaysBack at whatever range and feed you care about, and OnStart() will print your own rows-and-seconds number at the end, measured on your own hardware against your own ClickHouse instance.

Fig. 2. Per-day tick counts from the 7-day XAUUSD backfill.
A separate row-count query against the ticks table after the run matched the total BackfillDay() reported, which is the cross-check that matters here: because BackfillDay() only counts rows after FlushBatch() confirms the insert succeeded, the number OnStart() prints and the number ClickHouse actually stored should already agree by construction — this query is what confirms that in practice, rather than a dropped batch silently inflating a count taken straight from CopyTicksRange().
Conclusion
A RowBinary encoder and an HTTP client together are a small amount of code — a few hundred lines across two includes — but getting the byte-level details right matters more than the line count suggests. The Nullable encoding rule in particular is easy to get wrong in a way that only a live round trip against the real server will catch, which is the reason the self-test script exists at all rather than trusting the encoder on inspection alone. Every excerpt in this article was pulled directly out of the files in the attached archive, not retyped by hand, so what you read above is exactly what compiles and runs.
From here, the natural next steps are a retry queue for failed batches instead of the current drop-and-log behavior, and moving the HTTP calls off the main thread if tick volume ever outpaces what a synchronous WebRequest() can keep up with on a given network. Both would build on the design covered here rather than change it — the recorder as shipped has been tested against a real ClickHouse instance end to end, from a single tick through to a row you can query back out, and backfilled at the measured rate reported above for this one run and setup, not a rate claimed to hold everywhere.
If you adapt this for your own account, the places most worth re-checking first are the ones this article spent the most time on: the Nullable encoding in WriteNullableFloat64() and WriteNullableString(), the GET/POST routing inside CClickHouseHttpClient, and the column order in OnTick() and OnTradeTransaction() against whatever schema you end up deploying. Everything else in this recorder follows mechanically once those three decisions are correct, which is also why they're the three places a port to a different schema or a different broker is most likely to need a second look.
| File | Type | Description |
|---|---|---|
| ClickHouseRowBinary.mqh | Include | RowBinary byte-level encoder |
| ClickHouseHttpClient.mqh | Include | WebRequest()-based HTTP client (GET/POST routing) |
| TickRecorder_EA.mq5 | Expert Advisor | Live tick/deal recorder |
| ClickHouse_SelfTest.mq5 | Script | Encoder round-trip verification |
| ClickHouse_HistoryBackfill.mq5 | Script | Fast historical backfill + throughput measurement |
| setup.sql | SQL | Database and table DDL |
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.