Most Expert Advisor (EA) backtests assume an order fills at the price the EA saw, at the moment it decided. Live, there is a gap between decision and fill: the time the order takes to reach the broker's trade server, and whatever the price did in that time.
Our guide to why an EA trades worse live than in its backtest covers the cost side: spreads, commission, a slippage allowance, and matching live trades to a same-period backtest. This guide goes one level lower. It shows how to measure execution order by order from inside the EA, how to tell latency from ordinary market movement, how to test whether your strategy is sensitive to delay at all, and how to choose where the EA runs based on what you measured.
One point up front: a faster connection does not make a strategy better. It only removes one source of difference between the backtest and live trading. If the strategy has no edge after realistic costs, lower latency will not create one.
What latency and slippage actually are
Latency is the time between the EA deciding to trade and the broker confirming the fill. It has several parts: the EA's own processing, the terminal, the network route to the broker's trade server, and the server's handling of the order. Only the network part depends on where your EA runs.
Slippage is the difference between the price the EA expected and the price it received. Some slippage happens because price moved during the latency. Some would happen at any speed, because a stop order triggers at one price and fills at the next available one, or because the size of the order is larger than what is available at the quoted price.
The two are linked but not the same, and the fix for each is different. That is why measuring them separately matters.
Step 1: Log every order the EA sends
You cannot manage what you do not measure, and the terminal's trade history only tells you part of the story. It records the fill price, but not the price the EA saw when it decided, or how long the round trip took. Add that logging to the EA itself.
What to record
For every order request, write one row with:
- Time of the decision in server time, to the millisecond if possible.
- Order type: market buy or sell, or a pending order and its type.
- Expected price: the ask for a buy or the bid for a sell at the moment the EA decided.
- Fill price, from the trade result and, as a cross-check, from the deal in the account history.
- Round-trip time: how long the order request took to return.
- Spread at decision, so you can tell slippage from a wide spread.
- Return code, so rejected orders and requotes are counted, not lost.
- Terminal ping to the trade server at the time.
Exits matter as much as entries. Log the expected and actual price for every close the EA sends, and record stop-loss and take-profit fills from the deal history, since those are executed by the server rather than sent by the EA.
An MQL5 logging sketch
This is a minimal outline, not production code. It times a market order and writes one CSV row. Error handling, retries and pending orders need adding for real use.
#include <Trade\Trade.mqh>
CTrade trade;
void LogMarketOrder(const string sym, const ENUM_ORDER_TYPE type, const double lots)
{
MqlTick tick;
if(!SymbolInfoTick(sym, tick)) return;
double expected = (type == ORDER_TYPE_BUY) ? tick.ask : tick.bid;
double spread = tick.ask - tick.bid;
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
long ping_us = TerminalInfoInteger(TERMINAL_PING_LAST); // microseconds
ulong t0 = GetMicrosecondCount();
bool ok = trade.PositionOpen(sym, type, lots, expected, 0, 0);
ulong rtt_us = GetMicrosecondCount() - t0;
double filled = trade.ResultPrice();
int h = FileOpen("exec_log.csv", FILE_CSV|FILE_READ|FILE_WRITE|FILE_ANSI, ',');
if(h == INVALID_HANDLE) return;
FileSeek(h, 0, SEEK_END);
FileWrite(h, TimeToString(TimeTradeServer(), TIME_DATE|TIME_SECONDS), sym,
EnumToString(type), DoubleToString(expected, digits),
DoubleToString(filled, digits), DoubleToString(spread, digits),
(long)rtt_us, ping_us, (long)trade.ResultRetcode(), ok);
FileClose(h);
}
The round-trip time measured this way includes the terminal and the server, not just the network, which is what you want: it is the delay your strategy actually experiences. Check the fill price against the deal record in the account history, because some execution modes report the fill only in the deal.
A note on the deviation setting: MT5 lets an order specify a maximum acceptable deviation in points. Whether the broker applies it depends on the symbol's execution mode. With market execution, which many accounts use, the order is generally filled at the available price and the deviation may not be applied. Check the execution mode in the symbol specification rather than assuming the deviation protects you.
Step 2: Summarise the log by order type
After a few weeks on a demo or live account, the log can answer real questions. A short pandas script turns it into a summary. Slippage is signed so that a positive number always means a worse fill than expected.
import pandas as pd
cols = ["time", "symbol", "type", "expected", "filled", "spread",
"rtt_us", "ping_us", "retcode", "ok"]
log = pd.read_csv("exec_log.csv", names=cols, parse_dates=["time"])
log = log[log["ok"] == True]
point = 0.00001 # set to the symbol's point size
sign = log["type"].str.contains("BUY").map({True: 1, False: -1})
log["slip_pts"] = (log["filled"] - log["expected"]) * sign / point
log["rtt_ms"] = log["rtt_us"] / 1000
summary = log.groupby("type").agg(
orders=("slip_pts", "size"),
median_slip=("slip_pts", "median"),
p95_slip=("slip_pts", lambda s: s.quantile(0.95)),
share_improved=("slip_pts", lambda s: (s < 0).mean()),
median_rtt_ms=("rtt_ms", "median"),
p95_rtt_ms=("rtt_ms", lambda s: s.quantile(0.95)),
)
print(summary.round(2))
Run the same summary split by hour of the day and by whether a high-impact news release was within a few minutes. Execution quality is rarely uniform: it is usually worse at the session open, around rollover and during news.
Reading the distribution
Hypothetical log summary, for illustration only. It is not from any strategy, broker or account. It shows the shape of what to look for.
| Order type | Orders | Median slippage (points) | 95th percentile (points) | Share filled better than expected | Median round trip (ms) |
|---|---|---|---|---|---|
| Market entry | 180 | 0 | 6 | 22% | 85 |
| EA-sent exit | 160 | 1 | 9 | 18% | 90 |
| Stop-loss (server) | 45 | 4 | 31 | 4% | not applicable |
Hypothetical example only. Not a result from any strategy or account.
How to read it:
- Look at the tail, not the median. A median of zero with a 95th percentile of several points means most fills are fine and a few are costly. Those few can decide whether the strategy holds its edge.
- Compare order types. Stop-loss fills in this hypothetical table slip far more than market entries. That is normal, because stops trigger when price is moving fast, and it means the backtest's stop fills deserve the heaviest allowance.
- Check the share of improved fills. In a working market, some orders fill better than expected. If almost none ever do while many fill worse, the pattern is worth understanding. Read the broker's order execution policy, and ask how it treats price improvement.
- Count the rejections. Orders with a failure return code are not in the slippage figures at all, but a missed entry or a failed exit can cost more than any slippage.
Step 3: Separate latency from market movement
High slippage does not automatically mean high latency. To tell them apart, check whether slippage grows with round-trip time.
log["rtt_bucket"] = pd.qcut(log["rtt_ms"], 4, labels=["fastest", "q2", "q3", "slowest"])
print(log.groupby("rtt_bucket", observed=True)["slip_pts"].describe()[["count", "mean", "75%"]])
- Slippage rises clearly with round-trip time: latency is costing you, and a shorter route to the server could help.
- Slippage is similar across all buckets, but high in certain hours or around news: the cause is market conditions and liquidity, not your connection. Moving the EA will not change it much. Avoiding those windows, or widening the backtest's cost assumptions for them, will.
- Round-trip times are usually short with occasional very long ones: look for the cause of the spikes, such as terminal freezes, a busy machine, or network trouble, before blaming the broker.
Step 4: Test delay sensitivity in the Strategy Tester
The MT5 Strategy Tester has a Delays setting. It can run with zero latency, with a fixed delay in milliseconds, or with a random delay. Treat it like any other input and sweep it, the same way our guide to parameter sensitivity sweeps strategy parameters.
- Run the test with zero latency as the baseline.
- Re-run with a fixed delay close to your measured median round trip.
- Re-run with a delay near your measured 95th percentile, and then double it.
- Run the random delay option as a cross-check.
Use "Every tick based on real ticks" for these runs, because delay only matters if the tester can see price moving during it.
Then compare average trade, profit factor and drawdown across the runs. A strategy whose results barely change across realistic delays is not latency-sensitive, and the location of its VPS is a reliability question, not a speed question. A strategy whose results fall away as the delay increases depends on speed, and you now know roughly how much speed it needs. Our guide to reading an MT5 Strategy Tester report explains where each of these figures sits in the report and how it is calculated.
Which strategies care about latency
| Strategy type | Typical latency sensitivity | Why |
|---|---|---|
| Swing or position, holding for days | Low | A fill a fraction of a second later is small against the size of the move. |
| Intraday, holding for hours | Low to moderate | Matters mostly on entries during fast moves and on exits around news. |
| Short-term, targets of a few pips | High | The delay can be a meaningful share of the target. |
| Entries on breakouts or news releases | High | The EA trades exactly when price moves fastest. |
| Logic that reacts to every tick | High | Any delay changes which ticks the EA acts on. |
Treat this table as a starting assumption only. The Delays sweep in Step 4 is the test for your own strategy.
Server-side and EA-side stops
Where a stop lives changes what latency does to it.
- Stops and targets attached to the position are held on the broker's trade server in MT5. They trigger there, so your connection speed does not delay them, and they still work if your terminal goes offline. They can still slip, because a stop becomes a market order when it triggers. Over a weekend or a news release, that slip can become a gap; our guide to weekend gaps, swaps and news spikes shows how to test for it.
- Virtual or hidden stops are managed by the EA, which watches price and sends a close order when the level is hit. Every one of those closes pays the full round trip, and none of them happens if the terminal, the VPS or the connection is down.
If your EA uses virtual stops, test it in the tester with realistic delays, and consider a wider protective stop on the server as a backstop in case the EA cannot act. That is a design choice to make deliberately, not a default.
Choosing where the EA runs
Only once you know how sensitive the strategy is does the choice of machine become a sensible question.
Find the broker's trade server
The terminal shows the ping to the current trade server in its connection status, and the access server list shows the alternatives. If you are unsure where the server is hosted, ask the broker which data centre or region it uses. A VPS in the same region usually gives the shortest network route. The exact location matters far more for a latency-sensitive strategy than for a slow one.
VPS selection criteria
Judge any VPS, or any machine, on these points rather than on its marketing:
- Measured round trip to your broker's server, from the terminal itself, at the times your EA trades.
- Stability of that latency, not just the average. Occasional long spikes can matter more than a slightly higher typical time.
- Dedicated memory and processor share enough for every terminal you run, with headroom. A terminal that freezes for a few seconds while the machine is overloaded adds more delay than any network.
- Uptime and maintenance windows. Know when the provider restarts machines, and make sure the terminal and the EA restart automatically and recover their state.
- Control over operating-system updates, so the machine does not restart for an update at a moment you did not choose.
- Accurate system clock, kept in sync. The EA should still use the trade server's time, not the machine's.
- Monitoring and remote access, so you hear about a disconnection quickly and can stop the EA from your phone.
Our EA pre-live checklist covers the wider infrastructure stage: restarts, alerts and time assumptions.
Measure before and after
Run the logging EA on a demo account from your current machine for a week, then from the candidate VPS on the same account for a week, trading the same symbols at the same hours. Compare the round-trip distributions and the slippage by order type. Decide on the numbers. If the strategy was not latency-sensitive in Step 4 and the measurements barely differ, choose on reliability and cost.
Common execution-measurement mistakes
- Relying on the trade history alone. It has the fill price but not the price the EA expected or the round-trip time.
- Averaging away the tail. A small average slippage can hide a handful of large ones on stop-loss exits.
- Ignoring rejected orders. Missed entries and failed exits never show up as slippage, but they change results.
- Blaming the connection for market conditions. If slippage does not grow with round-trip time, a faster VPS will not fix it.
- Testing only with zero latency. The tester's default can be far kinder than live execution for short-term strategies.
- Using virtual stops without a backstop. They depend entirely on the EA, the terminal and the connection staying up.
- Measuring on demo and assuming live is identical. Demo execution can differ from live, especially for larger sizes and during fast markets. Re-check the log once live.
Execution checklist
- Every order logged with expected price, fill price, spread, round-trip time, ping and return code
- Stop-loss and take-profit fills taken from the deal history and included in the log
- Slippage summarised by order type, hour of day and news proximity, with the 95th percentile recorded
- Share of improved fills and number of rejections checked
- Slippage compared across round-trip-time buckets to separate latency from market movement
- Strategy Tester Delays setting swept from zero to beyond the measured 95th percentile
- Decision recorded: latency-sensitive or not
- Stop placement checked: server-side stops, or virtual stops with a deliberate backstop
- Machine or VPS chosen on measured round trip, stability, resources, uptime and update control
- Backtest cost assumptions updated with the measured slippage, then the stress tests re-run
Frequently asked questions
How do I measure slippage on an MT5 EA?
Log the price the EA expected at the moment it decided, and the fill price it received, for every order. Sign the difference so that a positive number means a worse fill, then summarise it by order type. Include stop-loss fills from the deal history, because those are usually where slippage is largest.
Does a VPS reduce slippage?
Only the part caused by latency. If your log shows slippage rising with round-trip time, a VPS closer to the broker's trade server can reduce it. If slippage comes mainly from fast markets, news or thin liquidity, moving the EA will change little.
Where should my VPS be located?
Close to the broker's trade server, measured by the ping and round-trip times from the terminal itself. Ask the broker which region or data centre hosts its servers. For slower strategies, reliability, restarts and update control matter more than a few milliseconds.
What does the Delays setting in the MT5 Strategy Tester do?
It makes the tester simulate a delay between an order being sent and being filled, either fixed or random. Sweeping it from zero up to your measured round-trip times shows whether your strategy's results depend on execution speed.
Will lower latency make my EA profitable?
No. Lower latency removes one difference between the backtest and live trading. It does not create an edge, and a strategy can be executed quickly and still lose money.
Want a second pair of eyes?
Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.
Read the Sample Stress-Test ReportWant your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit
Disclaimers
CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.
All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. The only figures in this article are a hypothetical log summary for teaching purposes, not results from any strategy, broker or account. We do not guarantee the outcome of any prop firm challenge.