preview
Does the Terminal Run the Model You Trained? ONNX Contract and Golden-File Checks in MQL5

Does the Terminal Run the Model You Trained? ONNX Contract and Golden-File Checks in MQL5

MetaTrader 5 — Examples |
180 0
Ali Akbar
Ali Akbar

Contents

  1. Introduction
  2. What is already published
  3. Architecture
  4. Section 1: The export side
  5. Section 2: Checking the contract
  6. Section 3: The classifier
  7. Section 4: The golden file
  8. Section 5: Check files for your own model
  9. Section 6: Checking the code
  10. Section 7: The EA in the Strategy Tester
  11. Section 8: A retrained model with the same signature
  12. Section 9: A consistency check outside MQL5
  13. What the checks do not cover
  14. Limitations
  15. Conclusion
  16. Attached files


Introduction

My first ONNX helper class for this article failed in a way I did not see at first. It created the session, set the input shape, and called OnnxRun() with one buffer for the predicted label. The model was a scikit-learn pipeline with two outputs, the label and the class probabilities. So every call failed with error 5804, and the journal said "incorrect parameters count passed to OnnxRun, expected 3 instead of 2". My own test script then reported 50 rows with 0 matches and 0 mismatches, and still printed PASS. The model was fine. The code around it was wrong, and the test could not tell.

That mistake changed the topic of the article. Exporting a model to ONNX is well covered on MQL5. I did not find a set of checks for an EA to run in OnInit before its first prediction. So I wrote three classes and a Python tool:

  • COnnxContract compares a model with a small contract file. The file lists the inputs and outputs the code expects, the feature order, the class labels, and the SHA-256 of the model file.
  • COnnxClassifier loads a classifier only if it passes that check, and gives OnnxRun() a buffer for every output.
  • COnnxParity runs a golden file through the terminal and compares every probability with the answer onnxruntime gave in Python for the same row.
  • The script make_check_files.py writes the contract and the golden file for a classifier exported with zipmap off, from your own rows. It can also audit the log an EA writes while it runs.

The checks answer different questions. The hash shows whether the file is byte for byte the one the contract was written for. The signature check shows whether the code can call the model at all. The golden file shows whether the terminal computes the same numbers as onnxruntime on the rows in that file. None of them says whether the model is any good, and the golden file says nothing about rows outside it.

I tested the checks in terminal build 6230 on one model. It is a StandardScaler followed by a RandomForestClassifier, trained on EURUSD H1 features computed from the terminal's own indicators. The Python package versions are listed in Limitations. The test script runs 36 checks. On all 2,033 golden rows the terminal matched onnxruntime within 1.49e-7. A model retrained with another seed has the same signature and a different hash, and it changes 241 labels on the golden rows. In the Strategy Tester the EA runs both checks in OnInit and then predicts every bar of a later period. Only the first of those bars is also in the golden file. A Python audit of its log found the same labels as onnxruntime and probabilities within 1.49e-7. The model itself is only the test case. It has no edge, and the article does not evaluate it as a strategy.


What is already published

MetaQuotes' article How to use ONNX models in MQL5 prints the type information of every input and output with OnnxGetInputTypeInfo() and OnnxGetOutputTypeInfo(). It sets the output shapes by hand. Classification models in the Scikit-Learn library and their export to ONNX exports classifiers with the default ZipMap output and reads the resulting sequence of maps in MQL5. It then compares the accuracy on the Iris set in Python and in MQL5. From Matrices to Models and Wasserstein Distance for Live Feature-Drift Detection put the scaler inside the ONNX graph, and the second one also watches the live distribution of the inputs. Pipelines in MQL5 does the preprocessing in MQL5 itself.

I found no article that checks a model file against a fixed contract before the EA trades, or compares the terminal's probabilities with Python row by row. Both gaps matter. Accuracy on a whole dataset can match while single rows differ, and a retrained model can have exactly the same signature as the old one.


Architecture

The module consists of four include files, two MQL5 scripts, one EA, and three Python scripts. Fig. 1 shows how the files from the export side reach the checks, and how the EA's log is checked after a Strategy Tester run.

From the export script to the EA

The model, its contract, and the golden rows are checked before the first prediction

The export script or make_check_files.py writes the model, the contract, the golden rows, and the trees. The contract check, the classifier, and the parity run sit between them and the EA. After a Strategy Tester run, the EA log is audited in onnxruntime and rechecked with a standard-library script

Fig. 1. The export script or make_check_files.py writes the model, the contract, the golden rows, and the trees. The contract check, the classifier, and the parity run sit between them and the EA. After a Strategy Tester run, the EA log is audited in onnxruntime and rechecked with a standard-library script

File Contents
OnnxContract.mqh ENUM_ONNX_CHECK, SOnnxValueSpec, COnnxContract: reads the contract and the model signature, hashes the model bytes, and compares them
OnnxClassifier.mqh COnnxClassifier: load, check, set the batch size, Predict(), class labels, timing
OnnxParity.mqh SOnnxParityReport, COnnxParity: golden-file run against onnxruntime, scikit-learn reported if present
OnnxFeatures.mqh COnnxFeatures: the four example features, shared by ExportFeatures.mq5 and the EA
ExportFeatures.mq5 Script: writes the features, labels, and prices of the chart symbol to features.csv
TestOnnxParity.mq5 Script: 36 checks with PASS or FAIL on the files export_model.py wrote
OnnxParityEA.mq5 Example EA: both checks in OnInit, one Predict() per bar, a per-bar log
make_check_files.py Writes the contract and the golden file for a classifier with zipmap off, and audits an EA log
export_model.py Trains the example model and writes the model, its check files, the trees, and the broken variants for the tests
parity_crosscheck.py Standard-library consistency check: walks the trees and recomputes the features from the price data


Section 1: The export side

The example features come from ExportFeatures.mq5, which uses the same COnnxFeatures class as the EA. They are the 14-period RSI, the 14-period ATR divided by the close, the 10-bar return, and the width of the 20-period Bollinger Bands divided by the close. The label looks six bars ahead. A return above half the ATR of the bar is class 2, below minus half the ATR is class 0, and anything in between is class 1. ExportFeatures.mq5 also writes the high, low, and close of every bar, so that Section 9 can recompute the features without MQL5.

The script export_model.py splits the rows by time into three parts:

Part Rows Used for
Before 2026.01.01 18,624 Training. The last six rows are left out, because their labels look at bars of the golden period
From 2026.01.01 (inclusive) to 2026.05.01 (exclusive) 2,033 The golden file
2026.05.01 to 2026.09.30 2,593 Not used in Python. The EA runs on this period in the tester

The table dates are the script parameters, compared with the text of the time column. A row belongs to the golden file when 2026.01.01 <= time < 2026.05.01. My MetaQuotes-Demo data has no H1 bars on New Year's Day. The bar after 2025.12.31 23:00 is 2026.01.02 00:00. So the first golden row is 2026.01.02 00:00, and the last golden row is 2026.04.30 23:00. The six-row gap removes training rows only, never golden rows. Data from another server can give a different row count for the same dates.

Without the six-row gap the last training rows would carry information from the first golden bars into the model. That does not change any parity result, but it could make the accuracy below look better than it is. On the golden rows the model's accuracy is 34.7%, below the 37.2% share of the largest class. The model has no edge, and nothing in the checks depends on it having one.

The script fits a StandardScaler and a RandomForestClassifier in one Pipeline and converts it with skl2onnx. The default conversion of a classifier ends in a ZipMap node, so the probability output is a sequence of maps from class to probability. The option zipmap False turns it into a plain float tensor of shape [N, 3]. An EA can read that tensor into a matrix:

def export(pipe, nfeat, path, zipmap=False, double=False):
    kind = DoubleTensorType if double else FloatTensorType
    opts = None if zipmap else {id(pipe.steps[-1][1]): {"zipmap": False}}
    model = convert_sklearn(pipe, initial_types=[("float_input", kind([None, nfeat]))],
                            options=opts, target_opset={"": 17, "ai.onnx.ml": 3})
    onnx.save(model, path)
    return model

Next to model.onnx, make_check_files.py writes the contract. It lists each input and output by position with its name, its kind, its element type, and its dimensions. A dimension of -1 is free. Three more rows follow:

kind,index,name,type,elem,dims
input,0,float_input,tensor,float,-1x4
output,0,label,tensor,int64,-1
output,1,probabilities,tensor,float,-1x3
features,4,,,,rsi14|atr14_norm|ret10|bbw20
classes,3,,,,0|1|2
sha256,0,,,,b77b0d3f8d284cf27e4de401514352ffec22a81316d26cfd8610a63e1d8e3269
  • The features row names the feature columns in the order the model takes them. COnnxParity uses these names to find the columns of the golden file, and the contract check compares their count with the width of the input.
  • The classes row lists the class labels in the order of the probability columns. The contract check compares their count with the width of the probability output. The label values themselves can only be checked when the model answers, so Predict() refuses any label that is not in this list.
  • The sha256 row holds the hash of model.onnx.

The script then writes golden.csv with the four features of every golden row. Each row also holds the label and probabilities from onnxruntime and from scikit-learn. A third file, forest.json, holds the scaler and every tree as plain numbers for the check in Section 9. The script also writes five broken variants for the tests: the default ZipMap export, a double input, a model trained on five features, the model without its probability output, and the same pipeline trained with another seed. Its output on my data:

rows 23256, train 18624 (the last 6 rows before 2026.01.01 left out), golden 2033 (2026.01.02 00:00 to 2026.04.30 23:00), after the golden period 2593
golden-period accuracy 0.3468, share of the largest class 0.3724
onnxruntime vs scikit-learn: 0 of 2033 labels differ, largest probability difference 5.76e-08
graph name fe8ed67da66940d5838d242c8d80865f; split nodes 2335, threshold equal to the nearest float32 1753, to the largest float32 not above it 2335
model.onnx             tensor float -1x4 | tensor int64 -1 | tensor float -1x3  sha256 b77b0d3f8d284cf2
model_zipmap.onnx      tensor float -1x4 | tensor int64 -1 | sequence  sha256 26af6a58c51cc4de
model_double.onnx      tensor double -1x4 | tensor int64 -1 | tensor float -1x3  sha256 3c9b5d99371c5294
model_5features.onnx   tensor float -1x5 | tensor int64 -1 | tensor float -1x3  sha256 2cc81b6448e99c46
model_label_only.onnx  tensor float -1x4 | tensor int64 -1  sha256 f84cbbe74f58fbc4
model_retrained.onnx   tensor float -1x4 | tensor int64 -1 | tensor float -1x3  sha256 cfb071c80acd6122


Section 2: Checking the contract

A check ends with one code:

//+------------------------------------------------------------------+
//| Result of a contract check. OK is 0. Among the other codes a     |
//| smaller value is a more serious problem, and when a check finds  |
//| several problems the smallest code becomes the result            |
//+------------------------------------------------------------------+
enum ENUM_ONNX_CHECK
  {
   ONNX_CHECK_OK=0,           // the model matches the contract
   ONNX_CHECK_NO_MODEL,       // the model handle is invalid
   ONNX_CHECK_NO_CONTRACT,    // the contract is missing, empty or inconsistent
   ONNX_CHECK_INPUT_COUNT,    // the model has a different number of inputs
   ONNX_CHECK_OUTPUT_COUNT,   // the model has a different number of outputs
   ONNX_CHECK_NOT_TENSOR,     // a value is a sequence or a map, not a tensor
   ONNX_CHECK_ELEM_TYPE,      // a tensor has a different element type
   ONNX_CHECK_SHAPE,          // a dimension differs, or a non-batch dimension is free
   ONNX_CHECK_HASH,           // the signature matches, the file is not the one in the contract
   ONNX_CHECK_NAME            // a name differs (a problem only in strict mode)
  };

ONNX_CHECK_OK is 0. Among the other codes, a smaller value is a more serious problem. A check does not stop at the first problem. It records every problem it finds, and the smallest code becomes the result. Problem() does this, and it is also where a name difference is set aside unless strict mode is on:

//+------------------------------------------------------------------+
//| Record a problem. A name problem changes the result only in      |
//| strict mode. Otherwise the smallest non-zero code wins           |
//+------------------------------------------------------------------+
void COnnxContract::Problem(ENUM_ONNX_CHECK &worst,const ENUM_ONNX_CHECK code,const string text)
  {
   int n=ArraySize(m_problems);
   ArrayResize(m_problems,n+1);
   ArrayResize(m_codes,n+1);
   m_problems[n]=text;
   m_codes[n]=code;
   if(code==ONNX_CHECK_NAME && !m_strict)
      return;
   if(worst==ONNX_CHECK_OK || code<worst)
      worst=code;
  }

ReadModel() collects the actual signature with OnnxGetInputCount(), OnnxGetOutputCount(), the name functions, and the type information functions. Check() then compares it with the contract and the model bytes:

//+------------------------------------------------------------------+
//| Compare the model and its file bytes with the contract           |
//+------------------------------------------------------------------+
ENUM_ONNX_CHECK COnnxContract::Check(const long handle,const uchar &model[])
  {
   ArrayResize(m_problems,0);
   ArrayResize(m_codes,0);
   ENUM_ONNX_CHECK worst=ONNX_CHECK_OK;
   m_model_sha=Sha256(model);
   if(handle==INVALID_HANDLE || !ReadModel(handle))
     {
      Problem(worst,ONNX_CHECK_NO_MODEL,"the model handle is invalid or its values cannot be read");
      m_worst=worst;
      return(worst);
     }
   if(ArraySize(m_expected)==0)
     {
      Problem(worst,ONNX_CHECK_NO_CONTRACT,"the contract is empty");
      m_worst=worst;
      return(worst);
     }
//--- the extra rows must agree with the contract's own input and output rows (a free width is a shape problem)
   if(ArraySize(m_features)==0 || (InputWidth()>0 && ArraySize(m_features)!=InputWidth()))
      Problem(worst,ONNX_CHECK_NO_CONTRACT,StringFormat("the contract names %d features for an input of width %I64d",
              ArraySize(m_features),InputWidth()));
   if(Classes()==0 || (LastDim("output",1)>0 && Classes()!=LastDim("output",1)))
      Problem(worst,ONNX_CHECK_NO_CONTRACT,StringFormat("the contract lists %d classes for a probability output of width %I64d",
              Classes(),LastDim("output",1)));
//--- counts first: OnnxRun() takes the values by position, so a missing output shifts everything
   int ein=0,eout=0,ain=0,aout=0;
   for(int i=0; i<ArraySize(m_expected); i++)
      if(m_expected[i].kind=="input")
         ein++;
      else
         eout++;
   for(int i=0; i<ArraySize(m_actual); i++)
      if(m_actual[i].kind=="input")
         ain++;
      else
         aout++;
   if(ain!=ein)
      Problem(worst,ONNX_CHECK_INPUT_COUNT,StringFormat("inputs: the contract has %d, the model has %d",ein,ain));
   if(aout!=eout)
      Problem(worst,ONNX_CHECK_OUTPUT_COUNT,StringFormat("outputs: the contract has %d, the model has %d",eout,aout));
//--- then every value that both sides have
   for(int i=0; i<ArraySize(m_expected); i++)
     {
      int k=Find(m_actual,m_expected[i].kind,m_expected[i].index);
      if(k<0)
         continue;
      string where=StringFormat("%s %d",m_expected[i].kind,m_expected[i].index);
      if(m_actual[k].type!=m_expected[i].type)
        {
         Problem(worst,ONNX_CHECK_NOT_TENSOR,StringFormat("%s '%s' is a %s, the contract expects a %s",where,
                 m_actual[k].name,m_actual[k].type,m_expected[i].type));
         continue;
        }
      if(m_actual[k].elem!=m_expected[i].elem)
         Problem(worst,ONNX_CHECK_ELEM_TYPE,StringFormat("%s '%s' holds %s, the contract expects %s",where,
                 m_actual[k].name,m_actual[k].elem,m_expected[i].elem));
      //--- dimension 0 is the batch and may be free, every other dimension must be fixed and equal
      bool same=(ArraySize(m_actual[k].dims)==ArraySize(m_expected[i].dims));
      for(int j=0; same && j<ArraySize(m_actual[k].dims); j++)
        {
         long a=m_actual[k].dims[j],e=m_expected[i].dims[j];
         if(j==0 ? (a>=0 && e>=0 && a!=e) : (a<0 || e<0 || a!=e))
            same=false;
        }
      if(!same)
         Problem(worst,ONNX_CHECK_SHAPE,StringFormat("%s '%s' has shape %s, the contract expects %s (only dimension 0 may be free)",
                 where,m_actual[k].name,DimsText(m_actual[k].dims),DimsText(m_expected[i].dims)));
      if(m_actual[k].name!=m_expected[i].name)
         Problem(worst,ONNX_CHECK_NAME,StringFormat("%s is named '%s', the contract says '%s'",where,
                 m_actual[k].name,m_expected[i].name));
     }
//--- identity last: a matching signature says nothing about the weights inside the file
   if(m_sha256=="")
     {
      if(m_need_hash)
         Problem(worst,ONNX_CHECK_HASH,"the contract has no sha256 row");
     }
   else
      if(m_model_sha!=m_sha256)
         Problem(worst,ONNX_CHECK_HASH,StringFormat("the model file has SHA-256 %s, the contract expects %s",
                 m_model_sha=="" ? "(no bytes given)" : StringSubstr(m_model_sha,0,16)+"...",StringSubstr(m_sha256,0,16)+"..."));
   m_worst=worst;
   return(worst);
  }

The counts come first in the code because OnnxRun() binds its buffers by position. A model with one output fewer does not fail on a name. The mismatch shows up in the first OnnxRun() call, as it did in my first version. Because the smallest code wins, the order of the calls inside Check() does not change the result. A ZipMap model checked in strict mode has three problems at once (a sequence output, a different label name, and a different hash), and the result is ONNX_CHECK_NOT_TENSOR. Test 15 in Section 6 checks exactly this.

Dimension 0 is treated as the batch, and a free size there matches any size. Every other dimension must be fixed and equal on both sides. A model with a free feature or class dimension fails with ONNX_CHECK_SHAPE. This is a deliberate restriction. COnnxClassifier needs those sizes to build its buffers, and a model whose dimension 0 is not a batch does not fit this class at all.

The hash compares the bytes the session was created from with the sha256 row. A model with the same signature and other weights passes every other test in Check() and fails this one. When a check fails, Signature() returns what the model reports, one value per line, and the hash of its bytes.

A name difference is always listed, but it fails the check only when SetStrictNames(true) is set. OnnxRun() takes the buffers by position and does not use the names, and skl2onnx changes them with its options ("output_label" with ZipMap, "label" without it).


Section 3: The classifier

COnnxClassifier owns the session. LoadFile() reads the model as bytes and creates the session with OnnxCreateFromBuffer(), so the hash covers exactly what the session runs. Prepare() runs the contract check after the session is created. A model that fails is released at once, and the error text names the problem:

//+------------------------------------------------------------------+
//| Check the contract and fix the shapes, release on any failure    |
//+------------------------------------------------------------------+
bool COnnxClassifier::Prepare(const string contract_text,const uchar &model[])
  {
   if(m_handle==INVALID_HANDLE)
     {
      m_check=ONNX_CHECK_NO_MODEL;
      m_error=StringFormat("the model could not be created, error %d",GetLastError());
      return(false);
     }
   m_contract.LoadText(contract_text);
   m_check=m_contract.Check(m_handle,model);
   if(m_check!=ONNX_CHECK_OK)
     {
      m_error=EnumToString(m_check)+": "+m_contract.Worst();
      Release();
      return(false);
     }
//--- batch 1: one bar per call, dimension 0 of every value becomes 1
   if(!m_contract.ApplyShapes(m_handle,1))
     {
      m_error=StringFormat("setting the shapes failed, error %d",GetLastError());
      Release();
      return(false);
     }
   m_features=m_contract.InputWidth();
   m_classes=m_contract.Classes();
   m_contract.Labels(m_labels);
   m_error="";
   return(true);
  }

ApplyShapes() sets dimension 0 of every input and output to 1. The label output has the shape [-1], so the output needs a shape as well as the input. Predict() then passes one matrix in and one buffer for each output:

//+------------------------------------------------------------------+
//| One row in, the label and the probabilities out                  |
//+------------------------------------------------------------------+
bool COnnxClassifier::Predict(const vectorf &features,long &label,vectorf &probabilities)
  {
   label=-1;
   if(m_handle==INVALID_HANDLE)
     {
      m_error="the model is not loaded";
      return(false);
     }
   if((long)features.Size()!=m_features)
     {
      m_error=StringFormat("the model takes %I64d features, the row has %I64u",m_features,features.Size());
      return(false);
     }
   matrixf in(1,(ulong)m_features);
   in.Row(features,0);
   long out_label[1];
   matrixf out_prob(1,(ulong)m_classes);
//--- every output gets a buffer: with one buffer fewer OnnxRun() fails with error 5804
   ulong t0=GetMicrosecondCount();
   bool ok=OnnxRun(m_handle,ONNX_NO_CONVERSION,in,out_label,out_prob);
   ulong dt=GetMicrosecondCount()-t0;
   if(!ok)
     {
      m_error=StringFormat("OnnxRun failed, error %d",GetLastError());
      return(false);
     }
   if(m_runs<1000000)
     {
      if(m_runs>=ArraySize(m_us))
         ArrayResize(m_us,m_runs+1,10000);
      m_us[m_runs++]=dt;
     }
   label=out_label[0];
   probabilities=out_prob.Row(0);
//--- the label must be one of the contract's classes, or the probability columns mean something else
   if(ClassIndex(label)<0)
     {
      m_error=StringFormat("the model returned label %I64d, which is not in the contract's class list",label);
      label=-1;
      return(false);
     }
   return(true);
  }

The call passes ONNX_NO_CONVERSION. Without it the terminal converts the input data automatically, and the contract has already fixed the input as float. ClassIndex() maps a label to its probability column through the classes row. Each call is timed with GetMicrosecondCount(), and Latency() returns the median, the 99th percentile, and the maximum.


Section 4: The golden file

COnnxParity::Run() finds every column by its name. The feature columns come from the features row of the contract. The answer columns are ort_label, ort_p0, ort_p1, and so on. The scikit-learn columns skl_label and skl_p0 onwards are optional. Every row goes through Predict(). The largest difference to each Python answer is kept, and every row over the tolerance can be written to a file for inspection:

//+------------------------------------------------------------------+
//| Run every golden row and compare with the Python answers. Every  |
//| column is found by its name: the features by the names in the   |
//| contract, the answers as ort_label, ort_p0.. and skl_label,      |
//| skl_p0.. (the scikit-learn columns are optional)                 |
//+------------------------------------------------------------------+
bool COnnxParity::Run(COnnxClassifier &model,const string golden_file,const double tolerance,
                      SOnnxParityReport &rep,const string diff_file)
  {
   rep.Reset();
   rep.tolerance=tolerance;
   string names[];
   int nfeat=model.Contract().FeatureNames(names);
   int nprob=model.Classes();
   if(!model.IsReady() || nfeat!=model.Features() || nprob<1)
     {
      rep.reason="the model is not loaded or its contract has no feature names";
      return(false);
     }
   int h=FileOpen(golden_file,FILE_READ|FILE_TXT|FILE_ANSI);
   if(h==INVALID_HANDLE)
     {
      rep.reason="cannot open "+golden_file;
      return(false);
     }
   string head[];
   string first=FileReadString(h);
   StringTrimRight(first);
   int cols=StringSplit(first,',',head);
//--- column of every feature and every answer, by name
   int fcol[],ocol[],scol[];
   ArrayResize(fcol,nfeat);
   ArrayResize(ocol,nprob+1);
   ArrayResize(scol,nprob+1);
   for(int i=0; i<nfeat; i++)
      if((fcol[i]=Column(head,names[i]))<0)
         rep.reason+=" "+names[i];
   ocol[0]=Column(head,"ort_label");
   scol[0]=Column(head,"skl_label");
   for(int c=0; c<nprob; c++)
     {
      ocol[c+1]=Column(head,"ort_p"+IntegerToString(c));
      scol[c+1]=Column(head,"skl_p"+IntegerToString(c));
     }
   rep.has_skl=(scol[ArrayMinimum(scol)]>=0);
   if(ocol[ArrayMinimum(ocol)]<0)
      rep.reason+=" ort_label or ort_p0..ort_p"+IntegerToString(nprob-1);
   if(rep.reason!="")
     {
      rep.reason="missing columns:"+rep.reason;
      FileClose(h);
      return(false);
     }
   int d=INVALID_HANDLE;
   if(diff_file!="")
     {
      d=FileOpen(diff_file,FILE_WRITE|FILE_TXT|FILE_ANSI);
      if(d!=INVALID_HANDLE)
         FileWriteString(d,"line,mql_label,ort_label,skl_label,diff_ort,diff_skl\n");
     }
   vectorf x(nfeat),p;
   int line_no=1;
   while(!FileIsEnding(h))
     {
      string line=FileReadString(h);
      line_no++;
      StringTrimRight(line);
      if(line=="")
         continue;
      //--- a short line is an error in the file, not a row to skip
      string f[];
      if(StringSplit(line,',',f)<cols)
        {
         rep.bad_rows++;
         continue;
        }
      for(int i=0; i<nfeat; i++)
         x[i]=(float)StringToDouble(f[fcol[i]]);
      rep.rows++;
      long label;
      if(!model.Predict(x,label,p))
        {
         rep.failed++;
         continue;
        }
      //--- the same float32 graph should give the onnxruntime numbers, scikit-learn rounds differently
      double dort=0.0,dskl=0.0;
      for(int c=0; c<nprob; c++)
        {
         dort=MathMax(dort,MathAbs((double)p[c]-StringToDouble(f[ocol[c+1]])));
         if(rep.has_skl)
            dskl=MathMax(dskl,MathAbs((double)p[c]-StringToDouble(f[scol[c+1]])));
        }
      rep.max_ort=MathMax(rep.max_ort,dort);
      rep.max_skl=MathMax(rep.max_skl,dskl);
      if(label!=StringToInteger(f[ocol[0]]))
         rep.label_ort++;
      if(rep.has_skl && label!=StringToInteger(f[scol[0]]))
         rep.label_skl++;
      if(dskl>tolerance)
         rep.rows_skl++;
      if(d!=INVALID_HANDLE && (dort>tolerance || dskl>tolerance))
         FileWriteString(d,StringFormat("%d,%I64d,%s,%s,%.9g,%.9g\n",line_no,label,f[ocol[0]],
                                        rep.has_skl ? f[scol[0]] : "",dort,dskl));
     }
   FileClose(h);
   if(d!=INVALID_HANDLE)
      FileClose(d);
//--- scikit-learn is reported only: the terminal is held to the onnxruntime answers
   rep.passed=(rep.rows>0 && rep.bad_rows==0 && rep.failed==0 && rep.label_ort==0 && rep.max_ort<=tolerance);
   return(true);
  }

An empty line is skipped. A line with fewer fields than the header is counted as a bad line, and one bad line fails the run. The report passes only when there are rows, no bad lines, no failed Predict() calls, no label different from onnxruntime, and no probability further from onnxruntime than the tolerance. The difference to scikit-learn is reported but does not fail the run. So the run holds the terminal to the ONNX graph as onnxruntime executes it. The original scikit-learn model is only a reference, and Section 9 compares the two.

I use a tolerance of 1e-6. The largest difference to onnxruntime I measured on this model was 1.49e-7, so 1e-6 leaves room above it. The value is my choice for one model, one terminal build, and one onnxruntime version. I have not shown that it holds for others.


Section 5: Check files for your own model

The script export_model.py only knows the example model. For your own classifier, make_check_files.py needs the ONNX file and a CSV with a time column and one column per feature. The names given with --features must be in the order the model takes them. The order of the columns in the CSV does not matter.

python make_check_files.py write model.onnx features.csv --features rsi14,atr14_norm,ret10,bbw20 --from 2026.01.01 --to 2026.05.01
python make_check_files.py audit model.onnx ea_log.csv --features rsi14,atr14_norm,ret10,bbw20

The --from date is inclusive, and the --to date is exclusive. Both must use the text format of the time column. On the example features.csv, these dates select exactly the 2,033 golden rows of Section 1. The write mode creates model_contract.csv and golden.csv next to the model. The class labels come from the classifier node of the graph. If the graph has none, the script says so and uses 0 to C-1. A model whose probability output is not a [N, C] tensor, such as a ZipMap export, is refused with a message. On the example model and the golden period, the write mode produces the same contract rows as export_model.py:

contract: 4 features, classes [0, 1, 2], sha256 b77b0d3f8d284cf2
golden: 2033 rows from 2026.01.02 00:00 to 2026.04.30 23:00
own contract equals the export
own golden equals the export without the scikit-learn columns

The audit mode runs the features of a log through onnxruntime and compares the label and probability columns the EA wrote. Section 7 uses it on the tester log. I have tested the tool only on the example model and its broken variants, so another converter or model type may need changes.


Section 6: Checking the code

TestOnnxParity.mq5 runs 36 checks on the files export_model.py wrote. Checks 1 to 15 cover the contract: one broken model per kind of mismatch, the extra rows, the hash, the names, and a model with several problems. Checks 16 to 20 run broken models without any check, to see what the terminal itself does with them. Checks 21 to 28 cover the classifier, and checks 29 to 36 cover the golden file:

PASS  1 contract file loads                            classes 3, input width 4, 4 feature names
PASS  2 exported model matches its contract            ONNX_CHECK_OK
PASS  3 zipmap left on: output is not a tensor         output 1 'output_probability' is a sequence, the contract expects a tensor
PASS  4 double input: element type differs             input 0 'float_input' holds double, the contract expects float
PASS  5 five features: shape differs                   input 0 'float_input' has shape -1x5, the contract expects -1x4 (only dimension 0 may be free)
PASS  6 probability output removed: output count       outputs: the contract has 2, the model has 1
PASS  7 retrained model: same signature, other hash    the model file has SHA-256 cfb071c80acd6122..., the contract expects b77b0d3f8d284cf2...
PASS  8 empty contract                                 the contract is empty
PASS  9 invalid handle                                 ONNX_CHECK_NO_MODEL
PASS 10 class count differs from the probability width the contract lists 2 classes for a probability output of width 3
PASS 11 free non-batch dimension in the contract       input 0 'float_input' has shape -1x4, the contract expects -1x-1 (only dimension 0 may be free)
PASS 12 contract without a hash, hash required         the contract has no sha256 row
PASS 13 renamed output, default mode                   output 1 is named 'probabilities', the contract says 'output_probability'
PASS 14 renamed output, strict mode                    ONNX_CHECK_NAME
PASS 15 zipmap model, strict names: smallest code wins ONNX_CHECK_NOT_TENSOR, 3 problems listed
ONNX: incorrect parameters count passed to OnnxRun, expected 3 instead of 2 ['Scripts\OnnxParity\TestOnnxParity.mq5':162:27]
PASS 16 OnnxRun with one output buffer fails           error 5804
ONNX: invalid output parameter #1, array expected for 'ONNX_TYPE_SEQUENCE' ['Scripts\OnnxParity\TestOnnxParity.mq5':162:102]
PASS 17 zipmap model run with a probability matrix     error 5805
ONNX: invalid input parameter #0 size, expected 32 bytes instead of 16 ['Scripts\OnnxParity\TestOnnxParity.mq5':162:95]
PASS 18 double model run with a float matrix           error 5807
ONNX: invalid input parameter #0 size, expected 20 bytes instead of 16 ['Scripts\OnnxParity\TestOnnxParity.mq5':162:95]
PASS 19 five-feature model run with four features      error 5807
ONNX: incorrect parameters count passed to OnnxRun, expected 2 instead of 3 ['Scripts\OnnxParity\TestOnnxParity.mq5':162:66]
PASS 20 label-only model run with two output buffers   error 5804
PASS 21 classifier loads the exported model            4 features, 3 classes
PASS 22 probabilities sum to 1, label is the arg max   p = 0.301358 0.392670 0.305972, label 1
PASS 23 three features are refused                     the model takes 4 features, the row has 3
PASS 24 classifier refuses the zipmap model            ONNX_CHECK_NOT_TENSOR: output 1 'output_probability' is a sequence, the contract expects a tensor
PASS 25 classifier refuses the label-only model        ONNX_CHECK_OUTPUT_COUNT: outputs: the contract has 2, the model has 1
PASS 26 classifier refuses a missing contract          ONNX_CHECK_NO_CONTRACT: the contract is empty
PASS 27 classifier refuses the retrained model         ONNX_CHECK_HASH: the model file has SHA-256 cfb071c80acd6122..., the contract expects b77b0d3f8d284cf2...
PASS 28 contract with labels 5|6|7: Predict() refuses  the model returned label 1, which is not in the contract's class list
PASS 29 golden file, exported model                    PASS: 2033 rows, 0 bad lines, 0 failed, labels vs onnxruntime 0, max diff 1.49e-07 | scikit-learn: labels 0, max diff 1.27e-07, rows over 1e-06 0
PASS 30 golden file with one probability moved by 0.01 FAIL: 2033 rows, 0 bad lines, 0 failed, labels vs onnxruntime 0, max diff 0.01 | scikit-learn: labels 0, max diff 1.27e-07, rows over 1e-06 0
PASS 31 golden file with one short line fails          FAIL: 2032 rows, 1 bad lines, 0 failed, labels vs onnxruntime 0, max diff 1.49e-07 | scikit-learn: labels 0, max diff 1.27e-07, rows over 1e-06 0
PASS 32 golden file with the columns reversed          PASS: 2033 rows, 0 bad lines, 0 failed, labels vs onnxruntime 0, max diff 1.49e-07 | scikit-learn: labels 0, max diff 1.27e-07, rows over 1e-06 0
PASS 33 golden file without scikit-learn columns       PASS: 2033 rows, 0 bad lines, 0 failed, labels vs onnxruntime 0, max diff 1.49e-07
PASS 34 missing golden file is reported                cannot open OnnxParity\no_such_golden.csv
PASS 35 retrained model, no hash: contract passes      ONNX_CHECK_OK
PASS 36 retrained model fails the golden file          FAIL: 2033 rows, 0 bad lines, 0 failed, labels vs onnxruntime 241, max diff 0.0705 | scikit-learn: labels 241, max diff 0.0705, rows over 1e-06 2033
Predict() calls 10165: median 6 us, 99th percentile 16 us, max 14313 us
36 passed, 0 failed

Checks 16 to 20 are the reason for the contract. The terminal does refuse every broken model, but only in OnnxRun(), and in an EA that call happens in the first OnTick. The journal messages are clear, and the error codes are different:

Model What changed Contract check OnnxRun() without the check
model.onnx Nothing ONNX_CHECK_OK Runs
model_zipmap.onnx ZipMap left on ONNX_CHECK_NOT_TENSOR Error 5805, array expected for 'ONNX_TYPE_SEQUENCE'
model_double.onnx Double input ONNX_CHECK_ELEM_TYPE Error 5807, expected 32 bytes instead of 16
model_5features.onnx Five features ONNX_CHECK_SHAPE Error 5807, expected 20 bytes instead of 16
model_label_only.onnx Probability output removed ONNX_CHECK_OUTPUT_COUNT Error 5804, expected 2 instead of 3
model_retrained.onnx Trained with another seed ONNX_CHECK_HASH Runs, 241 of 2,033 labels differ

To confirm that the tests can fail, I introduced three defects into the classes, one per copy, and ran the test script on each defective copy. In the first copy, Run() ignored the probability difference and compared only the labels. The golden file with one probability moved by 0.01 then passed. Check 30 expects that file to fail, so check 30 reported FAIL. In the second copy, Check() skipped the output count. Checks 6 and 25 on the model without its probability output reported FAIL, because the result became ONNX_CHECK_HASH instead of ONNX_CHECK_OUTPUT_COUNT. In the third copy, Check() skipped the hash. Checks 7, 12, 15, and 27 reported FAIL, and the retrained model loaded without complaint. Each defect was found, and the code was restored.


Section 7: The EA in the Strategy Tester

OnnxParityEA.mq5 embeds the model and the contract as resources, so the hash is checked against the bytes inside the .ex5. The golden file comes in with #property tester_file. Both checks run in OnInit, and a model that fails either one never reaches OnTick:

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- a model that does not match the contract never reaches OnTick
   if(!g_model.LoadBuffer(ExtModel,ExtContract))
     {
      PrintFormat("OnnxParityEA: model refused, %s",g_model.Error());
      return(INIT_FAILED);
     }
   if(InpGolden!="")
     {
      SOnnxParityReport rep;
      if(!COnnxParity::Run(g_model,InpGolden,InpTolerance,rep) || !rep.passed)
        {
         PrintFormat("OnnxParityEA: golden file %s, %s",InpGolden,COnnxParity::Text(rep));
         return(INIT_FAILED);
        }
      PrintFormat("OnnxParityEA: golden file %s",COnnxParity::Text(rep));
     }
   if(!g_feat.Init(_Symbol,_Period))
      return(INIT_FAILED);
   if(InpLog!="")
     {
      g_log=FileOpen(InpLog,FILE_WRITE|FILE_TXT|FILE_ANSI|FILE_COMMON);
      if(g_log!=INVALID_HANDLE)
         FileWriteString(g_log,"time,"+COnnxFeatures::Names()+",label,p0,p1,p2,us\n");
     }
   g_trade.SetExpertMagicNumber(20261003);
   return(INIT_SUCCEEDED);
  }

On every new bar the EA computes the features of the closed bar with COnnxFeatures and calls Predict(). It writes the time, the features, the label, the probabilities, and the time of the call to a CSV file in the common Files folder. It also trades the signals with a fixed volume, so that the run goes through a complete OnTick path with orders. The trading result only describes the example model and is not evaluated here.

Parameter Value
Symbol and period EURUSD H1, 2026.05.01 to 2026.09.30
Modeling 1-minute OHLC
Golden file in OnInit 2,033 rows from 2026.01.02 00:00 to 2026.04.30 23:00, tolerance 1e-6
Deposit and volume 10,000 USD, 0.10 lots

The golden period and the Strategy Tester period do not overlap, except for the first predicted bar. The EA predicts the bar that has just closed. Its first prediction, at 2026.05.01 00:00, is for the bar of 2026.04.30 23:00, the last golden row. The other 2,591 bars are not in the golden file. As in a live EA, the golden file is fixed at export time, and a golden pass in OnInit says nothing about the later bars. To cover them, the EA logs every bar, and make_check_files.py audit reruns the logged features in onnxruntime after the tester run:

audit ea_log.csv: 2592 rows, labels differ 0, max probability diff 1.49e-07, rows over 1e-06 0 -> PASS

The results of the run:

Measure Value
Golden check in OnInit PASS, 2,033 rows, largest difference to onnxruntime 1.49e-7
Bars predicted 2,592, none failed
Audit of the log in onnxruntime PASS, 0 labels differ, largest probability difference 1.49e-7
Predict() time per bar median 9, 99th percentile 39, maximum 107 microseconds

I ran the same test three times, and the golden check and the log gave the same numbers every time. The time per call varies between runs and machines. These numbers come from an AMD Ryzen 5 PRO 5650U.

Time of one Predict() call per bar

EURUSD H1 in the tester, 2026.05.01 to 2026.09.30, one row per call

Histogram of the time of each Predict() call in the tester, in microseconds, with the median and the 99th percentile marked

Fig. 2. Histogram of the time of each Predict() call in the tester, in microseconds, with the median and the 99th percentile marked


Section 8: A retrained model with the same signature

The file model_retrained.onnx is the same pipeline trained on the same rows with random_state 8 instead of 7. Its inputs and outputs are identical to those of model.onnx, and its hash is not. With the full contract the classifier refuses it with ONNX_CHECK_HASH.

To see what the golden file does on its own, test 35 loads the same model against a contract without the sha256 row, with the hash requirement switched off. The contract check then passes. On the golden rows, 241 of 2,033 labels differ from the exported model, and the largest probability difference is 0.0705 (median 0.0126). The golden check fails.

A retrained model on the golden rows

Largest probability difference per row, retrained model minus exported model

Histogram of the largest probability difference per golden row between the retrained model and the exported model

Fig. 3. Histogram of the largest probability difference per golden row between the retrained model and the exported model

The hash fails for any change of the file, even one that changes no output. The golden file fails only if the change reaches its rows. So neither check replaces the other.


Section 9: A consistency check outside MQL5

When one implementation both produces and checks the numbers, the same error can pass both steps. The script parity_crosscheck.py uses only the Python 3 standard library. It is my second implementation of the same model and feature formulas, so I call it a consistency check. It does not replace a check by someone else. It reads forest.json and walks every tree itself, in two ways. The sklearn walk scales in float32 as (x - mean) / scale and compares with the float64 thresholds. The onnx walk scales as (x - mean) * (1 / scale) in float32. It compares with each threshold replaced by the largest float32 that is not above it, because skl2onnx writes the graph that way. A third walk, onnx-nearest, rounds the thresholds to the nearest float32 instead. It then compares both walks with the golden file and the EA log, and recomputes the four features from the price data in features.csv:

golden rows 2033, trees 50
walk         max diff vs onnxruntime  vs scikit-learn  labels differ: onnxruntime  scikit-learn
sklearn                5.79e-08        1.11e-16                          0             0
onnx                   5.79e-08        1.11e-16                          0             0
onnx-nearest           5.79e-08        1.11e-16                          0             0
rows where the two walks reach a different leaf: 0
rows whose onnx path passes a split closer than 1e-6: 2, closest 8.94e-07
EA log rows 2592, max diff vs the onnx walk 1.26e-07, labels differ 0, signals at 0.45: 491
EA log vs the onnx-nearest walk: max diff 0.00195, rows over 1e-6 1
features recomputed from prices: 22756 rows after 500 warm-up rows, largest relative difference rsi14 6e-08, atr14_norm 6.1e-08, ret10 6e-08, bbw20 6.1e-08
EA features matched to the export by time: 2592 rows, largest difference rsi14 0, atr14_norm 0, ret10 0, bbw20 0

Both walks reproduce scikit-learn within 1.11e-16 and onnxruntime within 5.79e-8 on the golden rows, and they reach the same leaf on every golden row. On the 2,592 bars of the tester run, the onnx walk matches the probabilities the EA logged within 1.26e-7. With the audit in Section 7, the terminal, onnxruntime, and the scikit-learn walk gave the same labels on every bar of the run. Their probabilities agree within 1.5e-7.

The line for the onnx-nearest walk shows an assumption of mine that was wrong. An earlier version of my onnx walk rounded every threshold to the nearest float32. It disagreed with the EA by 0.00195 on one bar, 2026.09.28 09:00. On that bar, tree 36 splits on atr14_norm at node 10, and the scaled value is exactly the nearest float32 of the threshold. skl2onnx did not store that value in this export. The export output in Section 1 shows that skl2onnx stored all 2,335 split thresholds as the largest float32 value that does not exceed the float64 threshold. For 582 of them, this value differs from the nearest float32. For a float32 input, x <= that value holds exactly when x <= the float64 threshold. So for a float32 input the graph takes the same branch as scikit-learn, and only my wrong walk went the other way.

Probability difference on every bar of the tester run

Terminal against onnxruntime and against the scikit-learn tree walk, log scale

Largest probability difference per bar of the terminal against onnxruntime and against the scikit-learn tree walk. The scale is logarithmic, with the tolerance as a dashed line. Exact matches are drawn at the bottom

Fig. 4. Largest probability difference per bar of the terminal against onnxruntime and against the scikit-learn tree walk. The scale is logarithmic, with the tolerance as a dashed line. Exact matches are drawn at the bottom

A row is fragile when its path passes very close to a split. A rounding difference of the size seen here can then send it to the other side. Fig. 5 shows how close each golden row comes to a threshold on its path.

Distance of the golden rows to the nearest split

Smallest distance between a scaled feature and a threshold on the row's path, over all 50 trees

Histogram of the smallest distance between a golden row's scaled feature and a split threshold on its path, on a log scale, with 1e-6 marked

Fig. 5. Histogram of the smallest distance between a golden row's scaled feature and a split threshold on its path, on a log scale, with 1e-6 marked

Two golden rows pass a split closer than 1e-6, and the closest is 8.94e-7 away. On both rows the terminal, onnxruntime, and scikit-learn still agree within 1.5e-7. Rows like these are where a different converter, opset, or arithmetic order could change a leaf, and a golden file only covers the ones it happens to contain.

The feature recomputation answers a different question. The export and the EA use the same COnnxFeatures code, so their features agree even if that code computes the wrong thing. The script computes the RSI with Wilder smoothing, the ATR as the mean of 14 true ranges, the 10-bar return, and the Bands width with the population deviation, from the high, low, and close columns. After 500 warm-up rows, the largest relative difference to the exported features is 6e-8 for the RSI and the return. For the ATR and the Bands width it is 6.1e-8. Both are the size of the rounding of a float32 value. The EA's features equal the exported ones exactly on all 2,592 bars. This shows that COnnxFeatures computes the formulas described in Section 1. It does not show that these formulas make good features.


What the checks do not cover

  • Model quality. A model that passes every check can still be useless, as the example model is.
  • Rows outside the golden file. The golden file proves only its own rows. Tree models are sensitive near split thresholds, and Fig. 5 shows how close some rows come to one.
  • Drift and out-of-domain inputs. Nothing here watches the live distribution of the features. The article on Wasserstein distance covers that.
  • A replaced bundle. If the model, the contract, and the golden file are all replaced together by a consistent new set, every check passes. The hash only proves that the model and its contract belong together.
  • The original scikit-learn model. The pass criterion compares the terminal with the ONNX graph as onnxruntime runs it. A difference between the graph and scikit-learn is only reported.
  • The feature formulas. The EA log is checked against the exported features and against a second implementation of the formulas. Whether the formulas are useful is outside the checks.


Limitations

All the numbers come from one model type, a StandardScaler with a RandomForestClassifier converted by skl2onnx 1.20.0 with opsets 17 and ai.onnx.ml 3. They also come from one symbol and timeframe, one training seed, and one terminal build (6230). Other converters, opsets, or model types will round in other places. The tolerance of 1e-6 and the rule to build the golden file from onnxruntime are based on this combination only.

The classes assume a classifier with zipmap off: output 0 is the label, output 1 is a [N, C] float tensor, the labels are integers, and dimension 0 of every value is the batch. Other models need other code. The contract format is my own CSV, and the hash covers the whole file. Everything inside the graph (opset, operators, scaler, trees) is covered only through that hash. The contract does not check these parts one by one. skl2onnx gives every converted graph a random name, which export_model.py prints. So two exports of the same fitted pipeline have different hashes, and the hash identifies one export. It does not identify a set of weights. The contract has to be written in the same run as the model, which both scripts do.

The 36 tests cover the defects I prepared: ZipMap, a double input, a five-feature model, a missing output, a retrained model, an inconsistent contract, edited golden files, and wrong class labels. They do not show that the classes handle other ONNX structures.

The model files, golden answers, and numbers in this article come from these Python packages:

Package Version
Python 3.12.10
numpy 2.5.3
scikit-learn 1.9.1
onnx 1.23.1
skl2onnx 1.20.0
onnxruntime 1.20.1

onnxruntime 1.30.0 crashed on import on my system, so the golden answers come from onnxruntime 1.20.1. The versions of other dependencies, such as SciPy and joblib, were not recorded. Other versions of scikit-learn or numpy can produce other trees, so a retrained model may differ from mine even with the same seed. A different onnxruntime version could change the last digits of the golden answers. The tolerance absorbs that only if the change stays below 1e-6.

The timings come from one CPU and include the copy into the input matrix. The tester run uses 1-minute OHLC modeling.

The script parity_crosscheck.py assumes that a node goes left when the value is at most the threshold, and that the forest probability is the mean of the normalized leaf values. It also assumes that a single float32 operation equals the double result rounded to float32, and that every graph threshold is the largest float32 not above the float64 one. It only knows random forests. Its feature formulas assume the terminal's RSI, ATR, and Bands definitions given in Section 9.


Conclusion

An ONNX model in an EA can be wrong in several ways that look alike in the journal at first. The file may not have the signature the code expects. It may have the right signature and be a different file. Or the terminal may compute other numbers than Python for the same rows. COnnxContract finds the first two in OnInit, with a code and a sentence instead of an error in the first OnTick. COnnxParity finds the third on the rows of a golden file, and make_check_files.py audit checks the bars the EA logged during a Strategy Tester run. COnnxClassifier puts the contract in front of the session and passes a buffer for every output. My first version passed one buffer too few.

On this EURUSD H1 model and build 6230, the terminal reproduced onnxruntime within 1.49e-7 on every golden row and on every bar of a later tester period. A model retrained with another seed had an identical signature and failed the hash. With the hash switched off, the golden file caught it on 241 rows. For this combination, build the golden file from onnxruntime, keep the contract and the golden file next to the model, and audit the EA's log afterwards.

To try it, unpack MQL5.zip into the terminal's data folder. The archive contains only code. Run ExportFeatures.mq5 on an EURUSD H1 chart, then export_model.py on the folder with the features.csv it writes, then TestOnnxParity.mq5. Compile OnnxParityEA.mq5 only after the export, because its resources need model.onnx and model_contract.csv. For your own model, use make_check_files.py instead of export_model.py.

Attached files

# Name Folder Description
1 OnnxContract.mqh MQL5/Include/OnnxParity/ Contract file, model signature, SHA-256, and the comparison with its codes
2 OnnxClassifier.mqh MQL5/Include/OnnxParity/ Classifier that loads only a checked model and passes a buffer for every output
3 OnnxParity.mqh MQL5/Include/OnnxParity/ Golden-file run against onnxruntime, scikit-learn reported if present
4 OnnxFeatures.mqh MQL5/Include/OnnxParity/ The four example features, shared by the export script and the EA
5 TestOnnxParity.mq5 MQL5/Scripts/OnnxParity/ Verification script, 36 checks with PASS or FAIL
6 ExportFeatures.mq5 MQL5/Scripts/OnnxParity/ Writes the features, labels, and prices of the chart symbol to features.csv
7 OnnxParityEA.mq5 MQL5/Experts/OnnxParity/ Example EA with both checks in OnInit and a per-bar log
8 make_check_files.py MQL5/Files/OnnxParity/ Writes the contract and the golden file for your own classifier, and audits an EA log
9 export_model.py MQL5/Files/OnnxParity/ Trains the example model and writes the model, its check files, the trees, and the test variants
10 parity_crosscheck.py MQL5/Files/OnnxParity/ Python 3 standard-library consistency check of the golden file, the EA log, and the features
11 MQL5.zip Unpack into the terminal's data folder All the files above, with MQL5 as the root folder and an OnnxParity subfolder in Include, Scripts, Experts, and Files. No model or data files

Every MQL5 file compiles with 0 errors and 0 warnings in MetaEditor build 6230. Tested on MetaTrader 5 build 6230 with MetaQuotes-Demo.

Attached files |
OnnxContract.mqh (19.31 KB)
OnnxClassifier.mqh (8.46 KB)
OnnxParity.mqh (7.55 KB)
OnnxFeatures.mqh (5.2 KB)
TestOnnxParity.mq5 (15.11 KB)
ExportFeatures.mq5 (3.66 KB)
OnnxParityEA.mq5 (7.33 KB)
export_model.py (7.54 KB)
MQL5.zip (28.47 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.
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 10): Transforms and the Graphics Context Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 10): Transforms and the Graphics Context
We add the missing pieces: an affine transform and a context layer for the Cairo-style engine in MQL5. The six-number matrix is applied as paths are built, turning user coordinates into pixels and enabling reusable widgets by translation, scale, and rotation. CCairoContext stores transform, clip, source, and fill rule, with Save/Restore to manage state safely.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Change Point Detection for Financial Time Series in MQL5 Change Point Detection for Financial Time Series in MQL5
Financial markets can shift between regimes, so detecting when the statistical behavior of returns changes is valuable for analysis. An MQL5 change point detector segments historical returns into periods with different mean and volatility using optimal partitioning with PELT pruning and a BIC-style default penalty. A sensitivity scan tests robustness by showing which detected breaks persist as settings vary.