The Tick Loop
Everything an EA does — every check, every trade, every modification — starts with a single event: a price tick. Understanding this loop is the foundation of understanding all EA behaviour.
Price tick arrives
Broker sends a new bid/ask price update to MT5. On XAUUSD this happens thousands of times per second.
MT5 calls OnTick()
MetaTrader 5 immediately wakes the EA by calling its OnTick() event handler. The EA code begins executing.
Read market state
EA reads current price, spread, open positions, indicator values, account balance, and session time.
Evaluate conditions
Checks entry conditions (should a new trade open?), exit conditions (should an open trade close or be modified?).
Send order or modify
If conditions are met, the EA sends a buy/sell order or modifies an existing trade via the broker API.
Wait for next tick
Execution ends. The EA sleeps until MT5 calls OnTick() again on the next price update.
The EA does not "watch the chart" — it is called by MT5.
The EA has no active process running between ticks. MT5 owns the timer. Every time a broker tick arrives, MT5 invokes the EA's OnTick() function, the code runs in milliseconds, and then stops. This event-driven design is what makes EAs both fast and resource-efficient.
What the EA Reads on Every Tick
Before the EA can make any decision, it pulls a snapshot of the current market state. This happens on every call to OnTick().
Price Data
- →Current bid and ask price
- →OHLC history (Open, High, Low, Close per bar)
- →Spread (ask minus bid)
- →Tick volume per bar
Indicator Values
- →Moving averages (MA, EMA, WMA)
- →ATR (Average True Range) for volatility
- →ADX for trend strength
- →RSI, MACD, Bollinger Bands, custom indicators
Account State
- →Current balance and equity
- →Free margin available
- →Open positions (symbol, lot, P&L)
- →Pending orders placed
Time & Session
- →Current server time
- →Day of week (some EAs skip Mondays/Fridays)
- →Trading session (London, NY, Asia)
- →Time since last trade
Spread matters more than most traders realise. A scalping EA that targets 30 pips on XAUUSD pays 0.5–2.0 pips in spread on every entry. Over 200 trades a month, even a 0.5 pip difference in broker spread translates into a meaningful difference in net profit. This is why spread filtering (Max Spread input) is a standard feature in well-built EAs.
Entry Logic: How the EA Decides to Trade
An EA's entry logic is a set of conditions that must all be true at the same time. Think of it as a checklist the EA runs through on every tick. Only when all conditions pass does it open a trade.
Example: Momentum Scalper Entry Checklist
ADX(14) > 20Trend is strong enough to justify an entryATR(14) > 0.80Market is volatile enough for the target to be reachableSpread ≤ Max Spread settingCurrent broker spread is acceptableWithin allowed trading hoursServer time is inside the London/NY session windowNo existing open positionEA is not already in a trade (single-position mode)EMA fast > EMA slow (for BUY)Price structure supports the directionIf ANY condition fails → no tradeAll conditions must pass simultaneously. One failure blocks the entry.More conditions generally mean fewer trades but higher quality setups. Fewer conditions mean more trades but potentially more noise. The art of EA design is calibrating this balance for the specific instrument and timeframe — XAUUSD M1 requires tighter filters than a daily-chart trend strategy.
Order Execution: From Signal to Open Trade
Once entry conditions are met, the EA sends an order to the broker. There are three main order types EAs use, each suited to a different strategy type.
Opens a trade immediately at the current market price. Used by most scalping EAs. Speed is the priority — price confirmation happens in the tick loop, not via a pending order.
Most common in scalpersA pending order that triggers when price reaches a specified level above (buy stop) or below (sell stop) the current price. Used by breakout EAs — the order only fills if price actually breaks out.
Used in breakout EAsTriggers when price pulls back to a specified level. Used by mean-reversion EAs expecting price to return to a level before continuing. Provides better entry pricing than market orders.
Used in range EAsSlippage on market orders. When the EA sends a market order, the broker fills it at the best available price — which during high-impact news events may be several pips away from the request. This is slippage. ECN brokers with low-latency execution minimise it, making them the preferred choice for scalping EAs like those built for XAUUSD.
Trade Management: What Happens After Entry
Opening a trade is only half the job. How the EA manages the trade after entry often determines whether a strategy is profitable in the long run. Most well-built EAs implement several layers of trade management.
Stop Loss (SL)
A fixed price level where the trade closes if it goes against the EA. Set at order placement. Acts as a hard cap on the loss per trade. Distance is usually based on ATR, a fixed pip value, or a recent swing level.
Take Profit (TP)
A fixed target where the trade closes automatically in profit. Some EAs use a single TP, others use multiple partial TPs to lock in gains at different levels.
Breakeven Move
Once price moves a defined number of pips in profit, the EA modifies the stop loss to the entry price. If price reverses, the trade closes at zero loss instead of a full SL hit.
Trailing Stop
The stop loss follows price as it moves in profit, maintaining a fixed pip distance behind the best price reached. If price reverses by that distance, the trade closes — locking in whatever profit had accumulated.
Partial Close
Closes a percentage of the open position at a TP level, then continues trailing the remainder. Balances locking in profit while staying in a winning trade.
Time Exit
Closes any open trade at a specific time — typically before market close on Friday, before high-impact news, or at the end of a session. Avoids holding positions through unpredictable conditions.
Three-Layer Protection (Pro-Scalper Standard)
Hard Stop Loss
Maximum loss cap
Breakeven Move
Locks in zero loss
Trailing Stop
Follows profits up
The Four EA Strategy Types Used on XAUUSD
Most XAUUSD Expert Advisors fall into one of four strategy categories. Each uses a different approach to detecting opportunities and managing risk.
Momentum Scalping
Detects short bursts of directional momentum using indicators like ADX (strength) and volume. Enters quickly, targets 20–50 pips, exits with a tight trailing stop. Works best in the London and New York sessions when volume is highest.
Range Breakout
Identifies a consolidation range over a defined period (e.g. the Asian session range). Places buy-stop above and sell-stop below the range. When price breaks out, the triggered order captures the move.
Volatility Spike Detection
Monitors ATR for an unusual expansion above its recent average. A sudden volatility spike often signals the start of a directional move. The EA enters in the direction of the spike with tight risk controls.
Semi-Automated (Manual Entry)
The human selects the direction and presses a button. The EA then takes over: sets SL/TP, moves to breakeven, trails the stop. Combines human market reading with robotic trade management — removing emotion from exits.
The Most Important EA Input Parameters
When you attach an EA to a chart, MT5 shows an inputs window with the EA's configurable settings. Here are the parameters you will encounter in almost every EA and what they control.
Lot SizeThe volume of each trade. Either fixed (e.g. 0.10) or calculated as a % of account balance divided by stop loss pips.
Stop Loss (pips)Maximum loss distance from entry, measured in pips. Directly affects lot sizing when using % risk mode.
Take Profit (pips)Target profit distance from entry in pips. Some EAs use dynamic TP based on ATR instead of a fixed value.
Max SpreadThe EA will not trade if the current spread exceeds this value. Essential for scalpers — a wide spread can turn a winning trade into a loss.
Magic NumberA unique ID the EA attaches to every trade it opens. Allows multiple EAs on the same account to coexist without interfering with each other.
Max TradesMaximum number of positions the EA can hold simultaneously. Prevents overexposure during a fast market.
Trading HoursStart and end time for the EA to place new trades. Common setting: restrict to London and NY sessions only. Avoids thin Asian session liquidity.
Breakeven Trigger (pips)How far into profit price must move before the EA moves the stop loss to entry price. Reduces risk-free trades.
How to Monitor a Running EA
A running EA is not a set-and-forget black box. Regular monitoring ensures the EA is performing as expected and lets you catch problems early — before they become significant losses.
Daily checks (5 minutes)
- ·EA is active — smiley face icon on chart
- ·Auto-trading button in toolbar is green
- ·No unexpected open positions
- ·Spread at normal levels for your broker
Weekly review (15 minutes)
- ·Check trade history — is win rate on track?
- ·Review drawdown versus expected maximum
- ·Check balance growth curve
- ·Compare to backtest expectations
Monthly assessment
- ·Is the EA performing within expected parameters?
- ·Has market behaviour changed significantly?
- ·Are lot sizes still appropriate for current balance?
- ·Consider pausing during major economic events
Warning signs to act on
- ·Drawdown exceeding the backtested maximum
- ·Win rate significantly below expectation
- ·Unusually wide spreads at broker
- ·EA not trading during expected session hours
Frequently Asked Questions
Does an EA run even when I close my computer?
No. An EA runs inside MetaTrader 5, which must be open and connected to your broker. If MT5 closes, the EA stops. To run an EA 24/5, you need a Virtual Private Server (VPS) that keeps MT5 running continuously.
Can an EA open multiple trades at the same time?
Yes, depending on how it is programmed. Some EAs only hold one trade at a time, others can open several simultaneously. The maximum number of open trades is usually a configurable input parameter.
What happens if the internet disconnects while an EA has open trades?
Open trades remain on the broker server — they do not close. Stop loss and take profit orders are already placed at the broker, so they will trigger even if MT5 disconnects. The EA cannot open new trades or manage positions while offline.
How does an EA know when to move the stop loss to breakeven?
The EA checks the current price relative to the entry on every tick. Once price has moved a configurable number of pips in profit, the EA modifies the stop loss order on the broker server to the entry price. This all happens automatically without your input.
What is a magic number in an EA?
A magic number is a unique integer the EA stamps on every trade it opens. This lets the EA identify its own trades when multiple EAs run on the same account, or when the same EA runs on multiple charts. Without unique magic numbers, an EA could accidentally manage trades it did not open.
Can an EA lose more than the stop loss amount?
Rarely, but yes — in extreme market conditions. Slippage at market open, news gaps, or broker requotes can cause the actual fill price to be worse than the stop loss level. This is why raw spread ECN brokers with fast execution matter, especially for scalping EAs.
Purpose-Built XAUUSD Expert Advisors
Every Pro-Scalper EA is built around the principles in this guide — transparent entry logic, three-layer trade management, and tight spread filtering for XAUUSD on MT5.