Overview
EATemplate.mq5 is a starting point for building your own Expert Advisor. The trading logic lives in one small USER SECTION at the top of the file:
- GetSignal() returns +1 (buy), -1 (sell) or 0 (nothing).
- SignalDataReady() returns true when the data needed by GetSignal() is available.
Everything else is already written: position sizing, stop loss and take profit placement, break-even, trailing stop, filters, order filling mode, retries, and support for both netting and hedging accounts.
The moving-average crossover included in the file is an example signal only, so that the template can be compiled and run as it is. It is not a trading strategy, and no result of any kind is implied.
Features
Signal timing
- Signal checked once per new bar of the signal timeframe (default), or on every tick.
- One entry per direction per signal bar.
Position sizing
- Fixed lot, or risk % of account balance (default) calculated from the stop-loss distance.
- Lots are rounded down to the volume step. A risk-based lot below the broker minimum is skipped (no trade).
- Broker maximum lot and the symbol volume limit are respected.
- If free margin is not enough, the lot is reduced to use at most 90% of free margin, and one line is printed. If even the minimum lot does not fit, the trade is skipped.
Stop loss / take profit
- Set in points from the entry price (Ask for buy, Bid for sell). 0 = none.
- A level closer than the broker's stop level is moved outward to the minimum allowed distance.
Break-even and trailing stop
- Break-even: after a set profit, the SL moves to entry plus an offset.
- Trailing stop: after a set profit, the SL follows price at a set distance, in steps (step 0 = 10% of the distance).
- The SL only moves in the favourable direction. Break-even and trailing are checked against the stop level separately, so one that is too close does not block the other.
- Close and modify requests are postponed while price is inside the broker's freeze level.
Filters (new entries only)
- Maximum spread (default 0 = off).
- Trading hours in server time, including windows that cross midnight.
- Weekdays, Friday cut-off time.
- News filter using the MT5 built-in economic calendar (live and demo accounts; switched off automatically in the Strategy Tester).
Trade management
- Optional close on opposite signal. This exit is not blocked by the entry filters.
- Allow long / allow short switches.
- Maximum positions per direction (hedging accounts).
- Order filling mode chosen automatically from what the symbol supports (FOK, IOC or Return).
- Retries on requote / price change / too many requests, with a set delay.
- No requests are sent outside the symbol's trade sessions.
- Works with any symbol name, including suffixes (EURUSD, EURUSD.raw, EURUSDm, XAUUSD ...), because everything is based on the chart symbol.
- Only positions with this EA's magic number on the chart symbol are managed.
- Nothing is printed in normal operation. Short one-line messages are printed only when something fails (the same message is not repeated within 60 seconds).
- Invalid inputs stop the EA from starting, with a one-line reason.
- No DLLs, no files, no web requests.
How to use your own signal
- Open EATemplate.mq5 and find the USER SECTION.
- Replace the body of GetSignal() with your own condition. Use closed bars (shift 1 and older) if you want the signal not to repaint.
- Replace SignalDataReady() so that it returns false until your data is ready. While it returns false, the bar is not marked as processed and is checked again on the next tick.
- If you remove the example MA, also remove its four inputs (fast/slow period, method, applied price), the two handle variables g_fastHandle and g_slowHandle, the MA period check in OnInit(), the two iMA handles in OnInit() and their release in OnDeinit(). Keep InpSignalTF: it is also used for new-bar detection.
A minimal outline (the conditions are placeholders for your own logic):
bool SignalDataReady()
{
return(Bars(_Symbol, InpSignalTF) > 100); // enough bars loaded
}
int GetSignal()
{
bool buyCondition = false; // set true when your buy condition is met
bool sellCondition = false; // set true when your sell condition is met
if(buyCondition)
return(SIGNAL_BUY); // +1
if(sellCondition)
return(SIGNAL_SELL); // -1
return(SIGNAL_NONE); // 0
} Inputs
Signal (example: MA cross)
- Signal timeframe: default current chart timeframe.
- Fast MA period: 10. Slow MA period: 30. Fast must be at least 1 and smaller than slow.
- MA method: EMA. MA applied price: Close.
- Check signal on new bar only (false = every tick): true.
Position sizing
- Lot mode: Fixed lot / Risk % of balance (needs Stop Loss). Default: Risk % of balance.
- Fixed lot: 0.10 (must be > 0). A value below the broker minimum is raised to the minimum.
- Risk per trade (% of balance): 1.0 (greater than 0, up to 100).
Stop loss / Take profit
- Stop loss (points, 0 = none): 300. Must be > 0 in risk % mode.
- Take profit (points, 0 = none): 600.
Break-even
- Use break-even: false.
- Break-even trigger (profit in points): 200.
- Break-even offset (points beyond entry): 20. Must be 0 or more and smaller than the trigger.
Trailing stop
- Use trailing stop: false.
- Trailing start (profit in points): 300 (0 or more).
- Trailing distance from price (points): 200 (more than 0).
- Trailing step (min SL move, points; 0 = 10% of distance): 50.
Filters
- Max spread in points (0 = off): 0.
- Use trading hours (server time): false.
- Start time HH:MM: 08:00. End time HH:MM (may cross midnight): 20:00.
- Trade on Monday ... Sunday: all true. Saturday and Sunday apply only if the symbol trades on those days.
- No new entries after Friday cut-off: true. Friday cut-off HH:MM: 20:00.
News filter (economic calendar)
- Use news filter (live/demo only): true.
- Currencies, e.g. "USD,EUR": empty = base currency and profit currency of the symbol.
- Minimum importance: High.
- Minutes before event (no new entries): 30. Minutes after event: 30.
Trade management
- Magic number: 20261108.
- Allow long trades: true. Allow short trades: true. At least one must be on.
- Max positions per direction (hedging accounts): 1 (1-100).
- Close positions on opposite signal: true.
- Max slippage (points): 10.
- Retries on requote / price change: 3 (0-10).
- Delay between retries (ms): 300 (0-5000).
- Order comment: EATemplate.
Important notes
Example signal
- The MA crossover is an example so that the file compiles and runs. It is not a trading strategy. This template does not promise or suggest any profit.
Time
- All times are trade server time.
- The end time of the trading-hours window is not included. For 22:00-06:00, entries are allowed until 05:59. Start time equal to end time means the whole day.
- The Friday cut-off is on by default (20:00). Saturday and Sunday are on by default.
Points
- All distances are in points of the chart symbol (_Point). The size of one point differs by symbol: a stop loss of 300 points is 30 pips on EURUSD (5-digit quotes) and 3.00 in price on gold quoted with two decimals. Check the values for each symbol.
Spread filter
- Off by default (0). If you use it, set it for each symbol. On gold, for example, the normal spread is often several tens of points.
News filter
- Works on live and demo accounts only. In the Strategy Tester the calendar is not available, so the filter is switched off automatically and backtests run as if it were disabled.
- If the calendar cannot be read, entries are not blocked, and one line is printed.
Risk % sizing
- A stop loss is required.
- The risk is calculated from balance and the SL distance only. Because the lot is rounded down, the planned loss at the SL is usually slightly below the set percentage. Commission, swap and slippage are not included and come on top of it, so the actual result at the SL is not exactly the set percentage.
- If the risk-based lot is below the broker minimum, the trade is skipped.
- If free margin is not enough, the lot is reduced automatically (up to 90% of free margin) and one line is printed.
Trade sessions (weekend, daily breaks)
- Outside the symbol's trade sessions, no orders and no SL changes are sent.
- A signal that appears while the market is closed is checked again within the same bar if the market opens. If the bar has already changed, no position is opened, so some signals (for example around the weekly open) can be skipped.
- An opposite-signal close is done as soon as the market opens.
- If a request is rejected as "market closed" (10018) or "trading disabled" (10017), no requests are sent for this symbol for 60 seconds.
Opposite-signal close
- While an opposite-signal close cannot be completed, no new position is opened. During trading hours it is retried every 5 seconds.
- While this close is pending, new signals are not checked.
Netting and hedging
- Netting accounts: one position per symbol. If there is already a position on the symbol from another EA or opened by hand, no new position is opened.
- Hedging accounts: up to the maximum number of positions per direction.
- A new order that ends in a timeout or connection error is not sent again, to avoid opening a duplicate position. Closes are retried.
Messages
- Nothing is printed in normal operation. Only errors are printed, as one short line, and the same text is not repeated within 60 seconds.
- Invalid inputs stop the EA from starting, with a one-line reason in the Experts log.
Scope
- Only positions with this EA's magic number on the chart symbol are managed. Use a different magic number for each copy on the same symbol.
- In new-bar mode, a bar whose signal was stopped by a filter (spread, time, news, position limit) is not checked again. In every-tick mode, the check is repeated on later ticks.
Disclaimer
This template is a free programming example. The included MA crossover is an example signal for testing the code, not a trading strategy. It gives no investment advice, no trading signals and no promise or suggestion of profit. Test any changes on a demo account first. Trading involves risk; use it at your own responsibility.