EA Builder · your rules, our teaching
Assemble your rules. Read the code they become.
Every choice on the left rewrites the MQL5 on the right, with a plain-English note beside each block. The guard rails explain risky settings; they never pick settings for you.
01Name, chart and direction
Letters, digits and underscores. Becomes the file name.
02Entry rule
Shorter average: reacts faster, crosses more often, more false starts.
Longer average: the baseline the fast one crosses. Must be longer than the fast average.
Watch out
- In a sideways market, averages cross back and forth and each cross pays the spread.
- Optimising both periods to the exact best pair is a classic way to overfit.
03Filters
04Stop loss
Bars averaged to measure typical range. MT5's iATR is a simple average of true range.
How many ATRs from entry the stop sits. Wider stops mean smaller positions for the same risk.
05Exit
A higher multiple wins less often. Break-even win rate = 1 ÷ (1 + R), before costs.
06Risk engine
Share of equity lost if the stop is hit. Many educators suggest 0.5–1%; above 2% the builder warns.
No new trades for the rest of the server day once equity is this far below the day's start. 0 switches it off.
Positions this EA may hold at once on this symbol.
Skip new entries when the spread is wider than this. 0 switches the filter off.
1 = off. Anything above 1 is martingale-style sizing; the builder explains why it is dangerous.
Watch out
- Correlated symbols add up: five 1% trades in one direction behave like one 5% trade.
- Martingale sizing turns ordinary losing streaks into account-ending ones.
Your rules, our teaching. MarketPanda provides no strategy, no settings that “work” and no signals. Everything here is education; nothing is a recommendation to trade.
Guard railsNothing risky flagged
Note: Break-even win rate 33% before costs
With a 2R target, a trade must win more than 33.3% of the time just to cover losses, before spread and commission. This is arithmetic, not a forecast of your win rate.
01
Header and trade library
Names the file, states plainly that these are your rules, and loads MetaTrader's standard CTrade class, which sends and checks orders for you.
//+------------------------------------------------------------------+ //| MyRules.mq5 | //| Rules written by you in the MarketPanda EA Builder. | //| Your rules, our teaching: MarketPanda supplies no strategy, no | //| signals and no settings that "work". Educational template only. | //| Test in the Strategy Tester and on a demo account before any | //| live use. A backtest describes the past; it is not a forecast. | //+------------------------------------------------------------------+ #property copyright "Your name" #property version "1.00" #property description "Your own rules. Educational template generated by MarketPanda EA World." #include <Trade/Trade.mqh> CTrade trade;02
Inputs: your dials
Every number you chose becomes an input you can change in MetaTrader's settings window or the Strategy Tester — without editing code. Fewer dials means fewer ways to overfit.
enum ENUM_RULE_DIRECTION { DIR_BOTH = 0, // Long and short DIR_LONG = 1, // Long only DIR_SHORT = 2 // Short only }; input group "General" input ENUM_TIMEFRAMES InpTimeframe = PERIOD_D1; // Timeframe the rules read input ENUM_RULE_DIRECTION InpDirection = DIR_BOTH; // Which side the rules may trade input ulong InpMagic = 260001; // Magic number: unique per EA and symbol input group "Entry: moving-average cross" input int InpFastPeriod = 10; // Fast average period input int InpSlowPeriod = 30; // Slow average period input ENUM_MA_METHOD InpMaMethod = MODE_EMA; // Averaging method input group "Stop and exit" input int InpAtrPeriod = 14; // ATR period input double InpAtrMult = 2.0; // Stop distance in ATRs input double InpRewardRisk = 2.0; // Take profit as a multiple of the stop (0 = none) input bool InpExitOnOpposite = false; // Close when the opposite rule fires input group "Risk engine" input double InpRiskPercent = 1.0; // % of equity lost if the stop is hit input double InpDailyLossPercent = 3.0; // No new trades today below this loss (0 = off) input int InpMaxPositions = 1; // Max open positions for this EA input int InpMaxSpreadPoints = 30; // Skip entries above this spread (0 = off)03
Handles and state
Indicator handles are created once and reused. The EA also remembers the last bar it decided on and the equity at the start of the server day.
//--- indicator handles (created once in OnInit) int hFast = INVALID_HANDLE; int hSlow = INVALID_HANDLE; int hAtr = INVALID_HANDLE; //--- state datetime lastBarTime = 0; // open time of the last bar we decided on double dayStartEquity = 0; int dayOfYear = -1;04
OnInit — prepare and validate
Runs once when the EA starts. It refuses to start if your inputs contradict each other, creates the indicator handles, and stamps every order with your magic number.
int OnInit() { if(InpFastPeriod >= InpSlowPeriod) { Print("Fast period must be shorter than slow period."); return(INIT_PARAMETERS_INCORRECT); } if(InpRiskPercent <= 0.0) return(INIT_PARAMETERS_INCORRECT); hFast = iMA(_Symbol, InpTimeframe, InpFastPeriod, 0, InpMaMethod, PRICE_CLOSE); hSlow = iMA(_Symbol, InpTimeframe, InpSlowPeriod, 0, InpMaMethod, PRICE_CLOSE); hAtr = iATR(_Symbol, InpTimeframe, InpAtrPeriod); if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE || hAtr == INVALID_HANDLE) { Print("Could not create an indicator handle. Error ", GetLastError()); return(INIT_FAILED); } trade.SetExpertMagicNumber(InpMagic); trade.SetDeviationInPoints(10); // max slippage accepted, in points return(INIT_SUCCEEDED); }05
OnDeinit — clean up
Runs when the EA is removed. It releases the indicators. Open trades stay open with the broker — removing an EA is not an exit.
void OnDeinit(const int reason) { if(hFast != INVALID_HANDLE) IndicatorRelease(hFast); if(hSlow != INVALID_HANDLE) IndicatorRelease(hSlow); if(hAtr != INVALID_HANDLE) IndicatorRelease(hAtr); // Open positions are NOT closed when the EA is removed. }06
OnTick — your rule list, in order
Runs on every price change but only decides once per new D1 bar. It reads like your written rules: new bar? opposite exit? daily loss hit? spread OK? rules met? room for another position? Then it sizes and sends.
void OnTick() { if(!IsNewBar()) return; // closed-bar logic: decide once per bar int raw = RulesDirection(); // +1 long rules met, -1 short, 0 none if(InpExitOnOpposite && raw != 0) CloseOpposite(raw); if(DailyLossReached()) return; // risk first // (no session filter selected) if(SpreadTooWide()) return; int dir = Allowed(raw); // direction setting if(dir == 0) return; if(CountMyPositions() >= InpMaxPositions) return; OpenWithRisk(dir); // stop first, then size, then send }07
Closed-bar helpers
IsNewBar() makes the EA act once per bar. Value() reads one number from an indicator with CopyBuffer; shift 1 is the last closed bar, so nothing the EA reads can still change.
bool IsNewBar() { datetime t = iTime(_Symbol, InpTimeframe, 0); // open time of the forming bar if(t == 0 || t == lastBarTime) return(false); lastBarTime = t; return(true); } // One value from an indicator buffer. shift 1 = last CLOSED bar. double Value(const int handle, const int shift) { double v[1]; if(CopyBuffer(handle, 0, shift, 1, v) != 1) return(EMPTY_VALUE); return(v[0]); }08
Your entry rules
Long when the 10-bar EMA closes above the 30-bar EMA (it was at or below one bar earlier); short on the opposite cross. Values come from shifts 1 and 2, so the cross has finished before the EA acts.
int RulesDirection() { double fast1 = Value(hFast, 1), fast2 = Value(hFast, 2); double slow1 = Value(hSlow, 1), slow2 = Value(hSlow, 2); if(fast1 == EMPTY_VALUE || fast2 == EMPTY_VALUE || slow1 == EMPTY_VALUE || slow2 == EMPTY_VALUE) return(0); // missing data: stand aside if(fast2 <= slow2 && fast1 > slow1) return(+1); // fast closed above slow if(fast2 >= slow2 && fast1 < slow1) return(-1); // fast closed below slow return(0); } int Allowed(const int dir) { if(dir == 0) return(0); if(dir > 0 && InpDirection == DIR_SHORT) return(0); if(dir < 0 && InpDirection == DIR_LONG) return(0); return(dir); }09
Circuit breakers
No new trades once equity is 3% below the day's start, none when the spread is above 30 points, and at most 1 open position carrying this EA's magic number.
bool SpreadTooWide() { if(InpMaxSpreadPoints <= 0) return(false); return(SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) > InpMaxSpreadPoints); } bool DailyLossReached() { MqlDateTime now; TimeToStruct(TimeCurrent(), now); if(now.day_of_year != dayOfYear) // a new server day: reset the baseline { dayOfYear = now.day_of_year; dayStartEquity = AccountInfoDouble(ACCOUNT_EQUITY); } if(InpDailyLossPercent <= 0.0) return(false); double lost = dayStartEquity - AccountInfoDouble(ACCOUNT_EQUITY); return(lost >= dayStartEquity * InpDailyLossPercent / 100.0); } int CountMyPositions() { int n = 0; for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); // also selects the position if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue; if((ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic) continue; n++; } return(n); }10
Position sizing
Size is worked out from the stop: a full loss costs 1% of equity. Lots are rounded down, and if the right size is below the broker minimum the trade is skipped rather than over-sized.
// Round DOWN to the broker's lot step; 0 means "cannot size this trade". double NormalizeLots(double lots) { double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP); double minL = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN); double maxL = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX); if(step <= 0) return(0); lots = MathFloor(lots / step) * step; if(lots < minL) return(0); return(MathMin(lots, maxL)); } double LotsForRisk(const double stopDistance) { double riskMoney = AccountInfoDouble(ACCOUNT_EQUITY) * InpRiskPercent / 100.0; double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE_LOSS); double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); if(tickValue <= 0 || tickSize <= 0 || stopDistance <= 0) return(0); double lots = riskMoney / (stopDistance / tickSize * tickValue); return(NormalizeLots(lots)); }11
Sending and closing orders
The stop sits 2 × ATR(14) from entry, measured on the last closed bar. The take profit is 2 × the stop distance. The result of every order is checked and any rejection is printed to the Experts log.
void OpenWithRisk(const int dir) { double price = (dir > 0) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID); double atr = Value(hAtr, 1); if(atr == EMPTY_VALUE || atr <= 0) return; double stopDistance = InpAtrMult * atr; // The broker may refuse stops closer than its minimum distance. double minDist = (double)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) * _Point; if(stopDistance <= minDist) { Print("Stop closer than the broker minimum: trade skipped."); return; } double sl = (dir > 0) ? price - stopDistance : price + stopDistance; double tp = 0.0; if(InpRewardRisk > 0) tp = (dir > 0) ? price + stopDistance * InpRewardRisk : price - stopDistance * InpRewardRisk; sl = NormalizeDouble(sl, _Digits); if(tp != 0.0) tp = NormalizeDouble(tp, _Digits); double lots = LotsForRisk(stopDistance); if(lots <= 0) { Print("Risk-based size is below the broker minimum lot: trade skipped, not over-sized."); return; } bool ok = (dir > 0) ? trade.Buy(lots, _Symbol, price, sl, tp, "MyRules") : trade.Sell(lots, _Symbol, price, sl, tp, "MyRules"); if(!ok || (trade.ResultRetcode() != TRADE_RETCODE_DONE && trade.ResultRetcode() != TRADE_RETCODE_PLACED)) PrintFormat("Order not filled: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription()); } void CloseOpposite(const int dir) { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(ticket == 0) continue; if(PositionGetString(POSITION_SYMBOL) != _Symbol) continue; if((ulong)PositionGetInteger(POSITION_MAGIC) != InpMagic) continue; long type = PositionGetInteger(POSITION_TYPE); if((dir > 0 && type == POSITION_TYPE_SELL) || (dir < 0 && type == POSITION_TYPE_BUY)) if(!trade.PositionClose(ticket)) PrintFormat("Close failed: %u %s", trade.ResultRetcode(), trade.ResultRetcodeDescription()); } }
Using the file
- In MetaTrader 5 open MetaEditor (F4), create or open MQL5/Experts/MyRules.mq5, paste, and Compile (F7). Fix anything the compiler reports before going further.
- Run it in the Strategy Tester (Ctrl+R) with realistic costs and “Every tick based on real ticks”.
- Forward-test unchanged on a demo account. Read Forward test, demo, then small live first.
Generated code is an educational template, provided as is. Check it line by line; you are responsible for anything you run.
Content source: Bundled MarketPanda content.