preview
Connecting MQL5 to Apache Cassandra: A Native CQL Binary Protocol (v4) Client for Tick-Level Feature Archival

Connecting MQL5 to Apache Cassandra: A Native CQL Binary Protocol (v4) Client for Tick-Level Feature Archival

MetaTrader 5 — Integration |
52 0
Bosede Gbadebo
Bosede Gbadebo

Introduction

MQL5 has no built-in Cassandra driver, and MetaTrader won't load ODBC or Cassandra client DLLs in a distributable EA — the only way out is a raw outbound TCP socket (SocketCreate/SocketConnect/SocketSend/SocketRead). Cassandra's native protocol is public, so this article builds a CQL binary protocol v4 client on top of that socket — version byte fixed at 0x04, no negotiation (v4 still works against Cassandra 5; v5 isn't implemented) — and puts it to work on something a trading EA genuinely needs: writing a per-tick feature vector — bid, ask, spread, signed volume delta, a short rolling realized-volatility estimate — into Cassandra on every tick OnTick is actually called for, batched for throughput, so the resulting table can feed a feature store, an offline training pipeline, or a post-trade audit trail with no CSV file or second process in between. One caveat up front: MetaTrader 5 doesn't guarantee a distinct OnTick call for every real tick, so this is a complete record of what the terminal handed the EA, not a provable capture of the whole tick stream (more in Limitations).

Six files implement this in layers: a byte-level encoder/decoder, a frame/opcode layer, a connection class that owns one socket and runs the STARTUP/SASL PLAIN handshake, a statement-level client adding PREPARE/EXECUTE/BATCH, the archiver EA that drives the stack from OnTick, and a self-test script that exercises every statement shape against a real node. Every excerpt below is copied verbatim from the accompanying archive.


Architecture

Component and data-flow overview

Fig. 1. The six files in this project and how a write reaches the wire. CqlProtocol.mqh and CqlBuffer.mqh are pulled in by CqlConnection.mqh for byte-level encoding; CqlClient.mqh sits above the connection and is the only layer the EA and self-test script talk to directly.

The stack is strictly layered bottom to top. CqlProtocol.mqh defines the wire constants — opcodes, consistency levels, RESULT kinds — and the 9-byte frame header. CqlBuffer.mqh is a growable byte array with a read cursor implementing the primitive encodings this schema needs: [short], [int], [long], [string], [long string], [bytes], [short bytes], [uuid], [double], and [consistency] — nothing else the spec defines (string lists/maps, inet, option lists) is needed here.

CqlConnection.mqh owns one outbound TCP socket and runs the handshake — STARTUP, then SASL PLAIN if the node asks for it — plus a blocking send/receive pair keyed on a self-assigned stream id. CqlClient.mqh sits above it and is the only layer the EA and self-test script call: Query(), Prepare()/ExecutePrepared(), and Batch() for the archiver's throughput path.

The partition key is (symbol, day_bucket), clustered by ts then a tie-breaking seq — so two ticks landing on the same millisecond get distinct rows instead of one overwriting the other. Each row's day_bucket comes from its own ts, and FlushBuffer() stops a chunk the moment the next row's bucket would differ, so every Batch() call always lands in one partition — the shape Cassandra recommends for UNLOGGED batching.

The connection never pipelines — every SendFrame() waits for its matching RecvFrame() before the next is built — so throughput comes entirely from batching rows, not overlapping requests (see Limitations).


CqlProtocol.mqh: Opcodes and the Frame Header

This file is the protocol's vocabulary: opcode values straight from protocol section 2.3. Every opcode this client sends or parses is defined here, plus four more kept as named constants it never uses — OPTIONS/SUPPORTED (capability negotiation this client skips) and REGISTER/EVENT (server push notifications) — since this is a synchronous request/response driver, never a listener for asynchronous server events.

//+------------------------------------------------------------------+
//| Frame opcodes                                                    |
//| Single-byte opcode values from the CQL native protocol v4 frame  |
//| header (section 2.3 of the protocol spec). Every opcode this     |
//| client actually sends or parses is defined below, and so are four|
//| it never uses -- OPTIONS/SUPPORTED (capability negotiation this  |
//| client skips) and REGISTER/EVENT (server push notifications) --  |
//| kept as named constants documenting the opcode space, not because|
//| this client sends or handles any of the four: it is a synchronous|
//| request/response driver, never a listener for asynchronous server|
//| events.                                                          |
//+------------------------------------------------------------------+
#define CQL_OP_ERROR             0x00  // server: operation failed, body is an error code + message
#define CQL_OP_STARTUP           0x01  // client: first frame on a new connection
#define CQL_OP_READY             0x02  // server: connection accepted, no auth required
#define CQL_OP_AUTHENTICATE      0x03  // server: SASL authenticator name follows
#define CQL_OP_OPTIONS           0x05  // client: ask server for supported options (unused here)
#define CQL_OP_SUPPORTED         0x06  // server: reply to OPTIONS (unused here)
#define CQL_OP_QUERY             0x07  // client: run one CQL statement, no prior PREPARE
#define CQL_OP_RESULT            0x08  // server: reply to QUERY / PREPARE / EXECUTE / BATCH
#define CQL_OP_PREPARE           0x09  // client: ask the server to parse and cache a statement
#define CQL_OP_EXECUTE           0x0A  // client: run a previously prepared statement by id
#define CQL_OP_REGISTER          0x0B  // client: subscribe to push events (not used by this client)
#define CQL_OP_EVENT             0x0C  // server: an unsolicited push event (not handled here)
#define CQL_OP_BATCH             0x0D  // client: run several prepared statements as one batch
#define CQL_OP_AUTH_CHALLENGE    0x0E  // server: SASL wants another round (not needed by PLAIN)
#define CQL_OP_AUTH_RESPONSE     0x0F  // client: SASL token reply to AUTHENTICATE/AUTH_CHALLENGE
#define CQL_OP_AUTH_SUCCESS      0x10  // server: SASL handshake finished, connection is usable

RESULT kinds are the [int] field every RESULT body opens with (section 4.2.5). Only Prepared is inspected in depth, for its statement id; the rest are recognised just so a caller can log which kind came back.

//+------------------------------------------------------------------+
//| RESULT kinds                                                     |
//| The [int] kind field at the start of every RESULT frame body     |
//| (protocol section 4.2.5). Prepared is the only kind this         |
//| client inspects in detail (it needs the statement id back);      |
//| Void/Rows/Set_keyspace/Schema_change are recognised only so      |
//| CCqlClient::ReadResult() can log which kind came back.           |
//+------------------------------------------------------------------+
#define CQL_RESULT_VOID          0x0001
#define CQL_RESULT_ROWS           0x0002
#define CQL_RESULT_SET_KEYSPACE   0x0003
#define CQL_RESULT_PREPARED       0x0004
#define CQL_RESULT_SCHEMA_CHANGE  0x0005

Every CQL message opens with the same fixed 9-byte header: version, flags, a 2-byte stream id, opcode, and a 4-byte signed body length. CqlFrameHeader is its parsed, in-memory form; every access to those fields goes through the two functions below rather than reading or writing a socket directly.

//+------------------------------------------------------------------+
//| CqlFrameHeader                                                   |
//| The fixed 9-byte frame header every CQL native-protocol          |
//| message starts with (protocol section 2.3): a version byte,      |
//| a flags byte, a 2-byte stream id (v3+ widened this from 1        |
//| byte to 2, which is why this client refuses to talk to           |
//| protocol v1/v2 servers), a 1-byte opcode and a 4-byte signed     |
//| body length. This struct is the parsed, in-memory form; the      |
//| wire form is built and read by WriteFrameHeader()/               |
//| ReadFrameHeader() below, never by touching these fields          |
//| directly against a socket.                                       |
//+------------------------------------------------------------------+
struct CqlFrameHeader
  {
   uchar             version;        // 0x04 request / 0x84 response for protocol v4
   uchar             flags;          // bit 0x01 = compression (never set by this client)
   short             stream;          // request/response correlation id, this client's own counter
   uchar             opcode;          // one of the CQL_OP_* values above
   int               length;          // body length in bytes, NOT including this 9-byte header
  };

WriteFrameHeader serializes a CqlFrameHeader into the 9 raw, big-endian bytes the wire format requires.

//+------------------------------------------------------------------+
//| WriteFrameHeader                                                 |
//| Serializes a CqlFrameHeader into the 9 raw bytes the wire        |
//| format requires, appending them to the caller's buffer at        |
//| offset 0 (the header always leads a frame, so this function      |
//| is only ever called at the start of building one).               |
//+------------------------------------------------------------------+
void WriteFrameHeader(uchar &dst[],const CqlFrameHeader &hdr)
  {
   ArrayResize(dst,9);
   dst[0]=hdr.version;
   dst[1]=hdr.flags;
   dst[2]=(uchar)((hdr.stream>>8)&0xFF);          // stream is big-endian on the wire
   dst[3]=(uchar)(hdr.stream&0xFF);
   dst[4]=hdr.opcode;
   dst[5]=(uchar)((hdr.length>>24)&0xFF);        // length is a big-endian signed int32
   dst[6]=(uchar)((hdr.length>>16)&0xFF);
   dst[7]=(uchar)((hdr.length>>8)&0xFF);
   dst[8]=(uchar)(hdr.length&0xFF);
  }

ReadFrameHeader is the mirror operation: it returns false if fewer than 9 bytes are available yet, leaving the blocking/retry loop to its caller, CCqlConnection::RecvFrame.

//+------------------------------------------------------------------+
//| ReadFrameHeader                                                  |
//| Parses the 9-byte header out of a buffer that has just come      |
//| off the socket. Returns false if fewer than 9 bytes are          |
//| available yet -- the caller (CCqlConnection::RecvFrame) is       |
//| responsible for blocking/retrying until a full header has        |
//| arrived; this function never blocks itself.                      |
//+------------------------------------------------------------------+
bool ReadFrameHeader(const uchar &src[],CqlFrameHeader &hdr)
  {
   if(ArraySize(src)<9)
      return(false);
   hdr.version=src[0];
   hdr.flags=src[1];
   hdr.stream=(short)((src[2]<<8)|src[3]);
   hdr.opcode=src[4];
   hdr.length=(int)(((uint)src[5]<<24)|((uint)src[6]<<16)|((uint)src[7]<<8)|(uint)src[8]);
   return(true);
  }


CqlBuffer.mqh: Encoding the Protocol's Primitive Types

Every value that goes onto or comes off the wire passes through CCqlBuffer, a single growable byte array with one read cursor — each instance is used purely in write mode or purely in read mode, never both.

//+------------------------------------------------------------------+
//| CCqlBuffer                                                       |
//| A growable raw byte array plus a read cursor, implementing the   |
//| handful of primitive encodings the CQL native protocol v4 spec   |
//| (section 3) defines: [short], [int], [long], [string], [long     |
//| string], [bytes], [short bytes], [uuid], [double] and            |
//| [consistency]. One instance is write-only (building a request    |
//| body) or read-only (walking a response body) -- the two modes are|
//| never mixed on the same instance, so there is a single cursor    |
//| rather than separate read/write positions. Per this project's    |
//| class-commenting convention, the declaration below gets this one |
//| header box for the whole class; every out-of-line method         |
//| implementation that follows still gets its own individual header |
//| box.                                                             |
//+------------------------------------------------------------------+
class CCqlBuffer
  {
private:
   uchar             m_data[];        // backing store; grows as Write*() appends
   int               m_pos;          // read cursor used only by Read*(); Write*() always appends
   void              Reserve(const int extra);
public:
                     CCqlBuffer(void);
                    ~CCqlBuffer(void) {}
   void              Clear(void);
   void              GetBytes(uchar &dst[]) const;
   void              GetRemaining(uchar &dst[]) const;
   void              SetBytes(const uchar &src[]);
   int               Size(void) const { return(ArraySize(m_data)); }
   int               Remaining(void) const { return(ArraySize(m_data)-m_pos); }
   //--- writers (append to m_data; used when building a request body)
   void              WriteByte(const uchar v);
   void              WriteShort(const ushort v);
   void              WriteInt(const int v);
   void              WriteLong(const long v);
   void              WriteDouble(const double v);        // CQL "double" = 8-byte big-endian IEEE754
   bool              WriteString(const string v);      // false if the UTF-8 encoding exceeds 65535 bytes
   void              WriteLongString(const string v);
   void              WriteBytes(const uchar &v[]);
   void              WriteShortBytes(const uchar &v[]);
   void              WriteUuid(const uchar &v[]);        // expects exactly 16 bytes
   void              WriteConsistency(const ushort level) { WriteShort(level); }
   void              WriteRaw(const uchar &v[]);
   //--- readers (advance m_pos; used when walking a response body)
   uchar             ReadByte(void);
   ushort            ReadShort(void);
   int               ReadInt(void);
   long              ReadLong(void);
   double            ReadDouble(void);
   string            ReadString(void);
   string            ReadLongString(void);
   bool              ReadBytes(uchar &dst[]);      // returns false on a NULL ([int] length == -1)
   bool              ReadShortBytes(uchar &dst[]);  // same NULL convention, [short] length field
  };

The constructor starts the instance empty with the cursor at 0, ready to build a request or to receive and read a body via SetBytes().

//+------------------------------------------------------------------+
//| CCqlBuffer::CCqlBuffer                                           |
//| Starts empty, read cursor at 0 -- an instance is ready to        |
//| either Write*() a request body from scratch or SetBytes() a      |
//| received body and then Read*() through it.                       |
//+------------------------------------------------------------------+
CCqlBuffer::CCqlBuffer(void)
  {
   m_pos=0;
   ArrayResize(m_data,0);
  }

WriteByte appends one raw byte. It is not a shared primitive the other fixed-width writers below call — WriteShort/WriteInt/WriteLong each write their own multi-byte encoding directly — WriteByte() is used on its own wherever the protocol calls for a single [byte] field, such as a BATCH request's type/kind byte.

//+------------------------------------------------------------------+
//| CCqlBuffer::WriteByte                                            |
//| Appends one raw byte. It is not a shared primitive the other     |
//| fixed-width writers below call -- WriteShort/WriteInt/WriteLong  |
//| each write their own multi-byte encoding directly. WriteByte()   |
//| is used on its own wherever the protocol calls for a single      |
//| [byte] field, such as a BATCH request's type/kind byte.          |
//+------------------------------------------------------------------+
void CCqlBuffer::WriteByte(const uchar v)
  {
   int n=ArraySize(m_data);
   Reserve(1);
   m_data[n]=v;
  }

WriteShort appends a 2-byte big-endian unsigned short using an explicit shift-and-mask, since MQL5 has no runtime endianness query and every MetaTrader platform this project targets is little-endian.

//+------------------------------------------------------------------+
//| CCqlBuffer::WriteShort                                           |
//| Appends a 2-byte big-endian unsigned short -- CQL's native       |
//| protocol is big-endian throughout (section 3), same as           |
//| network byte order, so there is no endianness branch here.       |
//| MQL5 gives no portable way to query host endianness, but         |
//| every supported MetaTrader platform is little-endian, so the     |
//| shifts below always do the right thing without a runtime check.  |
//+------------------------------------------------------------------+
void CCqlBuffer::WriteShort(const ushort v)
  {
   int n=ArraySize(m_data);
   Reserve(2);
   m_data[n+0]=(uchar)((v>>8)&0xFF);
   m_data[n+1]=(uchar)(v&0xFF);
  }

WriteDouble needs a trick, not a shift: CQL's double is the same 8-byte big-endian bit pattern WriteLong() already emits, so the job is reinterpreting those bits through MQL5's union keyword, never a numeric conversion:

//+------------------------------------------------------------------+
//| CCqlBuffer::WriteDouble                                          |
//| CQL's "double" column type is the raw 8-byte big-endian          |
//| IEEE754 bit pattern -- the same layout WriteLong() already       |
//| emits for a long -- so the whole job is reinterpreting the       |
//| double's bits as a long without converting its numeric value.    |
//| MQL5's union keyword does exactly that reinterpretation; no      |
//| string formatting or manual mantissa/exponent math is            |
//| involved. Used for the bid/ask/spread/volatility feature         |
//| columns; the archiver's timestamp and the prepared-statement     |
//| id use WriteLong/WriteShortBytes directly since those are        |
//| already integer/byte-string types with no bit-pattern step.      |
//+------------------------------------------------------------------+
union UCqlDoubleBits
  {
   double            as_double;
   long              as_long;
  };
void CCqlBuffer::WriteDouble(const double v)
  {
   UCqlDoubleBits bits;
   bits.as_double=v;
   WriteLong(bits.as_long);
  }

WriteString implements [string] — a [short] length prefix plus raw UTF-8 — and refuses to encode a value whose UTF-8 length would overflow that 65535-byte prefix, returning false with a diagnostic instead.

//+------------------------------------------------------------------+
//| CCqlBuffer::WriteString                                          |
//| [string] = [short] byte-length + UTF-8 bytes (max 65535          |
//| bytes). Refuses to encode a value whose UTF-8 length would       |
//| overflow that 16-bit prefix, returning false with a              |
//| diagnostic instead of writing a frame with a mismatched          |
//| length field. This is raw UTF-8, not base64 -- no                |
//| CryptEncode(CRYPT_BASE64,...) step is involved anywhere in       |
//| this encoding.                                                   |
//+------------------------------------------------------------------+
bool CCqlBuffer::WriteString(const string v)
  {
   uchar utf8[];
   int n=StringToCharArray(v,utf8,0,WHOLE_ARRAY,CP_UTF8)-1;  // drop the trailing NUL
   if(n<0) n=0;
   if(n>65535)
    {
      PrintFormat("CqlBuffer: WriteString value is %d UTF-8 bytes, which overflows the [string] 16-bit length prefix (max 65535) -- refusing to encode it",n);
      return(false);
    }
   ArrayResize(utf8,n);
   WriteShort((ushort)n);
   WriteRaw(utf8);
   return(true);
  }

WriteUuid is exposed for a future caller — nothing in this schema binds a uuid column yet — and checks its 16-byte length at runtime, since MQL5 won't accept a fixed-size array by reference.

//+------------------------------------------------------------------+
//| CCqlBuffer::WriteUuid                                            |
//| A uuid is 16 raw bytes with no length prefix at all (section     |
//| 3) -- distinct from WriteBytes()'s [int]-prefixed encoding.      |
//| MQL5 only allows a dynamic array as a by-reference parameter     |
//| (a fixed-size uchar[16] reference does not compile), so the      |
//| 16-byte requirement is enforced at runtime instead of by the     |
//| signature; a caller passing anything else gets a clear error     |
//| rather than a silently truncated or padded uuid. Exposed for a   |
//| future caller -- nothing in this project's tick-feature schema   |
//| or either .mq5 file currently binds a uuid column.               |
//+------------------------------------------------------------------+
void CCqlBuffer::WriteUuid(const uchar &v[])
  {
   if(ArraySize(v)!=16)
     {
      Print("CqlBuffer: WriteUuid requires exactly 16 bytes, got ",ArraySize(v));
      return;
     }
   WriteRaw(v);
  }

The read-side functions mirror the writers one for one; ReadDouble reverses WriteDouble() through the same union, never a numeric conversion.

//+------------------------------------------------------------------+
//| CCqlBuffer::ReadDouble                                           |
//| The read-side counterpart of WriteDouble(): reads the 8          |
//| big-endian bytes as a long via ReadLong(), then reinterprets     |
//| those bits as a double through the same UCqlDoubleBits union     |
//| WriteDouble() uses -- never a numeric int-to-double conversion.  |
//+------------------------------------------------------------------+
double CCqlBuffer::ReadDouble(void)
  {
   UCqlDoubleBits bits;
   bits.as_long=ReadLong();
   return(bits.as_double);
  }

ReadBytes mirrors WriteBytes() and must tell a genuine NULL from a real zero-length value: CQL encodes NULL as an [int] length of -1, so this returns false only on that exact marker, not on any negative length in general. A positive length is checked against Remaining() before anything is allocated — one that would read past the buffer is malformed data, not NULL, and is rejected the same way but with its own diagnostic. ReadShortBytes() applies the same check to its [short] field, and Cql_SelfTest.mq5's row parsing depends on this NULL-vs-real distinction staying exact.

//+------------------------------------------------------------------+
//| CCqlBuffer::ReadBytes                                            |
//| The read-side counterpart of WriteBytes(). Returns false (and    |
//| clears dst to a zero-length array) on a NULL marker ([int]       |
//| length == -1), so a caller can tell a genuine NULL apart from a  |
//| real zero-length value. A positive length that would read past   |
//| the end of the buffer is rejected the same way -- false, dst     |
//| cleared -- but with a distinct Print() diagnostic, since that    |
//| is malformed or truncated data, not a NULL. Cql_SelfTest.mq5's   |
//| row-parsing logic relies on the NULL-versus-real-value           |
//| distinction being exact.                                         |
//+------------------------------------------------------------------+
bool CCqlBuffer::ReadBytes(uchar &dst[])
  {
   int n=ReadInt();
   if(n<0)
     {
      ArrayResize(dst,0);
      return(false);
     }
   if(n>Remaining())
     {
      PrintFormat("CCqlBuffer::ReadBytes: declared length %d exceeds %d bytes remaining -- malformed frame",n,Remaining());
      ArrayResize(dst,0);
      return(false);
     }
   ArrayResize(dst,n);
   ArrayCopy(dst,m_data,0,m_pos,n);
   m_pos+=n;
   return(true);
  }


CqlConnection.mqh: Socket, Handshake, and Frame I/O

CCqlConnection owns one outbound socket and speaks the synchronous half of the protocol: STARTUP, the SASL handshake PasswordAuthenticator requires, and a blocking send/receive pair keyed on a self-assigned stream id. It deliberately skips multiplexing several requests on distinct stream ids — every request waits for its own reply before the next is built, and the batching one layer up in the EA recovers the throughput instead.

//+------------------------------------------------------------------+
//| CCqlConnection                                                   |
//| Owns one outbound TCP socket to a single Cassandra node and      |
//| speaks the synchronous half of the native protocol: STARTUP,     |
//| the SASL AUTHENTICATE/AUTH_RESPONSE/AUTH_SUCCESS exchange        |
//| PasswordAuthenticator requires, and a blocking SendFrame/        |
//| RecvFrame pair keyed on a self-assigned stream id. MQL5          |
//| sockets are outbound-only (no SocketBind/Listen/Accept) --       |
//| irrelevant here since this class only ever connects out to       |
//| the node, never listens for one. Multiplexing many in-flight     |
//| requests on distinct stream ids (what a production CQL driver    |
//| does for throughput) is deliberately NOT implemented: every      |
//| SendFrame() is followed by exactly one matching RecvFrame()      |
//| before the next request is built, which keeps the class          |
//| simple at the cost of one round trip per statement -- the        |
//| batching in TickFeatureArchiver_EA.mq5 is what recovers          |
//| throughput, not pipelining at this layer.                        |
//+------------------------------------------------------------------+
class CCqlConnection
  {
private:
   int               m_socket;        // SocketCreate() handle, INVALID_HANDLE when not connected
   short             m_next_stream;  // monotonically increasing, wraps at 32767 back to 1
   int               m_timeout_ms;    // SocketRead/SocketIsReadable polling timeout per attempt
   bool              ReadExact(uchar &dst[],const int n);
public:
                     CCqlConnection(void);
                    ~CCqlConnection(void);
   bool              Connect(const string host,const int port,const int timeout_ms);
   bool              Startup(bool &auth_required_out);
   bool              Authenticate(const string username,const string password);
   bool              SendFrame(const uchar opcode,const uchar &body[],short &stream_out);
   bool              RecvFrame(const short expect_stream,uchar &opcode_out,uchar &body_out[]);
   void              Close(void);
   bool              IsConnected(void) const { return(m_socket!=INVALID_HANDLE); }
  };

Connect opens the TCP socket within timeout_ms, establishing only the transport — Startup() and, if required, Authenticate() still have to run before any statement-level frame is valid.

//+------------------------------------------------------------------+
//| CCqlConnection::Connect                                          |
//| Opens the TCP socket and waits (bounded by timeout_ms) for it    |
//| to become connected. This only establishes the transport --      |
//| Startup() and, if the node requires it, Authenticate() still     |
//| have to run before any QUERY/PREPARE/EXECUTE/BATCH frame is      |
//| valid; sending one before that handshake completes is a          |
//| caller error this class does not guard against separately,       |
//| since every entry point in CCqlClient calls Connect/Startup/     |
//| Authenticate in that fixed order already.                        |
//+------------------------------------------------------------------+
bool CCqlConnection::Connect(const string host,const int port,const int timeout_ms)
  {
   m_timeout_ms=timeout_ms;
   m_socket=SocketCreate();
   if(m_socket==INVALID_HANDLE)
     {
      PrintFormat("CqlConnection: SocketCreate failed, error %d",GetLastError());
      return(false);
     }
   if(!SocketConnect(m_socket,host,(ushort)port,timeout_ms))
     {
      PrintFormat("CqlConnection: SocketConnect to %s:%d failed, error %d",host,port,GetLastError());
      SocketClose(m_socket);
      m_socket=INVALID_HANDLE;
      return(false);
     }
   return(true);
  }

Startup sends the mandatory STARTUP frame naming CQL_VERSION and reports which reply came back — READY or AUTHENTICATE (Authenticate() must run next) — through auth_required_out, since calling Authenticate() against a node that already answered READY is a real way to hang the handshake.

//+------------------------------------------------------------------+
//| CCqlConnection::Startup                                          |
//| Sends the mandatory first frame on a fresh connection: a         |
//| STARTUP whose body is a [string map] with a single               |
//| CQL_VERSION entry (section 4.1.1). This client never sends       |
//| COMPRESSION -- no compression algorithm is negotiated or         |
//| implemented anywhere in this project, so every frame on the      |
//| wire is plain, uncompressed CQL. The only two valid replies      |
//| are READY (node has no authenticator configured -- the           |
//| default for a stock Cassandra Docker image with no extra         |
//| config) or AUTHENTICATE (a real authenticator, e.g.              |
//| PasswordAuthenticator, is active and Authenticate() must run     |
//| next); which one came back is reported through                   |
//| auth_required_out rather than assumed, since calling             |
//| Authenticate() against a node that answered READY would send     |
//| an AUTH_RESPONSE the node never asked for and never replies      |
//| to -- a real, observed way to hang the handshake, not a          |
//| hypothetical edge case.                                          |
//+------------------------------------------------------------------+
bool CCqlConnection::Startup(bool &auth_required_out)
  {
   CCqlBuffer body;
   body.WriteShort(1);                      // [string map] with exactly one entry
   if(!body.WriteString("CQL_VERSION") || !body.WriteString("3.0.0"))
      return(false);
   uchar wire[];
   body.GetBytes(wire);
   short stream;
   if(!SendFrame(CQL_OP_STARTUP,wire,stream))
      return(false);
   uchar opcode,reply[];
   if(!RecvFrame(stream,opcode,reply))
      return(false);
   if(opcode==CQL_OP_READY)
     {
      auth_required_out=false;
      return(true);
     }
   if(opcode==CQL_OP_AUTHENTICATE)
     {
      auth_required_out=true;                // caller must call Authenticate() next
      return(true);
     }
   PrintFormat("CqlConnection: STARTUP got unexpected opcode 0x%02X",opcode);
   return(false);
  }

SendFrame assigns the next stream id, builds the 9-byte header for the given opcode and body, and writes both to the socket in one SocketSend call; the returned stream id is what RecvFrame() later uses to confirm a reply belongs to this request rather than a stale one.

//+------------------------------------------------------------------+
//| CCqlConnection::SendFrame                                        |
//| Builds the 9-byte header for 'body' with a freshly assigned      |
//| stream id, writes header+body to the socket in one               |
//| SocketSend() call, and hands the stream id back to the caller    |
//| so the matching RecvFrame() can confirm the reply correlates     |
//| to this request rather than a stray frame left over from a       |
//| prior exchange.                                                  |
//+------------------------------------------------------------------+
bool CCqlConnection::SendFrame(const uchar opcode,const uchar &body[],short &stream_out)
  {
   stream_out=m_next_stream;
   m_next_stream++;
   if(m_next_stream>=32767)
      m_next_stream=1;                      // wrap, skipping stream 0 (reserved)
   CqlFrameHeader hdr;
   hdr.version=0x04;                        // protocol v4 request
   hdr.flags=0x00;                          // no compression, no tracing
   hdr.stream=stream_out;
   hdr.opcode=opcode;
   hdr.length=ArraySize(body);
   uchar framed[];
   WriteFrameHeader(framed,hdr);
   int hdr_len=ArraySize(framed);
   ArrayResize(framed,hdr_len+ArraySize(body));
   ArrayCopy(framed,body,hdr_len,0,ArraySize(body));
   int sent=SocketSend(m_socket,framed,ArraySize(framed));
   if(sent!=ArraySize(framed))
     {
      PrintFormat("CqlConnection: SocketSend sent %d of %d bytes, error %d",
                  sent,ArraySize(framed),GetLastError());
      return(false);
     }
   return(true);
  }

RecvFrame blocks, bounded by the connection's timeout, until a complete frame — the 9-byte header plus its declared body bytes — has arrived, discarding anything whose stream id doesn't match what was asked for; that's safe only because this class never pipelines, so a mismatched frame is, by construction, stale. A response with the warnings flag (0x08) set is accepted rather than rejected: its body opens with a [string list] of server warning messages ahead of the normal payload (protocol section 2.2), which this method strips off before handing the real body to the caller.

//+------------------------------------------------------------------+
//| CCqlConnection::RecvFrame                                        |
//| Blocks (bounded by m_timeout_ms, polled via SocketIsReadable)    |
//| until a complete frame -- 9-byte header plus the body length     |
//| it declares -- has arrived, discarding anything whose stream     |
//| id does not match expect_stream. Discarding rather than          |
//| queueing a mismatched frame is safe only because this class      |
//| never pipelines (see the class header box above): with           |
//| exactly one request ever in flight, any frame that is not the    |
//| one just asked for is, by construction, stale and not            |
//| something a later call needs. Rejects outright, before any       |
//| body parsing, a response whose version byte is not 0x84 (v4      |
//| response), whose flags byte has compression/tracing/custom-      |
//| payload set (this client neither negotiates compression nor      |
//| parses the other two), or whose body length is negative or       |
//| over a 10MB sanity cap -- guessing the RESULT offset wrong, or   |
//| trusting an attacker-sized length, would be worse than           |
//| refusing the frame. Every one of those rejections also closes    |
//| the connection, since the body was never read off the socket     |
//| and leaving it there would corrupt the next frame boundary if    |
//| the connection were reused as-is. A response with the warnings   |
//| flag (0x08) set is accepted, not rejected: section 2.2 of the    |
//| protocol spec puts a leading [string list] of warning messages   |
//| on the body in that case, so this method strips that list off    |
//| before handing body_out to the caller, which can then parse it   |
//| exactly as it would an unwarned response of the same opcode.     |
//+------------------------------------------------------------------+
bool CCqlConnection::RecvFrame(const short expect_stream,uchar &opcode_out,uchar &body_out[])
  {
   uint start=GetTickCount();
   while(true)
     {
      uchar hdr_bytes[];
      if(!ReadExact(hdr_bytes,9))
        {
         if((int)(GetTickCount()-start)>m_timeout_ms)
           {
            Print("CqlConnection: RecvFrame timed out waiting for header");
            return(false);
           }
         Sleep(5);
         continue;
        }
      CqlFrameHeader hdr;
      ReadFrameHeader(hdr_bytes,hdr);
      if(hdr.version!=0x84)
        {
          PrintFormat("CqlConnection: RecvFrame got unexpected version byte 0x%02X, expected 0x84 (v4 response)",hdr.version);
          Close();
          return(false);
        }
      if((hdr.flags&(0x01|0x02|0x04))!=0)
        {
          PrintFormat("CqlConnection: RecvFrame got response flags 0x%02X (compression/tracing/custom-payload) this client does not support or parse -- rejecting and closing the connection rather than risk a wrong RESULT offset or leave unread bytes behind",hdr.flags);
          Close();
          return(false);
        }
      if(hdr.length<0 || hdr.length>10*1024*1024)
        {
          PrintFormat("CqlConnection: RecvFrame got an invalid body length %d (negative or over the 10MB sanity cap) -- rejecting and closing the connection rather than risk an unsafe allocation",hdr.length);
          Close();
          return(false);
        }
      uchar body[];
      if(hdr.length>0)
        {
         if(!ReadExact(body,hdr.length))
           {
            Print("CqlConnection: RecvFrame timed out waiting for body");
            return(false);
           }
        }
      else
         ArrayResize(body,0);
      if(hdr.stream!=expect_stream)
         continue;                          // stale frame from a prior exchange; drop it
      if((hdr.flags&0x08)!=0)
        {
          //--- warnings flag: the body starts with a [string list] of warning
          //--- messages, ahead of the normal opcode-specific payload (protocol
          //--- section 2.2). Walk it off with a scratch CCqlBuffer and keep
          //--- only the tail -- the real body -- so every existing RESULT/
          //--- ERROR parser downstream stays unaware warnings ever happened.
          CCqlBuffer wbuf;
          wbuf.SetBytes(body);
          int warn_count=(int)wbuf.ReadShort();
          for(int w=0;w<warn_count;w++)
             wbuf.ReadString();                         // warning text, logged below, not surfaced further
          wbuf.GetRemaining(body);
          if(warn_count>0)
             PrintFormat("CqlConnection: RecvFrame accepted a response carrying %d server warning(s)",warn_count);
        }
      opcode_out=hdr.opcode;
      ArrayCopy(body_out,body);
      return(true);
     }
   return(false);                            // unreachable: every real path above already returns or continues; kept only because MQL5 requires an explicit return after while(true)
  }


CqlClient.mqh: Statement-Level Operations and BATCH

Three small value-builder functions sit above SCqlValue, one per CQL column type the schema uses. Each wraps a CCqlBuffer encoder call and hands back a struct with no type id attached — the server already knows each bound column's type from the prepared statement, so the client only has to supply correctly-encoded bytes.

//+------------------------------------------------------------------+
//| SCqlValue                                                        |
//| One bound parameter for EXECUTE/BATCH: either NULL, or           |
//| already-encoded big-endian bytes (via CqlBigInt/CqlDouble/       |
//| CqlText below) ready to be wrapped in a [value] length prefix.   |
//| [value] is protocol section 3's name for a bound parameter --    |
//| on the wire it is the same [int] length + bytes shape as         |
//| [bytes] (and this project writes it with the same WriteBytes()/  |
//| -1 pair for that reason), except [value] also allows a -2        |
//| length meaning NOT_SET, which this struct's is_null flag never   |
//| needs since every column here is always bound. This struct       |
//| carries no type id -- the server already knows each column's     |
//| type from the prepared statement, so the client only has to      |
//| supply bytes in the right encoding, not redeclare the type on    |
//| every call.                                                      |
//+------------------------------------------------------------------+
struct SCqlValue
  {
   bool              is_null;
   uchar             data[];
  };

//+------------------------------------------------------------------+
//| CqlBigInt                                                        |
//| Builds a bound bigint parameter -- used for this project's       |
//| millisecond epoch timestamp column, reusing CCqlBuffer's own     |
//| WriteLong() rather than re-implementing the 8-byte big-endian    |
//| encoding here.                                                   |
//+------------------------------------------------------------------+
SCqlValue CqlBigInt(const long v)
  {
   SCqlValue r;
   r.is_null=false;
   CCqlBuffer b;
   b.WriteLong(v);
   b.GetBytes(r.data);
   return(r);
  }

//+------------------------------------------------------------------+
//| CqlDouble                                                        |
//| Builds a bound double parameter -- used for every price/         |
//| volatility feature column -- via CCqlBuffer's WriteDouble(),     |
//| which does the union bit-reinterpretation; nothing here          |
//| converts the number itself.                                      |
//+------------------------------------------------------------------+
SCqlValue CqlDouble(const double v)
  {
   SCqlValue r;
   r.is_null=false;
   CCqlBuffer b;
   b.WriteDouble(v);
   b.GetBytes(r.data);
   return(r);
  }

//+------------------------------------------------------------------+
//| CqlText                                                          |
//| Builds a bound text parameter -- used for the symbol and         |
//| day_bucket columns -- as raw UTF-8 bytes with no length          |
//| prefix inside r.data; the [value] length prefix itself is        |
//| added later by WriteQueryParams()/Batch() when the value is      |
//| actually written to the wire, not here.                          |
//+------------------------------------------------------------------+
SCqlValue CqlText(const string v)
  {
   SCqlValue r;
   r.is_null=false;
   uchar utf8[];
   int n=StringToCharArray(v,utf8,0,WHOLE_ARRAY,CP_UTF8)-1;
   if(n<0) n=0;
   ArrayResize(utf8,n);
   ArrayCopy(r.data,utf8);
   return(r);
  }

//+------------------------------------------------------------------+
//| CqlNullValue                                                     |
//| Builds an explicit NULL parameter. Nothing in                    |
//| TickFeatureArchiver_EA.mq5's INSERT currently binds a NULL --    |
//| every one of its 9 columns is always computed -- but             |
//| Cql_SelfTest.mq5 or a future caller may need one, and            |
//| WriteQueryParams()/Batch() already special-case is_null, so      |
//| this builder exists to make that path reachable without a        |
//| caller hand-rolling the is_null=true/empty-data pattern itself.  |
//+------------------------------------------------------------------+
SCqlValue CqlNullValue(void)
  {
   SCqlValue r;
   r.is_null=true;
   ArrayResize(r.data,0);
   return(r);
  }

CCqlClient builds on CCqlConnection to add the three statement-level operations this project needs: ad-hoc Query() for DDL and the self-test's verification SELECTs, Prepare()/ExecutePrepared() for a single bound statement, and Batch() for the archiver's throughput path. Its scope is deliberately narrow: no result paging, no serial consistency or lightweight transactions, no query tracing, and BATCH is always built as UNLOGGED with every statement bound to the same prepared id — the shape the archiver actually uses, not a general multi-statement batch builder.

//+------------------------------------------------------------------+
//| CCqlClient                                                       |
//| Builds on CCqlConnection to add the three statement-level        |
//| operations this project needs: ad-hoc Query() (used for DDL      |
//| and the self-test's verification SELECTs), Prepare()+Execute()   |
//| for a single bound statement, and Batch() for the archiver's     |
//| throughput path. Scope is deliberately narrow and stated here    |
//| plainly rather than implied by what compiles: no paging          |
//| (a result with more rows than fit one page is not handled --     |
//| every query this project issues returns a small, bounded row     |
//| count), no serial consistency / lightweight transactions, no     |
//| query tracing, and BATCH is only ever built as UNLOGGED with     |
//| every statement bound to the same prepared id, which is the      |
//| shape the archiver actually uses (many rows, one INSERT          |
//| statement) -- not a general multi-statement batch builder.       |
//+------------------------------------------------------------------+
class CCqlClient
  {
private:
   CCqlConnection    m_conn;
   string            m_host;          // remembered from Connect(), used again by Reconnect()
   int               m_port;
   int               m_timeout_ms;
   string            m_username;
   string            m_password;
   bool              SendAndReceive(const uchar opcode,const uchar &body[],
                                     uchar &reply_opcode,uchar &reply_body[]);
   void              WriteQueryParams(CCqlBuffer &buf,const ushort consistency,
                                       const SCqlValue &values[],const int count);
public:
   bool              Connect(const string host,const int port,const int timeout_ms,
                              const string username,const string password);
   bool              Reconnect(void);
   void              Close(void) { m_conn.Close(); }
   bool              IsConnected(void) const { return(m_conn.IsConnected()); }
   bool              Query(const string cql,const ushort consistency,
                            uchar &result_kind_out,uchar &result_body_out[]);
   bool              Prepare(const string cql,uchar &prepared_id_out[]);
   bool              ExecutePrepared(const uchar &prepared_id[],const SCqlValue &values[],
                                      const ushort consistency,
                                      uchar &result_kind_out,uchar &result_body_out[]);
   bool              Batch(const uchar &prepared_id[],const SCqlValue &flat_values[],
                            const int values_per_row,const int row_count,
                            const ushort consistency);
  };

Connect runs the handshake in order — transport connect, STARTUP, and Authenticate() only if required — and remembers the five connection parameters so Reconnect() below can repeat it later without the caller supplying them again.

//+------------------------------------------------------------------+
//| CCqlClient::Connect                                              |
//| Runs the handshake in order: transport connect, STARTUP, and     |
//| -- only if the node's STARTUP reply said so -- Authenticate().   |
//| A stock Cassandra Docker image with no extra configuration       |
//| runs AllowAllAuthenticator and answers STARTUP with READY, in    |
//| which case Authenticate() is skipped entirely; a node running    |
//| PasswordAuthenticator answers with AUTHENTICATE instead, and     |
//| this function then sends the SASL PLAIN exchange Authenticate()  |
//| implements -- a mechanism that needs an AUTH_CHALLENGE round     |
//| trip rather than one AUTH_RESPONSE is not handled here. Calling  |
//| Authenticate() unconditionally would send an AUTH_RESPONSE a     |
//| READY node never asked for and never replies to, hanging the     |
//| handshake -- so which path runs is decided from Startup()'s own  |
//| auth_required_out, never assumed. The five arguments are also    |
//| saved into m_host/m_port/m_timeout_ms/m_username/m_password so   |
//| a later Reconnect() can repeat exactly this same handshake       |
//| without the caller supplying them again.                         |
//+------------------------------------------------------------------+
bool CCqlClient::Connect(const string host,const int port,const int timeout_ms,
                          const string username,const string password)
  {
   m_host=host;
   m_port=port;
   m_timeout_ms=timeout_ms;
   m_username=username;
   m_password=password;
   if(!m_conn.Connect(host,port,timeout_ms))
      return(false);
   bool auth_required=false;
   if(!m_conn.Startup(auth_required))
     {
      m_conn.Close();
      return(false);
     }
   if(auth_required && !m_conn.Authenticate(username,password))
     {
      m_conn.Close();
      return(false);
     }
   return(true);
  }

Reconnect closes whatever is left of the current connection and runs Connect() again with the remembered parameters; a prepared id from before the reconnect is not reused, so the caller must re-Prepare() afterward.

//+------------------------------------------------------------------+
//| CCqlClient::Reconnect                                            |
//| Closes whatever is left of the current (possibly already-        |
//| dead) connection and runs the full Connect() handshake again     |
//| with the parameters remembered from the original call. This      |
//| exists because the MT5 terminal can invalidate an EA's socket    |
//| handle around OnDeinit, independent of how healthy the           |
//| connection was a moment before: SocketSend fails with            |
//| ERR_NETSOCKET_INVALIDHANDLE (error 5270) on EA removal, a        |
//| real, reproducible terminal behavior, not a hypothetical edge    |
//| case, so FlushBuffer() in TickFeatureArchiver_EA.mq5 calls this  |
//| and retries once rather than giving up on the first failure. A   |
//| prepared statement id from before the reconnect is NOT reused    |
//| across it: the caller must re-Prepare() after a successful       |
//| Reconnect(), since a fresh connection is not guaranteed to       |
//| recognize an id prepared on the old one.                         |
//+------------------------------------------------------------------+
bool CCqlClient::Reconnect(void)
  {
   m_conn.Close();
   return(Connect(m_host,m_port,m_timeout_ms,m_username,m_password));
  }

Batch builds one BATCH frame carrying row_count statements, every one the same prepared id with its own values_per_row-wide slice of a flattened parameter array — row r's column c lives at flat_values[r*values_per_row+c], since MQL5 has no native jagged-array parameter type and the 2D shape has to be passed flat. The batch type byte is always 0x01 (UNLOGGED), since every row this project batches targets the same partition key — exactly the case Cassandra's own documentation recommends UNLOGGED batching for; a LOGGED batch's extra atomicity guarantee is not needed here, and this method offers no guard against a caller passing rows that span more than one partition, which is the one misuse it does not protect against on its own.

Beyond the row-count check, the fully-serialized frame is also checked against CQL_BATCH_MAX_BYTES before it is sent, since a row count comfortably under 65535 can still serialize to something Cassandra's own batch_size_fail_threshold_in_kb will refuse outright — the row-count limit is the protocol's own ceiling, not a guarantee the server will accept the batch.

//+------------------------------------------------------------------+
//| CQL_BATCH_MAX_BYTES                                              |
//| Caps the serialized BATCH frame this client will send,           |
//| matching Cassandra's own default batch_size_fail_threshold_in_kb |
//| (50 KiB), so an oversized batch is rejected locally, with a      |
//| diagnostic, rather than round-tripping to the node only to be    |
//| refused there.                                                   |
//+------------------------------------------------------------------+
#define CQL_BATCH_MAX_BYTES  (50*1024)
//+------------------------------------------------------------------+
//| CCqlClient::Batch                                                |
//| Builds one BATCH frame (protocol section 4.1.7) of row_count     |
//| statements, every one the same prepared_id with its own          |
//| values_per_row-wide slice of the flattened flat_values array     |
//| (row r's column c is flat_values[r*values_per_row+c] -- MQL5     |
//| has no native jagged-array parameter type, so the 2D shape is    |
//| passed flat rather than as an array of arrays). Rejects up       |
//| front, before writing anything to the wire, a row_count          |
//| outside 1..65535 (the field is written as a ushort), a           |
//| flat_values array too short for row_count*values_per_row, or     |
//| a fully-serialized frame over CQL_BATCH_MAX_BYTES. Always        |
//| built as UNLOGGED (batch type 1): every row in this project's    |
//| batch targets the same partition key (symbol+day bucket, see     |
//| setup.cql), which is exactly the case Cassandra's own docs       |
//| recommend UNLOGGED batching for; LOGGED batches (which add an    |
//| atomicity guarantee across the whole batch via a batchlog)       |
//| are not used here and a multi-partition UNLOGGED batch --        |
//| those same docs warn increases coordinator load with no          |
//| atomicity benefit -- is not something this method should be      |
//| pointed at either, since it offers no guard against the          |
//| caller passing rows for more than one partition.                 |
//+------------------------------------------------------------------+
bool CCqlClient::Batch(const uchar &prepared_id[],const SCqlValue &flat_values[],
                        const int values_per_row,const int row_count,
                        const ushort consistency)
  {
   if(row_count<=0 || row_count>65535)
     {
      PrintFormat("CqlClient: Batch row_count %d is out of range, must be 1..65535",row_count);
      return(false);
     }
   if(ArraySize(flat_values)<row_count*values_per_row)
     {
      PrintFormat("CqlClient: Batch flat_values has %d elements, need at least %d for row_count=%d, values_per_row=%d",
                    ArraySize(flat_values),row_count*values_per_row,row_count,values_per_row);
      return(false);
     }
   CCqlBuffer req;
   req.WriteByte(0x01);                      // batch type: UNLOGGED
   req.WriteShort((ushort)row_count);
   for(int r=0;r<row_count;r++)
     {
      req.WriteByte(0x01);                  // statement kind: prepared id follows
      req.WriteShortBytes(prepared_id);
      req.WriteShort((ushort)values_per_row);
      for(int c=0;c<values_per_row;c++)
        {
         int idx=r*values_per_row+c;
         if(flat_values[idx].is_null)
            req.WriteInt(-1);
         else
            req.WriteBytes(flat_values[idx].data);
        }
     }
   req.WriteConsistency(consistency);
   req.WriteByte(0x00);                      // no further BATCH-level flags
   uchar wire[];
   req.GetBytes(wire);
   if(ArraySize(wire)>CQL_BATCH_MAX_BYTES)
     {
      PrintFormat("CqlClient: Batch serialized frame is %d bytes, over the %d-byte safety cap -- refusing to send it; use fewer rows per batch",
                    ArraySize(wire),CQL_BATCH_MAX_BYTES);
      return(false);
     }
   uchar reply_opcode,reply_body[];
   return(SendAndReceive(CQL_OP_BATCH,wire,reply_opcode,reply_body));
  }


TickFeatureArchiver_EA.mq5: Per-Tick Capture and Batched Flush

The EA's two flush triggers are independent and whichever fires first empties the buffer: a tick-count trigger (InpFlushTicks) and a time trigger (InpFlushMs), checked separately because a pure tick-count trigger would stall indefinitely during a quiet market, while a pure time trigger would send tiny, inefficient batches during a fast one.

//+------------------------------------------------------------------+
//| Inputs                                                           |
//| InpFlushTicks and InpFlushMs are the two independent flush       |
//| triggers: whichever fires first empties the buffer. A pure       |
//| tick-count trigger would stall during a quiet market (rows       |
//| sit unflushed indefinitely); a pure time trigger would send      |
//| tiny, inefficient batches during a fast one -- the pair covers   |
//| both. InpVolWindow sets how many trailing log-returns            |
//| realized_vol is computed over.                                   |
//+------------------------------------------------------------------+
input string   InpHost            = "127.0.0.1";     // Cassandra node host
input int      InpPort            = 9042;            // Cassandra native protocol port
input string   InpUsername        = "cassandra";     // SASL PLAIN username
input string   InpPassword        = "cassandra";     // SASL PLAIN password
input string   InpKeyspace        = "tick_features"; // Target keyspace (see setup.cql)
input int      InpFlushTicks      = 200;             // Flush after this many buffered rows
input int      InpFlushMs         = 2000;            // ...or after this many ms, whichever first
input int      InpVolWindow       = 20;              // Rolling window (ticks) for realized_vol
input int      InpSocketTimeoutMs = 5000;            // Socket connect/read timeout

// Backlog limits, independent of the per-tick inputs above: TFA_FLUSH_CHUNK_ROWS bounds every
// individual BATCH call FlushBuffer() makes while draining a backlog, and TFA_BACKLOG_ROWS_MAX
// bounds the backlog itself during a prolonged outage, trading the oldest unsent rows for a hard
// ceiling on memory rather than growing g_rows without limit. TFA_FLUSH_CHUNK_ROWS is sized against
// CQL_BATCH_MAX_BYTES, not just Batch()'s 65535-row protocol ceiling: each row's nine [value]-
// encoded columns (symbol, day_bucket, ts, seq, and five doubles), plus the per-row prepared-id framing,
// run to roughly 140-175 bytes on the wire, so a row count anywhere near the protocol ceiling would
// serialize to several times CQL_BATCH_MAX_BYTES and never be sendable at all. 250 rows stays well
// under CQL_BATCH_MAX_BYTES even at the high end of that per-row estimate, so every chunk Batch()
// is asked to build is one it can actually accept, and a backlog drain is never stalled by its own
// chunk being oversized once the connection itself is healthy.
#define TFA_FLUSH_CHUNK_ROWS   250
#define TFA_BACKLOG_ROWS_MAX  20000

None of these defaults were tuned from a search over a range — they're engineering starting points sized for a single chart:

Setting Purpose and basis
InpFlushTicks, InpFlushMs Two independent send conditions — row count and wait time — so a quiet market doesn't stall and a fast one doesn't send tiny batches.
InpVolWindow A window measured in ticks, not time — tick arrival rate depends on the feed, not on the chart's own timeframe.
InpSocketTimeoutMs Generous default for a local/same-datacenter connection; raise it over a slower link.
CQL_CONSISTENCY_LOCAL_QUORUM Trivially satisfied by the single-node deployment this project tested; revisit against replication factor on a multi-node cluster.

The trade-off is the same throughout: a smaller flush threshold lowers latency and batch size at the cost of more round trips, while a larger one does the reverse and risks a bigger loss window on failure; the single reconnect retry is sized the same way, and a longer expected outage should raise the retry count, accepting a longer delay before a real outage is reported upward.

TFA_FLUSH_CHUNK_ROWS and TFA_BACKLOG_ROWS_MAX answer a different question from the two flush triggers above: not when to flush, but how to behave once a flush has already failed and rows keep piling up. During a prolonged outage FlushBuffer() drains the backlog in chunks of at most TFA_FLUSH_CHUNK_ROWS rows rather than as one oversized BATCH; 250 is sized so a chunk's worst-case serialized footprint stays under the CQL_BATCH_MAX_BYTES cap, since nothing in FlushBuffer() shrinks a chunk that Batch() rejects as oversized — it only retries the same chunk once after a reconnect, which doesn't help when the chunk itself, not the connection, is the problem.

OnTick() enforces TFA_BACKLOG_ROWS_MAX as a hard ceiling on g_rows: once the backlog reaches that many unflushed rows, the oldest buffered row is dropped to make room for the newest one, with a diagnostic logged each time. This is a deliberate, bounded data-loss point — the alternative is letting g_rows grow without limit for as long as the outage lasts, risking an eventual out-of-memory failure that would lose everything, including the newest rows, instead of just the oldest ones.

Each buffered observation is one SFeatureRow — a plain data carrier with no methods, so it gets one header box for the whole struct, with field purposes documented inline instead.

//+------------------------------------------------------------------+
//| SFeatureRow                                                      |
//| One buffered, not-yet-flushed tick-feature observation. A        |
//| plain data carrier -- no methods, so per the project's class-    |
//| commenting convention this gets one header box for the whole     |
//| declaration rather than per-field boxes; field purposes are      |
//| documented with the trailing inline comments below instead.      |
//+------------------------------------------------------------------+
struct SFeatureRow
  {
   long              ts;            // milliseconds since epoch (TimeGMT-based)
   long              seq;            // tie-breaker for ticks sharing the same ts; set once in OnTick()
   double            bid;           // best bid at the tick
   double            ask;           // best ask at the tick
   double            spread;        // ask-bid at the tick, in price terms
   double            vol_delta;     // signed tick-volume change since the previous tick
   double            realized_vol;  // rolling stdev of the last InpVolWindow log-returns
  };

Every global below is owned by this one EA instance — no multi-symbol or multi-chart sharing. g_last_volume is declared ulong, matching MqlTick.volume exactly, so OnTick's vol_delta computation casts both operands to double before subtracting, not after: an unsigned ulong difference wraps to a huge positive value the moment volume decreases tick to tick, which a cast applied afterward can't undo.

//+------------------------------------------------------------------+
//| Globals                                                          |
//| Connection/statement state (g_client, g_insert_cql,              |
//| g_prepared_id), the unflushed row buffer (g_rows) and its flush  |
//| clock (g_last_flush_ms), and the per-tick running state OnTick() |
//| needs to compute vol_delta, realized_vol and seq incrementally   |
//| rather than rescanning history every tick. g_last_volume is      |
//| ulong, matching MqlTick.volume exactly, so the vol_delta         |
//| subtraction below must cast both sides to a signed type before   |
//| subtracting -- a plain ulong-ulong difference wraps to a huge    |
//| positive value the instant volume decreases tick to tick, rather |
//| than producing the negative delta the column is supposed to hold.|
//| g_next_seq is a plain, ever-increasing counter handed out once   |
//| per row in OnTick(), whose only job is to be distinct per row,   |
//| not to encode anything meaningful.                               |
//+------------------------------------------------------------------+
  bool            g_have_last_tick;   // false until OnTick's first real observation
  double          g_last_mid;         // (bid+ask)/2 from the previous tick, for log-return
  ulong           g_last_volume;      // previous tick's volume -- ulong, matches MqlTick.volume
  double          g_returns[];        // rolling log-return ring buffer, sized InpVolWindow in OnInit
  int             g_returns_pos;      // next write position in the ring buffer
  int             g_returns_filled;   // how many slots hold real data vs still zero-initialized
  long             g_next_seq;        // monotonic counter; next row's seq (see setup.cql)
  SFeatureRow     g_rows[];           // unflushed buffer; FlushBuffer() empties it on a trigger
  uint            g_last_flush_ms;    // GetTickCount() at the last successful flush
  CCqlClient      g_client;           // the one connection this EA owns
  string          g_insert_cql;       // the INSERT text, prepared once in OnInit
  uchar           g_prepared_id[];    // statement id PREPARE returned, reused by every EXECUTE/BATCH

OnInit connects, validates the three inputs that feed array and batch sizing, and prepares the INSERT once so OnTick never re-parses CQL text on the hot path — its 9-column order must match setup.cql's column order and Batch()'s values_per_row=9 exactly, since CQL binds positionally by ? order, not by name.

//+------------------------------------------------------------------+
//| OnInit                                                           |
//| Validates InpVolWindow, InpFlushTicks and InpFlushMs before      |
//| touching any of them -- an unchecked value here would otherwise  |
//| reach ArrayResize()/the modulo in OnTick's rolling-return buffer,|
//| or let a single BATCH grow past a sane row count, with no        |
//| diagnostic at all. Connects, runs the handshake, and prepares the|
//| INSERT once so OnTick never re-parses CQL text. The 9-column     |
//| order here must match setup.cql's feature_ticks column order and |
//| Batch()'s values_per_row=9 in FlushBuffer() exactly -- CQL binds |
//| positionally by '?' order, not by name, so a mismatch here would |
//| silently write values into the wrong columns rather than fail at |
//| prepare time.                                                    |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   if(InpVolWindow<=0 || InpVolWindow>100000)
     {
      PrintFormat("TickFeatureArchiver: InpVolWindow must be a positive integer, got %d",InpVolWindow);
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpFlushTicks<=0 || InpFlushTicks>5000)
     {
      PrintFormat("TickFeatureArchiver: InpFlushTicks must be a positive integer, no larger than 5000, got %d",InpFlushTicks);
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(InpFlushMs<=0)
     {
      PrintFormat("TickFeatureArchiver: InpFlushMs must be a positive integer, got %d",InpFlushMs);
      return(INIT_PARAMETERS_INCORRECT);
     }
   ArrayResize(g_returns,InpVolWindow);
   ArrayInitialize(g_returns,0.0);
   if(!g_client.Connect(InpHost,InpPort,InpSocketTimeoutMs,InpUsername,InpPassword))
     {
      Print("TickFeatureArchiver: failed to connect/authenticate to Cassandra");
      return(INIT_FAILED);
     }
   g_insert_cql=StringFormat(
      "INSERT INTO %s.feature_ticks (symbol, day_bucket, ts, seq, bid, ask, spread, vol_delta, realized_vol) "
      "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",InpKeyspace);
   if(!g_client.Prepare(g_insert_cql,g_prepared_id))
     {
      Print("TickFeatureArchiver: PREPARE failed, is setup.cql applied to this keyspace?");
      g_client.Close();
      return(INIT_FAILED);
     }
   g_last_flush_ms=GetTickCount();
   EventSetMillisecondTimer(MathMax(250,InpFlushMs/4));  // polls for the time-based trigger
   PrintFormat("TickFeatureArchiver: connected, prepared, archiving %s",_Symbol);
   return(INIT_SUCCEEDED);
  }

OnTick computes one feature row (bid, ask, spread, vol_delta, realized_vol), assigns it a seq from a plain monotonic counter, and appends it to the buffer before checking the tick-count flush trigger — the time trigger runs separately in OnTimer, since OnTick never fires during a quiet market. seq is set exactly once per row, here, so a reconnect-and-retry in FlushBuffer() resends the identical value, which is what keeps two ticks sharing one millisecond ts landing as two distinct rows instead of one overwriting the other. Worth flagging: MetaTrader 5 doesn't guarantee a distinct OnTick call for every real incoming tick, so the buffer holds everything OnTick was invoked for, not a provably complete capture of the tick stream (more on this in Limitations):

//+------------------------------------------------------------------+
//| OnTick                                                           |
//| Computes one feature row from the current tick and appends it to |
//| g_rows, then checks the tick-count flush trigger. seq is assigned|
//| here, once, from a simple monotonic counter, so a row keeps the  |
//| same seq through any later reconnect-and-retry of the chunk it   |
//| ends up in (FlushBuffer() resends the same SFeatureRow values on |
//| a retry, never rebuilding them) -- this is what lets two ticks   |
//| sharing one millisecond ts still land as two distinct rows       |
//| instead of one overwriting the other (see setup.cql). The        |
//| time-based trigger is checked in OnTimer() instead of here, since|
//| OnTick does not fire at all during a quiet market -- exactly the |
//| case the time trigger exists to cover. Before appending, enforces|
//| TFA_BACKLOG_ROWS_MAX: once the backlog is at that many rows, the |
//| oldest one is dropped to make room, with a diagnostic, rather    |
//| than letting the buffer grow without limit for as long as the    |
//| outage behind it lasts. Note this only ever runs when MT5        |
//| actually calls OnTick for a new tick -- the terminal does not    |
//| guarantee a distinct OnTick call for every real incoming tick,   |
//| and will not queue one behind a call still blocked in a          |
//| synchronous socket round trip, so this buffer is everything      |
//| OnTick was invoked for, not a provably complete capture of the   |
//| symbol's whole tick stream (see the article's Limitations        |
//| section).                                                        |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   MqlTick tick;
   if(!SymbolInfoTick(_Symbol,tick))
      return;
   SFeatureRow row;
   row.ts=(long)tick.time_msc;
   row.seq=g_next_seq++;
   row.bid=tick.bid;
   row.ask=tick.ask;
   row.spread=tick.ask-tick.bid;
   double mid=(tick.bid+tick.ask)/2.0;
   if(g_have_last_tick)
     {
      row.vol_delta=(double)tick.volume-(double)g_last_volume;  // cast before subtracting: ulong-ulong wraps on a decrease
      if(g_last_mid>0.0)
        {
         double log_return=MathLog(mid/g_last_mid);
         g_returns[g_returns_pos]=log_return;
         g_returns_pos=(g_returns_pos+1)%InpVolWindow;
         if(g_returns_filled<InpVolWindow)
            g_returns_filled++;
        }
     }
   else
     {
      row.vol_delta=0.0;                    // no previous tick to diff against yet
      g_have_last_tick=true;
     }
   row.realized_vol=ComputeRealizedVol();
   g_last_mid=mid;
   g_last_volume=tick.volume;
   int n=ArraySize(g_rows);
   if(n>=TFA_BACKLOG_ROWS_MAX)
     {
      for(int i=0;i<n-1;i++)
        g_rows[i]=g_rows[i+1];
      n--;
      PrintFormat("TickFeatureArchiver: backlog hit the %d-row cap, dropping the oldest buffered row to bound memory during a prolonged outage",TFA_BACKLOG_ROWS_MAX);
     }
   ArrayResize(g_rows,n+1);
   g_rows[n]=row;
   if(ArraySize(g_rows)>=InpFlushTicks)
      FlushBuffer();
  }

BuildDayBucket formats the (symbol, day_bucket) partition tag from a single row's own timestamp — it is called once per row, not once per chunk, so every row always gets its own correct calendar date; FlushBuffer() below is the piece that keeps a chunk from ever actually needing two different buckets.

//+------------------------------------------------------------------+
//| BuildDayBucket                                                   |
//| Formats one partitioning tag ('YYYY.MM.DD') from a millisecond   |
//| epoch timestamp. Called once per row, from that row's own ts --  |
//| not once per chunk -- so every row always gets its own correct   |
//| calendar date. FlushBuffer() separately groups rows into chunks  |
//| that never cross a day_bucket change in the first place, so in   |
//| practice every row inside one chunk still resolves to the same   |
//| string here, which is what keeps a single Batch() call always    |
//| targeting one partition (see setup.cql).                         |
//+------------------------------------------------------------------+
string BuildDayBucket(const long ts_msc)
  {
   datetime dt=(datetime)(ts_msc/1000);
   return(TimeToString(dt,TIME_DATE));
  }

FlushBuffer is the EA's write path: it drains the buffer in chunks of at most TFA_FLUSH_CHUNK_ROWS rows, stopping a chunk early the instant the next row's BuildDayBucket() would differ from the chunk's own — so a chunk can come out smaller right around a real UTC midnight, but every row inside it always shares one day_bucket and therefore one partition. Each chunk goes out as its own UNLOGGED batch; on failure it reconnects, re-Prepare()s, and retries that one chunk with the identical flattened values (seq included), leaving it and everything behind it buffered for the next trigger if the retry fails too.

//+------------------------------------------------------------------+
//| FlushBuffer                                                      |
//| Flattens g_rows into the (symbol, day_bucket, ts, seq, bid, ask, |
//| spread, vol_delta, realized_vol) column order Prepare()'s INSERT |
//| expects and drains it in chunks of at most TFA_FLUSH_CHUNK_ROWS  |
//| rows per BATCH call -- and ALSO stops a chunk early the moment   |
//| the next row's BuildDayBucket() would differ from the chunk's, so|
//| a chunk can end up smaller than TFA_FLUSH_CHUNK_ROWS right around|
//| a real UTC midnight, but every row inside it always shares one   |
//| day_bucket and therefore one partition, matching setup.cql's     |
//| (symbol, day_bucket) partition key. After a prolonged outage the |
//| backlog can be far larger than any single sane BATCH, and        |
//| resending it whole would just repeat the same row_count/byte-size|
//| rejection on every retry, which the row-count half of the chunk  |
//| cap exists to avoid. Each chunk that succeeds is dropped from the|
//| front of g_rows immediately, so a failure partway through a drain|
//| still keeps everything already flushed off the buffer. On a chunk|
//| failure this attempts one reconnect-and-retry before giving up on|
//| that chunk: the MT5 terminal can invalidate the EA's socket      |
//| handle around OnDeinit independent of how healthy the connection |
//| was moments before (ERR_NETSOCKET_INVALIDHANDLE, error 5270), a  |
//| real, reproducible terminal behavior rather than a hypothetical  |
//| edge case. A reconnect gets a new socket, so the chunk is retried|
//| against that, but the old g_prepared_id is not assumed valid on  |
//| it -- INSERT is re-Prepare()'d first. The retried chunk reuses   |
//| the exact same flat[] values built below, seq included, so a     |
//| retry upserts the same rows rather than minting new ones. If the |
//| retry still fails (a real outage, not a removal-time race),      |
//| draining stops there and that chunk plus everything still behind |
//| it is left buffered for the next trigger, rather than silently   |
//| dropping the rows; only a second, un-retriable failure during    |
//| OnDeinit's own final flush call can still lose what is buffered  |
//| at that instant, which is the one scenario no amount of          |
//| in-process retrying can fully close.                             |
//+------------------------------------------------------------------+
void FlushBuffer(void)
  {
   int total=ArraySize(g_rows);
   if(total==0)
    return;
   int sent=0;
   while(sent<total)
    {
      string bucket=BuildDayBucket(g_rows[sent].ts);
      int max_chunk=MathMin(TFA_FLUSH_CHUNK_ROWS,total-sent);
      int chunk=1;
      while(chunk<max_chunk && BuildDayBucket(g_rows[sent+chunk].ts)==bucket)
        chunk++;
      SCqlValue flat[];
      ArrayResize(flat,chunk*9);
      for(int r=0;r<chunk;r++)
        {
          int row_idx=sent+r;
          int base=r*9;
          flat[base+0]=CqlText(_Symbol);
          flat[base+1]=CqlText(BuildDayBucket(g_rows[row_idx].ts));  // each row's own bucket -- always 'bucket' by the grouping above
          flat[base+2]=CqlBigInt(g_rows[row_idx].ts);
          flat[base+3]=CqlBigInt(g_rows[row_idx].seq);
          flat[base+4]=CqlDouble(g_rows[row_idx].bid);
          flat[base+5]=CqlDouble(g_rows[row_idx].ask);
          flat[base+6]=CqlDouble(g_rows[row_idx].spread);
          flat[base+7]=CqlDouble(g_rows[row_idx].vol_delta);
          flat[base+8]=CqlDouble(g_rows[row_idx].realized_vol);
        }
      bool ok=g_client.Batch(g_prepared_id,flat,9,chunk,CQL_CONSISTENCY_LOCAL_QUORUM);
      if(!ok)
        {
          PrintFormat("TickFeatureArchiver: batch of %d rows failed, attempting reconnect",chunk);
          ok=(g_client.Reconnect() && g_client.Prepare(g_insert_cql,g_prepared_id) &&
              g_client.Batch(g_prepared_id,flat,9,chunk,CQL_CONSISTENCY_LOCAL_QUORUM));
          if(ok)
            Print("TickFeatureArchiver: reconnect succeeded, batch retried and flushed");
        }
      if(!ok)
        {
          PrintFormat("TickFeatureArchiver: reconnect-and-retry also failed, %d of %d buffered rows remain unflushed",
                          total-sent,total);
        break;
      }
      sent+=chunk;
    }
   if(sent>0)
    {
      int remaining=total-sent;
      for(int i=0;i<remaining;i++)
        g_rows[i]=g_rows[sent+i];
      ArrayResize(g_rows,remaining);
      g_last_flush_ms=GetTickCount();
    }
  }

The one failure this retry logic cannot close is a second, un-retriable failure during OnDeinit's own final flush call, since no further trigger runs after that.


Cql_SelfTest.mq5: Verifying the Stack Against a Real Node

Sockets do not run inside the Strategy Tester, so this script is the only way to exercise the full stack end to end: it connects, applies DDL, runs three single-row ExecutePrepared calls, runs one six-row Batch — two of those six rows deliberately share one ts with distinct seq values, exercising the duplicate-timestamp fix as a real round trip — then SELECTs the whole partition back to verify row count, clustering order, the seq tie-breaker, and value round-trip, and finally sends two more Batch calls tagged to two different day_bucket values and reads each partition back on its own, confirming FlushBuffer()'s one-partition-per-chunk split against a real node rather than only against the in-process loop. All of it runs against whatever real Cassandra node InpHost points at, never simulated.

//+------------------------------------------------------------------+
//| Check                                                            |
//| Logs one PASS/FAIL line and updates the tally -- every           |
//| verification in OnStart() goes through this instead of a raw     |
//| Print(), so the final summary count is never out of sync with    |
//| what was actually checked.                                       |
//+------------------------------------------------------------------+
void Check(const string label,const bool condition)
  {
   g_checks_run++;
   if(condition)
     {
      g_checks_passed++;
      PrintFormat("[PASS] %s",label);
     }
   else
      PrintFormat("[FAIL] %s",label);
  }

ParseRowsMetadata walks a ROWS result's <metadata> block far enough to reach the row data — result flags, column count, an optional paging state, then each column's name and type id — handling only the simple, non-collection type ids this schema's text/bigint/double columns actually need.

//+------------------------------------------------------------------+
//| ParseRowsMetadata                                                |
//| Walks a ROWS result's <metadata> block (protocol section         |
//| 4.2.5.2) far enough to reach the row data: result flags,         |
//| column count, an optional paging_state (read and discarded --    |
//| this project never requests a second page, matching the no-      |
//| paging scope stated on CCqlClient), then each column's           |
//| keyspace/table/name/type-id. Only simple, non-collection type    |
//| ids are handled -- every column this project's schema defines    |
//| is text/bigint/double, none of which carry extra option bytes    |
//| after the [short] type id, so that is the only shape this        |
//| parser needs to support.                                         |
//+------------------------------------------------------------------+
bool ParseRowsMetadata(CCqlBuffer &buf,int &columns_count_out)
  {
   int flags=buf.ReadInt();
   columns_count_out=buf.ReadInt();
   bool global_spec=((flags&0x0001)!=0);
   if((flags&0x0002)!=0)
     {
      uchar paging_state[];
      buf.ReadBytes(paging_state);          // discarded: this project never pages
     }
   if((flags&0x0004)!=0)
      return(true);                          // NO_METADATA flag: no column specs follow
   if(global_spec)
     {
      buf.ReadString();                      // shared keyspace name
      buf.ReadString();                      // shared table name
     }
   for(int i=0;i<columns_count_out;i++)
     {
      if(!global_spec)
        {
         buf.ReadString();                  // per-column keyspace name
         buf.ReadString();                  // per-column table name
        }
      buf.ReadString();                      // column name
      buf.ReadShort();                      // [option] type id, simple types only
     }
   return(true);
  }

The six-row BATCH exercises the exact same code path FlushBuffer() uses, with fixed test values instead of live ticks; rows 0 and 1 share ts=4000 with distinct seq values (10 and 11), so the duplicate-timestamp fix gets a real round trip through BATCH and back out through SELECT:

   //--- 6 BATCH rows, not 5: rows 0 and 1 deliberately share ts=4000 with
   //--- distinct seq values (10 and 11), to prove two ticks landing on the
   //--- same millisecond no longer overwrite one another now that seq is
   //--- part of the clustering key.
   long batch_ts[6] ={4000,4000,5000,6000,7000,8000};
   long batch_seq[6]={10,  11,  12,  13,  14,  15};
   SCqlValue flat[54];
   for(int i=0;i<6;i++)
     {
      int base=i*9;
      flat[base+0]=CqlText(test_symbol);
      flat[base+1]=CqlText(test_bucket);
      flat[base+2]=CqlBigInt(batch_ts[i]);
      flat[base+3]=CqlBigInt(batch_seq[i]);
      flat[base+4]=CqlDouble(1.2000+i*0.0001);
      flat[base+5]=CqlDouble(1.2003+i*0.0001);
      flat[base+6]=CqlDouble(0.0003);
      flat[base+7]=CqlDouble((double)(-5-i));
      flat[base+8]=CqlDouble(0.00004+i*0.00001);
     }
   Check("BATCH of 6 prepared inserts (2 sharing one ts)",
         client.Batch(prepared_id,flat,9,6,CQL_CONSISTENCY_ONE));

The SELECT that follows reads back all nine rows (three from EXECUTE, six from BATCH) across the seven returned columns (ts, seq, bid, ask, spread, vol_delta, realized_vol); the per-row checks — ascending (ts, seq) clustering order, the ask-bid == spread identity, and a dedicated check that the two ts=4000 rows came back as two distinct rows with seq 10 and 11 rather than one overwriting the other — cover the seq column and the collision case directly.

A node running its default authenticator exercises only STARTUP followed by READY, with no SASL challenge; Authenticate()'s SASL PLAIN exchange is implemented and called whenever a node replies AUTHENTICATE instead, but exercising that branch is left to the reader's own setup. After that, the script builds an 8-row buffer split evenly across two consecutive calendar days — four rows tagged day_bucket=2026.11.19 and four tagged 2026.11.20 — and sends them as two separate Batch calls, the same way FlushBuffer() would split a real backlog straddling midnight, then reads each day's partition back on its own to confirm it holds exactly its own four rows.

Run against a real node (Cassandra 5 in Docker, no SASL challenge beyond STARTUP/READY), this script prints Cql_SelfTest: 22/22 checks passed — the sixteenth being the dedicated check confirming the two ts=4000 rows came back as two distinct rows by seq rather than one overwriting the other, and the last four confirming the two day-boundary Batch calls each landed in, and stayed inside, their own partition.


Testing

Confirmation Run Duration and Rows Recovered by Reconnect

Fig. 2. Two live runs on EURUSD M5 against a real Cassandra node, one per flush setting. Both ran clean the entire time they were actually ticking; the one failure in each run happened at EA removal and was fully recovered by FlushBuffer's reconnect-and-retry path.

The environment behind both runs, for anyone trying to reproduce or compare against these numbers:

Item Value
Instrument/timeframe EURUSD, M5 chart
Broker/quote source The test MetaTrader 5 account's own live feed; not independently identified beyond that in this writeup
Cassandra version Cassandra 5, running in Docker on Windows (the same node the self-test script above ran against)
Docker image tag Not recorded at the time of the run — a stock public Cassandra 5 image with no extra configuration beyond what setup.cql applies
Host/keyspace 127.0.0.1 (the EA's InpHost default), keyspace tick_features
Replication Single node, so whatever replication factor setup.cql sets has no practical effect here; not meaningful to report for a one-node deployment
Authentication None — the node's default authenticator (no SASL challenge beyond STARTUP/READY)
Launch date/timezone Not recorded at the time of the run; the connect/elapsed times quoted below are terminal-local clock readings, not tagged to a timezone
Host OS/node resources Windows, single Docker container; CPU/RAM allocation to that container was not recorded

A reader on a different broker, OS, or Cassandra build should expect the row counts and timings below to shift accordingly — they describe this one setup, not a general benchmark.

The self-test script above, run against the live node on the current 9-column schema, printed Cql_SelfTest: 22/22 checks passed, including the day-boundary stage described below. Separately, the EA itself was run live on a EURUSD M5 chart against a real Cassandra node, once with InpFlushTicks=50 (connected 18:16:40, ran 29m 9s) and once with InpFlushTicks=200 (connected 18:46:31, ran 18m 37s). Across both runs combined — 47m 46s of live ticking — the table held 14,971 rows afterward, roughly 5.2 rows/second.

That figure is combined rather than split per setting, since both runs wrote into the same uncleared table. It shows the archiver kept up with live EURUSD M5 tick arrival at both settings without accumulating a backlog — not that this is anywhere near Cassandra's own throughput ceiling, which this test never measured server-side.

Each run ended with one failure during manual EA removal: SocketSend reported ERR_NETSOCKET_INVALIDHANDLE (error 5270) on an otherwise healthy connection, once on a 2-row batch and once on a 4-row batch. FlushBuffer()'s reconnect-and-retry path caught both — a fresh Reconnect(), a fresh Prepare(), and the batch succeeded on retry within roughly 200ms. The post-run row count of 14,971 is consistent with nothing dropped, though as a before/after table count rather than an independent audit, it confirms the retry path worked on these two runs rather than proving zero loss in general.

What these tests don't confirm: SASL PLAIN authentication against a node that requires it (implemented and self-tested at the API level, never exercised live); a multi-node cluster (replication, coordinator failover, inter-node consistency); a genuine outage longer than one retry; higher load or a multi-partition batch; and the protocol's non-happy-path responses (warning/tracing flags, a real ERROR frame, a partial-send timeout, an oversized batch, a bad credential, an invalidated prepared id after a schema change). The two live EA runs exercise the same successful path, and the two ERR_NETSOCKET_INVALIDHANDLE recoveries are two instances of one narrow failure mode, not evidence the reconnect path handles socket failures in general.

These tests validate the performance of the baseline scenario on a single node under the observed load and recovery from two socket invalidation events; performance limits and resilience to other failures have not been established.

One caveat: the two EA live-run row counts above predate the current 9-column schema and have not themselves been reconfirmed against it — the self-test above now covers the current schema, the seq collision fix, and the day-boundary split directly, but those two EA runs are still only an accurate record of what those specific runs measured on the schema in place at the time, not a validation of the schema or chunking logic shown here.

FlushBuffer()'s day-boundary split was confirmed directly against the live node, not just traced in isolation: the self-test built an 8-row buffer straddling a real calendar boundary — four rows tagged day_bucket=2026.11.19, four tagged 2026.11.20 — and sent them as two separate Batch calls, the same way FlushBuffer() splits a real backlog the instant BuildDayBucket() would change. Reading each partition back on its own confirmed each held exactly its own four rows, with nothing from one day_bucket showing up under the other. That is the same one-partition-per-chunk guarantee FlushBuffer() relies on, exercised as an actual round trip against Cassandra rather than only as a trace of the splitting loop.


Limitations and Practical Considerations

Protocol and API:CCqlConnection is strictly synchronous and single-connection — no pipelining, no connection pool, and no result paging, so every query this project issues returns a row count that fits one page by construction. Only the primitive types and response-header flags this project's own schema and testing actually need are implemented.

Capture completeness: this archiver only ever sees the ticks OnTick() is actually called for. MT5 doesn't guarantee a distinct OnTick() call for every real incoming tick, and a call blocked inside FlushBuffer()'s synchronous socket round trip can't be queued behind, so a tick arriving during a flush is simply never seen. seq protects against two seen ticks colliding on one millisecond ts; it does nothing for a tick the terminal never handed to OnTick() at all. Treat this table as a faithful record of what the EA was invoked for, not a provably complete capture of the tick stream — closing that gap would mean reconstructing missed ticks from a secondary source, which this project doesn't attempt.

Reliability:FlushBuffer()'s reconnect-and-retry handles exactly one failure mode — a momentary, already-resolved socket invalidation — and doesn't prove recovery from a longer outage, which exhausts the single retry and leaves the buffer growing. RecvFrame() rejects a wrong response version, a compressed/traced/custom-payload flag, or a negative or over-10MB declared length, closing the connection on every rejection; a warnings flag is accepted and its [string list] stripped off before the body reaches any parser — but that accepted path was never exercised against a real node returning a warning, only deliberately malformed input for the rejection paths.

The prepared-statement lifecycle only re-Prepare()s after a fresh connection; it doesn't detect a server-side invalidation of an otherwise still-open connection, the case a live schema change such as ALTER TABLE can trigger, so that failure would surface as an ordinary BATCH error with no automatic re-prepare. CqlProtocol.mqh recognizes the ERROR opcode but doesn't decode its body, so a real server-side error prints as an unexpected opcode rather than a readable diagnostic. CCqlClient::Batch() also doesn't guard against a multi-partition batch — BuildDayBucket() keeps every row this project's own code sends to one (symbol, day_bucket) partition, but nothing stops a caller from building a multi-partition BATCH, which Cassandra's own documentation warns raises coordinator load with no atomicity benefit.

Security: there is no TLS anywhere in this stack — credentials and every row of trading data cross the wire in plain SASL PLAIN and plain CQL, fine against a local Docker node but not over any untrusted link.

Data:BuildDayBucket() stamps its tag via TimeToString(dt, TIME_DATE); since MQL5's datetime carries no explicit timezone tag, the resulting day_bucket follows this terminal's own notion of the date rather than a guaranteed UTC conversion. vol_delta casts both ulong sides to double before subtracting so a volume decrease produces a correct negative delta instead of wrapping; this was only verified against one broker's feed, so a deployment on a different broker should confirm the same assumption holds.


Conclusion

The six files above take MQL5 from zero Cassandra support to a native client that connects, authenticates, prepares a statement once, and writes real tick-level feature data in UNLOGGED batches sized to the live trigger, over a protocol implemented entirely from its own public specification and a single outbound TCP socket. What was actually tested is one schema, one batching shape, single-page results, and no transport encryption; CqlConnection.mqh and CqlClient.mqh could plausibly be reused as-is for another EA needing the same shape — structured per-tick or per-bar columns, same-partition batches, small result sets — by writing its own flush logic and column mapping on top, the way TickFeatureArchiver_EA.mq5 does here. A schema with different types, a workload that needs paging, or a deployment needing TLS or a multi-node cluster would be asking this code to do things it was never built or tested for.

The two real EA-removal failures in Testing also show something narrower but concrete: a flush path with no reconnect logic would have silently dropped what was still buffered both times, and the one-shot reconnect-and-retry closed that specific gap in both observed cases — not a general guarantee against every way a socket-based EA's connection can fail.

File Type Description
CqlProtocol.mqh Include Opcodes, consistency levels, RESULT kinds, and the 9-byte frame header struct with its serializer/parser
CqlBuffer.mqh Include CCqlBuffer — growable byte buffer implementing the primitive encodings this schema needs ([short]/[int]/[long]/[string]/[bytes]/[uuid]/[double]/[consistency] and a couple more), including the union-based double bit-reinterpretation
CqlConnection.mqh Include CCqlConnection — socket ownership, STARTUP/SASL PLAIN handshake, synchronous SendFrame/RecvFrame
CqlClient.mqh Include CCqlClient — Query/Prepare/ExecutePrepared/Batch, reconnect-and-retry, value builders
TickFeatureArchiver_EA.mq5 Expert Advisor Per-tick feature capture, dual-trigger buffered flush, reconnect-and-retry on a failed batch
Cql_SelfTest.mq5 Script End-to-end verification against a real node: DDL, PREPARE, EXECUTE, BATCH (including two rows sharing one ts to confirm the seq tie-breaker), SELECT round-trip
setup.cql CQL schema file Keyspace and feature_ticks table DDL, run once via cqlsh before deployment
Attached files |
MQL5.zip (30.37 KB)
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Aggregating Order Flow Delta from Tick Data in MQL5 Aggregating Order Flow Delta from Tick Data in MQL5
Compute and visualize order flow delta in MQL5 from raw ticks, either per bar or cumulatively. The implementation applies the tick rule, threads state through bars, and annotates price–cumulative delta divergences closed on bars. Pure classes isolate logic for testing, and a synthetic tick script confirms behavior, improving robustness and clarity of the output.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
MQL5 Developer Gotchas (Part 2): A Multi-Line Text Block for Chart Labels Beyond the 63-Character Limit MQL5 Developer Gotchas (Part 2): A Multi-Line Text Block for Chart Labels Beyond the 63-Character Limit
CLabelBlock lets an EA show a long text as labels wrapped by pixel width and detect a truncated label. On the tested builds, native text objects and object names keep only the first 63 UTF-16 code units without an error. CCanvasBlock draws wider lines on one bitmap without that cap but cannot read its text back. Unit tests and screenshot checks cover one system and a few fonts.