preview
Native Apache Cassandra Client in MQL5: Writing Trade and Market Data via the CQL Binary Protocol

Native Apache Cassandra Client in MQL5: Writing Trade and Market Data via the CQL Binary Protocol

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

Contents

  1. Introduction
  2. Why a native client instead of a REST proxy
  3. Anatomy of a CQL frame
  4. Encoding the wire format, and the id that would not decode
  5. Inside the Expert Advisor
  6. A sizing bug the Strategy Tester caught
  7. Testing and validation
  8. Limitations
  9. Why this matters beyond this one EA
  10. Conclusion
  11. Files


Introduction

Say an EA is already trading and it's time to get its trade log out of local files and into a proper database. The usual move is a REST or gRPC gateway sitting in front of Cassandra, but that's another process to keep alive next to the terminal, configured and patched on its own. This article takes the more direct route instead: CQL v4 straight over an MQL5 socket - SocketConnect/SocketSend/SocketRead - no driver, no proxy service, no third-party DLL. It's the same approach the rest of this series has used for other wire protocols; earlier entries covered SFTP and a WebSocket bridge the same way.

The target here is specific and checkable: queue every closed deal - matched by symbol and magic number - into a Cassandra table in small batches, then read that table back through a separate connection and confirm its row count lines up with what the terminal's own deal history shows for the same filter. Three pieces get built toward that. First, CassandraStream_EA.mq5, a Donchian-breakout EA with ATR stops that does the writing. Second, CCassandraClient inside CassandraCore.mqh, the reusable client class any other EA or script can include on its own. Third, CassandraQuery_Dashboard.mq5, the script that does the reading back and the reconciling. It's a working integration example, not a durable trade log: the EA keeps trading if Cassandra never comes up, but the pending queue lives only in memory and isn't replayed later - more on that in Limitations.

Two real bugs turned up while I was building this, and both are documented here with the data that caught them - nothing smoothed over. One: a prepared-statement id that silently corrupted every PREPARE/EXECUTE/BATCH round trip, because it's framed differently on the wire from an ordinary bound parameter. Two: a position-sizing routine that would have torched a live account on a large-tick-value symbol.


Why a native client instead of a REST proxy

Cassandra doesn't speak HTTP. The usual workaround from an environment with no native driver is a small REST or gRPC gateway process in front of it - DataStax's HTTP API, or something hand-rolled - and the EA talks to that. It works, but now there's a process to keep alive next to the terminal, a second place for auth and TLS configuration to live, and a translation layer sitting between the gateway's JSON and Cassandra's own column types. A socket that speaks CQL directly removes that extra process and its own, separate auth/TLS surface - the EA's only outside dependency becomes the Cassandra node itself, on its native port, 9042. Auth and TLS don't disappear, though. If the cluster requires them, the EA has to speak them directly over the socket - that work belongs in Startup(), the client's own username/password handshake, or in a TLS-wrapped transport layer underneath it. This build's own validation, covered in the testing section, ran against a single node with neither enabled, so that part is left unexercised here.

What it costs you is that the binary framing has to be built and parsed by hand, byte by byte, inside MQL5. There's no StringToUtf8(), no unsigned 64-bit literal suffixes, no bit-cast from a double to its IEEE-754 bit pattern. The next two sections walk through how each of those gaps got closed.

Component layout

1. The EA calls into CCassandraClient, which frames CQL requests and pushes them down a raw TCP socket to the Cassandra node. The dashboard script is a separate reader: it opens its own connection and runs its own SELECT, so it can check what actually landed in the table against the terminal's own deal history without trusting the EA's own bookkeeping.


Anatomy of a CQL frame

Every CQL v4 message, request or response, opens with the same 9-byte header: a version byte, a flags byte, a 2-byte stream id, a 1-byte opcode, a 4-byte body length. SendFrame() builds that header on every outgoing request.

Two length-prefixed byte encodings turn up again and again in the body: an ordinary [bytes] value, carrying a 4-byte [int] length, and a [short bytes] value, carrying a 2-byte [short] length. A prepared-statement id is the second kind, not the first, and that single distinction is what section 4 is actually about.

Frame and value layouts

2. The 9-byte frame header is the same on every message. Below it, the two length-prefixed encodings this client needs sit side by side: [bytes] for an ordinary bound parameter, 4-byte length prefix, and [short bytes] for a prepared-statement id, 2-byte length prefix. Treating the second as the first is the mismatch described next.


Encoding the wire format, and the id that would not decode

The low-level writers and readers in CassandraCore.mqh each handle one wire type. Two of them exist purely because a prepared-statement id isn't an ordinary [bytes] value:

//+------------------------------------------------------------------+
//| Append a [short bytes] value: [short] length + raw bytes. A      |
//| prepared-statement id is framed this way on the wire - a 2-byte  |
//| length, not the 4-byte length ordinary [bytes] values use - so   |
//| it needs its own reader/writer rather than CqlPutBytes()         |
//+------------------------------------------------------------------+
void CqlPutShortBytes(uchar &buf[],const uchar &data[])
  {
   int n=ArraySize(data);
   CqlPutShort(buf,(ushort)n);
   for(int k=0; k<n; k++)
      CqlPutByte(buf,data[k]);
  }
//+------------------------------------------------------------------+
//| Read a [short bytes] value: [short] length + raw payload. Used   |
//| for a prepared-statement id, which carries a 2-byte length on    |
//| the wire rather than the 4-byte length CqlGetBytes() expects.    |
//| A length that claims more than what's left in buf is treated as  |
//| a malformed frame rather than read past the array's end          |
//+------------------------------------------------------------------+
void CqlGetShortBytes(const uchar &buf[],int &pos,uchar &out[])
  {
   int n=CqlGetShort(buf,pos);
   int avail=ArraySize(buf)-pos;
   if(n<0 || n>avail)
     {
      ArrayResize(out,0);
      pos=ArraySize(buf);
      return;
     }
   ArrayResize(out,n);
   for(int k=0; k<n; k++)
      out[k]=buf[pos+k];
   pos+=n;
  }

Earlier, the client also used CqlPutBytes()/CqlGetBytes() for the prepared id, assuming the encoding was the same as any other length-prefixed byte string. That compiles fine. It runs fine. It only falls apart the moment the id actually round-trips through a real server, because the spec puts the id under [short bytes], not [bytes]. A 4-byte length prefix misreads the first two id bytes as part of the length field, so EXECUTE and BATCH send a corrupted id, and the server rejects something that was, from the EA's side, exactly what PREPARE had just handed back.

Prepare() also guards a second, unrelated timing issue I ran into on a real single-node cluster: a PREPARE fired right after the CREATE TABLE that introduced the table can arrive before schema agreement has settled. A short retry loop rides that window out:

//+------------------------------------------------------------------+
//| PREPARE a parameterized statement, caching the server's prepared |
//| id on the result set for a later EXECUTE                         |
//+------------------------------------------------------------------+
bool CCassandraClient::Prepare(const string cql,SCqlResultSet &res)
  {
   //--- a PREPARE issued immediately after the CREATE TABLE that
   //--- introduced the table can arrive before schema agreement has
   //--- finished on a freshly started node, even with one node in
   //--- the cluster - observed directly on a real smoke test, where
   //--- the first PREPARE right after CREATE TABLE came back with a
   //--- RESULT frame whose kind was not Prepared; a short retry loop
   //--- rides out that window instead of failing the whole run on it
   int max_attempts=3;
   for(int attempt=1; attempt<=max_attempts; attempt++)
     {
      uchar body[];
      CqlPutLongString(body,cql);
      SendFrame(CQL_OP_PREPARE,body);
      uchar opcode,resp[];
      if(!ReadFrame(opcode,resp))
        {
         res.ok=false; res.message=m_last_error;
         return(false);
        }
      if(opcode==CQL_OP_ERROR)
        {
         ParseError(resp,res);
         return(false);
        }
      if(opcode!=CQL_OP_RESULT)
        {
         res.ok=false;
         res.message=StringFormat("unexpected opcode 0x%02X for PREPARE",opcode);
         return(false);
        }
      int pos=0;
      int kind=CqlGetInt(resp,pos);
      if(kind==CQL_RESULT_PREPARED)
        {
         CqlGetShortBytes(resp,pos,res.prepared_id);
         res.ok=true;
         res.kind=CQL_RESULT_PREPARED;
         return(true);
        }
      if(attempt<max_attempts)
         Sleep(300*attempt);
     }
   res.ok=false;
   res.message="PREPARE did not return a Prepared result after retrying";
   return(false);
  }

This retry loop only rides out one specific case: the server answering with a RESULT frame whose kind isn't Prepared yet - the schema-not-settled window above. If the server instead comes back with an ERROR opcode, say because the table genuinely isn't visible yet on a slower node, Prepare() fails right there without retrying.

Case 8 of the self-test in CqlRunSelfTest() exists purely to pin this encoding down - a 16-byte id goes through CqlPutShortBytes() and back through CqlGetShortBytes(), and the check covers both the 2-byte length prefix and a byte-for-byte match on the payload:

   //--- Case 8: a prepared-statement id round-trips through the
   //--- [short bytes] encoder/decoder with a 2-byte length prefix,
   //--- not the 4-byte prefix CqlPutBytes()/CqlGetBytes() use for
   //--- ordinary bound values - this is the exact framing mismatch
   //--- that corrupted every PREPARE/EXECUTE/BATCH round trip before
   //--- CqlPutShortBytes()/CqlGetShortBytes() were introduced
   total++;
   uchar id8[16];
   for(int k=0; k<16; k++)
      id8[k]=(uchar)(k+1);
   uchar b8[];
   CqlPutShortBytes(b8,id8);
   bool ok8=(ArraySize(b8)==18 && b8[0]==0 && b8[1]==16);
   if(ok8)
     {
      int p8=0;
      uchar out8[];
      CqlGetShortBytes(b8,p8,out8);
      ok8=(p8==18 && ArraySize(out8)==16);
      for(int k=0; ok8 && k<16; k++)
         ok8=(out8[k]==id8[k]);
     }
   if(ok8)
      passed++;


Inside the Expert Advisor

One thing worth settling before the table schema and the transaction handler below: a "row" in this table is one closed deal, not one closed position. OnTradeTransaction() fires per DEAL_ENTRY_OUT deal, so a position that closes across more than one such deal - a partial fill on the close, say - logs as more than one row, all sharing the same position_id. Keep that unit of account in mind while reading the schema and the handler that fills it.

ConnectAndPrepare() runs once, from OnInit(). It opens the socket, creates the keyspace and table if they're missing, and prepares the one INSERT statement the EA reuses for every logged trade:

//+------------------------------------------------------------------+
//| Open the socket, create keyspace/table if missing, and PREPARE   |
//| the INSERT statement the EA will reuse for every logged trade    |
//+------------------------------------------------------------------+
bool ConnectAndPrepare(void)
  {
   if(!g_client.Connect(InpHost,InpPort,5000))
      return(false);
   if(!g_client.Startup(InpUsername,InpPassword))
      return(false);

   SCqlResultSet res;
   string ddl_ks=StringFormat(
      "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = "
      "{'class':'SimpleStrategy','replication_factor':1}",InpKeyspace);
   if(!g_client.ExecuteSimple(ddl_ks,CQL_CONSISTENCY_ONE,res))
     {
      Print("CREATE KEYSPACE failed: ",res.message);
      return(false);
     }

   string use_ks=StringFormat("USE %s",InpKeyspace);
   if(!g_client.ExecuteSimple(use_ks,CQL_CONSISTENCY_ONE,res))
     {
      Print("USE keyspace failed: ",res.message);
      return(false);
     }

   string ddl_tbl=
      "CREATE TABLE IF NOT EXISTS trades ("
      "symbol text, magic bigint, ticket bigint, direction text, "
      "open_time_ms bigint, close_time_ms bigint, lots double, "
      "r_multiple double, profit double, "
      "PRIMARY KEY ((symbol,magic),close_time_ms,ticket)) "
      "WITH CLUSTERING ORDER BY (close_time_ms DESC)";
   if(!g_client.ExecuteSimple(ddl_tbl,CQL_CONSISTENCY_ONE,res))
     {
      Print("CREATE TABLE failed: ",res.message);
      return(false);
     }

   string insert_cql=
      "INSERT INTO trades (symbol,magic,ticket,direction,open_time_ms,"
      "close_time_ms,lots,r_multiple,profit) VALUES (?,?,?,?,?,?,?,?,?)";
   if(!g_client.Prepare(insert_cql,res))
     {
      Print("PREPARE failed: ",res.message);
      return(false);
     }
   ArrayCopy(g_prepared_id,res.prepared_id);
   g_cassandra_ready=true;
   PrintFormat("Cassandra ready: %s:%d, keyspace %s",InpHost,InpPort,InpKeyspace);
   return(true);
  }

If any of that fails - no node reachable, wrong keyspace, whatever - g_cassandra_ready stays false and OnInit() still returns INIT_SUCCEEDED. The strategy keeps trading either way; only the logging side goes dark. Note that InpKeyspace goes straight into ddl_ks and use_ks above through StringFormat(), with no identifier validation - it's an EA input, not untrusted network input, but a malformed keyspace name breaks the DDL rather than being caught ahead of time. OnTick() is the Donchian breakout itself - a new-bar gate, a channel check that excludes the signal bar from its own channel, and an ATR-scaled stop and target:

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   datetime bar_time=iTime(_Symbol,_Period,0);
   if(bar_time==g_last_bar_time)
      return;                         // only act once per closed bar
   g_last_bar_time=bar_time;

   if(PositionsTotal()>0 && PositionIsOpenHere())
      return;                         // one position at a time, this symbol/magic

   int direction=CheckDonchianSignal();
   if(direction==0)
      return;

   double atr[];
   if(CopyBuffer(g_handle_atr,0,1,1,atr)!=1)
      return;
   double atr_val=atr[0];
   if(atr_val<=0.0)
      return;

   double sl_dist=InpAtrMultSl*atr_val;
   double tp_dist=InpAtrMultTp*atr_val;
   double min_stop=MinStopDistance();
   if(sl_dist<min_stop) sl_dist=min_stop;
   if(tp_dist<min_stop) tp_dist=min_stop;

   double price=(direction>0 ? SymbolInfoDouble(_Symbol,SYMBOL_ASK)
                              : SymbolInfoDouble(_Symbol,SYMBOL_BID));
   double sl=(direction>0 ? price-sl_dist : price+sl_dist);
   double tp=(direction>0 ? price+tp_dist : price-tp_dist);
   double lots=CalcLotSize(sl_dist);
   if(lots<=0.0)
      return;

   MqlTradeRequest req;
   MqlTradeResult  result;
   ZeroMemory(req);
   ZeroMemory(result);
   req.action    = TRADE_ACTION_DEAL;
   req.symbol    = _Symbol;
   req.volume    = lots;
   req.type      = (direction>0 ? ORDER_TYPE_BUY : ORDER_TYPE_SELL);
   req.price     = price;
   req.sl        = NormalizeDouble(sl,_Digits);
   req.tp        = NormalizeDouble(tp,_Digits);
   req.deviation = 10;
   req.magic     = InpMagic;
   req.comment   = "CassandraStream";

   if(!OrderSend(req,result))
      PrintFormat("OrderSend failed: retcode=%d, comment=%s",
                  result.retcode,result.comment);
  }

A closed position gets picked up in OnTradeTransaction(), which filters by magic number and by DEAL_ENTRY_OUT, rebuilds the full position from the terminal's own deal history, and queues one row:

//+------------------------------------------------------------------+
//| Trade transaction handler - queues one row per closed position   |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
   if(trans.type!=TRADE_TRANSACTION_DEAL_ADD)
      return;
   if(!HistoryDealSelect(trans.deal))
      return;
   if((ulong)HistoryDealGetInteger(trans.deal,DEAL_MAGIC)!=InpMagic)
      return;
   if(HistoryDealGetInteger(trans.deal,DEAL_ENTRY)!=DEAL_ENTRY_OUT)
      return;                         // only log on position close

   long position_id=(long)HistoryDealGetInteger(trans.deal,DEAL_POSITION_ID);
   double profit=0.0,open_price=0.0,close_price=0.0,volume=0.0;
   long open_ms=0,close_ms=0;
   int dir_sign=0;
   if(!ReconstructPositionLeg(position_id,open_price,close_price,volume,
                              open_ms,close_ms,profit,dir_sign))
      return;

   double sl_distance=MathAbs(open_price-close_price); // used only when
   if(sl_distance<=0.0)                                // the trade wasn't
      sl_distance=SymbolInfoDouble(_Symbol,SYMBOL_POINT); // stopped exactly at SL
   double risked=sl_distance*volume*
                 SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE);
   double r_multiple=profit/MathMax(1.0,risked); // signed P/L over risk

   SCqlBindRow row;
   ArrayResize(row.vals,9);
   row.vals[0].type=CQL_BIND_TEXT;         row.vals[0].s=_Symbol;
   row.vals[1].type=CQL_BIND_BIGINT;       row.vals[1].i=(long)InpMagic;
   row.vals[2].type=CQL_BIND_BIGINT;       row.vals[2].i=position_id;
   row.vals[3].type=CQL_BIND_TEXT;         row.vals[3].s=(dir_sign>0 ? "BUY":"SELL");
   row.vals[4].type=CQL_BIND_TIMESTAMP_MS; row.vals[4].i=open_ms;
   row.vals[5].type=CQL_BIND_TIMESTAMP_MS; row.vals[5].i=close_ms;
   row.vals[6].type=CQL_BIND_DOUBLE;       row.vals[6].d=volume;
   row.vals[7].type=CQL_BIND_DOUBLE;       row.vals[7].d=r_multiple;
   row.vals[8].type=CQL_BIND_DOUBLE;       row.vals[8].d=profit;

   int n=ArraySize(g_pending);
   ArrayResize(g_pending,n+1);
   g_pending[n]=row;

   if(ArraySize(g_pending)>=InpBatchFlushCount)
      FlushPendingRows();
  }

Rows sit in g_pending[] and go out as one BATCH statement once InpBatchFlushCount is hit - one network round trip for a handful of trades, not one per close.


A sizing bug the Strategy Tester caught

CalcLotSize() turns a risk percentage and a stop distance into a lot size, with a tick-value/contract-size cross-check built in for brokers whose two pieces of symbol metadata don't agree:

//+------------------------------------------------------------------+
//| Tick-value-normalized lot size, with a contract-size cross-check |
//| fallback for brokers whose tick-value metadata disagrees with    |
//| the contract size, a zero-step guard, and a minimum-lot guard    |
//| that skips the trade rather than silently over-risking on a      |
//| large-per-point symbol                                           |
//+------------------------------------------------------------------+
double CalcLotSize(double sl_distance)
  {
   double balance=AccountInfoDouble(ACCOUNT_BALANCE);
   double risk_money=balance*(InpRiskPercent/100.0);

   double tick_size =SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   double tick_value=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
   double contract   =SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE);
   if(tick_size<=0.0 || contract<=0.0)
      return(0.0);

   double loss_per_lot_tick    =(sl_distance/tick_size)*tick_value;
   double loss_per_lot_contract=sl_distance*contract;

   double loss_per_lot=loss_per_lot_tick;
   if(loss_per_lot_tick<=0.0 ||
      MathAbs(loss_per_lot_tick-loss_per_lot_contract)/loss_per_lot_contract>2.0)
     {
      static bool warned=false;
      if(!warned)
        {
         PrintFormat("tick-value sizing disagrees with contract-size sizing "
                     "on %s (%.2f vs %.2f per lot) - falling back to "
                     "contract-size",_Symbol,loss_per_lot_tick,loss_per_lot_contract);
         warned=true;
        }
      loss_per_lot=loss_per_lot_contract;
     }
   if(loss_per_lot<=0.0)
      return(0.0);

   double raw_lots=risk_money/loss_per_lot;
   double step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   double vmin=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   double vmax=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
   if(step<=0.0)
      return(0.0);
   double lots=MathFloor(raw_lots/step)*step;
   if(lots<vmin)
     {
      //--- the risk-correct size rounds below the broker's minimum
      //--- tradable lot - skip the trade rather than force the
      //--- minimum, which would silently risk far more than
      //--- InpRiskPercent on a symbol with a large per-point value.
      //--- This is exactly what ground a XAUUSD backtest account
      //--- down from $10,000 to $25 before this guard was added
      return(0.0);
     }
   lots=MathMin(vmax,lots);
   return(lots);
  }

That 2.0 on the fallback check is a plain constant, not a value pulled from any broker spec - it tolerates up to a 200% difference between the tick-value and contract-size estimates before switching, chosen to only catch metadata that's clearly broken rather than to fine-tune sizing. A narrower tolerance is a one-line change if a given broker needs it.

The first version of this rounded a too-small risk-correct lot size up to the broker's minimum tradable lot, with a plain MathMax(). On most symbols you'd never notice - the minimum lot sits close enough to what InpRiskPercent would have produced anyway. XAUUSD is a different animal: a point there is worth far more per lot than on a typical FX pair, so the same rounding forced a position several times the actual risk budget. A H1 Strategy Tester run on XAUUSD, $10,000 deposit, took the account down to $25.49 - a 99.75% fall - with the old rounding still in place. Swap in the guard shown above (skip the trade when lots<vmin, don't resize it up) and an identical rerun closed at $249.81, a 97.50% fall.

$249.81 from $10,000 is still a 97.50% fall. The largest single losing trade came out identical in both runs, which rules out the one failure mode the guard was built to catch - the old rounding forcing an outsized position on that specific trade. It doesn't rule out sizing contributing more broadly across the run, since I never went through every trade comparing risk-per-trade before and after the fix. More likely both things are true at once: the guard stopped the one-trade catastrophe it targeted, and a plain, untuned Donchian/ATR breakout still doesn't suit gold's volatility over this window on top of that. I left XAUUSD out of the three-symbol matrix in the next section for that reason: next to EURUSD and GBPUSD, a near-total drawdown reads as a logging or sizing failure long before a reader reaches the caveat explaining it.


Testing and validation

CqlRunSelfTest() runs from OnInit(), before anything touches the network. It checks wire-level encode/decode correctness only, against hand-verified reference byte sequences - eight cases: [short]/[int]/[string] round trips, the exact STARTUP body byte sequence, the IEEE-754 bit-pattern conversion, a null [bytes] value, the 9-byte frame header order, and the [short bytes] case above. It doesn't touch the socket, authentication, or anything server-side; those get checked separately below. On my machine it comes back 8/8 passed.

A live smoke test covered what the self-test can't: I opened one position by hand on EURUSD, magic number 990042, against a running Cassandra node, then closed it. CassandraQuery_Dashboard.mq5 then ran its own, independent SELECT and checked the row count against the terminal's own deal history through a second, unrelated code path:

//+------------------------------------------------------------------+
//| Count closed positions for this symbol/magic directly from the   |
//| terminal's own account history, as an independent cross-check    |
//| against what Cassandra reports it received                       |
//+------------------------------------------------------------------+
int ReconcileAgainstTerminalHistory(void)
  {
   if(!HistorySelect(0,TimeCurrent()))
      return(0);
   int total_deals=HistoryDealsTotal();
   int closed_count=0;
   for(int i=0; i<total_deals; i++)
     {
      ulong deal=HistoryDealGetTicket(i);
      if(HistoryDealGetString(deal,DEAL_SYMBOL)!=_Symbol)
         continue;
      if((ulong)HistoryDealGetInteger(deal,DEAL_MAGIC)!=InpMagic)
         continue;
      if(HistoryDealGetInteger(deal,DEAL_ENTRY)==DEAL_ENTRY_OUT)
         closed_count++;
     }
   return(closed_count);
  }

Cassandra handed back 2 rows for that symbol/magic pair, and ReconcileAgainstTerminalHistory() separately counted 2 matching deals in the terminal's own history for the same filter - MATCH. The closing order itself got filled by the broker across two separate deals rather than one - a routine partial fill on the close, not a partial close I asked for - and OnTradeTransaction() logs per DEAL_ENTRY_OUT deal, not per position, so that single position produced two rows. Both counting paths - the rows CCassandraClient wrote and the deals ReconcileAgainstTerminalHistory() counts - are counting the same underlying deals, which is why they agree with each other even though the position itself was one. A position that closes over several such deals logs as several rows, not one collapsed row per position; see the Limitations section for what that means for anyone reading the table back.

A second check ran the EA in the Strategy Tester on three FX pairs. Settings: H1, "Every tick based on real ticks", 100% history quality, 2025.01.01-2026.10.01, $10,000 deposit. This exercises the full trade-management path - signal, sizing, stop/target, position rebuild, row queuing - across 10,713 to 10,854 H1 bars and tens of millions of ticks per symbol. One catch: the Strategy Tester's agent process has no route to the Cassandra node on localhost, so all three runs logged the same line at shutdown - rows queued but Cassandra is not connected, they'll be dropped at shutdown. That's the degraded-mode path in ConnectAndPrepare() from the previous section firing exactly as written, not a failure of the test. This matrix is checking strategy and sizing behavior under sustained tick load; it says nothing about the Cassandra path one way or the other, which is what the live smoke test above is for.

Three-symbol validation matrix

3. Net profit, maximum balance drawdown and profit factor for EURUSD, GBPUSD and USDJPY over the same 2025.01.01 - 2026.10.01 window. All three finished with a profit factor just under 1 and a small net loss - I used a plain, untuned Donchian/ATR breakout for this, and none of the three bars were picked over the others; the table below has every number behind them.

Symbol Trades Won % Net profit Profit factor Max balance DD Expected payoff
EURUSD 455 181/455 (39.78%) $-1,062.30 0.96 24.54% ($2,716.28) $-2.33
GBPUSD 472 190/472 (40.25%) $-816.48 0.97 23.34% ($2,470.84) $-1.73
USDJPY 476 191/476 (40.13%) $-938.03 0.97 19.52% ($2,108.05) $-1.97

All three runs cleared the 100% history-quality bar on real-tick modelling, so the counts and P/L figures above reflect the same tick stream MetaTrader itself replays, not a synthesized one. Every EA instance also passed its own 8/8 self-test at OnInit() before the tester produced a single bar of these results.


Limitations

What this did and didn't cover, plainly:

  • Client scope. This is a minimal single-node client, not a production Cassandra driver. End-to-end testing used one node without authentication or TLS; those configurations and multi-node operation remain unvalidated. The client has no token-aware routing or connection failover and ParseRows() decodes only the scalar CQL types this schema uses - text, int, bigint, timestamp, double, not collections or user-defined types. CqlGetShortBytes() checks the claimed length against what's left in the buffer before reading; the other wire readers in CassandraCore.mqh, including CqlGetBytes() for ordinary bound parameters, still trust a response's length prefix without that same check and could read past the buffer on a corrupted frame.
  • Validation scope. The Strategy Tester runs exercise trading logic, not Cassandra connectivity - the tester's agent process can't reach a localhost service. The live smoke test confirms a row-count / closing-deal-count match, not a field-by-field one: it doesn't confirm ticket, timestamps, direction, volume, profit and r_multiple came back correct in every row. CassandraQuery_Dashboard.mq5 is an independent connection and an independent SELECT, but it goes through the same CCassandraClient wire-encoding layer as the writer, so it can't rule out a bug shared by both sides of that layer. The self-test (CqlRunSelfTest()) only checks wire encoding against hand-verified byte sequences; it never opens a socket or runs a PREPARE / EXECUTE / BATCH cycle against a live server - the smoke test is the only thing here that does, and it did so once, on one node.
  • Delivery isn't durable. Pending rows exist only in g_pending[], in memory. The EA keeps trading if Cassandra is unreachable, but there's no reconnect/replay mechanism or persistent queue - OnDeinit() tries one last flush, and whatever's still unsent is discarded. A session where Cassandra never comes up loses every row from that session.
  • Row and metric semantics. Logging is triggered per DEAL_ENTRY_OUT deal, not per completed position, as noted above - one position can produce more than one row, all sharing the same position_id. r_multiple uses sl_distance = MathAbs(open_price-close_price), the realized open-to-close price distance, rather than the original stop distance, and must not be read as a true ex-ante R-multiple.
  • Sizing assumptions. loss_per_lot_contract = sl_distance*contract assumes the contract size converts directly to account-currency risk per lot; it doesn't perform currency conversion and isn't a general-purpose risk model, just a fallback for when tick-value metadata looks wrong. Validate it against the target instrument, broker specification and account currency before live use. InpKeyspace also goes straight into the DDL with no identifier validation, as noted in the previous section.


Why this matters beyond this one EA

CassandraCore.mqh doesn't depend on anything in CassandraStream_EA.mq5. The strategy logic, the risk sizing, the Donchian signal - all specific to this one EA. But CCassandraClient, the SCql* structs and the wire helpers drop straight into any project that needs to push structured data out of MQL5 into a column store with nothing in between: tick logs, order-flow captures, multi-symbol research datasets, anything that's outgrown CSV files on disk.


Conclusion

Getting here meant working through the CQL frame layout, fixing the prepared-statement id encoding that was silently breaking every EXECUTE and BATCH call, and wiring batched writes into a live EA. What came out of it is three pieces that work together: CCassandraClient as a reusable wire client, CassandraStream_EA.mq5 writing closing trades through it, and a small reader script that pulls the row count back out of Cassandra and checks it against the terminal's own history.

Three different checks backed that up, and each one covers a different slice of the system. CqlRunSelfTest() passed all eight of its wire-encoding cases, but that's bytes on a workbench, not a live socket. The one test that did open a real socket was the live smoke test against a single node: the reader came back with two rows, matching the two closing deals the terminal had logged for that one position - a count match, not a field-by-field one, and a reminder that one position can produce more than one row. Separately, the Strategy Tester runs put the Donchian/ATR logic through its paces across three FX pairs, which exercised the EA's trading code but never touched Cassandra at all and said nothing about whether the strategy itself is worth trading.

CCassandraClient should drop into other MQL5 projects that need to get structured data into a column store, within the bounds this article has been upfront about: the pending-row queue lives in memory only, a closed position can span multiple logged rows, and multi-node clusters, authentication and TLS were never part of the test. Whatever the Strategy Tester reported here is evidence that the trading logic ran as written - not evidence that the data pipeline is bulletproof, and not evidence the strategy makes money.

Files

File Type Description
MQL5\Include\CassandraClient\CassandraCore.mqh Include CQL binary protocol v4 wire encoding/decoding and the CCassandraClient class
MQL5\Experts\CassandraClient\CassandraStream_EA.mq5 Expert Advisor Donchian/ATR breakout strategy that streams every closed trade to Cassandra
MQL5\Scripts\CassandraClient\CassandraQuery_Dashboard.mq5 Script Reads logged trades back and checks the count against the terminal's own history
Attached files |
MQL5.zip (15.68 KB)
Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects Backtesting Indicator Signals in MQL5 Using Buffers and Chart Objects
The EA evaluates indicator signals from buffers or dated chart objects on historical closed bars, keeping execution separate from account reports. It models virtual positions with user-defined entry timing, stop loss, staged targets, partial exits, break-even, and optional reversal on opposite signals, and renders exit paths and statistics on the chart. EURUSD examples compare SMA buffer/object sources and test confirmed RSI divergence, illustrating a practical way to judge signals before building a dedicated EA.
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Difference Block) Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Difference Block)
The article presents a practical implementation of the EDCFlow framework's approaches, with a focus on the Multi-Scale Difference module. It demonstrates how sequential feature compression, the computation of differences across multiple scales, and adaptive multiscale attention enable the formation of a structured and informative representation of streaming data.
Building a HalfTrend Channel Indicator in MQL5 Building a HalfTrend Channel Indicator in MQL5
This article builds a HalfTrend Channel indicator in MQL5 that combines rolling price extremes with a HalfTrend baseline and a Wilder‑smoothed ATR(100) to form adaptive channel boundaries. It explains the trend‑state machine, ATR smoothing, and the logic for detecting close‑price crossings of the bands. The result helps you study confirmed directional shifts and price behavior around a volatility‑adjusted reference line.
Auditing an Expert Advisor From Its Trade History (Part 1): Rebuilding Positions From Deals Auditing an Expert Advisor From Its Trade History (Part 1): Rebuilding Positions From Deals
This article introduces TradeAudit, an MQL5 include library that rebuilds closed trades from raw deal history to produce one consistent record per trade. It handles partial closes, scale-ins on netting accounts, netting reversals, close-by pairs, and positions spanning the date range. A script exports the records to CSV, and a self-test script runs synthetic netting and close-by sequences. The result is a clean per-trade dataset for reliable EA statistics and verification.