Liquidity Sweep as Pullback — Equal-Lows Clustering, Penetration Bounds, and Three Worked Cases
The most conspiracy-laden concept in price action, rebuilt as engineering: mechanical level clustering, penetration bounds in ATR units, a reclaim window, and three worked cases with every number computed.
Liquidity sweeps arrive wrapped in narrative: "the market hunts your stops," "smart money grabs liquidity," screenshots of wicks that "had to" reverse. The narrative is unfalsifiable and, worse, unnecessary — the observable mechanics are enough. This final entry-technique guide in the series takes the sweep apart and rebuilds it: levels defined by mechanical equal-lows clustering, a sweep defined by penetration bounds in ATR units, a reclaim window that separates sweeps from breakouts, and three worked cases with every number produced by code that asserts its own claims.
1. What a Liquidity Level Is — Observable, Not Inferred
Start with what can be seen. Equal lows — two or more swing lows at nearly the same price — are visible on any chart. Market microstructure research documents why they matter: stop-loss orders tend to cluster just beyond obvious price levels, so a move through such a level mechanically triggers a batch of resting orders. That is a statement about where orders rest, established from actual order data, and it needs no story about intent. It is also the only part of the sweep concept this guide uses.
The rule set defines the level mechanically:
$$\text{Level} = \text{cluster of } \ge 2 \text{ confirmed pivot lows (L=3, R=3) with lows within } 0.10 \times \text{ATR}_{14} \text{ of each other}$$
The level value is the minimum low of the cluster (the deepest point the cluster has proven), and the touch count is the cluster size. In the worked data, three pivot lows at 1.08300, 1.08305 and 1.08302 — all within 0.5 pips of each other — form a 3-touch level at 1.08300. The level is usable only after the last member pivot is confirmed (three bars later, the same no-repainting discipline as every guide in this series).
What is deliberately absent: the claim that "institutions" placed orders at these lows, that the level was "engineered," or that any subsequent move was "hunted." Those claims cannot be tested, and a strategy built on untestable claims cannot be evaluated. The cluster, the penetration, the reclaim — those can all be measured.
2. The Sweep Definition — Two Numbers and a Window
A sweep is not "any wick below the level." It is an event with three parameters, all in ATR units so they are comparable across instruments:
Penetration bounds. The sweep bar's low must pierce the level by at least \(0.10 \times \text{ATR}_{14}\) (a one-tick pierce is noise, not a sweep) and at most \(0.50 \times \text{ATR}_{14}\) (a deep break is a breakout in progress, not a sweep). In the worked data: the sweep low of 1.08280 pierces the 1.08300 level by 2.0 pips, against bounds of 1.2 and 5.9 pips — a valid sweep by a comfortable margin on both sides.
The reclaim window. Price must close back at or above the level within 2 bars of the sweep. In the worked case the reclaim happens on the sweep bar itself (close 1.08330). A sweep with no reclaim inside the window is a breakout the rule set declines to fight — the failed case in Section 6 shows what fighting it costs.
The trigger. Even after a valid sweep and reclaim, the entry still requires a bullish engulfing bar within 2 bars of the reclaim, closing at or above the level. The sweep is the setup; the engulfing close is permission.
Those three elements are what make the sweep testable. Without the penetration bounds, every touch is a "sweep"; without the reclaim window, every break is a "sweep that hasn't reclaimed yet"; without the trigger, entries have no confirmation moment. Each parameter is a declared convention — and the sensitivity grid in Section 10 tests them.
3. The Exact Rules
Liquidity Sweep Pullback — Complete Rule Set (long side)
- Level: cluster of ≥ 2 confirmed pivot lows within 0.10 × ATR14 of each other. Value = minimum low of the cluster; touches = cluster size. Usable after the last member's confirmation.
- Sweep: a bar whose low pierces the level by \(p\) with \(0.10 \times \text{ATR} \le p \le 0.50 \times \text{ATR}\). Deeper than the cap kills the level (breakout).
- Reclaim: a close at or above the level within 2 bars of the sweep. A close more than 1.0 × ATR14 below the level before reclaim kills the level.
- Trigger: a bullish engulfing bar within 2 bars of the reclaim, closing at or above the level.
- Entry: at the trigger bar's close.
- Stop: lowest low from the sweep bar through the trigger, minus max(2 pips, 0.15 × ATR14).
- Targets: ref high = highest high from the level's last touch through the bar before the sweep. TP1 = ref high; TP2 = ref high + 0.5 × (ref high − level); TP3 = ref high + 1.0 × (same). Partials 50/30/20.
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 11, which asserts each claim.
| Bar | Open | High | Low | Close | Role |
|---|---|---|---|---|---|
| idx 8 | 1.08380 | 1.08400 | 1.08300 | 1.08320 | Touch 1 (pivot low 1.08300) |
| idx 14 | 1.08380 | 1.08400 | 1.08305 | 1.08340 | Touch 2 (pivot low 1.08305) |
| idx 20 | 1.08540 | 1.08560 | 1.08302 | 1.08350 | Touch 3 (pivot low 1.08302); ref high 1.08560 |
| idx 25 | 1.08390 | 1.08400 | 1.08280 | 1.08330 | Sweep: pierce 2.0 pips, reclaim same bar |
| idx 26 | 1.08330 | 1.08410 | 1.08320 | 1.08390 | Trigger: engulfing close 1.08390 |
The trigger check in full: prior bar idx 25 is red (close 1.08330 < open 1.08390). Bar idx 26 is green (close 1.08390 > open 1.08330). Engulfing requires open of idx 26 ≤ close of idx 25: \(1.08330 \le 1.08330\) ✓ (equality permitted). And close of idx 26 ≥ open of idx 25: \(1.08390 \ge 1.08390\) ✓. The close is at or above the level (1.08300) ✓, within 2 bars of the reclaim ✓. All conditions hold.
The trade arithmetic:
Level = 1.08300 (3 touches); confirmed at idx 23 Sweep idx 25: low 1.08280, penetration 2.0 pips Bounds: 0.10 x 11.88 = 1.2 pips <= 2.0 <= 0.50 x 11.88 = 5.9 pips OK Reclaim: idx 25 close 1.08330 >= 1.08300 OK Buffer = max(2, 0.15 x 11.88) = 2.00 pips (2-pip floor applies) Stop = sweep low 1.08280 - 0.000200 = 1.08260 Entry = 1.08390 (trigger close) Risk = 1.08390 - 1.08260 = 0.001300 = 13.00 pips Ref high (idx 20..24 max) = 1.08560 TP1 = 1.08560 : 17.0 pips = 1.31R (hit at idx 28) TP2 = 1.08690 : 30.0 pips = 2.31R (hit at idx 30) TP3 = 1.08820 : 43.0 pips = 3.31R (hit at idx 32) Blended 50/30/20 = 2.01R before costs, 1.93R after 1-pip spread Sizing ($10,000, 1% risk, EURUSD): cost-adjusted risk per lot = (13.00 + 1.0) x $10 = $140.00 lots = floor(100 / 140.00 / 0.01) x 0.01 = 0.71 money at risk = 0.71 x $140.00 = $99.40 P&L at blended: 1.93 x $99.40 = +$191.92
Notice what the sweep geometry produced: the stop sits just below the sweep low (13.00 pips of risk), and the first target is the price the market printed from the level's own last touch (1.08560) — 17 pips away. The blended outcome (1.93R) is driven by the projections beyond the ref high, and the 50% partial at TP1 exists because sweep continuations fail often enough that booking the proven level matters. The penetration check is doing quiet work here: 2.0 pips is deep enough to be a real probe of the level and shallow enough to remain a probe — inside the band where the reclaim hypothesis is testable.
5. Worked Case 2 — Failed: the Sweep That Kept Going
Same level, same sweep, same reclaim, same trigger — and the continuation that defines the failure mode:
| Bar | Open | High | Low | Close | Note |
|---|---|---|---|---|---|
| f27 | 1.08390 | 1.08410 | 1.08300 | 1.08320 | Slides back to the level |
| f28 | 1.08320 | 1.08340 | 1.08240 | 1.08260 | Low 1.08240 ≤ stop 1.08260 → filled |
The arithmetic of the loss: stop fill at 1.08260, entry 1.08390, so the realized loss is the full 13.00-pip risk plus the 1-pip spread — −1.08R, which at 0.71 lots is −$107.05. The close at 1.08260 is below the sweep low (1.08280) — the event that defined the setup did not hold, and price continued down. This is the sweep-then-continue failure mode: what looked like a reclaim was the pause before a real break. The stop's job is to make that failure boring, and it does — the loss is one risk unit, known before entry.
The recovery math: the account stands at $9,892.95; recovering requires +1.08% — one risk unit plus costs. At 5% risk the same event costs $545 and requires +5.8% to recover.
6. Worked Case 3 — Ambiguous: the Deep Sweep That Was a Breakout
The third case tests the penetration cap. Same level, same structure — and a sweep bar that goes far too deep:
Deep sweep: low 1.08220 pierces the level by 8.0 pips Max penetration = 0.50 x 12.31 = 6.2 pips 8.0 > 6.2 -> classified as a BREAKOUT, not a sweep. Level dead, NO TRADE. Counterfactual (cap disabled): entry 1.08390, stop 1.08200, risk 19.00 pips, outcome all targets, realized +1.32R - skipped.
The skipped trade paid +1.32R, and the cap refused it. This is the honest cost, stated with numbers, and the reasoning is mechanical rather than stylistic: a level pierced by more than half an ATR is being traded through, not tested — the same price action that precedes genuine breaks. The counterfactual's reward-to-risk also shows why the cap hurts less than it looks: the deeper sweep forces a wider stop (19.00 pips against 13.00), so the counterfactual earned only +1.32R versus the valid case's +1.93R on the same continuation. The cap trades away some winners to avoid the class of trades where "sweep" is just a hopeful name for "breakout in progress." If the cap-disabled variant accumulates better statistics on your data, the threshold moves — decided from the sample, not the counterfactual.
7. The Touch-Count Hypothesis
H1 (our own, falsifiable): Levels with 3 or more equal-low touches reclaim more often (higher continuation expectancy after costs) than 2-touch levels, because more equal lows mean more resting orders beyond the level — consistently across walk-forward blocks. Falsification: if 2-touch levels match or beat 3+-touch levels out-of-sample, the touch count is dropped from the setup description.
The harness buckets every trade by cluster size and reports both distributions. On the seeded synthetic demo the buckets are nearly empty (2-touch n = 0, 3+-touch n = 2 at +0.56R) — random data produces few equal-low clusters worth trading, and two trades prove nothing. The test's value is what it does on real data, where equal lows are everywhere and the touch-count question has an actual sample to answer.
8. The Evidence Question — and the Order-Book Limit
The mechanism this setup leans on — stops resting beyond obvious levels — comes from order-book research, and that research also defines the honest limit of the retail version: you cannot see the order book. A retail trader sees the level and the sweep; they cannot see the resting stops that make the level interesting. The setup is therefore an inference from price behavior, not a reading of the book. Two consequences follow, and both are stated rather than hidden. First, the rules must be conservative about what the sweep "means" — hence the penetration bounds and the reclaim window, which encode "this looked like a test, not a break" without claiming to know who traded. Second, the expected edge is smaller than the folklore implies: if the sweep were a reliable institutional fingerprint, the adjustment would be common knowledge and arbitraged away. The harness measures whatever is left after that reasoning — which is the only honest way to trade the concept.
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 = 13.00\) pips, cost \(C = 1\) pip, pip value \(V = \$10\) per lot: \(100 / (14.00 \times 10) = 0.7143\), floored to 0.71 lots — risking $99.40 including the spread. The outcome table for the three cases:
| Outcome | R | P&L |
|---|---|---|
| Full stop (Case 2) | −1.08R | −$107.05 |
| TP1 only, then breakeven (50% booked) | +0.58R | +$57.65 |
| TP1 + TP2 (80% booked, runner stopped at entry) | +1.23R | +$122.26 |
| All three targets (Case 1) | +1.93R | +$191.92 |
| Deep-sweep counterfactual (Case 3, cap off) | +1.32R | +$131.21 |
And expectancy:
$$E_R = p_{win}\cdot W_R - (1-p_{win})\cdot L_R$$
Illustrative inputs (hypothetical, NOT a claim): p = 50% W = 1.8R L = 1.0R Expectancy = 0.50 x 1.8 - 0.50 x 1.0 = +0.40R per trade Sensitivity: p = 40%: 0.40 x 1.8 - 0.60 x 1.0 = +0.12R (thin) p = 33%: 0.33 x 1.8 - 0.67 x 1.0 = -0.076R (dead) Breakeven win rate at W = 1.8R: 35.7% (36.3% with 1-pip spread)
The sweep profile sits between the pivot profile and the VWAP profile: a modest blended winner (~1.8R) with a breakeven win rate near 36%. That number is the one to track — sweep trades either reclaim (and often run to the proven ref high) or fail quickly through the sweep low, so the win/loss distribution is bimodal and the average win depends heavily on how often the runner reaches TP2/TP3. The 50/30/20 ladder is what makes the arithmetic survivable when runners die early.
10. Validation Protocol
The module implements the series protocol: chronological 60/20/20 split; the penetration cap and buffer chosen on train only; the frozen configuration evaluated on validation and test blocks; a sensitivity grid over cap ∈ {0.35, 0.50, 0.75} × buffer ∈ {0.10, 0.15, 0.25} × ATR; the touch-count hypothesis test on the full sample; costs per trade; entries at the trigger close; levels usable only after confirmation (no repainting). On the seeded synthetic demo: the train grid is flat-positive across cells (the cap never binds on random data, so all rows match), the chosen configuration returns no setups on validation and −0.63R on test (n = 2), and the touch buckets are 2-touch n = 0 versus 3+-touch n = 2. Sparse, noisy, and correct for a random walk — the harness refuses to manufacture a story where the data has none.
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 equal-lows cluster builder, the sweep/reclaim/trigger finder with penetration bounds, 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 sweep_pullback.py examples # verify the three worked cases python sweep_pullback.py validate # synthetic walk-forward + touch buckets python sweep_pullback.py csv EURUSD_H1.csv # the real test: your data
#!/usr/bin/env python3
"""
sweep_pullback.py - Liquidity sweep as pullback: reference implementation.
Companion code for the AlgoSpecial guide "Liquidity Sweep as Pullback"
(algospecial.com/blogs/liquidity-sweep-as-pullback). 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)
----------------------------------------------------------
A "liquidity level" here is a cluster of equal lows, built mechanically.
No intent claims are made; the mechanism referenced is documented market
microstructure (stop orders cluster just beyond obvious levels), not a
story about who is hunting whom:
- Level: two or more confirmed fractal pivot lows (L=3, R=3) whose lows
lie within tol = 0.10 * ATR14 of each other. The level value is the
minimum low of the cluster; the touch count is the cluster size.
Usable only after the last member pivot is confirmed (idx + 3).
- Sweep: a bar whose low pierces the level by penetration p where
min_pen <= p <= max_pen (defaults: 0.10 and 0.50 * ATR14). Deeper
than max_pen is treated as a breakout, not a sweep, and kills the
level.
- Reclaim: a close back at or above the level within 2 bars of the
sweep. A close more than 1.0 * ATR14 below the level before reclaim
kills the level.
- Trigger: a bullish engulfing bar within 2 bars of the reclaim bar,
closing at or above the level.
- Entry: at the trigger close.
- Stop: lowest low from the sweep bar through the trigger, minus
buffer = max(2 pips, 0.15 * ATR14).
- Targets: ref_high = highest high from the level's last touch through
the bar before the sweep. TP1 = ref_high; TP2 = ref_high + 0.5 *
(ref_high - level); TP3 = ref_high + 1.0 * (same). Partials 50/30/20.
WHAT THIS FILE CONTAINS
-----------------------
1. The equal-lows cluster builder, the sweep/reclaim/trigger finder and
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 (cluster membership, penetration
bounds, reclaim, trigger, stop fill, deep-sweep rejection).
3. A validation harness: 60/20/20 split, walk-forward, the touch-count
hypothesis test (2-touch vs 3+-touch levels - the article's H1) and
a sensitivity grid over penetration bounds and buffer.
USAGE
-----
python sweep_pullback.py examples # the three worked cases
python sweep_pullback.py validate # synthetic harness demo
python sweep_pullback.py csv EURUSD_H1.csv
"""
from __future__ import annotations
import sys
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple
from fib_pullback import (Bar, PIP, pips, atr_sma, fractal_lows,
is_bullish_engulfing, simulate_long, metrics,
synthetic_bars, load_mt5_csv, size_position)
@dataclass
class Level:
first_idx: int
last_idx: int
value: float
touches: int
confirmed_idx: int
@dataclass
class SweepSetup:
level: Level
sweep_idx: int
reclaim_idx: int
entry_idx: int
entry: float
stop: float
tp1: float
tp2: float
tp3: float
penetration: float
atr: float
@property
def risk(self) -> float:
return self.entry - self.stop
def find_levels(bars: Sequence[Bar], tol_atr: float = 0.10,
period: int = 14, left: int = 3, right: int = 3) -> List[Level]:
"""Clusters of equal lows within tol of the cluster anchor."""
lows = fractal_lows(bars, left, right)
levels: List[Level] = []
used = set()
for a_pos in range(len(lows)):
i = lows[a_pos]
if i in used:
continue
atr_idx = min(max(i + right, period - 1), len(bars) - 1)
a = atr_sma(bars, atr_idx, period)
if a is None:
continue
tol = tol_atr * a
cluster = [i]
for b_pos in range(a_pos + 1, len(lows)):
j = lows[b_pos]
if j in used:
continue
if abs(bars[j].l - bars[i].l) <= tol:
cluster.append(j)
used.add(j)
if len(cluster) >= 2:
first, last = cluster[0], cluster[-1]
value = min(bars[k].l for k in cluster)
confirmed = last + right
if confirmed < len(bars):
levels.append(Level(first, last, value, len(cluster), confirmed))
used.add(i)
return levels
def find_sweep_setup(bars: Sequence[Bar], level: Level,
min_pen_atr: float = 0.10, max_pen_atr: float = 0.50,
buffer_mult: float = 0.15, period: int = 14,
max_wait: int = 2) -> Optional[SweepSetup]:
for i in range(level.confirmed_idx + 1, len(bars)):
bar = bars[i]
a = atr_sma(bars, i, period)
if a is None:
continue
pen = level.value - bar.l
if pen <= 0:
continue
if pen < min_pen_atr * a:
continue # a touch, not a sweep
if pen > max_pen_atr * a:
return None # breakout, not a sweep: level dead
reclaim_idx = None
for j in range(i, min(i + max_wait + 1, len(bars))):
if bars[j].c >= level.value:
reclaim_idx = j
break
if bars[j].c < level.value - a:
return None # deep close before reclaim: dead
if reclaim_idx is None:
return None # swept and not reclaimed
for k in range(max(reclaim_idx, 1), min(reclaim_idx + 3, len(bars))):
if is_bullish_engulfing(bars[k - 1], bars[k]) and bars[k].c >= level.value:
sweep_low = min(x.l for x in bars[i:k + 1])
buffer = max(2 * PIP, buffer_mult * atr_sma(bars, k, period))
stop = sweep_low - buffer
if stop >= bars[k].c:
continue
ref_high = max(x.h for x in bars[level.last_idx:i])
if ref_high <= level.value:
ref_high = max(x.h for x in bars[level.first_idx:i])
span = ref_high - level.value
return SweepSetup(level, i, reclaim_idx, k, bars[k].c, stop,
ref_high, ref_high + 0.5 * span,
ref_high + span, pen, a)
return None # reclaimed but no trigger
return None
def collect_sweep_results(bars: Sequence[Bar], tol_atr: float = 0.10,
min_pen_atr: float = 0.10, max_pen_atr: float = 0.50,
buffer_mult: float = 0.15, spread_pips: float = 1.0,
start_idx: int = 0) -> List[Tuple[SweepSetup, object]]:
out: List[Tuple[SweepSetup, object]] = []
last_exit = -1
for level in find_levels(bars, tol_atr):
if level.confirmed_idx < start_idx or level.confirmed_idx <= last_exit:
continue
setup = find_sweep_setup(bars, level, min_pen_atr, max_pen_atr, buffer_mult)
if setup is None:
continue
res = simulate_long(bars, setup, spread_pips)
out.append((setup, res))
last_exit = res.exit_idx
return out
def run_sweep_strategy(bars: Sequence[Bar], tol_atr: float = 0.10,
min_pen_atr: float = 0.10, max_pen_atr: float = 0.50,
buffer_mult: float = 0.15, spread_pips: float = 1.0,
start_idx: int = 0) -> List:
return [res for (_, res) in collect_sweep_results(
bars, tol_atr, min_pen_atr, max_pen_atr, buffer_mult, spread_pips, start_idx)]
# --------------------------------------------------------------------------
# The three worked cases (literal arrays; assertions verify the article)
# --------------------------------------------------------------------------
PRE = [
Bar(1.08520, 1.08640, 1.08500, 1.08620), # 0
Bar(1.08620, 1.08760, 1.08600, 1.08740), # 1
Bar(1.08740, 1.08820, 1.08660, 1.08680), # 2
Bar(1.08680, 1.08740, 1.08560, 1.08580), # 3
Bar(1.08580, 1.08660, 1.08500, 1.08640), # 4
Bar(1.08640, 1.08680, 1.08520, 1.08540), # 5
Bar(1.08540, 1.08580, 1.08420, 1.08460), # 6
Bar(1.08460, 1.08480, 1.08360, 1.08380), # 7
]
LOWS = [
Bar(1.08380, 1.08400, 1.08300, 1.08320), # 8 L1 (low 1.08300)
Bar(1.08350, 1.08390, 1.08340, 1.08380), # 9
Bar(1.08380, 1.08440, 1.08370, 1.08420), # 10
Bar(1.08420, 1.08480, 1.08410, 1.08460), # 11
Bar(1.08460, 1.08490, 1.08400, 1.08420), # 12
Bar(1.08420, 1.08440, 1.08360, 1.08380), # 13
Bar(1.08380, 1.08400, 1.08305, 1.08340), # 14 L2 (low 1.08305)
Bar(1.08340, 1.08390, 1.08330, 1.08380), # 15
Bar(1.08380, 1.08440, 1.08370, 1.08420), # 16
Bar(1.08420, 1.08680, 1.08410, 1.08660), # 17 rally
Bar(1.08660, 1.08690, 1.08580, 1.08600), # 18
Bar(1.08600, 1.08620, 1.08500, 1.08540), # 19
Bar(1.08540, 1.08560, 1.08302, 1.08350), # 20 L3 (low 1.08302)
Bar(1.08350, 1.08440, 1.08340, 1.08420), # 21
Bar(1.08420, 1.08520, 1.08410, 1.08490), # 22 ref high 1.08520
Bar(1.08490, 1.08510, 1.08430, 1.08460), # 23
Bar(1.08460, 1.08480, 1.08390, 1.08410), # 24 red
]
SWEEP = Bar(1.08390, 1.08400, 1.08280, 1.08330) # 25 sweep low 1.08280
TRIGGER = Bar(1.08330, 1.08410, 1.08320, 1.08390) # 26 engulfing close
VALID_CONT = [
Bar(1.08390, 1.08460, 1.08370, 1.08440), # 27
Bar(1.08440, 1.08530, 1.08420, 1.08510), # 28 TP1 1.08520 hit
Bar(1.08510, 1.08580, 1.08490, 1.08560), # 29
Bar(1.08560, 1.08640, 1.08530, 1.08620), # 30 TP2 1.08630 hit
Bar(1.08620, 1.08690, 1.08590, 1.08670), # 31
Bar(1.08670, 1.08750, 1.08640, 1.08730), # 32 TP3 1.08740 hit
Bar(1.08730, 1.08780, 1.08700, 1.08760), # 33
Bar(1.08760, 1.08800, 1.08720, 1.08780), # 34
Bar(1.08780, 1.08820, 1.08740, 1.08800), # 35
]
FAILED_CONT = [
Bar(1.08390, 1.08410, 1.08300, 1.08320), # 27f
Bar(1.08320, 1.08340, 1.08240, 1.08260), # 28f low <= stop -> filled
]
DEEP_SWEEP = Bar(1.08390, 1.08400, 1.08220, 1.08330) # deep variant low 1.08220
def verify_worked_cases() -> None:
valid = PRE + LOWS + [SWEEP, TRIGGER] + VALID_CONT
failed = PRE + LOWS + [SWEEP, TRIGGER] + FAILED_CONT
ambig = PRE + LOWS + [DEEP_SWEEP, TRIGGER] + VALID_CONT
levels = find_levels(valid)
assert levels, "expected a level cluster"
lv = levels[0]
assert lv.value == 1.08300 and lv.touches == 3
assert lv.last_idx == 20
setup = find_sweep_setup(valid, lv)
assert setup is not None and setup.entry_idx == 26, "trigger at idx 26"
assert abs(setup.entry - 1.08390) < 1e-12
assert setup.sweep_idx == 25 and setup.reclaim_idx == 25
assert 0.10 * setup.atr <= setup.penetration <= 0.50 * setup.atr
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_sweep_setup(failed, lv)
assert setup_f is not None
res_f = simulate_long(failed, setup_f, spread_pips=1.0)
assert res_f.outcome == "stop"
levels_a = find_levels(ambig)
assert levels_a and levels_a[0].value == 1.08300
assert find_sweep_setup(ambig, levels_a[0]) is None, "deep sweep = breakout"
cf = collect_sweep_results(ambig, max_pen_atr=10.0)
assert len(cf) == 1 and cf[0][1].outcome == "all_targets"
def print_worked_cases() -> None:
valid = PRE + LOWS + [SWEEP, TRIGGER] + VALID_CONT
failed = PRE + LOWS + [SWEEP, TRIGGER] + FAILED_CONT
ambig = PRE + LOWS + [DEEP_SWEEP, TRIGGER] + VALID_CONT
lv = find_levels(valid)[0]
setup = find_sweep_setup(valid, lv)
buffer = max(2 * PIP, 0.15 * setup.atr)
print("=" * 66)
print("WORKED CASE 1 - VALID (1 pip = 0.0001)")
print("=" * 66)
print("Equal-lows cluster: idx %d, %d, %d lows 1.08300 / 1.08305 / 1.08302"
% (8, 14, 20))
print("Level = min = %.5f ; touches = %d ; confirmed at idx %d"
% (lv.value, lv.touches, lv.confirmed_idx))
print("Sweep B25: low %.5f pierces level by %.1f pips (ATR14 = %.2f pips)"
% (SWEEP.l, pips(setup.penetration), pips(setup.atr)))
print("Penetration bounds: %.1f <= %.1f <= %.1f pips -> valid sweep"
% (pips(0.10 * setup.atr), pips(setup.penetration), pips(0.50 * setup.atr)))
print("Reclaim: B25 close %.5f >= level -> reclaimed same bar" % SWEEP.c)
print("Trigger B26: engulfing close %.5f >= level" % setup.entry)
print("Buffer = %.2f pips; stop = sweep low - buffer = %.5f"
% (pips(buffer), setup.stop))
print("Risk = %.2f pips" % pips(setup.risk))
print("Ref high (idx 20..24 max) = %.5f" % setup.tp1)
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("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 continuation through)")
print("=" * 66)
setup_f = find_sweep_setup(failed, lv)
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("B28f low 1.08240 <= stop %.5f -> filled at stop" % setup_f.stop)
print("Close 1.08260 < sweep low 1.08280 -> sweep-then-continue 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 (deep sweep rejected as a breakout)")
print("=" * 66)
lv_a = find_levels(ambig)[0]
assert find_sweep_setup(ambig, lv_a) is None
cf = collect_sweep_results(ambig, max_pen_atr=10.0)
s_cf, r_cf = cf[0]
print("Deep sweep B25a: low 1.08220 pierces the level by %.1f pips"
% pips(s_cf.penetration))
print("Max penetration = 0.50 x %.2f = %.1f pips -> %.1f > %.1f: breakout, level dead"
% (pips(s_cf.atr), pips(0.50 * s_cf.atr), pips(s_cf.penetration), pips(0.50 * s_cf.atr)))
print("Counterfactual (cap disabled): entry %.5f, stop %.5f, risk %.2f pips"
% (s_cf.entry, s_cf.stop, pips(s_cf.risk)))
print("Counterfactual result: %s; realized %.2fR"
% (r_cf.outcome, r_cf.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("%-12s" % "max_pen_atr", end="")
for b in (0.10, 0.15, 0.25):
print("buffer=%.2f " % b, end="")
print()
best = (None, -999.0)
for mp in (0.35, 0.50, 0.75):
print("%-12.2f" % mp, end="")
for bm in (0.10, 0.15, 0.25):
m = metrics(run_sweep_strategy(train, max_pen_atr=mp, buffer_mult=bm))
e = m.get("expectancy_r", 0.0)
if e > best[1]:
best = ((mp, bm), e)
print("%9.3f " % e, end="")
print()
chosen = best[0] if best[0] else (0.50, 0.15)
print("Chosen on train: max_pen_atr=%.2f buffer=%.2f" % chosen)
for name, seg in (("validation", val), ("test", test)):
m = metrics(run_sweep_strategy(seg, max_pen_atr=chosen[0], buffer_mult=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("\nTouch-count hypothesis test (whole sample, chosen config):")
pairs = collect_sweep_results(bars, max_pen_atr=chosen[0], buffer_mult=chosen[1])
two = metrics([res for (s, res) in pairs if s.level.touches == 2])
three = metrics([res for (s, res) in pairs if s.level.touches >= 3])
print("2-touch levels : n=%d expectancy=%.3fR" % (two["n"], two.get("expectancy_r", 0.0)))
print("3+-touch levels: n=%d expectancy=%.3fR" % (three["n"], three.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 Sweep Trading
The intent narrative. "They hunted my stops" is the most expensive sentence in retail trading, because it converts a mechanical failure into a grievance — and grievances do not produce rule changes. The sweep either reclaimed within the window or it did not; the position either respected the stop or it did not. Trade the observables.
No penetration bounds. Without the floor, a one-tick pierce becomes a "sweep" and every touch of every level produces a setup. Without the cap, a full breakout becomes a "sweep that hasn't reclaimed yet," and the trader holds through the continuation that the cap exists to avoid. The band 0.10–0.50 × ATR is the entire difference between the concept and its caricature.
Chasing every equal low. Equal lows are everywhere; most are noise. The clustering tolerance (0.10 × ATR), the confirmation delay (no repainting), and the touch count together decide which clusters are levels worth watching. Traders who mark every double-bottom on the chart end up with a level every twenty bars and a sample that describes nothing.
Reclaim amnesia. A sweep without a reclaim inside the window is not "still pending" — it is a break in progress. Extending the window until the reclaim arrives is how a 2-bar rule becomes an infinite one, and how every breakout gets retroactively relabeled a sweep.
Forgetting the order-book limit. The mechanism (stops beyond obvious levels) is real; the visibility is not. Every claim beyond "price tested a level with resting orders near it and reclaimed" is inference. Rules that acknowledge this limit stay conservative; rules that pretend to see the book drift into conviction trades.
Ignoring the bimodal outcome distribution. Sweep trades tend to resolve quickly — reclaim and run, or fail through the sweep low. Averages hide this; the distribution does not. Log the outcomes per trade, not just the monthly P&L, because a strategy whose edge depends on the runner tail needs the tail monitored explicitly.
13. FAQ
What is a liquidity sweep in this rule set?
A cluster of equal lows (≥2 confirmed pivot lows within 0.10×ATR) pierced by 0.10–0.50×ATR and reclaimed by a close at or above the level within 2 bars. Deeper than the cap is a breakout, not a sweep.
Do sweeps prove institutions are hunting stops?
No. The documented mechanism is that stop orders cluster just beyond obvious levels — a statement about where orders rest, not about intent. The rules use the observable part: level, penetration, reclaim.
Why cap the penetration depth?
A shallow pierce tests a level; a deep break trades through it. Case 3: an 8.0-pip pierce against a 6.2-pip cap is classified as a breakout and skipped — counterfactual +1.32R (vs +1.93R for the valid case's shallower sweep, partly because the deeper sweep forces a 19.00-pip stop). A measured trade-off.
What is the reclaim window?
A close at or above the level within 2 bars of the sweep. Worked case: reclaim on the sweep bar itself. No reclaim in the window = breakout in progress; the rule set stands aside.
Where does the stop go?
Below the lowest low from sweep bar through trigger, minus max(2 pips, 0.15×ATR14): 1.08260 vs entry 1.08390 (13.00 pips). The sweep low is the event that must hold.
Are levels with more touches better?
That is the article's hypothesis: 3+-touch levels should reclaim more often than 2-touch levels. The harness buckets by touch count and reports both distributions — on synthetic data the buckets are nearly empty (2-touch n=0, 3+-touch n=2 at +0.56R), which proves the machinery and nothing else. Your data answers the question.
Continue the Series
- Pullback Trading Strategy — The Complete Guide (pillar)
- Fibonacci Pullback Strategy — Exact Rules and Three Worked Cases
- Order Block Pullback Entry — Displacement Thresholds
- Fair Value Gap Pullback — 3-Candle Rules and Fill Math
- Trendline Pullback Trading — Pivot-Fit Algorithm
- VWAP Pullback Strategy — Session Math and the Extension Gate
- Pivot Point Pullback — All Four Formula Families
- All Pullback Guides
Trade Structure With Live Tools
Zones, structure breaks and liquidity levels across 50+ symbols — the concepts in this series, computed live on your charts.
Go from article to implementation
Read the proof, then test the idea with calculators, free tools, case studies and a fixed-price build path.
Go deeper before you build, download or automate
Hand-picked engineering articles, indicator breakdowns and trading-system tools so visitors keep exploring instead of leaving after one page.
Pine Script to MT4/MT5 Conversion Planner
Analyze Pine strategies, repainting risk, TradingView alert bridges, MTF synchronization and the correct MQL4/MQL5 build path before paying for conversion.
Open planner
3-in-1 MT5 Indicator Bundle
12H Bias Engine, Smart Money Institutional Flow Dashboard and D1/H1 pending-signal logic with MQ5 + EX5 source included via Etsy.
MT5 Bank Orders Institutional Flow Dashboard
Supply/demand zones, BOS/CHoCH, liquidity levels, FVG, equal highs/lows and confirmed trade-plan logic explained with EX5 download.
MT5 Asia London NY Liquidity Engine
Asia range, London raid and New York continuation/reversal planning with internal session backtest stats and entry/SL/TP dashboard.
Interactive Brokers RSI Pair Trader
Tkinter desktop trading workflow, TWS API connection handling, RSI pair logic, risk controls and custom IBKR development positioning.
XAUUSD M30 CSV Data For Backtesting
Use clean MT5 historical data for Python backtests, strategy validation, spread checks and realistic gold EA research workflows.