Basics
What is an Expert Advisor?
The term, how it differs from indicators and scripts, how it works technically.
Practical knowledge · automated trading
The following points come from daily work on Expert Advisors, cBots and indicators. They have one thing in common: they cost money as soon as a system goes live — and all of them can be settled beforehand. The text is aimed at traders who want to have a system developed or understand an existing one. It is freely available, even without an order.
Applies to MetaTrader 5 and 4 (MQL5, MQL4), cTrader (cBot, cAlgo), TradingView (Pine Script) and TradeStation (EasyLanguage).
Basics
The term, how it differs from indicators and scripts, how it works technically.
Guide
Set-up in MetaTrader 5 and 4, troubleshooting when nothing trades.
Decision
Cost comparison, spotting overfitting, what to check before buying.
Most forex brokers run their trading servers on UTC+2 in winter and UTC+3 in summer, so that the trading day ends with the New York close. This switch follows the US daylight saving rule, not the European one — and the two diverge by two to three weeks every year.
The consequence: a trading window you describe as “08:00 to 17:00” shifts by an hour several times a year if the program simply queries the server time. In the critical weeks between the US and European clock changes, the deviation is then two hours. The same affects news filters, daily closes and the calculation of the daily loss.
With five-digit brokers, EURUSD has five decimal places instead of four. One pip then equals ten points. JPY pairs such as USDJPY use a different number of digits: three instead of two decimal places. Gold, indices and cryptocurrencies differ again.
A system that calculates internally in points but is parameterised with pip values works with ten times the intended stop. Conversely, a stop-loss meant as 200 becomes 20 points — and the position closes at the first spread widening. This is the most common reason why a system “trades completely differently than in the test”.
The same instrument has different names with different brokers: EURUSD, EURUSD.r, EURUSDm, EURUSD_i, EURUSD-ECN. Gold is listed as XAUUSD, GOLD or XAUUSD.spot, the DAX as GER40, DE40, DAX40 or GERMANY40. A system with hard-coded symbol names no longer runs after a change of broker — or worse: it runs but doesn't find the correlation symbols and makes decisions on an incomplete basis.
The same applies to multi-symbol systems that compare pairs internally, and to trade copiers between accounts at different brokers.
Brokers regularly adjust minimum lot size, lot step, leverage, stop level and margin requirements — often without separate notice to individual clients. A system that assumes a minimum lot size of 0.01 fails silently when the broker switches to 0.1. A system that sets the stop-loss two points from the current price receives an error message as soon as the broker introduces a stop level of ten points.
Particularly unpleasant is the case where the order is rejected but the program doesn't evaluate the error code: the position then remains open without protection.
Modelling quality, spread, commission and swap rates often determine the test result more than the trading strategy itself. A test with a constant one-pip spread produces figures that cannot be achieved in live trading — real spreads widen many times over around economic releases, at the daily rollover and in thin market phases.
For short-term strategies the effect is dramatic: a scalping system with an average profit target of five pips quickly loses its entire return with a realistic rather than an idealised spread. Add to that commissions, which are easily forgotten with ECN accounts, and swap costs on overnight positions.
A backtest whose result looks too good usually, unintentionally, uses information that was not yet available at the time of the decision. The typical sources: the close of the current, still running candle is accessed. An indicator from a higher timeframe delivers a value that is only final at the end of the hour but is queried at the beginning. An indicator redraws retrospectively as soon as new price data arrives.
Such systems show an almost perfect hit rate in the test and lose from day one in live trading. The cause is hard to see in the finished program, because the test runs through formally without errors.
Every additional optimisable parameter increases the probability that the optimisation finds random noise instead of robust market structure. Run ten thousand combinations and you are certain to find one that looks excellent on the test data — simply because with enough attempts something always looks good.
The touchstone is not the best value but its surroundings. If a system runs excellently with period 14 but loses money with 13 and 15, you haven't found a system but a coincidence. If, on the other hand, there is a broad plateau in which all neighbouring settings perform similarly, that is a robust result.
If you optimise for absolute profit, the variant with the greatest risk almost always wins — typically one that once survived an extreme drawdown and then happened to recover. Live, the account would have been liquidated in the meantime, or you would have switched the system off in frustration.
More sensible target metrics relate return to the risk taken: the recovery factor (net profit divided by maximum drawdown), the profit factor taking into account the number of trades, or a custom function that also rates the smoothness of the equity curve. In MetaTrader, such a fitness function can be defined yourself.
Price gaps at the Sunday open jump over stop-loss levels. Execution takes place at the next available price, not the desired one — so the actual loss can be considerably higher than planned. With indices and individual stocks, the same gaps occur overnight and around quarterly results.
The decision whether to close, reduce or hold on Fridays is a strategic one, not a technical one. But it has to be made, otherwise chance decides. The same applies to holidays with shortened trading and to the rollover of futures contracts.
Without a unique identifier, a trading system accesses positions opened by another one — and closes them according to its own rules. With two systems on one account, this leads to behaviour that can't be reproduced in any backtest and whose cause you search for for days.
Manual trading on the same account is also affected: a manually opened position without a magic number is readily taken over by a poorly protected system. In addition, margin usage must be considered across all systems, otherwise they block each other.
Terminal crash, Windows update, power cut, broker maintenance window: interruptions are the norm, not the exception. A program without state persistence no longer knows after a restart whether break-even has already been set, the first partial position already closed or the daily loss already counted.
In the best case, an action is executed twice. In the worst case, the system resets an already trailed stop to its initial value and thus gives up secured profit. With systems with multi-stage exit logic, the state can remain permanently inconsistent.
On demo accounts, practically every order is executed immediately and at the displayed price. In live trading, requotes, partial fills, execution delays and spread widening are added. With some account types, the execution model itself also differs.
For systems with wide targets the difference is bearable. For short-term strategies it decides between profit and loss: a delay of 300 milliseconds regularly costs a breakout system more than its entire calculated margin.
A computer that goes into power-saving mode at night doesn't trade. A Windows update that restarts at three in the morning interrupts running positions without warning. And a home internet connection fails more often than you think.
Then there is latency: a server geographically close to the broker's data centre shortens the execution delay considerably. For longer-term systems that is incidental; for short-term ones it is decisive.
Prop trading firms such as FTMO, FundedNext or E8 explicitly allow automated trading. But the conditions differ fundamentally from a retail account: leverage is usually limited to 1:50 to 1:100 instead of 1:500, spreads are wider, and there is a hard daily loss limit of typically five per cent and an overall drawdown limit of eight to ten per cent.
A system tested on a retail account with high leverage and tight spreads often breaches these limits on a prop account within the first week — not because the strategy is bad, but because the position sizes don't fit the rules. Techniques such as grid and martingale are particularly at risk because they increase the position size after losses; some providers therefore prohibit them altogether.
Also note the difference between static and trailing drawdown: with a trailing limit, the loss threshold rises with the account balance, which is much harder for algorithmic systems to handle.
There are now tools that automatically translate Pine Script into MQL5. They produce code that compiles without errors. But that is not the same as code that makes the same trading decisions — and the difference often only shows in live trading.
The reason lies in the execution models. Pine Script recalculates the entire history on every execution and continuously evaluates the running candle; MQL5 is event-driven and treats a running candle differently from a closed one. On top of that come different bar indexing, different default values of indicators with the same name, a different treatment of missing values and a completely different order model: Pine has a simplified strategy simulation, MQL5 real orders with rejections, partial fills and minimum distances.
The most time-consuming part of a development project is rarely the programming but clarifying open questions. A strategy that seems complete in the trader's head typically contains ten to twenty unresolved edge cases — exactly those described on this page.
Each of these questions leads to a query, every query costs time on both sides, and changes after implementation has started cost many times more than changes in the specification. If you supply your rules in writing beforehand, including the edge cases, you reduce the project costs noticeably — usually more than any price negotiation.
You don't have to solve them in advance — it's enough to know that they need to be clarified. We go through them together in the initial call, free of charge and without obligation.
EA-Programmierung is a service of NordZentrum GmbH & Co. KG, Germany: Expert Advisors, indicators and trading systems for MetaTrader 5 and 4, cTrader, TradingView and ATAS, developed by André Liebetrau, Dipl.-Inf., a development service provider since 2009. Fixed price based on a written specification, complete source code included.
Which additional specifications each strategy type needs is described under Expert Advisors by strategy.