FoundationsIntroductory23 min read

Bid, ask and spread: the cost that changes how you read a forex robot

Reconstruct a forex trade from its quotes to its net result: spread, position size, execution, commissions and checks you can inspect.

The candle closes above its opening price. Your robot bought at the beginning, sold at the end and still reports a loss. Your first thought is that something must be wrong with the code. You open the entry rule, inspect the indicator and run the test again. Nothing changes. Perhaps you started looking in the wrong place: the price drawn on the chart does not, by itself, explain the prices used to simulate the trades.

We will reconstruct that problem from the beginning. We will use a fictional quote, a small quantity stated in units and an accounting trail you can reproduce by hand. Then we will introduce an exit, a commission, an execution price different from the requested reference and a change in the spread. The purpose is to develop precise questions for inspecting a forex robot.

Understanding the cost of executing a rule is part of understanding the rule. You do not need to begin with a complicated model. You need to know what each number represents, what information you retained and what assumptions the simulator introduced when the information was missing.

Every trade, quote and result in the case study is hypothetical. These are not market observations or results from TradeAndRoll or Atlas. The sources document specific concepts and functions; the exercises and review procedure are original educational proposals. By the end, you should be able to distinguish a loss explained by costs, an inconsistency in units and a question that the available data cannot answer.

Two prices, two actions

Under the quoting convention used here, the bid is the price available for selling and the ask is the price available for buying. Their difference is the spread. This interpretation is described in OANDA’s explanation of bid and ask prices. A quote alone does not guarantee that any quantity can trade at that price: we start with a deliberately simple assumption.

Write down EUR/USD with a bid of 1.10000 and an ask of 1.10020. In our exercise, each euro of exposure is priced in dollars. If you buy 10,000 units of the base currency at the ask and immediately sell them at the bid, with no change in the quote and no additional charges, the price difference is −0.00020. Multiplying by 10,000 units gives a loss of two dollars. We have introduced no prediction and no profitable strategy; we have simply described a round trip.

The midpoint of that quote is 1.10010. It is a useful mathematical reference, but it is not an offered execution price in this example. Buying and selling at the midpoint would produce zero with an unchanged quote. That zero belongs to a different simulation with different assumptions. Comparing it with the two-dollar loss without explaining the distinction leads to the wrong discussion about the strategy.

Record the two actions on separate rows. On the first, write buy, 10,000 units, ask and 1.10020. On the second, write sell, the same quantity, bid and 1.10000. The table’s simplicity is useful: it makes you identify the side of the quote used by each action. If the program cannot recover those fields, you have an observability limitation before you have a conclusion about performance.

A useful check is to repeat the case with a quote that remains constant throughout the experiment. A rule that buys and immediately sells should not manufacture a profit under these assumptions. If it does, inspect signs, sides, size and conversion before studying the quality of its signals.

Pips, decimal places and money are different things

A pip expresses a conventional price change. It is not a fixed amount of money for every transaction. Many pairs use 0.0001, while pairs involving the yen commonly use 0.01. OANDA’s introduction to pips explains this distinction. For our fictional EUR/USD example, we explicitly set one pip equal to 0.0001, making a difference of 0.00020 equal to two pips.

Three different scales: price change, pips and monetary result for 10,000 units.
Converting a price change into money requires the quantity and the result currency.

With 10,000 units, a one-pip movement represents one dollar in this example’s linear model. With 20,000 units, it represents two dollars. The same spread in pips does not mean the same monetary cost when size changes. Nor does it necessarily have the same relative impact when the reference capital or the usual holding period changes.

Write the units beside each calculation: price difference in USD per EUR, quantity in EUR and result in USD. The EUR unit cancels in the multiplication. This small discipline catches mistakes that a table of unlabelled numbers can conceal. If you mix lots with units, or interpret a minimum price point as a complete pip, the result can change by a large factor without generating a programming error.

The MQL5 reference for symbol properties distinguishes contract size, minimum price change and calculation currencies. Inspect the properties of the actual instrument; do not infer all of them from the number of decimal places displayed on the screen. These fields describe a configuration and do not replace checking the contract you intend to study.

Before adding results from a file, create a short units sheet. Include the instrument name, quantity, the unit in which that quantity is stated, the adopted pip size and the output currency. If information is missing, mark it as unresolved. An empty field is more informative than a silent assumption that later propagates through thousands of trades.

A complete purchase, explained line by line

Return to the purchase of 10,000 units. At entry, bid and ask are 1.10000 and 1.10020. At exit, they become 1.10050 and 1.10070. Assume that the purchase executes exactly at the first ask and the sale exactly at the second bid. There are no commissions, financing adjustments or execution differences in this first calculation. The price result is 10,000 × (1.10050 − 1.10020), or three dollars.

The entry and exit midpoints are 1.10010 and 1.10060. Their difference is five pips, equivalent to five dollars at our chosen size. The executed transaction earns three pips. The two-pip gap between the measurements is explained by crossing half the spread at entry and half at exit. Because the two spreads are equal, the combined difference equals one complete spread.

Buying at 1.10020 and selling at 1.10050 produces three executed pips versus five midpoint pips.
A result calculated from execution prices already includes the effect of crossing the spread.
Hypothetical item Entry Exit
Bid 1.10000 1.10050
Ask 1.10020 1.10070
Midpoint 1.10010 1.10060
Price used by the long trade 1.10020 1.10050

This breakdown permits two equivalent accounting methods. You can begin with the movement between midpoints and subtract the cost of crossing the quotes. Alternatively, you can calculate the difference between execution prices directly. Do not combine the two methods as though they represented independent costs: that would subtract the same separation twice.

Now change only the exit quote. Keep its midpoint at 1.10060 but widen its spread to four pips: bid 1.10040 and ask 1.10080. The sale takes place at 1.10040 and the trade earns two dollars. The midpoint reference still shows five dollars. This time, the combined adjustment is three pips: one at entry and two at exit.

The second calculation helps avoid a common mechanical shortcut: always subtracting the entry spread as an approximation for the entire round trip. That approximation worked earlier because of a particular combination of assumptions. When quotes change in width, each end of the trade contributes its own distance from the reference. Retain both observations so that you can explain the difference later rather than reverse-engineering it from a final balance.

What changes for a short position

For a short trade, the economic sequence is reversed: you first sell and then buy to close. In our quote model, the initial sale uses the bid and the final purchase uses the ask. The linear result is quantity multiplied by selling price minus repurchase price. Changing a formula’s sign without checking these sides is an easy mistake to overlook.

Suppose you sell 10,000 units at a bid of 1.10000. Later, the quote is 1.09950/1.09970 and you repurchase at the ask of 1.09970. The price result is 10,000 × (1.10000 − 1.09970): another hypothetical three dollars. Midpoints fall from 1.10010 to 1.09960, a five-pip change. The difference is again two pips under our chosen constant spreads.

Also repeat an immediate sale and repurchase while the quote remains unchanged. It should produce the same two-dollar loss as the immediate purchase and sale, provided the exercise retains its symmetric assumptions. If the code returns different answers, the difference needs a concrete explanation. It might involve quote sides, conversion, an asymmetric charge or another condition that you did not actually hold constant.

The symmetry of the example is a diagnostic tool, not a universal property of the market. Effective costs and conditions may differ between directions. That is precisely why it is useful to distinguish an artificial test, where you control the inputs, from historical observations with changing conditions.

A review table should have one field for the position’s direction and another for the executed action. “Short position” and “buy” are not incompatible labels: the purchase may close that short. If a function chooses the quote side from the strategy’s label rather than from the action being executed, it will repeat the mistake on every exit.

Before expanding the investigation, require the program to explain four small cases: a winning purchase, a losing purchase, a winning sale and a losing sale. You do not need a full historical dataset to check these identities. You need carefully chosen prices that make the expected result unambiguous, including the direction of a loss when the market moves against the position.

What a candle cannot tell you

A file containing open, high, low and close provides four summaries per interval. Before using it, ask which price component it represents. The candlestick definitions in OANDA’s API distinguish bid, ask and midpoint components. A generic name such as “close” does not preserve that distinction if the file was exported without documentation.

A candle summarizes four values but does not, by itself, preserve the spread or the ordering of every event.
A limitation of the file should become an explicit assumption in the simulation.

Imagine that a candle’s high exceeds a target while its low crosses a stop. Those four numbers do not necessarily tell you which happened first. Nor do they automatically reconstruct the ask that existed when the bid touched a particular level. A simulator may adopt a rule to resolve the ambiguity; that rule needs to be described. Calculating a result under a path convention is different from observing that path.

The useful response depends on the question. If you only want to check the arithmetic of a closing-price signal, a simplified table may be sufficient as an exercise. If you want to decide which intrabar exit happened first, the same table may be inadequate. Adding more years does not recover the within-period information that was never recorded.

Construct two fictional paths compatible with the same candle: one visits the high first and the other visits the low first. If the rules produce different exits, you have identified sensitivity to missing information. You can present it as a range of scenarios or seek more detailed data. You do not need to choose the path that improves the outcome.

Keep a file specification covering origin, price component, time zone, granularity, coverage and treatment of gaps. Add a row explaining what the file cannot resolve. This last row can be as valuable as the others. It prevents another reader from interpreting a simplified simulation as an exact reconstruction of every decision and execution that could have occurred. It also gives you a concrete reason for requesting better data, rather than requesting more data indiscriminately.

Observed price, order and execution

An observation, a decision and an execution are different events. In an expanded version of our case, the robot observes an ask of 1.10020, decides to buy and receives an execution price of 1.10023. For the same 10,000 units, the difference of 0.00003 represents thirty cents relative to that entry reference. We will call it slippage relative to the observed price, explicitly identifying the reference.

Do not turn that definition into an automatic causal explanation. A price difference alone does not establish whether a delay, a quote change, a different available quantity or a rule of the execution environment was responsible. The record should help investigate those possibilities. Without times and references, you can measure a difference while still not knowing what mechanism produced it.

OANDA’s pricing documentation represents bid and ask levels alongside available quantities. That structure illustrates why a single price may provide an incomplete account of execution. We are not claiming that every broker exposes the same fields or that this API represents the environment of the robots offered by the service.

Add four times to the exercise log: observation, decision, submission and confirmation. If two clocks use different time zones, normalize them before subtracting. If one time records local receipt and another records the source event, do not describe them as identical measurements. The printed precision of a timestamp does not guarantee synchronized clocks.

For a simple sensitivity check, retain the signals and calculate the effect of an explicitly specified execution penalty. Then explain its limitation: it is an accounting scenario, not a complete recreation of decisions under different received prices. If the rules react to earlier executions, open positions or rejected orders, the full sequence may need to be simulated again.

This distinction prevents a column called “slippage” from appearing more realistic than it is. The column name supplies no evidence. Evidence comes from its definition, the observations supporting it and the connection between the adjustment and the procedure being evaluated. An unsupported adjustment may still be useful as a hypothetical scenario, provided that is how you label it.

A cost ledger that does not subtract twice

We will separate three levels of result: movement of a reference price, result from execution prices and result after additional charges. Our original long case produces five dollars between midpoints and three dollars between executions. Now add a fictional commission of fifty cents on each side. Total commission is one dollar, leaving two dollars.

Hypothetical reconciliation: five reference dollars, three from execution and two after commissions.
Each adjustment appears once and retains the reference from which it was calculated.
Hypothetical item Amount, USD Interpretation
Movement between midpoints 5.00 Analytical reference
Difference from crossing bid/ask −2.00 Already included in executions
Result from executions 3.00 Starting point for separate charges
Entry and exit commission −1.00 Additional charge in this example
Result after commissions 2.00 Before any further adjustment

Suppose an additional financing charge of forty cents applies to holding the position. The example’s result falls to 1.60 dollars. We have not calculated an actual tariff. We have introduced an assumed amount to practise reconciling separate items without mixing them. If that charge were already included in an exported result, subtracting it again would create another double-counting error.

OANDA Corporation’s financing explanation shows that a position may attract a charge or credit depending on its conditions, and that rates can change. Its schedules and conventions belong to that specific offering. When studying another contract, retain its applicable terms instead of importing someone else’s table as though it were universal.

Always ask whether a commission is quoted per side or per round trip, per unit or per lot, in which currency and with which minimum charges. You do not need to assume that every mechanism exists. You need a field for recording those that actually apply. An unknown cost should not silently become a zero cost.

When inspecting an aggregated report, reconcile one transaction before reconciling the entire month. If the small case does not balance, adding more rows merely obscures the problem. Once it balances, repeat the exercise with a trade containing each kind of charge present in the report. Preserve the original exported fields so that a later correction can be traced to its source rather than replacing the evidence.

Why the average spread may describe a different strategy

Imagine a fictional file with one hundred observations. Ninety have a spread of one pip and ten have a spread of four pips. The average per observation is 1.3 pips. Now imagine a robot whose twenty entries occur ten times in the first group and ten times in the second. The average spread at its entries is 2.5 pips. Both averages are correct, but they answer different questions.

An average spread of 1.3 pips across observations and 2.5 pips at entries reflects different sampling.
The robot selects moments; an average over the entire file may not describe those moments.

The example does not claim that robots always prefer expensive conditions. It demonstrates why you should inspect the distribution conditional on the decisions being studied. You can repeat the exercise for exits, quantities and trades that remain open longer. A large trade can contribute little to a simple count and much more to monetary accounting.

Start with three separate views: the distribution of spreads in the file, at entries and at exits. Document how the file is sampled before comparing them. One observation per minute and one observation per quote update do not necessarily weight elapsed time in the same way. Changing that weighting can change the average without changing a single transaction.

Then inspect the tail: how many decisions occur with spreads substantially wider than the rest of the sample? Describing a distribution does not require you to declare a universally correct threshold. It does require distinguishing exploratory description from a rule subsequently introduced to improve results. If you try several limits and choose the one that most improves the curve, you have added a development decision.

To keep the interpretation clear, preserve the original version and the filtered version as separate objects. The latter may deserve further evaluation, but it does not automatically inherit the interpretation of the former. The article on separating development and evaluation examines that boundary in more detail. Here the key point is that a cost measurement can itself become a selection parameter.

Read the simulator’s configuration

Before comparing two backtests, write down how each produced its execution prices. The documentation on real and generated ticks in MetaTrader 5 distinguishes within-minute spread variation in real ticks from reconstructions based on bars. That describes the modes; it does not certify that any particular test reproduces every feature of actual execution.

Consider two result files with the same dates, instrument and rule. One uses a detailed path while the other reconstructs intermediate observations. If they disagree, starting with final profit wastes information. Compare the first different decision instead. Did a signal change? Was an exit activated? Did one mode represent a price that the other did not? These questions narrow the search substantially.

It also matters which items the selected mode calculates. The MetaTrader 5 strategy-testing guide states that its profit-in-pips option omits certain checks and charges. A fast mode may serve a limited exploratory purpose; its report must retain that limitation when the result is interpreted. A shorter runtime is not evidence that omitted items are immaterial to your question.

Prepare a minimal engine specification covering version, data mode, price component, spread treatment, commissions, financing and execution rules. You do not need to understand every internal line of code to begin. You need to identify the choices that alter the question. A screenshot of the equity curve does not replace that specification.

If two programs use different terminology, translate it into observable events. Rather than debating whether both say “realistic”, ask what price the unchanged-quote case buys, what happens when a quote is missing and how a short position closes. Comparable small tests allow you to contrast behaviour that product labels do not describe.

Preserve discrepancies that remain unresolved. An unexplained difference does not force you to choose whichever program reports less profit, or whichever reports more. It requires a narrower conclusion and a clear statement of the observation or check needed to resolve it.

Two different tests: changing costs and changing decisions

When someone proposes “doubling the spread”, ask exactly what operation they intend to perform. One possibility is to subtract an additional amount from a fixed set of trades. Another is to modify the quotes and run all the rules again. The first holds the decision sequence constant; the second may change it. These are not interchangeable implementations of the same question.

The accounting adjustment can show how much of a result remains after an assumed penalty. It is useful as a quick diagnostic when you declare what stays fixed. If a trade earned three dollars from prices and you add a two-dollar penalty, one dollar remains before other charges. That calculation cannot tell you whether the trade would have existed under the modified quotes.

In a fresh simulation, a limit purchase might not execute, an exit might trigger earlier or a rule allowing only one position might remain occupied over a different interval. The subsequent effect is no longer an independent subtraction on each row. Decisions interact through the evolving state. To investigate that, preserve events and states rather than only the final list of gains and losses.

Give the exercises clear names. Call the first “additional penalty on fixed trades” and the second “simulation with modified quotes”. Compare which trades survive, which disappear and which change their timing. If you compare only totals, you can confuse a change in the number of transactions with a change in the cost of executing the same transactions.

For our educational review, define the scenarios beforehand and keep their results even when they are inconvenient. Do not search for a penalty just small enough to keep the final number positive. The purpose is to discover which assumptions support your interpretation of the system. Choosing a scenario does not automatically estimate the probability of that scenario in the future.

This connects to parameter neighbourhoods and robustness: perturbation provides information about sensitivity, but does not make a strategy safe. Interpretation depends on what you changed, what you held constant and how you selected the collection of checks.

From the result currency to the account currency

So far, all calculations have been expressed in dollars to keep the layers separate. If the reference account is denominated in euros, an additional conversion appears. Suppose, solely for the exercise, that the applied factor is 1.10 dollars per euro. A three-dollar result then becomes approximately 2.73 euros. The chosen factor and valuation time are part of that number.

Do not treat this simplified calculation as a universal valuation engine. MQL5’s profit-calculation function uses instrument conditions and returns an estimate in the account currency. Its documentation also explains that the estimate depends on the environment. Here, the function is a comparison reference, not a promise of a future execution price.

A useful review preserves two columns: the result before conversion and the result after conversion. Add the factor and its provenance. If the account total differs between two programs, you can investigate whether the transactions differ or only their monetary valuation. Without that separation, a conversion difference can look like a signal difference.

Check rounding as well. Rounding each transaction and then summing does not always produce the same answer as summing higher-precision amounts and rounding at the end. Do not introduce a convention merely to make the report match a preferred total. Choose the convention appropriate to the comparison and document the numerical tolerance you will accept.

Size deserves an independent check. Doubling units doubles the result of our linear model when every other assumption stays fixed. That does not demonstrate that actual execution at twice the quantity would retain the same prices and charges. An accounting identity does not establish execution capacity. This distinction matters when a small test is used to justify a different scale.

Finally, separate exposure from cash tied up or cash available. A report showing profit divided by a field called “capital” is incomplete if it does not explain that denominator. For this article, the useful discipline is to keep units visible and avoid turning a price calculation into a recommendation about how much to trade. The calculation can be correct while the proposed use of it remains unsupported.

A minimum record for reviewing your robot

The proposed review ends with a simple artifact: an event table you can read without opening the whole program. Begin with a stable test identifier and a separate trade identifier. Add instrument, direction, action, quantity, observation time, execution time, bid, ask, execution price and charges. You do not need to publish private data to use this structure in your own environment.

Four parts of a review record: data, decision, execution and monetary reconciliation.
A traceable review connects the observation to the decision and to its accounting result.

Choose five deliberately different cases: an unchanged-quote round trip, a winning purchase, a losing sale, a wider exit spread and a transaction with an additional charge. For each, write the expected result before executing the code. Then compare field by field. Agreement in the final total is insufficient if two intermediate errors happen to cancel.

If you use AI, assign a bounded task: “Explain which quote side each action uses and flag any ambiguous units.” Another useful request is: “Construct a small counterexample that fails if this function swaps bid and ask.” Do not simply ask it to confirm that the backtest is correct. A fluent answer can overlook exactly the assumption you intended to examine.

Here is an independent exercise. The fictional initial quote is 1.25000/1.25030. You buy 8,000 units and later sell when the quote is 1.25070/1.25110. The execution result is 8,000 × 0.00040 = 3.20 dollars. If commissions are forty cents on each side, 2.40 dollars remain. Check that you have not subtracted spreads again after already using the entry ask and exit bid.

The midpoint reference moves from 1.25015 to 1.25090, a difference of 7.5 pips. At 8,000 units, that represents six dollars. The adjustments relative to this reference are 1.5 pips at entry and two at exit: 3.5 pips, equivalent to 2.80 dollars. Subtracting them brings you back to the 3.20-dollar execution result. Two calculation paths arrive at the same answer when their assumptions are aligned.

Keep your explanation alongside the output. In a few weeks, it will be more useful than a screenshot containing only a green status box. Reconstructing a transaction is an observable skill that you can incorporate into your learning path as a trader. It gives you a small, repeatable way to demonstrate understanding rather than relying on how familiar the terminology feels.

What this review allows you to conclude

If the small calculations reconcile, you have gained confidence in a specific part of the implementation. You have checked that, under your assumptions, sides, units and charges connect consistently. You have not demonstrated that the strategy has an edge, that the data are sufficient or that future conditions will resemble past conditions. Those are subsequent questions requiring different investigations.

The foreign exchange market is not a single universal screen either. The BIS paper on the foreign exchange market describes its over-the-counter and fragmented organization. The practical implication for this exercise is modest: identify where the studied quotes come from and limit conclusions to what that information can support.

When reviewing a robot, request an explanation of its rules and its intended execution model. Ask about the instrument, units and conditions you need to reproduce. If an answer is missing, preserve it as an unresolved question. An orderly investigation can end in continuing, changing the question or rejecting an implementation. Any of these outcomes can save later work.

TradeAndRoll’s initial offering focuses on Forex. The free demo with ten robots includes Python source code, rules, research prompts and market-data CSV files. CSV files are exclusive to the demo; paid packs provide additional robots with their rules, code and prompt ideas. Use the questions in this article to inspect the demo materials. The examples above do not describe their performance or guarantee compatibility with a particular environment.

Before moving to the next article, try explaining the opening trade without looking at the formulas: what you bought, which quote side you used, the quantity and why an immediate round trip lost two dollars. If you can explain and reproduce it in a table, you have a useful starting point for questioning a much larger report.

Hypothetical quote with bid 1.10000, ask 1.10020 and a two-pip separation.
Two prices for two different actions. All figures in this article are educational examples.
Back to the Blog