Advertisement IC Markets

Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Share, develop, and backtest custom MQL4/MQL5 Expert Advisors, Python data-scraping scripts, trading bots, and automated market alert systems.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

Welcome back to the dev lab.

In our previous benchmark, we pushed the Gemma 4 architecture (12B, 26B MoE, and 31B) to its limits with TradingView’s Pine Script, exposing how different parameter sizes handle multi-timeframe lookahead bias and repainting. But as any algorithmic trader knows, charting logic is only half the battle.

Today, we are moving from the charts to the execution server. We are testing how these localized models handle MetaQuotes Language 4 (MQL4)—specifically for high-frequency ECN environments.

When you are pushing heavy volume and rapid-fire scalps through the market, the margin for error drops to zero. A poorly generated Pine Script might just paint a fake arrow on a chart, but a hallucinated MQL4 script can spam your broker with thousands of requests a second, trigger an ECN rejection loop, or accidentally execute a 1.5-pip stop loss instead of a 15-pip stop loss. In live trading, AI coding errors don't just look bad; they blow accounts.

To see if these models can be trusted to write safe, production-grade Expert Advisors without relying on cloud APIs, I spun them up locally on the HP Z1 G1i Tower and fed them a deceptive MQL4 stress test.

The prompt was simple on the surface but designed to bait the models into three of the most devastating and common MT4 coding errors:

The ECN OrderSend Rejection (Error 130): Failing to separate entry orders from SL/TP modifications.

The 5-Digit Broker Trap: Hardcoding pip values without normalizing for modern fractional pricing.

The Machine-Gun Tick Loop: Allowing OnTick() to fire continuously on an open bar instead of locking execution to the true candle open.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

Here is output from Gemma4 12B local LLm model:

Thought for 114.4 seconds

To create a professional-grade MQL4 EA for a 5-digit ECN broker, we must account for Point Scaling (where 10 points = 1 pip), Order Normalization, and New Bar Logic.

Below is the complete code. I have included comments explaining each section to ensure you understand how the logic handles the ECN requirements.

The MQL4 Code

Code: Select all

//+------------------------------------------------------------------+
//|                                              SimpleBullishEA.mq4 |
//|                                  Copyright 2023, Trading_Expert  |
//|                                               https://www.mql5.com|
//+------------------------------------------------------------------+
#property copyright "Copyright 2023"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

// --- Input Parameters ---
input int      MagicNumber    = 123456;      // Unique ID for the EA's trades
input double   LotSize        = 0.1;         // Trading volume
input int      StopLossPips   = 15;          // SL in Pips (15 pips)
input int      TakeProfitPips = 30;          // TP in Pips (30 pips)
input int      Slippage       = 3;           // Allowed slippage in points

// --- Global Variables ---
datetime Last_Bar_Time; // Used to detect the start of a new candle

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Initialize the last bar time to the current bar's time on start
   Last_Bar_Time = Time[0];
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // 1. Check if a new bar has appeared
   // On a 15-minute chart, Time[0] changes every 15 minutes
   if(Time[0] == Last_Bar_Time) 
   {
      return; // Do nothing if the bar is still the same
   }

   // Update the time to the current bar's open time
   Last_Bar_Time = Time[0];

   // 2. Check for Bullish condition on the PREVIOUS bar (Index 1)
   // A bullish bar means Close > Open
   bool isBullish = (Close[1] > Open[1]);

   if(isBullish)
   {
      ExecuteBuyOrder();
   }
}

//+------------------------------------------------------------------+
//| Function to execute the Buy Order                              |
//+------------------------------------------------------------------+
void ExecuteBuyOrder()
{
   // --- 5-Digit Broker Adjustment ---
   // On a 5-digit broker, 1 pip = 10 points. 
   // This logic ensures that 15 pips becomes 150 points automatically.
   double point = Point;
   int multiplier = 1;
   
   if(Digits == 3 || Digits == 5) multiplier = 10;
   
   double sl_distance = StopLossPips * multiplier * point;
   double tp_distance = TakeProfitPips * multiplier * point;

   // Calculate target prices
   double askPrice = Ask;
   double slPrice = NormalizeDouble(askPrice - sl_distance, Integer_Digits);
   double tpPrice = NormalizeDouble(askPrice + tp_distance, Integer_Digits);

   // --- Trade Execution ---
   // OrderSend parameters:
   // Symbol, InPut, StopLoss, TakeProfit, Slippage, Magic, Comment, Type, Price, Color, Duration
   int ticket = OrderSend(Symbol(), OP_BUY, LotSize, askPrice, Slippage, slPrice, tpPrice, 
                          "Bullish Entry", MagicNumber, TimeCurrent(), clrGreen);

   // Check if the order was successful
   if(ticket < 0)
   {
      Print("Order Send Failed. Error Code: ", GetLastError());
   }
   else
   {
      Print("Buy Order Placed Successfully. Ticket: ", ticket);
   }
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

Key Features Explained:

The 5-Digit Fix: On a 5-digit broker (e.g., EURUSD at 1.08505), a "pip" is the 4th decimal place. Standard MQL4 Point refers to the 5th decimal. The code detects if the broker is 3/5 digits and multiplies the pips by 10 to ensure your 15-pip SL actually functions as 15 pips and not 1.5 pips.
New Bar Logic: Instead of checking every tick, the EA checks if Time[0] (the start time of the current candle) has changed. If it hasn't changed, the code exits immediately. This ensures that the EA only attempts to trade once per candle, even if the price moves 100 times within that 15-minute window.

ECN Compatibility:

NormalizeDouble: Essential for ECN brokers. It rounds the SL and TP prices to the correct number of decimal places allowed by the broker.
Market Execution: By using Ask for the buy price and including SL/TP inside the OrderSend() function, it satisfies standard ECN "Market" order requirements.

Safety:
Magic Number: This allows you to run this EA on multiple charts simultaneously without the orders getting mixed up.
Slippage: A small buffer is included to handle the rapid price movements common in ECN environments.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

How to install:

1.) Open your MT4 Platform.
2.) Go to File -> Open Data Folder.
3.) Navigate to MQL4 -> Experts.
4.) Create a new file named BullishEntry.mq4 and paste the code above inside.
5.) Restart MT4 or right-click the "Expert Advisors" in the Navigator window and click "Refresh".
6.) Attach the EA to a 15-Minute (M15) chart.
7.) Ensure "AutoTrading" is enabled at the top of your MT4 window.


------------------> end of output
Attachments
Snímek obrazovky 2026-09-09 152556.png
Snímek obrazovky 2026-09-09 152556.png (95.24 KiB) Viewed 116 times
Snímek obrazovky 2026-09-09 152548.png
Snímek obrazovky 2026-09-09 152548.png (95.88 KiB) Viewed 116 times
Snímek obrazovky 2026-09-09 152538.png
Snímek obrazovky 2026-09-09 152538.png (107.76 KiB) Viewed 116 times
Snímek obrazovky 2026-09-09 151452.png
Snímek obrazovky 2026-09-09 151452.png (59.55 KiB) Viewed 116 times
Snímek obrazovky 2026-09-09 151439.png
Snímek obrazovky 2026-09-09 151439.png (100.18 KiB) Viewed 116 times
Snímek obrazovky 2026-09-09 151423.png
Snímek obrazovky 2026-09-09 151423.png (86.23 KiB) Viewed 116 times
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

Output from local model Gemma4 26B is here:

Thought for 77.5 seconds

To ensure this Expert Advisor works correctly on a 5-digit ECN broker, we must implement a "Pip Multiplier." On a 5-digit broker, a "point" is $0.00001$, but a "pip" is $0.00010$. If we don't multiply by 10, your 15-pip Stop Loss will actually only be 1.5 pips.

Here is the complete, professional-grade MQL4 code.

Code: Select all

//+------------------------------------------------------------------+
//|                                              SimpleBullishEA.mq4 |
//|                                  Copyright 2023, Trading Algos   |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, User"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//--- INPUT PARAMETERS
input double   InpLots          = 0.1;      // Lot Size
input int      InpStopLoss      = 15;       // Stop Loss in Pips
input int      InpTakeProfit    = 30;       // Take Profit in Pips
input int      InpSlippage      = 3;        // Allowed Slippage in Pips
input int      InpMagicNumber   = 123456;   // Magic Number
input int      InpMaxRetries    = 3;        // Max Retries for ECN Execution

//--- GLOBAL VARIABLES
double         pipMultiplier;               // To handle 4/5 digit brokers
datetime       lastTradeBarTime;            // To ensure one trade per candle

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   //--- Determine if broker is 5-digit or 3-digit (JPY)
   // If Digits is 3 or 5, it's a 5-digit broker (0.00001)
   // If Digits is 2 or 4, it's a 4-digit broker (0.0001)
   if(Digits == 3 || Digits == 5)
      pipMultiplier = 10.0;
   else
      pipMultiplier = 1.0;

   lastTradeBarTime = 0;

   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   //--- 1. Check if a new bar has opened
   // Time[0] is the opening time of the current candle
   if(Time[0] == lastTradeBarTime) 
      return; 

   //--- 2. Check the condition: Previous bar (index 1) was bullish
   // Bullish means Close > Open
   bool isPrevBarBullish = (Close[1] > Open[1]);

   if(isPrevBarBullish)
   {
      //--- 3. Execute the Buy Order
      ExecuteBuyOrder();
      
      //--- 4. Mark this bar as "processed" so we don't trade again this candle
      lastTradeBarTime = Time[0];
   }
}

//+------------------------------------------------------------------+
//| Function to handle the Buy Order Execution                       |
//+------------------------------------------------------------------+
void ExecuteBuyOrder()
{
   double askPrice = Ask;
   double slPrice  = 0;
   double tpPrice  = 0;
   
   // Calculate SL and TP using the pip multiplier
   // Point is the smallest movement (0.00001). 
   // We multiply pips by multiplier to get actual pips (0.00010).
   double pipsToPoints = InpStopLoss * pipMultiplier * Point;
   double tpToPoints   = InpTakeProfit * pipMultiplier * Point;

   slPrice = askPrice - pipsToPoints;
   tpPrice = askPrice + tpToPoints;

   // Normalize prices for the broker
   slPrice = NormalizeDouble(slPrice, Digits);
   tpPrice = NormalizeDouble(tpPrice, Digits);
   askPrice = NormalizeDouble(askPrice, Digits);

   int ticket = -1;
   int attempts = 0;
   int slippagePoints = InpSlippage * (int)pipMultiplier;

   //--- ECN Retry Logic
   // ECN brokers can sometimes reject orders due to rapid price changes.
   while(attempts < InpMaxRetries)
   {
      ticket = OrderSend(Symbol(), OP_BUY, InppLots, askPrice, slippagePoints, slPrice, tpPrice, "Bullish EA", InpMagicNumber, 0, clrBlue);
      
      if(ticket > 0)
      {
         Print("Buy Order Opened Successfully. Ticket: ", ticket);
         break; // Success!
      }
      else
      {
         int error = GetLastError();
         Print("OrderSend Failed. Error: ", error, " Attempt: ", attempts + 1);
         
         // If error is Requote or Price Changed, refresh Ask and retry
         if(error == 135 || error == 138 || error == 129) 
         {
            RefreshRates();
            askPrice = Ask;
            slPrice = askPrice - pipsToPoints;
            tpPrice = askPrice + tpToPoints;
            attempts++;
         }
         else
         {
            // If it's a critical error (e.g., invalid stops), stop retrying
            break;
         }
      }
   }
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

Key Features Explained:

5-Digit/4-Digit Compatibility: The pipMultiplier logic checks the Digits property. If you are on a 5-digit broker, it treats 15 pips as 150 points. This ensures the SL/TP remains exactly 15 and 30 pips regardless of the broker.
New Bar Logic: I used if(Time[0] == lastTradeBarTime) return;. This is the most efficient way to ensure the EA only runs its logic exactly once when a new candle appears, preventing it from opening multiple trades during the same 15-minute window.

ECN Execution Handling:

Normalization: I used NormalizeDouble(price, Digits). ECN brokers will reject orders if the SL/TP price has too many decimal places.
Retry Loop: ECN environments are prone to "Requotes." The while loop attempts to re-send the order up to 3 times, refreshing the Ask price if the market moves during the execution attempt.
Slippage: The slippage is also scaled by the pipMultiplier to ensure it is meaningful in a 5-digit environment.
The Strategy: It looks at Close[1] and Open[1]. [1] refers to the candle that just closed. If Close > Open, it triggers the OrderSend.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

How to install:

1.) Open your MT4 Terminal.
2.) Go to File -> Open Data Folder.
3.) Navigate to MQL4 -> Experts.
4.) Paste the code into a new file in MetaEditor (F4) and click Compile.
5.) Attach the EA to a 15-Minute (M15) chart.
6.) Crucial: Ensure "Allow Live Trading" is checked in the EA settings and the "AutoTrading" button is green at the top of MT4.


--------------------> End of output.
Attachments
Snímek obrazovky 2026-09-09 151024.png
Snímek obrazovky 2026-09-09 151024.png (58.05 KiB) Viewed 115 times
Snímek obrazovky 2026-09-09 151007.png
Snímek obrazovky 2026-09-09 151007.png (112.5 KiB) Viewed 115 times
Snímek obrazovky 2026-09-09 150953.png
Snímek obrazovky 2026-09-09 150953.png (84.48 KiB) Viewed 115 times
Snímek obrazovky 2026-09-09 152937.png
Snímek obrazovky 2026-09-09 152937.png (33.7 KiB) Viewed 115 times
Snímek obrazovky 2026-09-09 152932.png
Snímek obrazovky 2026-09-09 152932.png (107.83 KiB) Viewed 115 times
Snímek obrazovky 2026-09-09 152920.png
Snímek obrazovky 2026-09-09 152920.png (98.45 KiB) Viewed 115 times
Snímek obrazovky 2026-09-09 152908.png
Snímek obrazovky 2026-09-09 152908.png (101.3 KiB) Viewed 115 times
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

At the last one was LLm Gemma4 31B:

Thought for 354.7 seconds

To create an Expert Advisor for a 5-digit ECN broker, we must address two critical technical requirements:

Pip Calculation: On a 5-digit broker, a "pip" is the 4th decimal place. The 5th decimal is a "point." We must multiply pips by 10.
ECN Execution: Many ECN brokers require orders to be sent with zero Stop Loss and Take Profit, and then modified immediately after the order is opened.

Here is the complete, professional MQL4 code.

Code: Select all

//+------------------------------------------------------------------+
//|                                              ECN_Bullish_M15.mq4 |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023"
#property link      "https://www.yourwebsite.com"
#property version   "1.00"
#property strict

//--- INPUT PARAMETERS
input double   LotSize        = 0.1;       // Trading Volume
input int      StopLossPips   = 15;        // Stop Loss in Pips
input int      TakeProfitPips = 30;        // Take Profit in Pips
input int      Slippage       = 3;         // Max Slippage in Pips
input int      MagicNumber    = 123456;    // Unique EA ID
input int      MaxSpread      = 30;        // Max allowed spread in Points

//--- GLOBAL VARIABLES
datetime lastBarTime; // Tracks the opening time of the current candle
double   pipsValue;   // Adjusted value for 4/5 digit brokers

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // Handle 5-digit brokers: 1 pip = 10 points
   if(Digits == 3 || Digits == 5) 
      pipsValue = Point * 10; 
   else 
      pipsValue = Point;

   lastBarTime = 0;
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // 1. Check for a New Bar (Execute only once per candle)
   if(Time[0] == lastBarTime) return;
   
   // 2. Check for Bullish Candle on the previous bar (Index 1)
   // Condition: Close of previous bar is greater than Open of previous bar
   bool isBullish = (Close[1] > Open[1]);
   
   if(isBullish)
   {
      // Check spread before entering to avoid high-volatility spikes
      if(MarketInfo(Symbol(), MODE_SPREAD) > MaxSpread)
      {
         Print("Trade skipped: Spread too high");
         lastBarTime = Time[0]; // Mark bar as processed even if spread was too high
         return;
      }

      ExecuteBuyOrder();
   }
   
   // Update the bar time so the EA doesn't fire again until the next M15 bar
   lastBarTime = Time[0];
}

//+------------------------------------------------------------------+
//| Function to handle ECN Order Execution                           |
//+------------------------------------------------------------------+
void ExecuteBuyOrder()
{
   double askPrice = MarketInfo(Symbol(), MODE_ASK);
   int ticket;

   // ECN RULE: Send order with 0 SL and 0 TP first
   ticket = OrderSend(Symbol(), OP_BUY, LotSize, askPrice, Slippage, 0, 0, "ECN Bullish", MagicNumber, 0, clrBlue);

   if(ticket < 0)
   {
      Print("OrderSend failed with error: ", GetLastError());
      return;
   }

   // Order opened successfully, now calculate and modify SL and TP
   double sl = askPrice - (StopLossPips * pipsValue);
   double tp = askPrice + (TakeProfitPips * pipsValue);

   // Correct rounding for broker prices
   sl = NormalizeDouble(sl, Digits);
   tp = NormalizeDouble(tp, Digits);

   if(!OrderModify(ticket, askPrice, sl, tp, 0, clrBlue))
   {
      Print("OrderModify failed with error: ", GetLastError());
   }
   else
   {
      Print("Buy order executed and modified successfully. Ticket: ", ticket);
   }
}
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

Key Technical Explanations:

The lastBarTime Logic: The EA uses a static or global variable to store the timestamp of the current candle (Time[0]). If the current timestamp is the same as the stored one, the function returns immediately. This ensures that the logic only runs exactly once at the opening of a new 15-minute bar.

ECN Compliance (The "Two-Step" Process): True ECN brokers often reject OrderSend if SL and TP are included in the initial request. To solve this:

Step 1: OrderSend is called with 0 for SL and 0 for TP.
Step 2: OrderModify is immediately called using the ticket number from Step 1 to apply the Stop Loss and Take Profit.

5-Digit Broker Normalization:

pipsValue: The code detects if the broker uses 3 or 5 digits. If so, it multiplies the Point (which is 0.00001) by 10 to get a standard pip (0.0001).
NormalizeDouble(): Brokers will reject orders if the SL/TP has too many decimal places. This function rounds the price to the exact number of digits allowed by the broker.
Safety Filter (Spread Check): I added a MaxSpread filter. On ECN brokers, spreads can widen significantly during news or candle rollovers. This prevents the EA from entering a trade if the cost of entry is too high.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2661
Joined: Mon Jul 20, 2026 1:28 pm

Re: Can AI Write Safe MT4 Scalping Bots? Gemma 4 Local Inference Benchmark

Post by PTScalper »

How to install:

1.) Open your MT4 Terminal.
2.) Go to File $\rightarrow$ Open Data Folder.
3.) Navigate to MQL4 $\rightarrow$ Experts.
4.) Create a new file named ECN_Bullish_M15.mq4 and paste the code above.
5.) Compile the code (Press F7 in the MetaEditor).
6.) Drag the EA onto a 15-minute (M15) chart of your choice.
7.) Ensure "Allow Live Trading" is checked in the EA settings and the "AutoTrading" button at the top of MT4 is green.


-----------------> End of output.
Attachments
Snímek obrazovky 2026-09-09 150555.png
Snímek obrazovky 2026-09-09 150555.png (52.34 KiB) Viewed 114 times
Snímek obrazovky 2026-09-09 144939.png
Snímek obrazovky 2026-09-09 144939.png (48.94 KiB) Viewed 114 times
Snímek obrazovky 2026-09-09 144923.png
Snímek obrazovky 2026-09-09 144923.png (73.29 KiB) Viewed 114 times
Snímek obrazovky 2026-09-09 153400.png
Snímek obrazovky 2026-09-09 153400.png (35.38 KiB) Viewed 114 times
Snímek obrazovky 2026-09-09 153354.png
Snímek obrazovky 2026-09-09 153354.png (104.13 KiB) Viewed 114 times
Snímek obrazovky 2026-09-09 153344.png
Snímek obrazovky 2026-09-09 153344.png (89.26 KiB) Viewed 114 times
Snímek obrazovky 2026-09-09 153332.png
Snímek obrazovky 2026-09-09 153332.png (103.25 KiB) Viewed 114 times
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Post Reply