sifting/io
Quant Research & Backtesting
9 min readSiftingIO Team

MAE and MFE in Python: Add Trade Excursions to Your Journal

Calculate maximum adverse and favourable excursion from historical candles. Includes long and short formulas, a Python example and a SiftingIO API request.

MAE and MFE in Python: Add Trade Excursions to Your Journal

A trade closes 30 pips in profit. While it was open, it was down 20 pips at one point and up 60 pips at another. A journal that saves only the final result loses both of those details.

Maximum adverse excursion, or MAE, records the largest move against a position during its holding period. Maximum favourable excursion, or MFE, records the largest move in its favour. Together, they add useful context to a trade's final profit or loss.

This guide shows how to calculate price MAE and MFE from historical candles, work through a complete example in Python, and add the results to a trading journal using SiftingIO market data. All trade prices and results in the worked example are illustrative.

What MAE and MFE measure#

For a long position, a lower price is adverse and a higher price is favourable. For a short position, the directions reverse.

Both measurements stop when the trade closes. A rally an hour after exit does not belong in that trade's MFE, even if it appears on the same chart.

MeasureQuestion it answersMeasurement window
MAEHow far did the price move against my entry?While the position was open
MFEHow far did the price move in my favour?While the position was open
Realised resultWhere did I actually exit relative to entry?Entry fill to exit fill

We report MAE and MFE as non-negative distances. An MAE of 20 pips means an adverse move of 20 pips, rather than a signed loss of minus 20 pips. Keeping that convention explicit makes journal exports easier to interpret.

These are price measurements. To calculate position-level profit or loss, you also need size, contract specifications, fees and any required currency conversion. Scaling into or out of a position requires a position ledger rather than one fixed-size calculation.

The formulas for long and short trades#

Let entry be the entry price, high the highest observed price while the trade was open, and low the lowest observed price over the same period.

DirectionMAEMFE
Longmax(0, entry − low)max(0, high − entry)
Shortmax(0, high − entry)max(0, entry − low)

The zero floor matters. If every observed price is above a long trade's entry, the adverse excursion is zero. It is not a negative loss.

For percentage values, divide each distance by the entry price and multiply by 100. For pips, divide by the instrument's pip size. EURUSD uses 0.0001 for one pip; use the appropriate convention for each instrument rather than applying that value to every symbol.

A worked EURUSD example#

Consider a long position entered at 1.1000 and closed at 1.1030. During the holding period, the lowest price is 1.0980 and the highest is 1.1060.

ResultCalculationValue
MAE(1.1000 − 1.0980) ÷ 0.000120 pips
MFE(1.1060 − 1.1000) ÷ 0.000160 pips
Realised price move(1.1030 − 1.1000) ÷ 0.0001+30 pips

At a constant position size of 10,000 EUR, those movements correspond to $20 adverse, $60 favourable and $30 realised before costs. EURUSD is quoted in USD per EUR, so multiplying the price difference by the EUR quantity gives the USD amount.

The exit captured half the largest favourable price move observed during this trade. That is a description of this example, not evidence that exiting at the high was achievable or that holding longer would improve future results.

Use only prices from the holding period#

Time boundaries matter more than the arithmetic.

A one-minute candle labelled 10:00:00 covers the interval from 10:00:00 up to, but not including, 10:01:00. If a trade opens at 10:00:35, that candle may contain a high or low from before the entry.

For trades aligned to candle boundaries, select the bars fully contained in the holding period. A trade from 10:00:00 to 10:05:00 uses the candles beginning at 10:00, 10:01, 10:02, 10:03 and 10:04. It does not use the candle beginning at 10:05.

For entries or exits within a candle, there are two useful approaches. Use recorded live observations to measure the exact time window, or calculate an estimate from the fully contained candles and label it accordingly. The second approach omits the partial entry and exit intervals, so it may miss an extreme.

Keep the price basis consistent too. Historical candle highs and lows describe the supplied price series. A journal using actual execution fills should store those fills separately and label the excursion as a market-price measure. Executable bid or ask prices can produce a different result.

Request the historical candles#

SiftingIO returns historical bars with time, open, high, low, close and volume fields. This calculation uses the timestamp, high and low; volume is not needed.

Create an API key in your SiftingIO account, then set it as the SIFTINGIO_API_KEY environment variable in your local environment. The following request retrieves one-minute EURUSD bars for an example window and saves the response as eurusd-bars.json:

curl --fail-with-body --silent --show-error --compressed \
  --get "https://api.sifting.io/v1/hist/forex/EURUSD/bars" \
  --header "X-API-Key: ${SIFTINGIO_API_KEY}" \
  --header "Accept-Encoding: gzip" \
  --data-urlencode "start=2026-11-24T10:00:00Z" \
  --data-urlencode "end=2026-11-24T10:05:00Z" \
  --data-urlencode "interval=1m" \
  --data-urlencode "order=asc" \
  --data-urlencode "limit=1000" \
  --output eurusd-bars.json

The response contains a data array. Each bar's t field is its opening time in Unix milliseconds. The API's end bound is inclusive, so filter the returned bars to your holding period before calculating the result.

For larger requests, follow meta.next_cursor until no further page remains. The forex historical data documentation explains the request parameters and response format. The historical API overview lists the corresponding endpoints for other markets.

Calculate MAE and MFE in Python#

The example below runs with Python's standard library. Save it as trade_excursions.py and run python3 trade_excursions.py.

It uses five illustrative one-minute candles, an entry at 10:00 UTC and an exit at 10:05 UTC. Decimal arithmetic keeps the quoted price differences exact.

from datetime import datetime
from decimal import Decimal


def epoch_ms(value):
    return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000)


def price_excursions(entry, side, bars, entry_ms, exit_ms):
    entry = Decimal(str(entry))
    if not entry.is_finite() or entry <= 0:
        raise ValueError("Entry must be a positive finite price")
    if side not in {"long", "short"} or exit_ms <= entry_ms:
        raise ValueError("Check direction and holding period")

    # This example accepts only complete one-minute bars.
    selected = [
        bar for bar in bars
        if entry_ms <= bar["t"] and bar["t"] + 60_000 <= exit_ms
    ]
    if not selected:
        raise ValueError("No complete bars inside the holding period")

    highs, lows = [], []
    for bar in selected:
        high, low = Decimal(str(bar["h"])), Decimal(str(bar["l"]))
        if not all(x.is_finite() and x > 0 for x in (high, low)):
            raise ValueError("Bar prices must be positive and finite")
        if low > high:
            raise ValueError("A bar low cannot exceed its high")
        highs.append(high)
        lows.append(low)

    high, low, zero = max(highs), min(lows), Decimal("0")
    if side == "long":
        return max(zero, entry - low), max(zero, high - entry)
    return max(zero, high - entry), max(zero, entry - low)


start = epoch_ms("2026-11-24T10:00:00Z")
finish = epoch_ms("2026-11-24T10:05:00Z")
ranges = [
    ("1.1010", "1.0990"),
    ("1.1020", "1.0980"),
    ("1.1040", "1.1000"),
    ("1.1060", "1.1020"),
    ("1.1050", "1.1025"),
]
bars = [
    {"t": start + i * 60_000, "h": high, "l": low}
    for i, (high, low) in enumerate(ranges)
]
mae, mfe = price_excursions("1.1000", "long", bars, start, finish)
pip = Decimal("0.0001")
print(f"MAE: {mae / pip:.1f} pips")
print(f"MFE: {mfe / pip:.1f} pips")

Expected output:

MAE: 20.0 pips
MFE: 60.0 pips

To use the downloaded response, replace the illustrative ranges and bars definitions with the following code, then supply the entry price and timestamps from your own trade record:

import json

with open("eurusd-bars.json", encoding="utf-8") as handle:
    payload = json.load(handle, parse_float=Decimal)
bars = payload["data"]

The actual API prices will not reproduce the illustrative result. The function measures the observations supplied to it; it does not verify that every expected candle is present. Check coverage, remove duplicate timestamps and finish pagination before labelling a result complete. An empty window should remain unavailable rather than appearing as zero excursion.

Turn the calculation into a useful journal view#

Save one row per completed trade with its symbol, direction, entry and exit times, actual fills, price-series source, bar interval, MAE and MFE. Record whether the calculation covers the full holding period or only complete interior candles.

A compact journal can show three values together: adverse excursion, favourable excursion and the final result. Add the holding period beside them. A five-minute trade and a two-day trade have very different opportunities to move away from entry.

For reviewing a group of trades, plot MAE on the horizontal axis and the final result on the vertical axis. A second view can use MFE against the final result. Group similar instruments and setups, and use percentages or another consistent unit when comparing different price scales.

This helps you identify questions worth investigating: whether a particular setup experiences larger adverse moves, whether longer holding periods change the pattern, or whether exits behave differently by session. Test any resulting rule on a separate period before treating it as an improvement. The largest move in a completed trade was not known at entry.

Add live excursion tracking#

The same calculation can run while a position is open. Start the running high and low at the entry price, then update them with each accepted observation from the SiftingIO WebSocket stream. Keep each observation's timestamp so you can stop the measurement at exit.

Keep a coverage flag alongside the numbers. If the connection drops, mark the interrupted interval and reconcile it with historical bars after reconnecting. Those bars can restore observed extrema for complete intervals, while recorded live observations remain useful for partial entry and exit candles.

A live journal can then show current movement, running MAE and running MFE in one view. The completed trade retains the same definitions used while it was open.

Build the first version with one trade#

Choose one completed trade, retrieve its historical candles and calculate the two excursions. Check the time window against the chart before processing a full journal. Once the calculation is consistent, reuse the same workflow for other supported instruments.

Start with a free SiftingIO account to build and test a private journal within the plan limits. For a customer-facing journal or analytics product, review the available plans and confirm the access and commercial permissions for your application.

Keep reading

Related posts