preview
A Thin gRPC Inference Client: Serving a Live Python Model to MetaTrader 5 Without ONNX

A Thin gRPC Inference Client: Serving a Live Python Model to MetaTrader 5 Without ONNX

MetaTrader 5 — Integration |
182 0
Olamide Daniel Adebayo
Olamide Daniel Adebayo

Introduction

The usual route from a trained scikit-learn model to a live MetaTrader 5 chart is ONNX: export the model, load it with OnnxCreate(), and run inference inside the terminal. That route is hard to beat for a plain function from a fixed feature vector to an output, but it gets awkward once custom code sits in front of the model. The model is a LightGBM classifier, but its input pipeline matters more. A custom transformer converts a window of raw closes into three features: a rolling z-score of log returns, ATR-normalized momentum, and a percentile-ranked volatility regime bucket.

Exporting the transformer requires extra work because skl2onnx has no converter for the custom class. You would need to register one, rewrite the rolling statistics and percentile rank with ONNX operators, and maintain that implementation alongside the Python original. This article takes the other route: the trained pipeline stays in a Python process, and the Expert Advisor asks it for predictions over the network.

WebRequest() cannot speak gRPC because it lacks HTTP/2 and protobuf framing. A thin REST/JSON gateway translates an HTTP POST into a gRPC call and back. The EA stays HTTP/JSON-only; the gateway contains no feature engineering; the model never sees MQL5. Each component has a single responsibility.

This is an integration pattern, not a trading system: the offline replay uses one chronological split and no trading costs, so it describes the confidence gate's behavior and says nothing about future profit. The EA manages one position per symbol, and the indicator reads globals from a single EA instance, so treat the kit as a single-chart setup.

We follow the data in the order it moves: the feature pipeline and its training, the gRPC service, the gateway, the MQL5 client, the EA's signal and risk logic, and a small indicator for the probabilities. Then come the run order, a Strategy Tester limitation that forced a separate offline test, and that test's results. 


Architecture

Two Python processes run alongside the terminal, the inference service and the gateway, and the EA runs inside MetaTrader itself. Each part talks only to its neighbor. From the EA's side this is an ordinary REST call, an HTTP POST with a JSON body and a JSON reply, and that is deliberate: the gRPC contract lives behind the gateway, where Python can use the standard generated stubs.

MQL5 EA → HTTP/JSON → REST gateway → gRPC/protobuf → inference service → predict_proba() → LightGBM pipeline

Fig. 1. Request and response flow from the MQL5 EA through the REST gateway and the gRPC service to the trained pipeline.

Every call carries the last InpLookback completed closes and tick volumes for the chart symbol, oldest first: raw prices, not engineered features. Feature engineering runs only once, in inference_service.py, using the same RollingFeatureTransformer as in training. This avoids a second implementation of the rolling z-score and ATR normalization in MQL5 and prevents drift from the Python version. That single source of truth is the reason to pay for the network hop.

The price is a local round trip on every decision. For bar-close decisions on M15 that is a small cost; for a tick-scalping system it would be the wrong trade. I do not quote a latency figure, because the only run in which I could have measured it never reached the network. The EA writes the round-trip time of every successful call to a CSV file, so you can measure it on your own machine.

Start-up order is forgiving. gRPC reconnects automatically: if the service is down, the gateway returns HTTP 502, Predict() fails, and OnTick() returns without touching any position. Once the service is up, no restart is required.


The Feature Pipeline

The three window lengths are declared once, at module level in train_model.py. The transformer reads them from there, and the inference service gets the same values because it imports the same class. Change a window in one place and training and serving move together.

Feature lookback windows (train_model.py)

#+-------------------------------------------------------------------+
#| Feature lookback windows                                          |
#+-------------------------------------------------------------------+
L1_RETURN_ZSCORE = 20   # window for the rolling log-return z-score
ATR_PERIOD = 14         # window for the ATR-normalized momentum term
L2_VOL_REGIME = 50      # window for the realized-volatility percentile rank

RollingFeatureTransformer is a standard scikit-learn transformer, so it can be placed in a Pipeline before the classifier. Its fit() method does nothing, because there is nothing to learn: every feature is computed directly from the window that is passed in. All the work happens in transform().

RollingFeatureTransformer

#+-------------------------------------------------------------------+
#| RollingFeatureTransformer                                         |
#+-------------------------------------------------------------------+
class RollingFeatureTransformer(BaseEstimator, TransformerMixin):
    """
    The window-dependent piece. Given a 2D array of raw (close, volume)
    rows - oldest to newest - it computes the three engineered features
    the model is trained on. Only the close column feeds them; volume rides
    along in the contract so a future feature can use it:

      r_t          = rolling z-score of log returns over L1_RETURN_ZSCORE
      m_t          = ATR-normalized momentum over ATR_PERIOD
      vol_regime_t = percentile rank of rolling realized volatility over
                     L2_VOL_REGIME, bucketed 0 (low) / 1 (mid) / 2 (high)

    This exact class is imported by both train_model.py and
    inference_service.py, so there is only ever one implementation of the
    math - the model never sees a feature computed a different way at
    inference time than it saw at training time.
    """

    #+---------------------------------------------------------------+
    #| RollingFeatureTransformer.fit                                 |
    #+---------------------------------------------------------------+
    def fit(self, X, y=None):
        return self

    #+---------------------------------------------------------------+
    #| RollingFeatureTransformer.transform                           |
    #+---------------------------------------------------------------+
    def transform(self, X):
        closes = X[:, 0]

        log_ret = np.diff(np.log(closes), prepend=np.log(closes[0]))
        r_t = _rolling_zscore(log_ret, L1_RETURN_ZSCORE)

        atr = _true_range_average(closes, ATR_PERIOD)
        momentum = closes - np.roll(closes, ATR_PERIOD)
        momentum[:ATR_PERIOD] = 0.0
        m_t = np.divide(momentum, atr, out=np.zeros_like(momentum), where=atr > 0)

        realized_vol = pd.Series(log_ret).rolling(L2_VOL_REGIME, min_periods=1).std().to_numpy()
        pct_rank = pd.Series(realized_vol).rolling(L2_VOL_REGIME, min_periods=1).apply(
            lambda w: (w.rank(pct=True).iloc[-1]), raw=False
        ).to_numpy()
        vol_regime_t = np.digitize(pct_rank, bins=[0.33, 0.66]).astype(float)

        # One feature row per input bar. Training needs the full history
        # aligned against every label; a live call only wants the newest
        # row, so that "latest only" slicing happens at prediction time in
        # inference_service.py instead - not here, where it would silently
        # collapse the whole training set down to a single row.
        return np.column_stack([r_t, m_t, vol_regime_t])

The return shape is critical. transform() returns one feature row per input row because training requires features aligned with every label. Collapsing to the last row inside transform() is tempting, but it breaks training: fit() on the classifier would receive a single feature row however much history went in. Keep transform() honest, one row out per row in, and let the caller pick the row; you will see that slice in the gRPC service.

Two helper functions do the rolling arithmetic. Both are plain pandas underneath, so the window each statistic covers is easy to read off:

_rolling_zscore

#+-------------------------------------------------------------------+
#| _rolling_zscore                                                   |
#+-------------------------------------------------------------------+
def _rolling_zscore(series: np.ndarray, window: int) -> np.ndarray:
    s = pd.Series(series)
    mean = s.rolling(window, min_periods=1).mean()
    std = s.rolling(window, min_periods=1).std().replace(0, np.nan)
    return ((s - mean) / std).fillna(0.0).to_numpy()

_true_range_average

#+-------------------------------------------------------------------+
#| _true_range_average                                               |
#+-------------------------------------------------------------------+
def _true_range_average(closes: np.ndarray, period: int) -> np.ndarray:
    tr = np.abs(np.diff(closes, prepend=closes[0]))
    return pd.Series(tr).rolling(period, min_periods=1).mean().to_numpy()

The helper _true_range_average() is a rolling mean of absolute close-to-close changes, not true range despite the name, and it only scales the momentum term. The EA's stop distance uses the real iATR() indicator, which is a different calculation, and the two are kept apart on purpose.

One subtlety about window length is easy to miss. The volatility regime feature ranks 50 values of a rolling standard deviation spanning 50 returns, so it needs roughly 100 bars to warm up; min_periods=1 means the first few dozen training rows use a shorter window; their effect is negligible across years of history. At serving time, with the default InpLookback of 64, the last row's regime bucket is noisier than most of training saw. Retrain with a lookback of 100 bars or more, or match training windows to what the service receives, if this matters for your use.

The pipeline itself is the transformer feeding an LGBMClassifier configured for three classes - Sell, Hold, Buy:

build_pipeline

#+-------------------------------------------------------------------+
#| build_pipeline                                                    |
#+-------------------------------------------------------------------+
def build_pipeline() -> Pipeline:
    return Pipeline(steps=[
        ("features", RollingFeatureTransformer()),
        ("model", LGBMClassifier(
            objective="multiclass",
            num_class=3,
            n_estimators=300,
            learning_rate=0.03,
            max_depth=4,
            subsample=0.8,
            colsample_bytree=0.8,
            random_state=42,
        )),
    ])


Training and Label Design

Labels come from a forward-return threshold. Look five bars ahead; if the price moved more than 0.06% up, the bar is a Buy, more than 0.06% down a Sell, and anything else a Hold. A bar can only be labeled when all five future bars exist, so the last five bars of the training segment get no label and are left out of training; they are not quietly marked Hold. The scheme is deliberately plain: it exercises every part of the plumbing but encodes no trading thesis, and make_labels() is the first function to replace if you adapt this code. The numbers that define the setup are constants at the top of train_model.py, and none of them is tuned:

Training constants

#+-------------------------------------------------------------------+
#| Training constants                                                |
#+-------------------------------------------------------------------+
# --- training setup: demonstration defaults, not tuned values
FORWARD_BARS = 5          # label horizon, in bars
LABEL_THRESHOLD = 0.0006  # forward return needed for a Buy/Sell label (0.06%)
TRAIN_FRACTION = 0.70     # earliest share of the history used for training

Here is the labeling function itself:

make_labels

#+-------------------------------------------------------------------+
#| make_labels                                                       |
#+-------------------------------------------------------------------+
def make_labels(closes: np.ndarray, forward_bars: int = FORWARD_BARS,
                threshold: float = LABEL_THRESHOLD) -> np.ndarray:
    """Sell=0 / Hold=1 / Buy=2, from a simple forward-return threshold. This
    is a demo model for the plumbing, not a claimed trading edge, so the
    labeling scheme is deliberately plain.

    A bar can only be labeled if the full forward window exists. The last
    forward_bars bars have no future to look at, so they get no label and the
    result is forward_bars shorter than closes. Callers must cut the feature
    rows to the same length."""
    fwd_ret = (closes[forward_bars:] - closes[:-forward_bars]) / closes[:-forward_bars]
    labels = np.ones(len(fwd_ret), dtype=int)
    labels[fwd_ret > threshold] = 2
    labels[fwd_ret < -threshold] = 0
    return labels

Training uses MT5's bar export (Symbols → Bars → Export Bars). The export is tab-separated and uses bracketed column names (<CLOSE>, <TICKVOL>), not a comma-separated CSV with friendly headers. Retail FX has no traded-volume feed and the <VOL> column is zero, so tick volume, the number of price updates per bar, is the usual stand-in. The three features use only the close. The entry point cuts the history chronologically at TRAIN_FRACTION: the model is fitted on the earliest 70% of the bars and never sees the rest, which the testing section keeps for an out-of-sample replay. Labels are built from the training segment alone, so none of them looks across the split.

Training entry point

#+-------------------------------------------------------------------+
#| Training entry point                                              |
#+-------------------------------------------------------------------+
if __name__ == "__main__":
    # MT5's "Export Bars" writes a TAB-separated file with bracketed headers
    # (<DATE> <TIME> <OPEN> <HIGH> <LOW> <CLOSE> <TICKVOL> <VOL> <SPREAD>),
    # not a comma CSV with plain names - read it exactly as MT5 wrote it.
    df = pd.read_csv("gbpusd_m15_history.csv", sep="\t")
    df.columns = df.columns.str.strip()
    closes = df["<CLOSE>"].to_numpy()
    # Retail FX has no real traded volume, so <VOL> is just zeros here -
    # <TICKVOL> (price-update count per bar) is the standard proxy and the
    # only one of the two that actually carries information.
    volumes = df["<TICKVOL>"].to_numpy()

    # Chronological split: the model only ever sees the earliest part of the
    # file. The rest is kept back for backtest_offline.py.
    n_train = int(len(closes) * TRAIN_FRACTION)
    labels = make_labels(closes[:n_train])
    X_raw = np.column_stack([closes[:n_train], volumes[:n_train]])[:len(labels)]

    pipeline = build_pipeline()
    pipeline.fit(X_raw, labels)

    print(f"Training rows: {len(labels)} of {len(closes)} bars "
          f"({df['<DATE>'].iloc[0]} to {df['<DATE>'].iloc[len(labels) - 1]})")
    print("Class balance (Sell/Hold/Buy):", np.bincount(labels, minlength=3))
    joblib.dump(pipeline, "model_pipeline.joblib")
    print("Saved model_pipeline.joblib")

The label threshold also sets the class balance, and the class balance shapes every probability the model produces, so the entry point prints np.bincount(labels) after training. A skewed class balance shifts the probabilities, and with them the confidence threshold you will need later.

LightGBM suits this shape of problem. The three features sit on different scales, a z-score, an ATR-normalized ratio and a 0/1/2 bucket, and gradient-boosted trees split each feature independently, so the mismatch doesn't hurt them as it would a distance-based or linear model. Three hundred shallow trees at a low learning rate is a conservative, untuned choice meant to carry the plumbing, not win a hyperparameter search.


The gRPC Service

The .proto contract is narrow. Raw closes and volumes go in; three probabilities and a model version string come out. No engineered features cross the wire in either direction, so the contract stays stable even if the feature math inside the pipeline changes.

inference.proto

//+------------------------------------------------------------------+
//| inference.proto                                                  |
//+------------------------------------------------------------------+
syntax = "proto3";

package grpcinference;

// The real gRPC contract. This is the part of the system that actually
// speaks gRPC end to end - MetaTrader never sees this wire format, it only
// ever talks to the thin REST/JSON gateway that sits in front of it.
service InferenceService {
  rpc Predict (PredictRequest) returns (PredictResponse);
}

// Raw inputs only. All feature engineering (rolling z-scores, ATR-normalized
// momentum, the volatility-regime bucket) happens inside the Python service,
// using the exact same RollingFeatureTransformer the model was trained with -
// there is deliberately no second implementation of this math in MQL5.
message PredictRequest {
  string symbol = 1;
  repeated double closes = 2;   // oldest to newest, length == lookback
  repeated double volumes = 3;  // oldest to newest, length == lookback
}

message PredictResponse {
  double p_sell = 1;
  double p_hold = 2;
  double p_buy = 3;
  string model_version = 4;
}

The Python stubs are generated from this file with grpc_tools.protoc (the exact command is in the run-order section). The servicer that implements the contract is short on purpose. It loads the pickled pipeline once at start-up, and each Predict() call is a shape check, a predict_proba() call and a response to fill in. Before any of that, the module needs one import that looks pointless at first glance:

Import required to load the pickled pipeline

#+-------------------------------------------------------------------+
#| Import required to load the pickled pipeline                      |
#+-------------------------------------------------------------------+
# Never called here. train_model.py pickled the pipeline while running as
# __main__, so joblib recorded the transformer as __main__.RollingFeatureTransformer.
# This process is its own __main__, and the class has to exist in that
# namespace or joblib.load() raises AttributeError.
from train_model import RollingFeatureTransformer  # noqa: F401

Nothing in the service calls RollingFeatureTransformer directly. The import is there for pickle. The pipeline was saved while train_model.py ran as __main__, so joblib recorded the class as __main__.RollingFeatureTransformer. The service is its own __main__, and unless the class exists in that namespace, joblib.load() fails with an AttributeError that is confusing until you know the quirk. Move the class into a package and retrain so the recorded path becomes a real module path.

InferenceServicer

#+-------------------------------------------------------------------+
#| InferenceServicer                                                 |
#+-------------------------------------------------------------------+
class InferenceServicer(inference_pb2_grpc.InferenceServiceServicer):

    #+---------------------------------------------------------------+
    #| InferenceServicer.__init__                                    |
    #+---------------------------------------------------------------+
    def __init__(self, model_path: str = MODEL_PATH):
        self._pipeline = joblib.load(model_path)

    #+---------------------------------------------------------------+
    #| InferenceServicer.Predict                                     |
    #+---------------------------------------------------------------+
    def Predict(self, request, context):
        closes = np.asarray(request.closes, dtype=float)
        volumes = np.asarray(request.volumes, dtype=float)

        if closes.shape[0] < 2 or closes.shape[0] != volumes.shape[0]:
            context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
            context.set_details("closes/volumes must be equal length and at least 2 bars")
            return inference_pb2.PredictResponse()

        x_raw = np.column_stack([closes, volumes])
        # The transformer emits one feature row per input bar, so a window of
        # N bars comes back as N rows of probabilities. Only the last row
        # describes the newest closed bar, which is the one MQL5 wants.
        proba = self._pipeline.predict_proba(x_raw)[-1]  # [P(sell), P(hold), P(buy)]

        return inference_pb2.PredictResponse(
            p_sell=float(proba[0]),
            p_hold=float(proba[1]),
            p_buy=float(proba[2]),
            model_version=MODEL_VERSION,
        )

The [-1] after predict_proba() is the caller-side slice promised earlier: the pipeline returns one row of probabilities per bar in the window, and only the last row describes the newest closed bar. A request with fewer than two bars, or with closes and volumes of different lengths, is rejected with INVALID_ARGUMENT instead of being fed to the model.

serve

#+-------------------------------------------------------------------+
#| serve                                                             |
#+-------------------------------------------------------------------+
def serve(bind_address: str = "127.0.0.1:50051") -> None:
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
    inference_pb2_grpc.add_InferenceServiceServicer_to_server(InferenceServicer(), server)
    server.add_insecure_port(bind_address)
    server.start()
    print(f"gRPC InferenceService listening on {bind_address}")
    try:
        while True:
            time.sleep(3600)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == "__main__":
    serve()

serve() starts a standard grpc.server with a small thread pool on the loopback address, so you can test it with grpcurl or a ten-line Python client, with no MetaTrader involved.


The Thin REST Gateway

This process exists because WebRequest() speaks HTTP/JSON and gRPC needs HTTP/2 and protobuf. It decodes the JSON body, calls the gRPC stub, and encodes the answer as JSON. It is intentionally the least interesting file in the project: no feature engineering, no model, nothing clever. The gRPC channel is created once and shared by every request:

Shared gRPC channel and stub

#+-------------------------------------------------------------------+
#| Shared gRPC channel and stub                                      |
#+-------------------------------------------------------------------+
# One channel for the life of the process. gRPC connects lazily and
# reconnects on its own, so start-up order of the two processes is not
# critical: a call made while the service is down simply fails with 502.
_channel = grpc.insecure_channel(GRPC_TARGET)
_stub = inference_pb2_grpc.InferenceServiceStub(_channel)

call_grpc() builds the protobuf request, calls the stub with a two-second deadline, and returns a plain dictionary. The probabilities are rounded to four decimals for a practical reason: Python's json.dumps prints a very small float such as 0.000034 in exponent form, and I would rather not depend on how StringToDouble() treats that on every build. Four decimals are plenty for a confidence gate.

call_grpc

#+-------------------------------------------------------------------+
#| call_grpc                                                         |
#+-------------------------------------------------------------------+
def call_grpc(symbol: str, closes: list, volumes: list) -> dict:
    request = inference_pb2.PredictRequest(symbol=symbol, closes=closes, volumes=volumes)
    response = _stub.Predict(request, timeout=2.0)
    # Rounded to 4 decimals so that json.dumps never emits exponent notation
    # (3.4e-05) for a tiny probability; plain decimals are all MQL5 has to parse.
    return {
        "p_sell": round(response.p_sell, 4),
        "p_hold": round(response.p_hold, 4),
        "p_buy": round(response.p_buy, 4),
        "model_version": response.model_version,
    }

PredictHandler answers POST /predict and nothing else. A malformed body gets HTTP 400, a failed gRPC call gets HTTP 502, and every reply carries a Content-Length header so the client does not have to wait for the connection to close:

PredictHandler

#+-------------------------------------------------------------------+
#| PredictHandler                                                    |
#+-------------------------------------------------------------------+
class PredictHandler(BaseHTTPRequestHandler):

    #+---------------------------------------------------------------+
    #| PredictHandler._reply                                         |
    #+---------------------------------------------------------------+
    def _reply(self, status: int, body: dict) -> None:
        payload = json.dumps(body).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    #+---------------------------------------------------------------+
    #| PredictHandler.do_POST                                        |
    #+---------------------------------------------------------------+
    def do_POST(self):
        if self.path != "/predict":
            self._reply(404, {"error": "unknown path"})
            return

        try:
            length = int(self.headers.get("Content-Length", 0))
            body = json.loads(self.rfile.read(length))
            result = call_grpc(body["symbol"], body["closes"], body["volumes"])
        except (ValueError, KeyError, TypeError) as exc:
            self._reply(400, {"error": f"bad request: {exc}"})
        except grpc.RpcError as exc:
            self._reply(502, {"error": str(exc)})
        else:
            self._reply(200, result)

    #+---------------------------------------------------------------+
    #| PredictHandler.log_message                                    |
    #+---------------------------------------------------------------+
    def log_message(self, format, *args):
        pass  # keep stdout clean; the EA-side latency log is the real record


if __name__ == "__main__":
    server = HTTPServer(GATEWAY_ADDRESS, PredictHandler)
    print(f"REST gateway listening on http://{GATEWAY_ADDRESS[0]}:{GATEWAY_ADDRESS[1]}/predict")
    server.serve_forever()

Keeping the gateway this small is a debugging decision. I can rule this file out in a minute and move on to the two places where something interesting can go wrong: the payload built by the MQL5 client, and the model logic behind the service.

Gateway entry point

#+-------------------------------------------------------------------+
#| Gateway entry point                                               |
#+-------------------------------------------------------------------+
if __name__ == "__main__":
    server = HTTPServer(GATEWAY_ADDRESS, PredictHandler)
    print(f"REST gateway listening on http://{GATEWAY_ADDRESS[0]}:{GATEWAY_ADDRESS[1]}/predict")
    server.serve_forever()

HTTPServer handles one request at a time. That is enough for one chart making one call per bar; if you attach the EA to many symbols, switch to ThreadingHTTPServer.


The MQL5 Client

Everything the EA knows about the network sits in one include file, GrpcInferenceClient.mqh, wrapped in a class so the EA never calls WebRequest() itself. The file starts with its properties and the result structure, which keeps failure handling clean on the calling side: one bool return value plus a filled-in struct, with no half-populated result to misread.

Properties

//+------------------------------------------------------------------+
//| Properties                                                       |
//+------------------------------------------------------------------+
#property copyright "Olamide Adebayo"
#property link      "https://www.mql5.com"

Result Structure

//+------------------------------------------------------------------+
//| Result Structure                                                 |
//+------------------------------------------------------------------+
struct SInferenceResult
  {
   bool              ok;                 // true if the round trip succeeded and parsed cleanly
   double            p_sell;             // P(Sell) returned by the Python service
   double            p_hold;             // P(Hold) returned by the Python service
   double            p_buy;              // P(Buy) returned by the Python service
   double            latency_ms;         // wall-clock round trip time for this call
   int               http_code;          // raw WebRequest() return code, 0/-1 on transport failure
   string            error;              // human-readable failure reason, empty when ok == true
  };

CGrpcInferenceClient - Class Declaration

//+------------------------------------------------------------------+
//| Class Declaration                                                |
//+------------------------------------------------------------------+
class CGrpcInferenceClient
  {
private:
   string            m_gateway_url;      // full REST gateway endpoint, e.g. http://127.0.0.1:8000/predict
   string            m_symbol;           // symbol name sent in the payload, for the Python-side log
   int               m_timeout_ms;       // WebRequest timeout budget per call
   int               m_lookback;         // number of trailing bars sent as raw features

   double            ExtractJsonNumber(const string &json,const string &key,const double fallback);

public:
                     CGrpcInferenceClient(void);
   void              Init(const string gateway_url,const string symbol,
                           const int timeout_ms,const int lookback);
   void              BuildPayload(const double &close[],const long &volume[],string &json_out);
   bool              Predict(const double &close[],const long &volume[],SInferenceResult &result);
  };

The constructor puts the object into a safe state, and Init() stores the endpoint, symbol, timeout and lookback that the EA passes in from its inputs:

CGrpcInferenceClient::CGrpcInferenceClient

//+------------------------------------------------------------------+
//| CGrpcInferenceClient::CGrpcInferenceClient                       |
//+------------------------------------------------------------------+
CGrpcInferenceClient::CGrpcInferenceClient(void)
  {
//--- safe defaults until Init() is called
   m_gateway_url = "";
   m_symbol      = "";
   m_timeout_ms  = 2000;
   m_lookback    = 64;
  }

CGrpcInferenceClient::Init

//+------------------------------------------------------------------+
//| CGrpcInferenceClient::Init                                       |
//+------------------------------------------------------------------+
void CGrpcInferenceClient::Init(const string gateway_url,const string symbol,
                                const int timeout_ms,const int lookback)
  {
   m_gateway_url = gateway_url;
   m_symbol      = symbol;
   m_timeout_ms  = timeout_ms;
   m_lookback    = lookback;
  }

BuildPayload() walks the close and volume arrays oldest to newest, matching the training order, and assembles the JSON body by hand with StringFormat(). MQL5 ships no JSON library, and the payload shape is fixed and flat, so a library would be pure overhead:

CGrpcInferenceClient::BuildPayload

//+------------------------------------------------------------------+
//| CGrpcInferenceClient::BuildPayload                               |
//+------------------------------------------------------------------+
void CGrpcInferenceClient::BuildPayload(const double &close[],const long &volume[],string &json_out)
  {
   string closes_csv  = "";
   string volumes_csv = "";
//--- walk the arrays oldest-to-newest, matching training-time ordering
   for(int i = 0; i < m_lookback; i++)
     {
      closes_csv  += DoubleToString(close[i], _Digits);
      volumes_csv += IntegerToString((long)volume[i]);
      if(i < m_lookback - 1)
        {
         closes_csv  += ",";
         volumes_csv += ",";
        }
     }

   json_out = StringFormat("{\"symbol\":\"%s\",\"closes\":[%s],\"volumes\":[%s]}",
                            m_symbol, closes_csv, volumes_csv);
  }

Parsing the reply works in the same spirit. ExtractJsonNumber() finds a key, walks forward to the next comma or closing brace, trims whitespace and converts the text between. It is not a general JSON parser; it only has to read the fixed reply that gateway.py always sends:

CGrpcInferenceClient::ExtractJsonNumber

//+------------------------------------------------------------------+
//| CGrpcInferenceClient::ExtractJsonNumber                          |
//+------------------------------------------------------------------+
double CGrpcInferenceClient::ExtractJsonNumber(const string &json,const string &key,const double fallback)
  {
   string needle = "\"" + key + "\":";
   int    pos    = StringFind(json, needle);
   if(pos < 0)
      return(fallback);

   int start = pos + StringLen(needle);
   int end   = start;
//--- a JSON number ends at the next comma or closing brace, whichever comes first
   while(end < StringLen(json) && StringGetCharacter(json, end) != ',' && StringGetCharacter(json, end) != '}')
      end++;

   string number_text = StringSubstr(json, start, end - start);
   StringTrimLeft(number_text);
   StringTrimRight(number_text);
   return(StringToDouble(number_text));
  }

Predict() ties it together. It resets the output struct first, so a failed call can never leak a stale prediction, checks that the arrays are long enough, builds the payload, sends it with a timing measurement around the call, and parses the reply. A reply that does not contain all three probability keys counts as a failure rather than a default Hold:

CGrpcInferenceClient::Predict

//+------------------------------------------------------------------+
//| CGrpcInferenceClient::Predict                                    |
//+------------------------------------------------------------------+
bool CGrpcInferenceClient::Predict(const double &close[],const long &volume[],SInferenceResult &result)
  {
//--- reset the output struct so a partial/failed call never leaks a stale prediction
   result.ok          = false;
   result.p_sell      = 0.0;
   result.p_hold      = 0.0;
   result.p_buy       = 0.0;
   result.latency_ms  = 0.0;
   result.http_code   = 0;
   result.error       = "";

   if(ArraySize(close) < m_lookback || ArraySize(volume) < m_lookback)
     {
      result.error = "insufficient history for lookback=" + IntegerToString(m_lookback);
      return(false);
     }

   string payload_json;
   BuildPayload(close, volume, payload_json);

   uchar  request_body[];
   uchar  response_body[];
   string response_headers;
   int    request_len = StringToCharArray(payload_json, request_body, 0, WHOLE_ARRAY, CP_UTF8) - 1;
   ArrayResize(request_body, request_len);

   string headers = "Content-Type: application/json\r\n";

   ulong  started_us = GetMicrosecondCount();
   int    code = WebRequest("POST", m_gateway_url, headers, m_timeout_ms,
                             request_body, response_body, response_headers);
   result.latency_ms = (GetMicrosecondCount() - started_us) / 1000.0;
   result.http_code  = code;

   if(code != 200)
     {
      result.error = StringFormat("WebRequest failed, code=%d, GetLastError=%d", code, GetLastError());
      return(false);
     }

   string response_json = CharArrayToString(response_body, 0, WHOLE_ARRAY, CP_UTF8);

//--- a reply without all three probabilities is a failure, never a default Hold
   if(StringFind(response_json, "\"p_sell\"") < 0 ||
      StringFind(response_json, "\"p_hold\"") < 0 ||
      StringFind(response_json, "\"p_buy\"")  < 0)
     {
      result.error = "malformed gateway reply, missing probability keys";
      return(false);
     }

   result.p_sell = ExtractJsonNumber(response_json, "p_sell", 0.0);
   result.p_hold = ExtractJsonNumber(response_json, "p_hold", 1.0);
   result.p_buy  = ExtractJsonNumber(response_json, "p_buy", 0.0);
   result.ok     = true;

   return(true);
  }

On a non-200 code, a transport failure or a malformed reply, Predict() returns false and records the reason in result.error. OnTick() then returns immediately, touching no position: no new trade opens, nothing reverses, and any position already open stays open. The Strategy Tester section later shows why that fail-open behavior matters.


The Expert Advisor: Signal and Risk Logic

The EA begins with its properties and includes, then its inputs. The inputs fall into the gateway connection, the confidence gate, and the risk parameters that turn a signal into an order:

Properties and Includes

//+------------------------------------------------------------------+
//| Properties and Includes                                          |
//+------------------------------------------------------------------+
#property copyright "Olamide Adebayo"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property description "Thin gRPC-backed inference client EA - GBPUSD M15 wiring demo"

#include <Trade/Trade.mqh>
#include <GrpcInference/GrpcInferenceClient.mqh>

Inputs

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input group "Gateway Connection";
input string InpGatewayURL = "http://127.0.0.1:8000/predict";  // REST gateway endpoint the thin client calls
input int    InpTimeoutMs  = 2000;                             // WebRequest timeout budget per call, in milliseconds
input int    InpLookback   = 64;                               // trailing bars of close/volume sent per inference call

input group "Signal";
input double InpConfidenceThreshold = 0.55;  // minimum P(Buy)/P(Sell) required to act, else Hold

input group "Risk Management";
input double InpRiskPercent = 1.0;  // percent of account balance risked per trade
input int    InpAtrPeriod   = 14;   // ATR period used for the stop-distance floor
input double InpSlAtrMult   = 2.0;  // stop-loss distance, in ATR multiples
input double InpTpAtrMult   = 3.0;  // take-profit distance, in ATR multiples

input group "Housekeeping";
input int    InpMagic = 559010;  // magic number for every order this EA sends

Global Objects

//+------------------------------------------------------------------+
//| Global Objects                                                   |
//+------------------------------------------------------------------+
CTrade               trade;            // handles order execution once a signal clears risk checks
CGrpcInferenceClient client;           // the thin WebRequest-based inference client
int                  g_atr_handle;     // ATR indicator handle used for the stop-distance floor
datetime             g_last_bar_time;  // guards OnTick() to fire the inference call once per bar
double               g_latencies[];    // successful round-trip latencies, for the summary/OnTester
int                  g_calls_ok;       // successful inference calls so far this run
int                  g_calls_failed;   // failed or timed-out inference calls so far this run

OnInit() configures the trade object, initializes the client, creates an iATR() handle for the stop-distance floor, and creates the MQL5\Files\GrpcInference folder up front. FileOpen() will not create a missing folder, and I prefer a loud message at start-up to a latency log that silently never gets written:

OnInit

//+------------------------------------------------------------------+
//| OnInit                                                           |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   trade.SetExpertMagicNumber(InpMagic);
   trade.SetTypeFillingBySymbol(_Symbol);

   client.Init(InpGatewayURL, _Symbol, InpTimeoutMs, InpLookback);

   g_atr_handle = iATR(_Symbol, PERIOD_CURRENT, InpAtrPeriod);
   if(g_atr_handle == INVALID_HANDLE)
     {
      Print("OnInit: failed to create ATR handle, error=", GetLastError());
      return(INIT_FAILED);
     }

//--- seed with the current bar's open time, not 0 - otherwise the very first
//--- tick after attaching mid-bar is treated as a new bar and fires an
//--- inference call immediately, before a full bar of data has formed
   g_last_bar_time = iTime(_Symbol, PERIOD_CURRENT, 0);
   g_calls_ok      = 0;
   g_calls_failed  = 0;
   ArrayResize(g_latencies, 0);

//--- FileOpen() does not create a missing MQL5\Files subfolder on its own -
//--- create it once up front so the latency CSV never fails silently later
   if(!FolderCreate("GrpcInference"))
      Print("OnInit: FolderCreate(\"GrpcInference\") returned false, error=", GetLastError());

   return(INIT_SUCCEEDED);
  }

OnTick() is gated by IsNewBar(), so the model is asked once per bar rather than once per tick; there is no reason to send the gateway sixty requests a minute for a model trained on M15 closes. The bars are copied from shift 1, because when a new bar opens, bar 0 holds a single tick and the model was trained on completed bars:

IsNewBar

//+------------------------------------------------------------------+
//| IsNewBar                                                         |
//+------------------------------------------------------------------+
bool IsNewBar(void)
  {
   datetime current_bar_time = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(current_bar_time == g_last_bar_time)
      return(false);

   g_last_bar_time = current_bar_time;
   return(true);
  }

OnTick

//+------------------------------------------------------------------+
//| OnTick                                                           |
//+------------------------------------------------------------------+
void OnTick(void)
  {
   if(!IsNewBar())
      return;

   double close[];
   long   volume[];
   ArraySetAsSeries(close, false);
   ArraySetAsSeries(volume, false);

//--- start at shift 1: bar 0 has only just opened, the model must see closed bars
   if(CopyClose(_Symbol, PERIOD_CURRENT, 1, InpLookback, close) != InpLookback ||
      CopyTickVolume(_Symbol, PERIOD_CURRENT, 1, InpLookback, volume) != InpLookback)
     {
      Print("OnTick: not enough history yet for lookback=", InpLookback);
      return;
     }

   SInferenceResult result;
   if(!client.Predict(close, volume, result))
     {
      LogFailure(result);
      return;                                     // fail-open: no result means Hold, never a blind trade
     }

   g_calls_ok++;
   ArrayResize(g_latencies, ArraySize(g_latencies) + 1);
   g_latencies[ArraySize(g_latencies) - 1] = result.latency_ms;

   PublishProbabilities(result);

   int signal = DecideSignal(result);
   if(signal != 0)
      ManageAndOpen(signal);
//--- signal == 0 (Hold) is a deliberate no-op on an open position, never a flatten
  }

The confidence gate is one small function, and the testing section later is nothing more than its threshold swept across several values. A side needs both to clear the threshold and to beat the opposite side:

DecideSignal

//+------------------------------------------------------------------+
//| DecideSignal                                                     |
//+------------------------------------------------------------------+
int DecideSignal(const SInferenceResult &result)
  {
   if(result.p_buy >= InpConfidenceThreshold && result.p_buy > result.p_sell)
      return(1);

   if(result.p_sell >= InpConfidenceThreshold && result.p_sell > result.p_buy)
      return(-1);

   return(0);
  }

The stop distance never trusts the ATR value alone. Some symbols report zero stops or freeze levels, and a stop closer than the server allows gets the order rejected. The minimum distance is the greater of the broker's stops and freeze levels, plus the current spread and a safety pad. The final distance is the greater of this minimum and the ATR-based value. The ATR is read from the last completed bar, for the same reason as the price window:

GetStopDistance

//+------------------------------------------------------------------+
//| GetStopDistance                                                  |
//+------------------------------------------------------------------+
double GetStopDistance(void)
  {
   double atr_buffer[];
   ArraySetAsSeries(atr_buffer, true);
   if(CopyBuffer(g_atr_handle, 0, 1, 1, atr_buffer) != 1)
      return(0.0);

   double atr_distance = atr_buffer[0] * InpSlAtrMult;

//--- never trust the stops/freeze level alone, some symbols report 0 -
//--- use MAX(stops level, freeze level) + spread + a safety pad as the floor
   long   stops_level_points  = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   long   freeze_level_points = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_FREEZE_LEVEL);
   double point               = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
   double spread_points       = (double)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
   double safety_pad_points   = 10.0;

   double floor_distance = (MathMax((double)stops_level_points, (double)freeze_level_points)
                             + spread_points + safety_pad_points) * point;

   return(MathMax(atr_distance, floor_distance));
  }

Position sizing runs through a sequence of guards. A risk-percent formula comes first. Then OrderCalcMargin() checks the result against free margin, because a lot size that fits the risk budget can still be more than the account can open. A volume below the broker's minimum skips the trade instead of rounding up into more risk than intended, and the lot is clamped to both SYMBOL_VOLUME_MAX and SYMBOL_VOLUME_LIMIT. If either the tick size or tick value is unavailable, the function returns zero and the trade is skipped:

CalcLotSize

//+------------------------------------------------------------------+
//| CalcLotSize                                                      |
//+------------------------------------------------------------------+
double CalcLotSize(const double sl_distance_price,const ENUM_ORDER_TYPE order_type)
  {
   if(sl_distance_price <= 0.0)
      return(0.0);

   double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tick_size  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double risk_money = AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPercent / 100.0;

   if(tick_size <= 0.0 || tick_value <= 0.0)
      return(0.0);

   double loss_per_lot = (sl_distance_price / tick_size) * tick_value;
   if(loss_per_lot <= 0.0)
      return(0.0);

   double lot = risk_money / loss_per_lot;

   double volume_step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   lot = MathFloor(lot / volume_step) * volume_step;

//--- clamp by real account margin via OrderCalcMargin, never the risk
//--- formula alone - a technically correct lot can still exceed free margin
   double margin_required = 0.0;
   double price = (order_type == ORDER_TYPE_BUY)
                  ? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
                  : SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(OrderCalcMargin(order_type, _Symbol, lot, price, margin_required))
     {
      double free_margin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
      if(margin_required > free_margin && margin_required > 0.0)
        {
         double margin_ratio = free_margin / margin_required;
         lot = MathFloor(lot * margin_ratio / volume_step) * volume_step;
        }
     }

//--- below the broker minimum: skip the trade rather than rounding up
   double volume_min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   if(lot < volume_min)
      return(0.0);

//--- clamp to both SYMBOL_VOLUME_MAX and SYMBOL_VOLUME_LIMIT, not max alone
   double volume_max   = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   double volume_limit = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_LIMIT);
   lot = MathMin(lot, volume_max);
   if(volume_limit > 0.0)
      lot = MathMin(lot, volume_limit);

//--- re-floor to the step one last time and normalize to its own precision, not a fixed
//--- 2 digits - the MathMin clamps above can leave sub-step drift, and a broker with a
//--- 0.001 step needs 3 digits, not 2
   lot = MathFloor(lot / volume_step) * volume_step;

//--- count the step's decimal digits by repeated multiplication rather than
//--- -MathLog10() - log10 only gives the right digit count for a step that is
//--- a clean power of ten; a step like 0.25 or 0.5 needs this loop instead
   int lot_digits = 0;
   if(volume_step > 0.0)
     {
      double step_check = volume_step;
      while(MathAbs(step_check - MathRound(step_check)) > 0.0000001 && lot_digits < 8)
        {
         step_check *= 10.0;
         lot_digits++;
        }
     }
   return(NormalizeDouble(lot, MathMax(lot_digits, 0)));
  }

Fig. 2. Decision flow from a new bar's signal through position handling, stop-distance calculation and lot sizing.

ManageAndOpen() manages one position per symbol and magic number. SelectOwnPosition() walks the open positions and keeps the first one whose symbol and magic number both match, so a manual trade or another EA is never closed or counted. On a hedging account other tickets stay untouched; a netting account merges every position on a symbol into one, so run the EA on a symbol that nothing else trades there:

SelectOwnPosition

//+------------------------------------------------------------------+
//| SelectOwnPosition                                                |
//+------------------------------------------------------------------+
bool SelectOwnPosition(ulong &ticket,long &position_type)
  {
//--- keep only this EA's own position: same symbol and same magic number,
//--- so a manual trade or another EA on the symbol is never touched
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      ulong candidate = PositionGetTicket(i);     // also selects the position
      if(candidate == 0)
         continue;

      if(PositionGetString(POSITION_SYMBOL) != _Symbol ||
         PositionGetInteger(POSITION_MAGIC) != InpMagic)
         continue;

      ticket        = candidate;
      position_type = PositionGetInteger(POSITION_TYPE);
      return(true);
     }

   return(false);
  }

An opposite signal closes the EA's position before a new one opens. CloseOwnPosition() counts the close as done only when three things hold: PositionClose() returned true, the server's return code is TRADE_RETCODE_DONE, and the ticket is really gone from the terminal. If any of them fails, ManageAndOpen() logs it and returns, so a new trade is never opened on top of a position that is still there:

CloseOwnPosition

//+------------------------------------------------------------------+
//| CloseOwnPosition                                                 |
//+------------------------------------------------------------------+
bool CloseOwnPosition(const ulong ticket)
  {
   if(!trade.PositionClose(ticket) || trade.ResultRetcode() != TRADE_RETCODE_DONE)
     {
      PrintFormat("CloseOwnPosition: close request failed, retcode=%u (%s)",
                  trade.ResultRetcode(), trade.ResultRetcodeDescription());
      return(false);
     }

//--- a DONE retcode is not enough on its own: confirm the position is gone
//--- from the terminal before anything opens in the other direction
   for(int attempt = 0; attempt < 10; attempt++)
     {
      if(!PositionSelectByTicket(ticket))
         return(true);
      Sleep(50);
     }

   PrintFormat("CloseOwnPosition: position %I64u still open after a DONE retcode", ticket);
   return(false);
  }

A signal in the direction of an open position does nothing, so the EA never pyramids into a position. A Hold signal does nothing either: it is never a reason to flatten. Stop-loss and take-profit prices are normalized to the symbol's digits before the order is sent, and the order's own return code is checked and logged:

ManageAndOpen

//+------------------------------------------------------------------+
//| ManageAndOpen                                                    |
//+------------------------------------------------------------------+
void ManageAndOpen(const int signal)
  {
   ENUM_ORDER_TYPE order_type = (signal > 0) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;

//--- only this EA's own position counts. An opposite one is closed first and
//--- a new trade opens only after that close is confirmed. Hold never reaches
//--- this function, so a position is never flattened silently
   ulong ticket        = 0;
   long  position_type = 0;
   if(SelectOwnPosition(ticket, position_type))
     {
      bool is_opposite = (signal > 0 && position_type == POSITION_TYPE_SELL) ||
                          (signal < 0 && position_type == POSITION_TYPE_BUY);
      if(!is_opposite)
         return;                                  // already positioned with the signal, nothing to do

      if(!CloseOwnPosition(ticket))
        {
         Print("ManageAndOpen: opposite position still open, no new trade this bar");
         return;
        }
     }

   double sl_distance = GetStopDistance();
   double lot = CalcLotSize(sl_distance, order_type);
   if(lot <= 0.0)
     {
      Print("ManageAndOpen: lot size rounded to 0, skipping trade");
      return;
     }

   double price = (order_type == ORDER_TYPE_BUY)
                  ? SymbolInfoDouble(_Symbol, SYMBOL_ASK)
                  : SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double tp_distance = sl_distance * (InpTpAtrMult / InpSlAtrMult);

   double sl_price = NormalizeDouble((order_type == ORDER_TYPE_BUY) ? price - sl_distance : price + sl_distance, _Digits);
   double tp_price = NormalizeDouble((order_type == ORDER_TYPE_BUY) ? price + tp_distance : price - tp_distance, _Digits);

   bool sent = (order_type == ORDER_TYPE_BUY)
               ? trade.Buy(lot, _Symbol, price, sl_price, tp_price, "GrpcInference")
               : trade.Sell(lot, _Symbol, price, sl_price, tp_price, "GrpcInference");

   if(!sent || trade.ResultRetcode() != TRADE_RETCODE_DONE)
      PrintFormat("ManageAndOpen: order failed, retcode=%u (%s)",
                  trade.ResultRetcode(), trade.ResultRetcodeDescription());
  }

The remaining functions are bookkeeping. PublishProbabilities() writes the latest probabilities into terminal global variables for the indicator. LogFailure() counts and reports a failed call without ever treating it as a signal. WriteLatencyLog() and ComputeLatencyStats() produce the latency CSV and the min, median, p95 and max figures that OnDeinit() and OnTester() print:

PublishProbabilities

//+------------------------------------------------------------------+
//| PublishProbabilities                                             |
//+------------------------------------------------------------------+
void PublishProbabilities(const SInferenceResult &result)
  {
   GlobalVariableSet("GRPC_INF_P_SELL", result.p_sell);
   GlobalVariableSet("GRPC_INF_P_HOLD", result.p_hold);
   GlobalVariableSet("GRPC_INF_P_BUY",  result.p_buy);
   GlobalVariableSet("GRPC_INF_TIME",   (double)TimeCurrent());
  }

LogFailure

//+------------------------------------------------------------------+
//| LogFailure                                                       |
//+------------------------------------------------------------------+
void LogFailure(const SInferenceResult &result)
  {
   g_calls_failed++;
   PrintFormat("LogFailure: inference call failed, http_code=%d error=%s - holding flat this bar",
               result.http_code, result.error);
  }

WriteLatencyLog

//+------------------------------------------------------------------+
//| WriteLatencyLog                                                  |
//+------------------------------------------------------------------+
void WriteLatencyLog(void)
  {
   if(ArraySize(g_latencies) == 0)
      return;

   int file_handle = FileOpen("GrpcInference\\latency_log.csv", FILE_WRITE | FILE_CSV | FILE_ANSI);
   if(file_handle == INVALID_HANDLE)
     {
      Print("WriteLatencyLog: FileOpen failed, error=", GetLastError());
      return;
     }

   FileWrite(file_handle, "call_index", "latency_ms");
   for(int i = 0; i < ArraySize(g_latencies); i++)
      FileWrite(file_handle, i, g_latencies[i]);

   FileClose(file_handle);
  }

ComputeLatencyStats

//+------------------------------------------------------------------+
//| ComputeLatencyStats                                              |
//+------------------------------------------------------------------+
void ComputeLatencyStats(double &out_min,double &out_median,double &out_p95,double &out_max)
  {
   out_min    = 0.0;
   out_median = 0.0;
   out_p95    = 0.0;
   out_max    = 0.0;

   int n = ArraySize(g_latencies);
   if(n == 0)
      return;

   double sorted[];
   ArrayCopy(sorted, g_latencies);
   ArraySort(sorted);

   out_min    = sorted[0];
   out_max    = sorted[n - 1];
   out_median = sorted[n / 2];

   int p95_index = (int)MathCeil(0.95 * n) - 1;
   p95_index = MathMax(0, MathMin(n - 1, p95_index));
   out_p95 = sorted[p95_index];
  }

OnDeinit

//+------------------------------------------------------------------+
//| OnDeinit                                                         |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(g_atr_handle != INVALID_HANDLE)
      IndicatorRelease(g_atr_handle);

   WriteLatencyLog();

   double lat_min, lat_median, lat_p95, lat_max;
   ComputeLatencyStats(lat_min, lat_median, lat_p95, lat_max);

   PrintFormat("OnDeinit: calls_ok=%d calls_failed=%d latency_ms min=%.1f median=%.1f p95=%.1f max=%.1f",
               g_calls_ok, g_calls_failed, lat_min, lat_median, lat_p95, lat_max);
  }

OnTester() returns the reliability of the wiring, not profit. For a system whose whole premise is that a network call succeeds on every bar, the fraction of calls that returned a clean 200 is the number that tells you whether the plumbing works:

OnTester

//+------------------------------------------------------------------+
//| OnTester                                                         |
//+------------------------------------------------------------------+
double OnTester(void)
  {
   int total_calls = g_calls_ok + g_calls_failed;
   if(total_calls == 0)
      return(0.0);

   double reliability = (double)g_calls_ok / (double)total_calls;

   double lat_min, lat_median, lat_p95, lat_max;
   ComputeLatencyStats(lat_min, lat_median, lat_p95, lat_max);
   PrintFormat("OnTester: reliability=%.4f calls_ok=%d calls_failed=%d latency_ms median=%.1f p95=%.1f",
               reliability, g_calls_ok, g_calls_failed, lat_median, lat_p95);

   return(reliability);
  }


Seeing the Probabilities: GrpcInference_ProbView

The EA publishes its last three probabilities to global variables after every successful call. GrpcInference_ProbView only reads them back and draws three lines in a separate window: Sell, Hold and Buy. It runs no inference of its own, so it always agrees with what the EA acted on. It starts with its properties, which set up the window and the three plots:

Properties

//+------------------------------------------------------------------+
//| Properties                                                       |
//+------------------------------------------------------------------+
#property copyright "Olamide Adebayo"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   3
#property indicator_label1  "P(Sell)"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrCrimson
#property indicator_label2  "P(Hold)"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrSilver
#property indicator_label3  "P(Buy)"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrDodgerBlue

Inputs

//+------------------------------------------------------------------+
//| Inputs                                                           |
//+------------------------------------------------------------------+
input int InpMaxHistoryBars = 500;  // history cap applied only on the indicator's first calculation

Indicator Buffers

//+------------------------------------------------------------------+
//| Indicator Buffers                                                |
//+------------------------------------------------------------------+
double buf_sell[];  // plot 1 - mirrors the EA's last published GRPC_INF_P_SELL
double buf_hold[];  // plot 2 - mirrors the EA's last published GRPC_INF_P_HOLD
double buf_buy[];   // plot 3 - mirrors the EA's last published GRPC_INF_P_BUY

OnInit

//+------------------------------------------------------------------+
//| OnInit                                                           |
//+------------------------------------------------------------------+
int OnInit(void)
  {
   SetIndexBuffer(0, buf_sell, INDICATOR_DATA);
   SetIndexBuffer(1, buf_hold, INDICATOR_DATA);
   SetIndexBuffer(2, buf_buy,  INDICATOR_DATA);

   ArraySetAsSeries(buf_sell, false);
   ArraySetAsSeries(buf_hold, false);
   ArraySetAsSeries(buf_buy,  false);

   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);

   IndicatorSetString(INDICATOR_SHORTNAME, "GrpcInference ProbView");
   IndicatorSetInteger(INDICATOR_DIGITS, 3);

   return(INIT_SUCCEEDED);
  }

ReadGlobal() guards against the indicator loading before the EA has published anything. It returns a fallback value instead of reading a global variable that does not exist:

ReadGlobal

//+------------------------------------------------------------------+
//| ReadGlobal                                                       |
//+------------------------------------------------------------------+
double ReadGlobal(const string name,const double fallback)
  {
   if(!GlobalVariableCheck(name))
      return(fallback);

   return(GlobalVariableGet(name));
  }

In OnCalculate(), bars that opened since the last call inherit the previous value so the line stays continuous, and the newest bar is overwritten with whatever the globals hold right now. A finished bar is never touched again, so each bar keeps the value that was current while it was forming:

OnCalculate

//+------------------------------------------------------------------+
//| OnCalculate                                                      |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   int start;
//--- first call: cap the initial history draw at InpMaxHistoryBars
   if(prev_calculated == 0)
     {
      start = MathMax(0, rates_total - InpMaxHistoryBars);
      for(int i = 0; i < start; i++)
        {
         buf_sell[i] = EMPTY_VALUE;
         buf_hold[i] = EMPTY_VALUE;
         buf_buy[i]  = EMPTY_VALUE;
        }
     }
   else
      start = prev_calculated;      // never touch a finished bar: it keeps the value published during it

//--- bars opened since the last call inherit the previous value, so the line
//--- stays continuous; the newest bar is then overwritten with the live globals
   for(int i = start; i < rates_total - 1; i++)
     {
      buf_sell[i] = (i > 0) ? buf_sell[i - 1] : 0.5;
      buf_hold[i] = (i > 0) ? buf_hold[i - 1] : 0.5;
      buf_buy[i]  = (i > 0) ? buf_buy[i - 1]  : 0.0;
     }

   int last = rates_total - 1;
   buf_sell[last] = ReadGlobal("GRPC_INF_P_SELL", (last > 0) ? buf_sell[last - 1] : 0.5);
   buf_hold[last] = ReadGlobal("GRPC_INF_P_HOLD", (last > 0) ? buf_hold[last - 1] : 0.5);
   buf_buy[last]  = ReadGlobal("GRPC_INF_P_BUY",  (last > 0) ? buf_buy[last - 1]  : 0.0);

   return(rates_total);
  }


Setup and Run Order

Unpack MQL5.zip into the terminal data folder (File → Open Data Folder in MetaTrader). The EA, the include file and the indicator land in their GrpcInference subfolders under Experts, Include and Indicators, and the Python files in MQL5\Files\GrpcInference\Python. You need Python 3.10-3.12, matching requirements.txt, and every command below runs from that Python folder. The sequence is install, generate the gRPC stubs, train, replay if you want the offline numbers, start the service, start the gateway, then bring up MetaTrader:

Commands

# 1. install the pinned dependencies
pip install -r requirements.txt

# 2. generate inference_pb2.py and inference_pb2_grpc.py from the contract
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. inference.proto

# 3. save the exported bars here as gbpusd_m15_history.csv, then train
python train_model.py

# 4. optional: replay the bars against the trained model (takes several minutes)
python backtest_offline.py

# 5. start the gRPC service, then the gateway, each in its own terminal
python inference_service.py
python gateway.py

In MetaTrader, open Tools → Options → Expert Advisors, tick "Allow WebRequest for listed URL" and add http://127.0.0.1:8000. Without this entry every call fails, whatever the code does. Then compile the include file and the EA from the MQL5 folder, attach GrpcInference_EA to a GBPUSD M15 chart with algorithmic trading enabled, and optionally add GrpcInference_ProbView to the same chart.


What Happened in the Strategy Tester

The natural way to backtest the EA is the built-in Strategy Tester, and that is where the first surprise appeared. The tester executes the EA in a local test agent, and in this setup WebRequest() failed on every bar - to 127.0.0.1 as well, and with the URL already on the allowed list in the terminal options. I treat this as a property of the tester rather than a configuration mistake, because nothing I tried changed it.


Fig. 3. WebRequest() works from a live or demo chart, but returned -1 on every bar inside the Strategy Tester's local agent.

Every metric in the report came back at zero, and the diagnostic line printed by OnDeinit() made the cause obvious:

OnDeinit: calls_ok=0 calls_failed=17358 latency_ms min=0.0 median=0.0 p95=0.0 max=0.0

All 17,358 bars of that run logged WebRequest failed, code=-1 through LogFailure(). Because Predict() fails open, the EA did what it is supposed to do when a call fails: it held flat. The zero trades were the EA behaving correctly against a network path the tester would not provide, not a flaw in the trading logic.

The lesson reaches beyond this one system. If an EA's decisions depend on a live network call, the built-in tester cannot tell "the model said no" apart from "the network never answered". Failing open is still right for live trading, because a network hiccup should never manufacture a trade, but the backtest has to happen somewhere else, which is why the next section uses a standalone script.

A separate gotcha shows up on a live demo chart: IsNewBar() only fires when a bar opens, so over a weekend calls_ok and calls_failed both stay at zero. That means no bar has opened yet, not that the wiring is broken.


Testing: An Offline Replay Across Confidence Thresholds

Since the Strategy Tester cannot exercise the network path, backtest_offline.py replays historical bars straight against the trained pipeline. It mirrors the EA's decision logic: the same confidence gate, an ATR-based stop and take-profit, one position at a time, and the same 64-bar trailing windows. The ATR and the stop floor only approximate the EA's own (detailed below), so this checks the signal and timing, not the EA's exact trades, and it does not replace forward-testing on a demo account.

The replay uses a time scale that mirrors the EA, which decides once per bar, on a bar that has just closed, and trades at the market on the first tick of the next bar. For each bar t, the signal comes from bar t-1. At the open of bar t, an opposite position is closed and a new one is opened, with stops based on the ATR of bar t-1. The replay then tests the position against the high and low of bar t. A trade is tested on the very bar it was opened in. When one bar touches both the stop and the target, the stop is booked first.

Read the numbers with these limits in mind. Fills are at the open, the stop or the target, with no spread, commission, slippage, gaps or execution delay, no broker-side order restrictions modeled, and the ATR and stop floor only approximate the EA's own. The out-of-sample segment is one hold-out, not a walk-forward test, on one instrument with no trading costs - not evidence of a durable edge, only whether the in-sample picture survives on later bars.

Data. Every number below comes from one MetaTrader 5 bar export: GBPUSD M15, 94,221 bars from 2023.01.02 07:00:00 to 2026.10.16 23:45:00, in MetaQuotes-Demo server time. The first 65,954 bars, up to 2025.08.28 00:30:00, are the training segment, and the remaining 28,267 bars, from 2025.08.28 00:45:00, are the hold-out. The exported file's SHA-256 is 4ba111428b8af1ae99c266ed4bbf7f6d4992ae138e8a2c7c5acfdfacc9a42586. Reproducing these figures needs this exact export; a fresh one, even over the same dates, can shift the bar count and move every number below.

Several settings shape these results. The table separates common conventions from demonstration defaults and marks the one setting that was swept; none were checked for sensitivity, which is the natural next step:

Parameter Value Basis
ATR period 14 Common convention (the indicator's default period)
Stop and target 2.0 and 3.0 x ATR Arbitrary demo default; not tested
Label horizon and threshold 5 bars, 0.06% Arbitrary demo default; not tested
Feature windows 20, 14 and 50 bars Arbitrary demo default; not tested
InpLookback 64 bars Arbitrary, below the ~100 bars the regime feature needs; not tested
LightGBM 300 trees, rate 0.03, depth 4 Arbitrary; not tuned
TRAIN_FRACTION 0.70 Common single-split convention; not tested
InpConfidenceThreshold 0.55 Arbitrary default; the only parameter swept, in the table below

The settings mirror the EA's input defaults. RollingFeatureTransformer is imported for the same reason as in inference_service.py: train_model.py pickled the pipeline as __main__, so the class must exist here before joblib.load() can rebuild it. TRAIN_FRACTION keeps the split point in one place:

Imports and constants

#+-------------------------------------------------------------------+
#| Imports and constants                                             |
#+-------------------------------------------------------------------+
import hashlib
import json

import numpy as np
import pandas as pd
import joblib

# train_model.py pickled the pipeline while running as __main__, so joblib.load()
# looks for RollingFeatureTransformer in this script's namespace. The import is
# never called directly; without it the load fails with AttributeError.
from train_model import RollingFeatureTransformer, TRAIN_FRACTION  # noqa: F401

# --- must mirror GrpcInference_EA.mq5's own input defaults ---
LOOKBACK = 64
ATR_PERIOD = 14
SL_ATR_MULT = 2.0
TP_ATR_MULT = 3.0
PIP = 0.0001  # GBPUSD, 5-digit broker

HISTORY_FILE = "gbpusd_m15_history.csv"
THRESHOLDS = [0.55, 0.50, 0.45, 0.40, 0.00]

The script computes a Wilder-smoothed ATR as a stand-in for the terminal's iATR(), which averages the true range differently, and it skips the EA's broker-level floor entirely, since that depends on live symbol properties no CSV file carries:

wilder_atr

#+-------------------------------------------------------------------+
#| wilder_atr                                                        |
#+-------------------------------------------------------------------+
def wilder_atr(high: np.ndarray, low: np.ndarray, close: np.ndarray, period: int) -> np.ndarray:
    """Wilder-smoothed ATR, used here as a stand-in for the terminal's iATR(),
    which GetStopDistance() in the EA calls. The two average the true range
    differently, so the stops in this replay are close to, but not identical
    to, the EA's. It is also a different ATR from the simpler one inside
    RollingFeatureTransformer, and the two are deliberately kept separate."""
    n = len(close)
    tr = np.zeros(n)
    tr[0] = high[0] - low[0]
    for i in range(1, n):
        tr[i] = max(high[i] - low[i], abs(high[i] - close[i - 1]), abs(low[i] - close[i - 1]))

    atr = np.full(n, np.nan)
    atr[period - 1] = tr[:period].mean()
    for i in range(period, n):
        atr[i] = (atr[i - 1] * (period - 1) + tr[i]) / period
    return atr

compute_probabilities() runs the pipeline on the same 64-bar window the EA sends for each bar. Only the LightGBM step is batched, producing the same numbers as calling the pipeline bar by bar. The result is then rounded to four decimals, the precision gateway.py sends over the wire and the only precision DecideSignal() ever sees. The probabilities are computed once, so every threshold below reuses them instead of repeating the slow part:

compute_probabilities

#+-------------------------------------------------------------------+
#| compute_probabilities                                             |
#+-------------------------------------------------------------------+
def compute_probabilities(pipeline, closes: np.ndarray, volumes: np.ndarray) -> np.ndarray:
    """P(sell), P(hold), P(buy) for the signal taken at the close of each bar.
    Row s holds the prediction made when bar s has just closed, from the same
    trailing LOOKBACK-bar window the EA sends. Rows without a full window stay
    NaN. The model sees each window exactly as it would live; only the
    LightGBM step is batched, which gives identical numbers and runs faster."""
    n = len(closes)
    probs = np.full((n, 3), np.nan)
    features = pipeline.named_steps["features"]
    rows = []
    for s in range(LOOKBACK - 1, n - 1):
        window = np.column_stack([closes[s - LOOKBACK + 1:s + 1], volumes[s - LOOKBACK + 1:s + 1]])
        rows.append(features.transform(window)[-1])
        if len(rows) % 5000 == 0:
            print(f"  features {len(rows)}/{n - LOOKBACK}", flush=True)
    probs[LOOKBACK - 1:n - 1] = pipeline.named_steps["model"].predict_proba(np.array(rows))
    # gateway.py rounds p_sell/p_hold/p_buy to 4 decimals before the EA ever sees them
    # (round(response.p_sell, 4), etc.), so round here too: DecideSignal() in the EA
    # always acts on the rounded value, never the raw model output.
    return np.round(probs, 4)

signals_for() is the EA's DecideSignal() applied to a whole array:

signals_for

#+-------------------------------------------------------------------+
#| signals_for                                                       |
#+-------------------------------------------------------------------+
def signals_for(probs: np.ndarray, threshold: float) -> np.ndarray:
    """The EA's DecideSignal(): +1 Buy, -1 Sell, 0 Hold. NaN rows give 0."""
    p_sell, p_buy = probs[:, 0], probs[:, 2]
    signals = np.zeros(len(probs), dtype=int)
    signals[(p_buy >= threshold) & (p_buy > p_sell)] = 1
    signals[(p_sell >= threshold) & (p_sell > p_buy)] = -1
    return signals

replay() is the time scale above written as code: signals[t - 1] is the decision from the previous close, the position opens or reverses at opens[t], and bar t's range is tested in the same iteration:

replay

#+-------------------------------------------------------------------+
#| replay                                                            |
#+-------------------------------------------------------------------+
def replay(signals, opens, highs, lows, closes, atr, start: int, stop: int):
    """Replay the bars start..stop-1 and return a list of (pips, exit_reason).
    signals[t - 1] is the decision taken at the close of bar t-1."""
    trades = []
    position = None  # (side, entry_price, stop_price, target_price)

    for t in range(start, stop):
        signal = signals[t - 1]

        # 1 + 2: act on the signal at the open of bar t
        if signal != 0:
            if position is not None and position[0] == -signal:
                trades.append((position[0] * (opens[t] - position[1]) / PIP, "reverse"))
                position = None
            if position is None and not np.isnan(atr[t - 1]):
                entry = opens[t]
                sl_dist = atr[t - 1] * SL_ATR_MULT
                tp_dist = atr[t - 1] * TP_ATR_MULT
                position = (signal, entry, entry - signal * sl_dist, entry + signal * tp_dist)

        # 3: test the range of bar t against the open position
        if position is not None:
            side, entry, sl, tp = position
            hit_sl = lows[t] <= sl if side == 1 else highs[t] >= sl
            hit_tp = highs[t] >= tp if side == 1 else lows[t] <= tp
            if hit_sl:
                trades.append((side * (sl - entry) / PIP, "stop"))
                position = None
            elif hit_tp:
                trades.append((side * (tp - entry) / PIP, "target"))
                position = None

    if position is not None:  # still open at the end of the segment
        trades.append((position[0] * (closes[stop - 1] - position[1]) / PIP, "end"))
    return trades

Every trade carries an exit reason; summarize() counts them alongside the usual stats:

summarize

#+-------------------------------------------------------------------+
#| summarize                                                         |
#+-------------------------------------------------------------------+
def summarize(trades) -> dict:
    pips = np.array([p for p, _ in trades])
    reasons = [r for _, r in trades]
    out = {"trades": len(pips)}
    out.update({f"exit_{r}": reasons.count(r) for r in ("stop", "target", "reverse", "end")})
    if len(pips) == 0:
        return out
    wins, losses = pips[pips > 0], pips[pips < 0]
    equity = np.concatenate(([0.0], np.cumsum(pips)))
    out.update({
        "win_rate": float(len(wins) / len(pips) * 100),
        "profit_factor": float(wins.sum() / abs(losses.sum())) if losses.sum() != 0 else None,
        "net_pips": float(pips.sum()),
        "avg_pips": float(pips.mean()),
        "max_drawdown_pips": float((equity - np.maximum.accumulate(equity)).min()),
    })
    return out

main() prints the data summary, replays both segments at every threshold, and saves the rows to replay_results.json:

main - data summary and replay loop over thresholds

#+-------------------------------------------------------------------+
#| main                                                              |
#+-------------------------------------------------------------------+
def main() -> None:
    df = pd.read_csv(HISTORY_FILE, sep="\t")
    df.columns = df.columns.str.strip()
    opens, highs = df["<OPEN>"].to_numpy(), df["<HIGH>"].to_numpy()
    lows, closes = df["<LOW>"].to_numpy(), df["<CLOSE>"].to_numpy()
    volumes = df["<TICKVOL>"].to_numpy()
    n = len(closes)
    n_train = int(n * TRAIN_FRACTION)
    stamp = df["<DATE>"].astype(str) + " " + df["<TIME>"].astype(str)

    with open(HISTORY_FILE, "rb") as f:
        digest = hashlib.sha256(f.read()).hexdigest()
    print(f"History file: {HISTORY_FILE}  sha256={digest}")
    print(f"Bars: {n}  from {stamp.iloc[0]} to {stamp.iloc[-1]}")
    print(f"In-sample (trained on): bars 0..{n_train - 1}, {stamp.iloc[0]} to {stamp.iloc[n_train - 1]}")
    print(f"Out-of-sample:          bars {n_train}..{n - 1}, {stamp.iloc[n_train]} to {stamp.iloc[-1]}")

    pipeline = joblib.load("model_pipeline.joblib")
    atr = wilder_atr(highs, lows, closes, ATR_PERIOD)
    probs = compute_probabilities(pipeline, closes, volumes)

    segments = {"in-sample": (LOOKBACK, n_train), "out-of-sample": (n_train, n)}
    results = {"history": {"file": HISTORY_FILE, "sha256": digest, "bars": n,
                           "first_bar": stamp.iloc[0], "last_bar": stamp.iloc[-1],
                           "split_bar": n_train, "train_end": stamp.iloc[n_train - 1],
                           "split_time": stamp.iloc[n_train]},
               "segments": {}}
    for name, (start, stop) in segments.items():
        best = np.nanmax(probs[start - 1:stop - 1, [0, 2]], axis=1)
        print(f"\n{name}: bars {start}..{stop - 1}; max(P(Buy), P(Sell)) percentiles "
              f"50/90/99/max = {np.percentile(best, [50, 90, 99, 100]).round(3)}")
        rows = []
        for threshold in THRESHOLDS:
            signals = signals_for(probs, threshold)
            stats = summarize(replay(signals, opens, highs, lows, closes, atr, start, stop))
            stats["threshold"] = threshold
            rows.append(stats)
            if stats["trades"] == 0:
                print(f"  threshold {threshold:.2f}: no trades")
                continue
            pf = "inf" if stats["profit_factor"] is None else f"{stats['profit_factor']:.2f}"
            print(f"  threshold {threshold:.2f}: trades={stats['trades']} win={stats['win_rate']:.1f}% "
                  f"PF={pf} net={stats['net_pips']:+.1f} avg={stats['avg_pips']:+.2f} "
                  f"maxDD={stats['max_drawdown_pips']:.1f} exits stop/target/reverse/end="
                  f"{stats['exit_stop']}/{stats['exit_target']}/{stats['exit_reverse']}/{stats['exit_end']}")
        results["segments"][name] = {"start": start, "stop": stop, "rows": rows}

    with open("replay_results.json", "w") as f:
        json.dump(results, f, indent=2)
    print("\nSaved replay_results.json")

Script entry point

#+-------------------------------------------------------------------+
#| Script entry point                                                |
#+-------------------------------------------------------------------+
if __name__ == "__main__":
    main()

I replayed both segments at five confidence thresholds, changing only CONFIDENCE_THRESHOLD: the EA's default of 0.55, three lower values, and 0.00 as a diagnostic with the gate removed. Fig. 4 shows the trade count and the profit factor, and the table has the full figures.

Fig. 4. Trade count (log scale) and profit factor at each confidence threshold, in-sample and out-of-sample, from the gate fully open (0.00) to the EA's default (0.55). Pale profit-factor bars rest on fewer than 30 trades.

Read the table below the same way: it demonstrates how the confidence gate behaves on this one export, not proof of a trading advantage.

Segment Confidence threshold Total trades Win rate Profit factor Net result (pips) Average per trade (pips) Max drawdown (pips)
In-sample 0.55 (EA default) 4 50.0% 2.11 +32.8 +8.19 -14.8
In-sample 0.50 7 57.1% 2.60 +71.1 +10.15 -14.9
In-sample 0.45 18 38.9% 1.08 +17.1 +0.95 -77.6
In-sample 0.40 204 45.6% 1.24 +529.4 +2.60 -227.6
In-sample 0.00 (gate removed) 26,839 54.6% 1.15 +11,743.5 +0.44 -563.7
Out-of-sample 0.55 (EA default) 1 100.0% no losses +46.4 +46.42 0.0
Out-of-sample 0.50 6 50.0% 1.34 +27.3 +4.54 -61.7
Out-of-sample 0.45 11 45.5% 1.26 +33.6 +3.05 -55.4
Out-of-sample 0.40 84 40.5% 1.05 +48.0 +0.57 -254.4
Out-of-sample 0.00 (gate removed) 11,397 53.6% 1.02 +608.1 +0.05 -865.9

At the EA's default of 0.55 the gate passes 4 trades in-sample and 1 out-of-sample, against 26,839 and 11,397 with the gate removed, so it keeps under 0.1% of the signals. Each step down in threshold admits more of them.

Only the 0.40 threshold has at least 30 trades in both segments: 204 in-sample and 84 out-of-sample, with profit factors of 1.24 and 1.05. The edge fades on the later bars: a profit factor that close to 1.0, on so few trades and before any cost, is break-even for practical purposes. The rows share one model and the same bars, filtered by the same score, so their signals overlap heavily and they are not independent confirmations. The rows with fewer than 30 trades are too thin to read.

With the gate removed the EA trades 26,839 times in-sample and 11,397 out-of-sample. The win rate is 54.6% and 53.6%, the profit factor 1.15 and 1.02, and the average trade is worth +0.44 and +0.05 pips. Out-of-sample, 87% of the trades end on an opposite signal, 11% at the stop and 2% at the target. A spread above 0.05 pips per round trip would erase that average.


Conclusion

The claim here is narrow, and I think it holds: a custom scikit-learn pipeline can serve live predictions to an MT5 Expert Advisor without an ONNX export, using WebRequest(), a thin REST/JSON gateway and a real gRPC service. Every link in that chain is small and specific. The EA builds its payload from completed bars, the gateway translates JSON to protobuf and back, the service imports a class only so that pickle can find it, and the caller picks the last row out of what the pipeline returns.

What the article does not show is a trading edge. At the default threshold the replay produces 4 trades in-sample and 1 out-of-sample, and the best-populated gated row fades toward break-even on the later bars. All of it is cost-free, from one pair and one split. Treat the numbers as a description of how the confidence gate behaves, and judge the model only after a walk-forward test with spread and commission included.

Two practical lessons carry over to other projects. First, this setup cannot validate an EA that depends on WebRequest() in the Strategy Tester. Plan an offline harness that follows the EA's timeline: generate a signal on a closed bar, enter on the next bar, and test stops from the entry bar onward. Second, match your serving window to what training used; the volatility regime bucket here is one example. The next step is a demo forward-test, which will give you real latency and reliability figures.

Attached files

File Location Purpose
GrpcInference_EA.mq5 MQL5\Experts\GrpcInference\ Expert Advisor: new-bar logic, confidence gate, risk and order management
GrpcInferenceClient.mqh MQL5\Include\GrpcInference\ CGrpcInferenceClient class and SInferenceResult structure
GrpcInference_ProbView.mq5 MQL5\Indicators\GrpcInference\ Indicator that plots the published probabilities
inference.proto MQL5\Files\GrpcInference\Python\ gRPC contract. Also attached as inference.proto.txt, because the file uploader does not accept the.proto extension
train_model.py MQL5\Files\GrpcInference\Python\ Feature transformer, pipeline and training script
inference_service.py MQL5\Files\GrpcInference\Python\ gRPC server that hosts the pipeline
gateway.py MQL5\Files\GrpcInference\Python\ REST/JSON gateway for WebRequest()
backtest_offline.py MQL5\Files\GrpcInference\Python\ Offline replay behind the threshold table, in-sample and out-of-sample
requirements.txt MQL5\Files\GrpcInference\Python\ Pinned Python dependencies
MQL5.zip Archive root: MQL5\ Archive with all files listed above. Unpack it into the terminal data folder and every file lands in its required place.
Attached files |
train_model.py (6.75 KB)
requirements.txt (0.13 KB)
gateway.py (2.7 KB)
backtest_offline.py (11.18 KB)
MQL5.zip (19.5 KB)
Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of
This article describes refactoring an EA‑scoped news filter into a reusable MQL5 class. Inputs move into a configuration struct, while events, currency mapping, saved stops, a suspension flag, and a private CTrade object become per‑instance state. The class lets one EA run multiple filters with different thresholds and responses, share one rule table, and reduce duplicated code while keeping each filter independently configurable.
Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (Conclusion) Neural Networks in Trading: Mesh-Based Approximation of Event Streams as a Tool for Analyzing Price Patterns (Conclusion)
The article presents an adaptation of the EEMFlow framework for building highly effective trading models using MQL5. MeshFlow estimation algorithms with advanced feature correlation are considered, allowing for accurate analysis of market dynamics and forecasting of price flows. Testing confirmed positive mathematical expectation, moderate drawdowns and high decision-making efficiency.
Implementing a Zone-Aware Rollover Window Gate in MQL5 Implementing a Zone-Aware Rollover Window Gate in MQL5
CTradeWindows blocks EA entries during the daily rollover spread spike. Each window is a clock time in a zone such as New York, so it follows that zone through DST. CSpreadProfile learns the windows from tick spreads and saves them to a file that an EA can load. Unit tests and Strategy Tester runs on one server show that a window fixed in server time misses the spike in weeks when the US and EU DST dates differ.
Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer
An MQL5 prop-firm guard must evaluate account rules before it acts and verify that protective actions have completed. This article examines eight rules, two-phase directive resolution, position closing, Algo Trading state checks and restart recovery. A demo and synthetic tests show how to use the guard and verify its rule logic.