The given errors are:
Full Code:
Delete, ,0 and ,1 in iMA after AppliedPrice
#include <Trade\Trade.mqh> CTrade trade; // === Input Parameters === input double LotSize = 0.1; input int TakeProfitPts = 200; input int StopLossPts = 0; // 0 = automatic SL (last top/bottom) input int OpenTradeMode = 1; // 1 = Both, 2 = Buy only, 3 = Sell only input int FastMAPeriod = 50; input ENUM_MA_METHOD FastMAMethod = MODE_EMA; input int SlowMAPeriod = 100; input ENUM_MA_METHOD SlowMAMethod = MODE_EMA; input int TrendMAPeriod = 200; input ENUM_MA_METHOD TrendMAMethod = MODE_SMA; input ENUM_APPLIED_PRICE AppliedPrice = PRICE_CLOSE; //+------------------------------------------------------------------+ //| Initialization | //+------------------------------------------------------------------+ int OnInit() { return INIT_SUCCEEDED; } //+------------------------------------------------------------------+ //| Utility: Get last lowest price (previous 10 bars) | //+------------------------------------------------------------------+ double GetLastLow() { double lowest = iLow(_Symbol, _Period, 1); for (int i = 2; i <= 10; i++) { double low = iLow(_Symbol, _Period, i); if (low < lowest) lowest = low; } return lowest; } //+------------------------------------------------------------------+ //| Utility: Get last highest price (previous 10 bars) | //+------------------------------------------------------------------+ double GetLastHigh() { double highest = iHigh(_Symbol, _Period, 1); for (int i = 2; i <= 10; i++) { double high = iHigh(_Symbol, _Period, i); if (high > highest) highest = high; } return highest; } //+------------------------------------------------------------------+ //| Expert Tick Function | //+------------------------------------------------------------------+ void OnTick() { if (PositionsTotal() > 0) return; // Only one trade at a time // === MA Calculations === double fastMA_0 = iMA(_Symbol, _Period, FastMAPeriod, 0, FastMAMethod, AppliedPrice); double fastMA_1 = iMA(_Symbol, _Period, FastMAPeriod, 0, FastMAMethod, AppliedPrice); double slowMA = iMA(_Symbol, _Period, SlowMAPeriod, 0, SlowMAMethod, AppliedPrice); double trendMA_0 = iMA(_Symbol, _Period, TrendMAPeriod, 0, TrendMAMethod, AppliedPrice); double trendMA_1 = iMA(_Symbol, _Period, TrendMAPeriod, 0, TrendMAMethod, AppliedPrice); double close_0 = iClose(_Symbol, _Period, 0); double close_1 = iClose(_Symbol, _Period, 1); // === Buy Logic === bool buy1 = (fastMA_1 < trendMA_1 && fastMA_0 > trendMA_0); // Cross above trend MA bool buy2 = (close_1 < fastMA_1 && close_0 > fastMA_0 && fastMA_0 > trendMA_0 && slowMA > trendMA_0); // Price crosses fastMA while both MAs above trend // === Sell Logic === bool sell1 = (fastMA_1 > trendMA_1 && fastMA_0 < trendMA_0); // Cross below trend MA bool sell2 = (close_1 > fastMA_1 && close_0 < fastMA_0 && fastMA_0 < trendMA_0 && slowMA < trendMA_0); // Price crosses below fastMA while both MAs below // === Open Trade if Signal Fires === double sl = 0, tp = 0; if ((buy1 || buy2) && (OpenTradeMode == 1 || OpenTradeMode == 2)) { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); tp = ask + TakeProfitPts * _Point; if (StopLossPts > 0) sl = ask - StopLossPts * _Point; else sl = GetLastLow(); if (trade.Buy(LotSize, _Symbol, ask, sl, tp, "3MA Buy")) Print("Buy Order Sent | SL=", sl, " TP=", tp); } if ((sell1 || sell2) && (OpenTradeMode == 1 || OpenTradeMode == 3)) { double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); tp = bid - TakeProfitPts * _Point; if (StopLossPts > 0) sl = bid + StopLossPts * _Point; else sl = GetLastHigh(); if (trade.Sell(LotSize, _Symbol, bid, sl, tp, "3MA Sell")) Print("Sell Order Sent | SL=", sl, " TP=", tp); } }
It's foolish to code in this framework without even looking at the reference
- www.mql5.com
in the simplest form, iMA can be created like this inside the expert:
input int MA_Period = 20; double ma_buf[]; int handle = INVALID_HANDLE; int OnInit() { handle = iMA(_Symbol, _Period, MA_Period, 0, MODE_EMA, PRICE_CLOSE); ArraySetAsSeries(ma_buf, true); return (INIT_SUCCEEDED); } void OnDeinit(const int reason){ IndicatorRelease(handle); Comment(""); } void OnTick() { if (CopyBuffer(handle, 0, 0, 2, ma_buf)==-1) { Print("problem loading MA data"); GetLastError(); } double ema_latest_bar = ma_buf[0]; double ema_penultimate_bar = ma_buf[1]; string str = "EMA value on the current bar: " + DoubleToString(ema_latest_bar) + "\n" + "EMA value on the second-last bar: " + DoubleToString(ema_penultimate_bar); Comment(str); }
copy this into a text file, and save as a reference
The given errors are:
Full Code:
Thank you for your indicator! I kept its strengths as the foundation and removed the listed risks and weaknesses. Here’s the result on EUR/USD-H1 from 1 January 2025 up to today. Best of luck with your trading and any further tweaks!
Strengths
- Clear trend filter – The 200‑period SMA keeps the EA from trading against the primary market direction.
- Two independent entry patterns – A fast‑MA ↔ trend‑MA crossover and a price ↔ fast‑MA crossover offer greater flexibility in capturing momentum.
- Automatic stop‑loss based on market structure – When no fixed SL is supplied, the EA places the stop at the most recent swing high/low instead of an arbitrary distance.
- Clean, easily maintained code – The logic is compact and readable, and the CTrade class abstracts most order‑handling details.
Weaknesses & risk factors
- Repainting signals – Because the strategy checks the still‑forming bar (fastMA_0, trendMA_0, close_0), a signal can vanish before the candle closes, inflating back‑test results.
- Global position check – PositionsTotal() counts every open trade across all symbols; a position on another instrument can block this EA from trading the current symbol.
- No runtime error handling – The return value of trade.Buy()/trade.Sell() is not properly validated, so requotes or broker rejections can leave the EA inactive without warning.
- _Point versus pip confusion – Using raw _Point means “200 points” equals only 20 pips on a 5‑digit broker but 200 pips on a 4‑digit broker, producing inconsistent risk‑to‑reward ratios.
- Fixed lot size – A hard‑coded LotSize ignores account balance, stop‑loss distance, and volatility; risk per trade scales unpredictably.
- No trading‑time or spread filter – The EA trades through news spikes, widened spreads, and low‑liquidity sessions, increasing slippage risk.
- Pending orders ignored – The single‑position check does not include pending orders, so multiple positions might be opened unintentionally.
- Hard‑coded swing look‑back – GetLastLow/High() always scans the last 10 bars; on lower timeframes this is minutes, on higher timeframes many hours, which may be inappropriate.
- No minimum stop‑distance check – The EA does not adapt the SL to the broker’s minimum distance, so orders can be rejected outright.
#property copyright "BND" #property link "https://www.mql5.com/en/users/bnd" #property version "1.00" #property description "Created - 2025.06.20" //+------------------------------------------------------------------+ //| 3_‑MA_Tren_ EA – robust, MT5‑compliant version | //+------------------------------------------------------------------+ #include <Trade\Trade.mqh> CTrade trade; //==================================================================== // INPUT PARAMETERS //==================================================================== input double RiskPercent = 1.0; // % of balance to risk per trade input double FixedLotSize = 0.0; // >0 → use fixed lot; =0 → use RiskPercent input int TakeProfitPips = 20; // TP distance in pips input int StopLossPipsManual = 0; // fixed SL in pips; 0 → last swing input int SL_LookbackBars = 10; // bars to look back for swing SL input int OpenTradeMode = 1; // 1 = Buy+Sell | 2 = Buy only | 3 = Sell only input int FastMAPeriod = 50; input ENUM_MA_METHOD FastMAMethod = MODE_EMA; input int SlowMAPeriod = 100; input ENUM_MA_METHOD SlowMAMethod = MODE_EMA; input int TrendMAPeriod = 200; input ENUM_MA_METHOD TrendMAMethod = MODE_SMA; input ENUM_APPLIED_PRICE Price = PRICE_CLOSE; input bool UseTradingHours = false; input int SessionStartHour = 7; // server time input int SessionEndHour = 22; input int MaxSpreadPoints = 30; // maximum allowed spread //==================================================================== // GLOBAL VARIABLES //==================================================================== double pip; // price value of one pip int stopLevel; // broker’s minimum SL distance (points) int fastMAHandle = INVALID_HANDLE; int slowMAHandle = INVALID_HANDLE; int trendMAHandle = INVALID_HANDLE; datetime lastSignalTime = 0; // prevents duplicate trades on same bar //==================================================================== // HELPER FUNCTIONS //================================================================---- //-------------------------------------------------------------------- // Initialise pip factor & stop‑level //-------------------------------------------------------------------- void InitTradingParameters() { pip = (_Digits == 3 || _Digits == 5) ? 10 * _Point : _Point; stopLevel = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL); } //-------------------------------------------------------------------- // Detect a new closed bar //-------------------------------------------------------------------- bool IsNewBar() { static datetime prevTime = 0; datetime now = iTime(_Symbol, _Period, 0); if (now != prevTime) { prevTime = now; return true; } return false; } //-------------------------------------------------------------------- // Check spread and, optionally, trading session //-------------------------------------------------------------------- bool TradingAllowed() { int spreadPts = (int)((SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point); if (spreadPts > MaxSpreadPoints) return false; if (UseTradingHours) { MqlDateTime dt; TimeToStruct(TimeCurrent(), dt); if (dt.hour < SessionStartHour || dt.hour >= SessionEndHour) return false; } return true; } //-------------------------------------------------------------------- // Last swing high/low over SL_LookbackBars //-------------------------------------------------------------------- double GetExtreme(bool lowest) { double extreme = lowest ? iLow(_Symbol, _Period, 1) : iHigh(_Symbol, _Period, 1); for (int i = 2; i <= SL_LookbackBars; ++i) { double price = lowest ? iLow(_Symbol, _Period, i) : iHigh(_Symbol, _Period, i); if (lowest ? (price < extreme) : (price > extreme)) extreme = price; } return extreme; } //-------------------------------------------------------------------- // Risk‑based lot calculation //-------------------------------------------------------------------- double CalculateLot(double slPrice, double entryPrice) { if (FixedLotSize > 0) return FixedLotSize; double riskMoney = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100.0; double slDistance = MathAbs(entryPrice - slPrice); double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); if (slDistance < tickSize) slDistance = tickSize; double lots = riskMoney / (slDistance / tickSize * tickValue); double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double min = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double max = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); lots = MathFloor(lots / step) * step; lots = MathMax(lots, min); lots = MathMin(lots, max); return NormalizeDouble(lots, 2); } //-------------------------------------------------------------------- // Enforce broker minimum SL distance //-------------------------------------------------------------------- double AdjustSL(double entry, double sl, bool isBuy) { double distPts = MathAbs(entry - sl) / _Point; if (distPts < stopLevel) { double adjust = (stopLevel - distPts) * _Point; sl = isBuy ? (entry - adjust) : (entry + adjust); } return sl; } //==================================================================== // EXPERT EVENTS //================================================================---- //-------------------------------------------------------------------- // OnInit – create indicator handles //-------------------------------------------------------------------- int OnInit() { InitTradingParameters(); fastMAHandle = iMA(_Symbol, _Period, FastMAPeriod, 0, FastMAMethod, Price); slowMAHandle = iMA(_Symbol, _Period, SlowMAPeriod, 0, SlowMAMethod, Price); trendMAHandle = iMA(_Symbol, _Period, TrendMAPeriod, 0, TrendMAMethod, Price); if (fastMAHandle == INVALID_HANDLE || slowMAHandle == INVALID_HANDLE || trendMAHandle == INVALID_HANDLE) { Print("Failed to create indicator handles. Error: ", GetLastError()); return INIT_FAILED; } return INIT_SUCCEEDED; } //-------------------------------------------------------------------- // OnDeinit – release resources //-------------------------------------------------------------------- void OnDeinit(const int reason) { if (fastMAHandle != INVALID_HANDLE) IndicatorRelease(fastMAHandle); if (slowMAHandle != INVALID_HANDLE) IndicatorRelease(slowMAHandle); if (trendMAHandle != INVALID_HANDLE) IndicatorRelease(trendMAHandle); } //-------------------------------------------------------------------- // OnTick – main loop //-------------------------------------------------------------------- void OnTick() { if (!IsNewBar() || !TradingAllowed() || PositionSelect(_Symbol)) return; // --------------------------------------------------------------- // Pull MA values for bars 0–2 (we only use 1 & 2 to avoid repainting) // --------------------------------------------------------------- double fastMA[3], slowMA[2], trendMA[3]; if (CopyBuffer(fastMAHandle, 0, 0, 3, fastMA) != 3) return; if (CopyBuffer(slowMAHandle, 0, 0, 2, slowMA) != 2) return; if (CopyBuffer(trendMAHandle, 0, 0, 3, trendMA) != 3) return; double fastMA_1 = fastMA[1], fastMA_2 = fastMA[2]; double slowMA_1 = slowMA[1]; double trendMA_1 = trendMA[1], trendMA_2 = trendMA[2]; double close_1 = iClose(_Symbol, _Period, 1); double close_2 = iClose(_Symbol, _Period, 2); // --------------------------------------------------------------- // Signal logic (non‑repainting) // --------------------------------------------------------------- bool buy1 = (fastMA_2 < trendMA_2 && fastMA_1 > trendMA_1); bool buy2 = (close_2 < fastMA_2 && close_1 > fastMA_1 && fastMA_1 > trendMA_1 && slowMA_1 > trendMA_1); bool sell1 = (fastMA_2 > trendMA_2 && fastMA_1 < trendMA_1); bool sell2 = (close_2 > fastMA_2 && close_1 < fastMA_1 && fastMA_1 < trendMA_1 && slowMA_1 < trendMA_1); datetime barTime = iTime(_Symbol, _Period, 1); if (barTime == lastSignalTime) return; // avoid duplicates bool buySignal = (buy1 || buy2) && (OpenTradeMode == 1 || OpenTradeMode == 2); bool sellSignal = (sell1 || sell2) && (OpenTradeMode == 1 || OpenTradeMode == 3); if (!buySignal && !sellSignal) return; // --------------------------------------------------------------- // Order parameters // --------------------------------------------------------------- bool isBuy = buySignal; double entryPrice = isBuy ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); double tp = isBuy ? entryPrice + TakeProfitPips * pip : entryPrice - TakeProfitPips * pip; double sl; if (StopLossPipsManual > 0) sl = isBuy ? entryPrice - StopLossPipsManual * pip : entryPrice + StopLossPipsManual * pip; else sl = isBuy ? GetExtreme(true) : GetExtreme(false); sl = AdjustSL(entryPrice, sl, isBuy); double lot = CalculateLot(sl, entryPrice); // --------------------------------------------------------------- // Place order // --------------------------------------------------------------- bool sent = isBuy ? trade.Buy(lot, _Symbol, entryPrice, sl, tp, "3MA‑Buy") : trade.Sell(lot, _Symbol, entryPrice, sl, tp, "3MA‑Sell"); if (sent) Print((isBuy ? "BUY" : "SELL"), " ", _Symbol, " | Entry=", DoubleToString(entryPrice, _Digits), " SL=", DoubleToString(sl, _Digits), " TP=", DoubleToString(tp, _Digits), " Lot=", lot); else Print("Order send failed. Error: ", GetLastError()); lastSignalTime = barTime; } //+------------------------------------------------------------------+
i get this error when i try compiling
I have attached the bot file as well
Kindly assist.
i get this error when i try compiling
I have attached the bot file as well
Kindly assist.
The reply -
Forum on trading, automated trading systems and testing trading strategies
William Roeder, 2025.06.20 22:22
Please, don't request help for ChatGPT (or other A.I.) generated code. It generates horrible code, mixing MQL4 and MQL5. Please use the Freelance section for such requests — https://www.mql5.com/en/jobYou’re right—ChatGPT (and other AIs) still stumble: it can’t even rewrite a simple sequence of numbers without introducing errors, and it mixes MQL4 with MQL5.
If you need dependable code, the best path is to invest some time in C / C++; once you understand those fundamentals, MQL5 will click. It takes patience, but start coding and keep practicing—then you’ll immediately spot it when the AI produces nonsense again.
And if you decide not to code yourself, hiring a freelancer is a perfectly sensible option; there are some truly skilled developers here who can do an excellent job.
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use

The given errors are:
Full Code: