Free learning tools Test your finance and trading knowledge before you build, buy, or automate.
Pullback series — entry techniques

Order Block Pullback Entry — Exact Rules, Displacement Thresholds, and Three Worked Cases

The most-hyped concept in modern price action, rebuilt as an engineering specification: a mechanical definition, an ATR-quantified displacement threshold, close-through mitigation, and three worked cases with every number computed.

Order blocks have a marketing problem. The dominant version of the concept arrives wrapped in institutional storytelling — "the banks placed orders here, so price must return" — with no definition precise enough to test and no threshold that separates a real order block from every other red candle on the chart. This guide keeps what is mechanically useful and discards the story: an exact operational definition, a displacement threshold measured in ATR units, a structural invalidation rule, three worked cases with full arithmetic, and a complete Python implementation that tests the whole thing — including the question of whether the displacement threshold itself matters.

1. What an Order Block Actually Is — Observable vs Inferred

Strip the narrative and what remains is a price structure: a displacement move that breaks structure usually starts from a specific candle, and price often returns to that candle's range before continuing. That is the entire observable claim. In this rule set, a bullish order block (OB) is defined mechanically:

OB = the last red-close candle immediately before the consecutive green run that closes above the most recent confirmed swing high.

Three components, each checkable on a chart: the green run is a maximal sequence of green closes; the break of structure (BOS) is a close above the most recent confirmed swing high (fractal, 3 bars each side, confirmed 3 bars later — the same pivot definition used throughout this series); and the last red candle before the run is the zone. The zone is that candle's full range — low to high.

Now the distinction this series insists on: observable vs inferred. Observable: the run happened, the close broke the level, the red candle sits at the origin, price returned. Inferred: that institutions, banks, or "smart money" placed orders there. The academic microstructure literature does show that short-horizon price changes are driven mainly by order flow imbalance — the imbalance between supply and demand at the best prices — with a near-linear relationship between imbalance and price change. That is a real mechanism. But it does not license the claim that any specific candle is an institutional footprint, because nobody outside the venue's order book can see who traded. The mechanical definition works without the story; the story adds nothing testable. We keep the definition.

Why might price return to the origin of a displacement move at all? Three mundane, observable reasons, none requiring intent: unfilled resting orders accumulate at the level where the move started; participants who missed the run use the retracement to enter; and traders who chased the move defend entries near its origin. The stop-loss side matters too — stop orders cluster just beyond obvious levels like the zone low, which is exactly why our stop rule includes a buffer below it rather than sitting on the level.

2. The Displacement Threshold — Quantifying "Strong Move"

Every order block guide says "wait for a strong displacement move" and none of them says how strong. Unquantified adjectives are where discretionary systems die, so we quantify with one number and make it testable:

$$\text{leg range} = \text{leg high} - \text{OB low} \ \ge\ k \times \text{ATR}_{14}\ (\text{at the BOS bar}), \qquad k = 1.5\ \text{by default}$$

The leg is the green run from the OB candle to the BOS bar; its high is the highest high in that run, and its range is measured from the OB candle's low. ATR14 is the SMA-of-true-range convention from this series. The default k = 1.5 is a convention, not a discovery — which is why the implementation ships with a sensitivity grid over k ∈ {1.0, 1.5, 2.0, 2.5}, and why the article's hypothesis test compares strong displacement (≥1.5×ATR) against weak (≥0.75×ATR) directly.

Two details make the definition airtight. First, the BOS condition is not "price went up a lot" — it is specifically a close above the most recent confirmed swing high, and the swing high must have been confirmed before the BOS bar, so the definition never uses information from the future. Second, the run must be a consecutive green sequence: the OB is the candle immediately before it, so there is exactly one candidate per BOS — no judgment, no "well, this one looks more like an order block."

The threshold does real work. Without it, every small green nudge creates an "order block" and the strategy degenerates into buying random congestion. With k = 1.5, the detection requires a move that is at least one and a half average ranges — a run that visibly displaced price rather than drifted. In the worked data below, the leg spans 76.0 pips against a threshold of 33.1 pips: the qualification is not marginal, and the code asserts it.

3. The Exact Rules

Order Block Pullback — Complete Rule Set (long side)

  • Detection: consecutive green run closing above the most recent confirmed swing high (BOS). The bar immediately before the run must be red; it is the OB candidate.
  • Qualification: leg range (OB low → run high) ≥ 1.5 × ATR14 at the BOS bar. Zone = OB candle's [low, high].
  • Retest: the zone is armed when any later bar's low reaches the zone top. Close-through mitigation (a close below the zone low) invalidates the OB permanently — the default rule; a wick-only variant is provided and tested.
  • Trigger: the first bullish engulfing bar that touches the zone (low ≤ zone top) with a close at or above the zone low.
  • Entry: at the trigger bar's close.
  • Stop: zone low − buffer, buffer = max(2 pips, 0.15 × ATR14 at the trigger).
  • Targets: TP1 = leg high (the BOS high); TP2 = leg high + 0.5 × leg range; TP3 = leg high + 1.0 × leg range (full projection). Partials 50/30/20.
  • Invalidation: close below the zone low (default). One entry per OB; no re-entries.

Note what is absent: no requirement that the OB "swept liquidity" first, no higher-timeframe order block overlay, no premium/discount filter. Those can be added as testable filters later — but every one of them must earn its place with sample data, not with narrative.

4. Worked Case 1 — Valid: Every Number Computed

Synthetic labeled data, EURUSD-like H1, 1 pip = 0.0001. Every value is computed by the module in Section 12, which asserts each claim. The structural bars:

BarOpenHighLowCloseRole
B41.090201.092001.089801.09160Swing high (confirmed at B7)
B81.086001.086401.085001.08540OB candle (red) — zone [1.08500, 1.08640]
B9–B10Green run continues (closes 1.08740, 1.09020)Displacement leg
B111.090201.092601.089901.09240BOS: close 1.09240 > 1.09200
B141.087601.087701.086201.08640Retest: low 1.08620 touches zone top
B151.086301.087901.086001.08770Trigger: engulfing close 1.08770

The trigger check in full: prior bar B14 is red (close 1.08640 < open 1.08760). Bar B15 is green (close 1.08770 > open 1.08630). Engulfing requires open of B15 ≤ close of B14: \(1.08630 \le 1.08640\) ✓. And close of B15 ≥ open of B14: \(1.08770 \ge 1.08760\) ✓. The trigger bar's low (1.08600) touches the zone top (1.08640) ✓, and the close (1.08770) is above the zone low (1.08500) ✓. All conditions hold.

The trade arithmetic:

ATR14 at BOS (B11) = 22.07 pips
Qualification: leg range 76.0 pips >= 1.5 x 22.07 = 33.1 pips  OK
ATR14 at trigger (B15) = 23.07 pips
Buffer = max(2, 0.15 x 23.07) = 3.46 pips
Stop = zone low - buffer = 1.08500 - 0.000346 = 1.08465
Entry = 1.08770 (trigger close)
Risk = 1.08770 - 1.08465 = 0.003046 = 30.46 pips

TP1 = leg high 1.09260 : 49.0 pips = 1.61R  (hit at B18)
TP2 = 1.09640 : 87.0 pips = 2.86R  (hit at B21)
TP3 = 1.10020 : 125.0 pips = 4.10R  (hit at B24)

Blended 50/30/20 = 2.48R before costs, 2.45R after 1-pip spread

Sizing ($10,000, 1% risk, EURUSD):
  cost-adjusted risk per lot = (30.46 + 1.0) x $10 = $314.60
  lots = floor(100 / 314.60 / 0.01) x 0.01 = 0.31
  money at risk = 0.31 x $314.60 = $97.53
  P&L at blended: 2.45 x $97.53 = +$238.85

Two things to notice. The stop is 30.46 pips — wider than the OB candle itself (14 pips) because the entry fires 13 pips above the zone low and the buffer sits below the zone. And the risk-to-reward ladder (1.61R to 4.10R) comes from the leg projection, not from optimism: TP1 is simply the high the market already printed, and TP3 projects the leg's own range forward once. If the leg was 76 pips, the full projection asks for one more 76 pips — ambitious but structurally defined, and the 50% partial at TP1 exists precisely because full projections fail often.

5. Worked Case 2 — Failed: the Trigger That Went Nowhere

The failed version uses the identical OB, identical trigger, identical entry and stop — and a different continuation:

BarOpenHighLowCloseNote
B16f1.087701.088001.086601.08690Stall; no follow-through
B17f1.086901.087101.085801.08600Sliding back to the zone
B18f1.086001.086201.084401.08460Low 1.08440 ≤ stop 1.08465 → filled

The arithmetic of the loss: stop fill at 1.08465, entry 1.08770, so the realized loss is the full 30.46-pip risk plus the 1-pip spread — −1.03R, which at 0.31 lots is −$100.73. The close at 1.08460 is also below the zone low (1.08500), confirming close-through mitigation: the zone is now dead, and the rule set forbids re-entry on it even if price later rallies. This is the point of having the rule — the failed OB is retired permanently, which prevents the classic sequence of re-entering a broken level three times and calling it "averaging in."

The recovery math mirrors the Fibonacci guide: the account stands at $9,899.27; returning to $10,000 requires +1.02% — one risk unit plus costs. That symmetry is why risk stays at 1%: each loss is recovered by one average winner, and no single structural failure can damage the compounding engine. At 5% risk the same event costs $503 and requires +5.3% to recover; three in a row require roughly +17.5%.

6. Worked Case 3 — Ambiguous: the Close That Missed by One Pip

This is the case that exposes the real decision inside every order block system: what counts as mitigation failure? The same OB, a retest that wicks four pips through the zone low, and a close that lands 0.1 pip below the zone low:

B14a: wick low 1.08460 - pierces zone low 1.08500 by 4.0 pips
B15a: closes 1.08499 - one tenth of a pip below the zone low

Strict rule (close-through invalidation): the OB is DEAD. No trade.
Wick-only variant: the OB survives; the variant then triggers at B16a:
  entry 1.08580, stop 1.08465, risk 11.45 pips
  counterfactual blended result: 8.26R before costs, 8.17R after spread

Look at that counterfactual number and understand why it is dangerous: the variant's entry sits 8 pips above the zone low with an 11-pip stop, so every R is tiny and the R-multiple looks spectacular. This is precisely the mechanism behind the "99% win rate" order block screenshots — tiny stops make giant R-multiples on the winners, while the loser distribution gets quietly excluded. The honest comparison is not this single case but the sample: the implementation runs both rule variants over your whole dataset and reports both expectancy distributions, including the losers the variant takes that the strict rule skipped.

The strict rule skipped a winner here. That is the price of a bright-line rule, and the correct response is mechanical: log the case, and if the wick-only variant accumulates a genuinely better sample — more total R after costs, consistent across walk-forward blocks — adopt it prospectively as the new rule. What is never correct is switching rules mid-stream because one close-by-a-pip was annoying. The 0.1-pip miss is not the market telling you the rule is wrong; it is the market sitting exactly on the boundary the rule draws, which is what boundaries are for.

7. Mitigation Variants — the Trade-Off, Stated Plainly

VariantInvalidation conditionWhat it catchesWhat it costs
Close-through (default)Any close beyond the zone edgeGenuine failures early; fewer whipsaw re-entriesSkips deep-wick retests that later work (Case 3: 8.17R missed)
Wick-onlyOnly a full bar beyond the zoneDeep sweeps of the zone that reclaimKeeps zones alive longer; more entries into dying structures; smaller effective stop distances after deep wicks

Neither variant is "correct." The default is close-through because it fails fast and keeps the statistics clean — a dead zone is dead, and the next setup is a fresh OB with a fresh BOS. The wick-only variant is one flag away in the code (`wick_invalidation=True`) so the comparison runs on your data instead of on your opinions.

8. The Evidence Question — and the Displacement Hypothesis

The burden of proof for this setup is specific: does the displacement threshold do anything? If order blocks with strong displacement (leg ≥ 1.5×ATR) perform the same as order blocks with weak displacement (≥ 0.75×ATR), then the threshold is decoration and the strategy is really just "buy retests of structure" with extra steps. The implementation tests this directly — same detection, same triggers, same stops, same costs, two displacement bands — and the article's hypothesis is stated as falsifiable:

H1 (our own, falsifiable): Order blocks formed with displacement ≥ 1.5×ATR14 produce higher continuation expectancy than order blocks with displacement between 0.75× and 1.5×ATR, after costs, consistently across walk-forward blocks. Falsification: if the weak band matches or beats the strong band out-of-sample, the threshold is dropped and the rule set simplifies to the BOS + trigger + stop logic.

No performance claims: the numbers in the validation section below are from the seeded synthetic demo, where no edge can exist by construction — and that is the point. A harness that finds money in a random walk is broken. Your exported CSV is the real test.

9. Risk Math — the Complete Arithmetic

Position sizing with costs, for the Case 1 trade:

$$\text{Lots}=\left\lfloor\frac{E \times \text{risk\%}}{(S + C)\times V}\Big/0.01\right\rfloor \times 0.01$$

with equity \(E = \$10{,}000\), risk 1%, stop \(S = 30.46\) pips, cost \(C = 1\) pip, pip value \(V = \$10\) per lot: \(100 / (31.46 \times 10) = 0.3179\), floored to 0.31 lots — risking $97.53 including the spread. The outcome table for the three cases:

OutcomeRP&L
Full stop (Case 2)−1.03R−$100.73
TP1 only, then breakeven (50% booked)+0.78R+$76.20
TP1 + TP2 (80% booked, runner stopped at entry)+1.55R+$151.29
All three targets (Case 1)+2.45R+$238.85

And expectancy, the number that decides whether any of this is a business:

$$E_R = p_{win}\cdot W_R - (1-p_{win})\cdot L_R$$

Illustrative inputs (hypothetical, NOT a claim):
  p = 45%   W = 2.0R   L = 1.0R
  Expectancy = 0.45 x 2.0 - 0.55 x 1.0 = +0.35R per trade

Sensitivity:
  p = 35%:  0.35 x 2.0 - 0.65 x 1.0 = +0.05R  (thin)
  p = 30%:  0.30 x 2.0 - 0.70 x 1.0 = -0.10R  (dead)

Breakeven win rate at W = 2.0R: 33.3%  (33.6% with 1-pip spread)

The blended average win is the load-bearing variable: it depends on how often runners reach TP2/TP3, which is exactly what the partial ladder (50/30/20) trades against variance. And the drawdown arithmetic: ten straight losses at 1% cost 9.6% of the account; at 5% they cost 40% and require +67% to recover. The stop distance is the market's decision; the risk percentage is yours.

10. Validation Protocol

The module implements the series protocol: chronological 60/20/20 split; parameters (displacement multiple, buffer) chosen on train only; the frozen configuration evaluated on validation and test blocks; a sensitivity grid over k ∈ {1.0, 1.5, 2.0, 2.5} × buffer ∈ {0.10, 0.15, 0.25} × ATR; the displacement-band hypothesis test (strong vs weak) on the full sample; costs charged per trade; entries at the trigger close (no look-ahead); OB detection uses only pivots confirmed before the BOS bar (no repainting). On the seeded synthetic demo the harness reports exactly what it must: grid expectancies scattered by noise, the train-chosen configuration finding no qualified setups out-of-sample (a strict threshold on unstructured data), and the strong-vs-weak displacement comparison showing no reliable difference — 0.03R for strong (n = 14) versus 0.27R for weak (n = 15) on random data, both indistinguishable from zero before costs. That is the correct result when there is no structure to find, and it is why the harness can be trusted with your data.

11. The Complete Implementation

The module below imports the shared library published with the Fibonacci guide (keep both files in the same folder). It contains the detector, the setup finder with both mitigation variants, the three worked cases as literal OHLC arrays with assertions verifying every number quoted above, and the full validation harness. Run it three ways:

python ob_pullback.py examples     # verify the three worked cases
python ob_pullback.py validate     # synthetic walk-forward + hypothesis demo
python ob_pullback.py csv EURUSD_H1.csv   # the real test: your data
#!/usr/bin/env python3
"""
ob_pullback.py - Order block pullback entry: reference implementation.

Companion code for the AlgoSpecial guide "Order Block Pullback Entry"
(algospecial.com/blogs/order-block-pullback-entry). Imports the shared
library published with the Fibonacci guide (fib_pullback.py) - keep both
files in the same folder. Pure standard library, Python 3.7+.

OPERATIONAL DEFINITION (ours - stated so it can be tested)
----------------------------------------------------------
An "order block" in this rule set is a fully mechanical, observable price
structure. It makes NO claim about who placed orders, why, or intent:

- A bullish OB candidate is the last red-close candle immediately before
  the first green candle of the consecutive green run that closes above
  the most recent confirmed swing high (break of structure, BOS).
- The displacement leg is that green run. It qualifies when
  leg_range >= disp_mult * ATR14 at the BOS bar (default disp_mult = 1.5).
- The OB zone is the full range of the red candle: [low, high].
- Mitigation: the zone is "retested" when any later bar's low reaches the
  zone top. Close-through mitigation (a close below the zone low) is the
  structural invalidation in the default rule set. A wick-only variant is
  provided for testing.
- Entry: the first bullish engulfing bar that touches the zone (low <= zone
  top) with a close at or above the zone low. Entry at that close.
- Stop: zone low - buffer, buffer = max(2 pips, 0.15 * ATR14).
- Targets: TP1 = displacement leg high (the BOS high); TP2 = leg high +
  0.5 x leg range; TP3 = leg high + 1.0 x leg range (full projection).

WHAT THIS FILE CONTAINS
-----------------------
1. The detector, setup finder and trade simulation (reusing the shared
   simulator with identical partials and costs).
2. The three worked cases from the article as literal OHLC arrays with
   assertions verifying every claim (OB location, zone, BOS, leg range,
   trigger condition, stop fill, invalidation).
3. A validation harness: 60/20/20 split, walk-forward, a displacement
   baseline (weak vs strong displacement - the article's H1), and a
   sensitivity grid over disp_mult and buffer.

USAGE
-----
    python ob_pullback.py examples     # the three worked cases
    python ob_pullback.py validate     # synthetic harness demo
    python ob_pullback.py csv XAUUSD_H1.csv
"""

from __future__ import annotations

import random
import sys
from dataclasses import dataclass
from typing import List, Optional, Sequence

from fib_pullback import (Bar, PIP, pips, atr_sma, fractal_highs,
                          is_bullish_engulfing, simulate_long, metrics,
                          synthetic_bars, load_mt5_csv, size_position)


@dataclass
class OrderBlock:
    ob_idx: int          # index of the red candle
    zone_lo: float
    zone_hi: float
    bos_idx: int         # index of the BOS bar
    leg_high: float
    leg_range: float
    sh_idx: int          # swing high that was broken
    sh_value: float
    atr_at_bos: float


@dataclass
class OBSetup:
    ob_idx: int
    zone_lo: float
    zone_hi: float
    bos_idx: int
    leg_high: float
    leg_range: float
    entry_idx: int
    entry: float
    stop: float
    tp1: float
    tp2: float
    tp3: float

    @property
    def risk(self) -> float:
        return self.entry - self.stop


def find_order_blocks(bars: Sequence[Bar], disp_mult: float = 1.5,
                      period: int = 14, left: int = 3, right: int = 3) -> List[OrderBlock]:
    """Mechanical OB detection: last red candle before a qualifying BOS run."""
    highs = fractal_highs(bars, left, right)
    sh_info = [(i, bars[i].h, i + right) for i in highs]  # (idx, value, usable)
    obs: List[OrderBlock] = []
    for b in range(1, len(bars)):
        bar = bars[b]
        if bar.c <= bar.o:  # BOS bar must be green
            continue
        # most recent swing high confirmed at or before b
        cand = None
        for (si, sv, usable) in reversed(sh_info):
            if usable <= b:
                cand = (si, sv)
                break
        if cand is None:
            continue
        si, sv = cand
        if not (bars[b - 1].c <= sv < bar.c):  # the close crosses the SH here
            continue
        # start of the consecutive green run ending at b
        s = b
        while s > 0 and bars[s].c > bars[s].o:
            s -= 1
        if s == 0:
            continue
        ob = bars[s]
        if not (ob.c < ob.o):
            continue
        run = bars[s + 1:b + 1]
        leg_high = max(x.h for x in run)
        leg_range = leg_high - ob.l
        a = atr_sma(bars, b, period)
        if a is None or leg_range < disp_mult * a:
            continue
        obs.append(OrderBlock(s, ob.l, ob.h, b, leg_high, leg_range, si, sv, a))
    return obs


def find_ob_setup(bars: Sequence[Bar], ob: OrderBlock, buffer_mult: float = 0.15,
                  period: int = 14, wick_invalidation: bool = False) -> Optional[OBSetup]:
    """First engulfing trigger at the zone, or invalidation."""
    for i in range(ob.bos_idx + 1, len(bars)):
        bar, prev = bars[i], bars[i - 1]
        if wick_invalidation:
            if bar.h < ob.zone_lo:      # whole bar beyond the zone = dead
                return None
        else:
            if bar.c < ob.zone_lo:      # close-through mitigation = dead
                return None
        if bar.l <= ob.zone_hi and is_bullish_engulfing(prev, bar) and bar.c >= ob.zone_lo:
            a = atr_sma(bars, i, period)
            if a is None:
                continue
            buffer = max(2 * PIP, buffer_mult * a)
            stop = ob.zone_lo - buffer
            if stop >= bar.c:
                continue
            return OBSetup(ob.ob_idx, ob.zone_lo, ob.zone_hi, ob.bos_idx, ob.leg_high,
                           ob.leg_range, i, bar.c, stop,
                           ob.leg_high, ob.leg_high + 0.5 * ob.leg_range,
                           ob.leg_high + ob.leg_range)
    return None


def run_ob_strategy(bars: Sequence[Bar], disp_mult: float = 1.5,
                    buffer_mult: float = 0.15, spread_pips: float = 1.0,
                    wick_invalidation: bool = False,
                    start_idx: int = 0) -> List:
    results = []
    last_exit = -1
    for ob in find_order_blocks(bars, disp_mult):
        if ob.bos_idx < start_idx or ob.bos_idx <= last_exit:
            continue
        setup = find_ob_setup(bars, ob, buffer_mult, wick_invalidation=wick_invalidation)
        if setup is None:
            continue
        res = simulate_long(bars, setup, spread_pips)
        results.append(res)
        last_exit = res.exit_idx
    return results


# --------------------------------------------------------------------------
# The three worked cases (literal arrays; assertions verify the article)
# --------------------------------------------------------------------------

PRE = [
    Bar(1.08220, 1.08420, 1.08200, 1.08400),  # B-2
    Bar(1.08400, 1.08580, 1.08380, 1.08560),  # B-1
    Bar(1.08560, 1.08640, 1.08480, 1.08580),  # B0
]
STRUCT = [
    Bar(1.08600, 1.08780, 1.08580, 1.08740),  # B1
    Bar(1.08740, 1.08920, 1.08700, 1.08880),  # B2
    Bar(1.08880, 1.09060, 1.08840, 1.09020),  # B3
    Bar(1.09020, 1.09200, 1.08980, 1.09160),  # B4  <- swing high 1.09200
    Bar(1.09160, 1.09180, 1.08960, 1.08980),  # B5
    Bar(1.08980, 1.09000, 1.08780, 1.08800),  # B6
    Bar(1.08800, 1.08820, 1.08580, 1.08600),  # B7
    Bar(1.08600, 1.08640, 1.08500, 1.08540),  # B8  <- OB candle (red)
    Bar(1.08540, 1.08760, 1.08520, 1.08740),  # B9
    Bar(1.08740, 1.09040, 1.08720, 1.09020),  # B10
    Bar(1.09020, 1.09260, 1.08990, 1.09240),  # B11 <- BOS close above 1.09200
]
RETEST = [
    Bar(1.09240, 1.09260, 1.08960, 1.09000),  # B12
    Bar(1.09000, 1.09020, 1.08760, 1.08790),  # B13
    Bar(1.08760, 1.08770, 1.08620, 1.08640),  # B14 <- touches zone top
]
TRIGGER = Bar(1.08630, 1.08790, 1.08600, 1.08770)  # B15 engulfing
VALID_CONT = [
    Bar(1.08770, 1.08960, 1.08740, 1.08930),
    Bar(1.08930, 1.09120, 1.08890, 1.09090),
    Bar(1.09090, 1.09280, 1.09050, 1.09250),  # TP1 1.09260 hit
    Bar(1.09250, 1.09420, 1.09210, 1.09390),
    Bar(1.09390, 1.09560, 1.09350, 1.09530),
    Bar(1.09530, 1.09680, 1.09490, 1.09650),  # TP2 1.09640 hit
    Bar(1.09650, 1.09820, 1.09610, 1.09790),
    Bar(1.09790, 1.09960, 1.09750, 1.09930),
    Bar(1.09930, 1.10060, 1.09890, 1.10030),  # TP3 1.10020 hit
]
FAILED_CONT = [
    Bar(1.08770, 1.08800, 1.08660, 1.08690),
    Bar(1.08690, 1.08710, 1.08580, 1.08600),
    Bar(1.08600, 1.08620, 1.08440, 1.08460),  # low 1.08440 <= stop -> filled
]
AMBIG_CONT = [
    Bar(1.08790, 1.08800, 1.08460, 1.08530),  # B14a wick 4 pips through zone low
    Bar(1.08530, 1.08560, 1.08480, 1.08499),  # B15a close 1 pip below zone low
    Bar(1.08499, 1.08620, 1.08470, 1.08580),  # B16a variant trigger (engulfing)
    Bar(1.08580, 1.08600, 1.08500, 1.08520),  # B17a red
    Bar(1.08520, 1.08690, 1.08500, 1.08670),  # B18a
    Bar(1.08670, 1.08860, 1.08640, 1.08830),  # B19a
    Bar(1.08830, 1.09040, 1.08790, 1.09010),  # B20a
    Bar(1.09010, 1.09220, 1.08970, 1.09190),  # B21a
    Bar(1.09190, 1.09400, 1.09150, 1.09370),  # B22a TP1
    Bar(1.09370, 1.09580, 1.09330, 1.09550),  # B23a
    Bar(1.09550, 1.09740, 1.09510, 1.09710),  # B24a TP2
    Bar(1.09710, 1.09900, 1.09670, 1.09870),  # B25a
    Bar(1.09870, 1.10060, 1.09830, 1.10030),  # B26a TP3
]


def verify_worked_cases() -> None:
    valid = PRE + STRUCT + RETEST + [TRIGGER] + VALID_CONT
    failed = PRE + STRUCT + RETEST + [TRIGGER] + FAILED_CONT
    ambig = PRE + STRUCT + RETEST[:2] + AMBIG_CONT

    obs = find_order_blocks(valid)
    assert obs and obs[0].ob_idx == 10, "expected the B8 order block first"
    ob = obs[0]
    assert ob.zone_lo == 1.08500 and ob.zone_hi == 1.08640
    assert ob.bos_idx == 13 and ob.sh_value == 1.09200
    assert abs(ob.leg_high - 1.09260) < 1e-12
    assert abs(ob.leg_range - 0.00760) < 1e-12
    assert ob.leg_range >= 1.5 * ob.atr_at_bos

    setup = find_ob_setup(valid, ob)
    assert setup is not None and setup.entry_idx == 17
    assert abs(setup.entry - 1.08770) < 1e-12
    assert setup.stop < ob.zone_lo
    res_v = simulate_long(valid, setup, spread_pips=1.0)
    assert res_v.outcome == "all_targets" and len(res_v.tp_hits) == 3

    setup_f = find_ob_setup(failed, ob)
    assert setup_f is not None
    res_f = simulate_long(failed, setup_f, spread_pips=1.0)
    assert res_f.outcome == "stop"

    obs_a = find_order_blocks(ambig)
    assert obs_a and obs_a[0].ob_idx == 10
    assert find_ob_setup(ambig, obs_a[0]) is None, "close-through must invalidate"
    variant = find_ob_setup(ambig, obs_a[0], wick_invalidation=True)
    assert variant is not None, "wick-only variant must survive"
    assert variant.entry_idx == 18
    res_var = simulate_long(ambig, variant, spread_pips=1.0)
    assert res_var.outcome == "all_targets"


def print_worked_cases() -> None:
    valid = PRE + STRUCT + RETEST + [TRIGGER] + VALID_CONT
    failed = PRE + STRUCT + RETEST + [TRIGGER] + FAILED_CONT
    ambig = PRE + STRUCT + RETEST[:2] + AMBIG_CONT

    ob = find_order_blocks(valid)[0]
    setup = find_ob_setup(valid, ob)
    a_entry = atr_sma(valid, setup.entry_idx)
    buffer = max(2 * PIP, 0.15 * a_entry)

    print("=" * 66)
    print("WORKED CASE 1 - VALID (1 pip = 0.0001)")
    print("=" * 66)
    print("OB candle B8: o=%.5f h=%.5f l=%.5f c=%.5f (red)"
          % (STRUCT[7].o, STRUCT[7].h, STRUCT[7].l, STRUCT[7].c))
    print("Zone = [%.5f, %.5f]" % (ob.zone_lo, ob.zone_hi))
    print("Swing high broken: %.5f (B4, confirmed B7)" % ob.sh_value)
    print("BOS bar B11 close %.5f > %.5f" % (1.09240, ob.sh_value))
    print("ATR14 at BOS = %.2f pips" % pips(ob.atr_at_bos))
    print("Leg range = %.1f pips >= 1.5 x %.2f = %.1f pips -> qualifies"
          % (pips(ob.leg_range), pips(ob.atr_at_bos), pips(1.5 * ob.atr_at_bos)))
    print("ATR14 at trigger = %.2f pips; buffer = %.2f pips" % (pips(a_entry), pips(buffer)))
    print("Trigger B15: engulfing close %.5f (touched zone: low %.5f <= %.5f)"
          % (setup.entry, TRIGGER.l, ob.zone_hi))
    print("Stop = zone low - buffer = %.5f" % setup.stop)
    print("Risk = %.2f pips" % pips(setup.risk))
    for name, tp in (("TP1", setup.tp1), ("TP2", setup.tp2), ("TP3", setup.tp3)):
        print("%s = %.5f : %.1f pips = %.2fR" % (name, tp, pips(tp - setup.entry),
                                                 pips(tp - setup.entry) / pips(setup.risk)))
    res = simulate_long(valid, setup, spread_pips=1.0)
    blended = 0.5 * pips(setup.tp1 - setup.entry) / pips(setup.risk) + \
              0.3 * pips(setup.tp2 - setup.entry) / pips(setup.risk) + \
              0.2 * pips(setup.tp3 - setup.entry) / pips(setup.risk)
    print("TP hits at bars %s" % [h[1] for h in res.tp_hits])
    print("Blended 50/30/20 = %.2fR before costs, %.2fR after 1-pip spread"
          % (blended, res.realized_r))
    lots, risk_money = size_position(10000.0, 1.0, pips(setup.risk))
    print("Sizing: lots = %.2f; risk+cost = $%.2f; P&L = $%.2f"
          % (lots, risk_money, res.realized_r * risk_money))
    print()

    print("=" * 66)
    print("WORKED CASE 2 - FAILED (trigger, then close-through)")
    print("=" * 66)
    setup_f = find_ob_setup(failed, ob)
    res_f = simulate_long(failed, setup_f, spread_pips=1.0)
    print("Same entry %.5f, stop %.5f, risk %.2f pips"
          % (setup_f.entry, setup_f.stop, pips(setup_f.risk)))
    print("B18f low 1.08440 <= stop %.5f -> filled at stop" % setup_f.stop)
    print("B18f close 1.08460 < zone low 1.08500 -> close-through confirmed")
    print("Outcome: %s at bar %d; realized %.2fR; P&L $%.2f"
          % (res_f.outcome, res_f.exit_idx, res_f.realized_r, res_f.realized_r * risk_money))
    print()

    print("=" * 66)
    print("WORKED CASE 3 - AMBIGUOUS (close 1 pip below zone -> dead by rule)")
    print("=" * 66)
    obs_a = find_order_blocks(ambig)
    assert find_ob_setup(ambig, obs_a[0]) is None
    variant = find_ob_setup(ambig, obs_a[0], wick_invalidation=True)
    res_var = simulate_long(ambig, variant, spread_pips=1.0)
    a_var = atr_sma(ambig, variant.entry_idx)
    print("B14a wick low 1.08460 pierces zone low 1.08500 by 4.0 pips")
    print("B15a closes 1.08499 - 0.1 pip below zone low: strict rule -> NO TRADE")
    print("Wick-only variant triggers at B16a: entry %.5f, stop %.5f, risk %.2f pips"
          % (variant.entry, variant.stop, pips(variant.risk)))
    blended_a = 0.5 * pips(variant.tp1 - variant.entry) / pips(variant.risk) + \
                0.3 * pips(variant.tp2 - variant.entry) / pips(variant.risk) + \
                0.2 * pips(variant.tp3 - variant.entry) / pips(variant.risk)
    print("Missed (variant) blended: %.2fR before costs, %.2fR after spread"
          % (blended_a, res_var.realized_r))
    print()


# --------------------------------------------------------------------------
# Validation harness
# --------------------------------------------------------------------------

def walk_forward_report(bars: Sequence[Bar]) -> None:
    n = len(bars)
    i60, i80 = int(n * 0.6), int(n * 0.8)
    train, val, test = bars[:i60], bars[i60:i80], bars[i80:]
    print("=" * 66)
    print("VALIDATION (synthetic bars, seed 7) - machinery demo only")
    print("=" * 66)
    print("Split: train %d, validation %d, test %d bars" % (len(train), len(val), len(test)))

    print("\nSensitivity grid on TRAIN (expectancy R/trade):")
    print("%-10s" % "disp_mult", end="")
    for b in (0.10, 0.15, 0.25):
        print("buffer=%.2f " % b, end="")
    print()
    best = (None, -999.0)
    for dm in (1.0, 1.5, 2.0, 2.5):
        print("%-10.1f" % dm, end="")
        for bm in (0.10, 0.15, 0.25):
            m = metrics(run_ob_strategy(train, dm, bm))
            e = m.get("expectancy_r", 0.0)
            if e > best[1]:
                best = ((dm, bm), e)
            print("%9.3f " % e, end="")
        print()
    chosen = best[0] if best[0] else (1.5, 0.15)
    print("Chosen on train: disp_mult=%.1f buffer=%.2f" % chosen)

    for name, seg in (("validation", val), ("test", test)):
        m = metrics(run_ob_strategy(seg, chosen[0], chosen[1]))
        if m["n"] == 0:
            print("%s: no setups" % name)
            continue
        print("%s: n=%d win=%.0f%% avg_win=%.2fR avg_loss=%.2fR expectancy=%.3fR PF=%.2f maxDD=%.2fR"
              % (name, m["n"], 100 * m["win_rate"], m["avg_win_r"], m["avg_loss_r"],
                 m["expectancy_r"], m["profit_factor"], m["max_dd_r"]))

    print("\nDisplacement hypothesis test (whole sample, same buffer):")
    strong = metrics(run_ob_strategy(bars, 1.5, chosen[1]))
    weak = metrics(run_ob_strategy(bars, 0.75, chosen[1]))
    print("strong (>=1.5xATR): n=%d expectancy=%.3fR" % (strong["n"], strong.get("expectancy_r", 0.0)))
    print("weak   (>=0.75xATR): n=%d expectancy=%.3fR" % (weak["n"], weak.get("expectancy_r", 0.0)))
    print("(Synthetic data proves the harness runs; it cannot establish an edge.)")


def main() -> None:
    mode = sys.argv[1] if len(sys.argv) > 1 else "examples"
    if mode == "examples":
        verify_worked_cases()
        print_worked_cases()
    elif mode == "validate":
        walk_forward_report(synthetic_bars(3000, seed=7))
    elif mode == "csv" and len(sys.argv) > 2:
        bars = load_mt5_csv(sys.argv[2])
        print("Loaded %d bars from %s" % (len(bars), sys.argv[2]))
        walk_forward_report(bars)
    else:
        print(__doc__)


if __name__ == "__main__":
    main()

12. Failure Modes Specific to Order Blocks

Unquantified displacement. The single biggest source of bad order blocks. If "strong move" means whatever looks strong on the day, the strategy cannot be tested and every losing trade has a story. The 1.5×ATR threshold turns the adjective into a number — and the module's sensitivity grid tests whether the number matters.

Zones drawn from the wrong candle. Guides disagree on whether the OB is the last red candle, the red candle with the biggest body, or "the candle before the sweep." Pick one definition, publish it, and apply it forever. Ours is stated in Section 1 and coded in the detector: last red-close candle before the consecutive green run that breaks structure. No exceptions.

Re-entering dead zones. After close-through mitigation, the OB is retired. Traders who re-enter a broken zone two or three times convert a −1R event into a −3R event and call the market unfair. One entry per OB, no re-entries — this is a rule, not a suggestion.

Reading intent into structure. "The banks swept my stop" is not a falsifiable statement, and strategies built on it cannot be evaluated. The mechanics you can actually work with — order flow imbalance drives short-horizon price changes, stops cluster beyond obvious levels — are already in the rule set (the zone, the buffer). The story adds nothing but conviction, and conviction is what makes traders hold through invalidation.

Ignoring the cost burden on small zones. An OB candle with a 6-pip range on M5 produces stops that make the 1-pip spread 15%+ of risk — the breakeven win rate moves from 33.3% to 40%, and the strategy usually dies quietly. Below H1, the zone must be wide enough that the spread is a rounding error, or the trade is skipped.

Targets that ignore the structure they came from. TP3 is a full leg projection; asking for it in a counter-trend context or at a higher-timeframe supply level is asking the market for something the structure never implied. The partial ladder exists because projections fail — 50% books at the high that already printed, and the runner is allowed to fail.

13. FAQ

What is an order block in this rule set?

The last red-close candle immediately before the consecutive green run that closes above the most recent confirmed swing high (BOS). Its full range is the zone. No claim is made about who placed orders — the definition is observable and testable.

What displacement threshold qualifies an order block?

Leg range (OB low to run high) must be at least 1.5×ATR14 at the BOS bar. The grid tests 1.0/1.5/2.0/2.5, and the hypothesis test compares strong (≥1.5×) against weak (≥0.75×) displacement directly.

Wick mitigation or close-through mitigation?

Default: close-through — a close beyond the zone edge kills the OB. The wick-only variant is one flag away and is tested side by side; the choice is a measured trade-off (Case 3 shows the strict rule skipping 8.17R on a 0.1-pip close), not a preference.

Where does the stop go?

Zone low minus max(2 pips, 0.15×ATR14) for a bullish OB. The zone edge is the structural invalidation; the buffer covers the stop cluster that sits just beyond obvious levels.

Do order blocks prove institutions are buying there?

No. What is observable: order flow imbalance drives short-horizon price changes, and large runs concentrate volume at their origin. The institutional story is interpretation, not evidence — and the mechanical definition works without it.

Can I automate order block detection?

Yes — the implementation in this article detects OB, BOS, displacement qualification, retest, trigger, stop and targets, then runs walk-forward validation and the displacement baseline on your CSV. Every rule is deterministic.

Continue the Series

Trade Structure With Live Tools

Zones, structure breaks and liquidity levels across 50+ symbols — the concepts in this series, computed live on your charts.

Browse MT5 Tools Live Signals

🚀 Invite friends — Earn $5 You both get $5 credit on Go Ad · opencode.ai AI-Powered Coding Agent — Try Free Build apps, fix bugs & ship faster with opencode. Get $5 free credit when you join. × Ad · quo.com QuoPhone — $20 Visa Gift Card Free Sign up to Quo, subscribe 3 months, get a $20 Visa gift card. Atif's referral gift for you. ×