Build a Custom Breaker Block Detector on TradingView
Table of Contents
- Introduction
- What Is Breaker Block Detection
- Why Breaker Block Detection Matters for Traders and Investors
- Core Concepts
- Step‑by‑Step Guide
- Practical Tips for Better Results
- Common Mistakes to Avoid
- Frequently Asked Questions
- Conclusion
Introduction
How you build a breaker block detector sits at the center of this guide, and mastering it reshapes the way traders read price action.
Last week the EUR/USD 4‑hour chart slipped below a tight range, then surged 80 pips after a bullish breakout. Swing traders who relied on generic moving‑average crossovers missed the move entirely. The oversight was not a misread of direction; it was a failure to spot a classic breaker block—a rectangle that captures a supply‑demand imbalance and often precedes a strong reversal.
If you depend on built‑in “breakout” alerts, you may be blind to these high‑probability zones. Writing a custom detector in Pine Script gives you control over swing‑high/low criteria, the hierarchy of timeframes, and the exact moment an alert fires.
In the pages that follow we walk through the logic, the code, the testing methodology, and the deployment steps needed to turn a vague price‑action pattern into a repeatable entry rule on TradingView.
What Is Breaker Block Detection?
Breaker block detection is the systematic identification of price zones where a prior swing high (bearish block) or swing low (bullish block) is retested and then broken, signaling a potential reversal. In plain language, a breaker block is a rectangle drawn from the extreme of a prior swing to the point where price re‑enters the market with momentum in the opposite direction.
Consider the daily chart of SPY, the S&P 500 ETF. After a three‑day pullback, price broke the prior swing high, closed below it, and then rallied back into the zone. The rectangle formed between the swing high and the subsequent low acted as a clear short‑entry signal for traders watching the 400‑day moving average.
The detection algorithm translates that visual cue into a set of Boolean conditions that a script can evaluate on each bar.
Why Breaker Block Detection Matters for Traders and Investors
Professional floor traders at the CME and algorithmic desks at hedge funds routinely scan for supply‑demand imbalances. A breaker block is a concrete representation of that imbalance. Retail traders who incorporate the detector can:
* Align entries with market microstructure, reducing reliance on lagging indicators.
* Generate alerts tied to a specific price level, sharpening order‑placement precision.
* Backtest a rule‑based entry/exit framework across multiple assets—forex pairs, equity ETFs, or futures—while respecting a single definition of a breakout.
Ignoring breaker blocks can lead to false breakouts, wider spreads, or missed risk‑to‑reward opportunities that the block naturally defines.
Identifying Bullish and Bearish Breaker Blocks — mechanism explained
A bullish breaker block forms after a downtrend when price creates a lower swing low, then rallies and breaks above the prior swing high. The block is the range between that swing low and the breakout high. Conversely, a bearish block follows an uptrend, with a higher swing high that is later broken lower.
Concrete scenario: On the 4‑hour EUR/USD chart the price makes three consecutive lower lows at 1.0800, 1.0775, and 1.0750. The next candle closes above 1.0800, finishing at 1.0815. The script marks the range 1.0750‑1.0800 as a bullish breaker block. A trader can place a long entry at 1.0815 with a stop just below 1.0750, establishing a clear risk boundary.
Using Pine Script’s security, highest, and lowest functions for multi‑timeframe capture — mechanism explained
Breaker blocks gain reliability when confirmed on a higher timeframe. Pine Script’s security function lets you request the high and low of a higher‑resolution bar while staying on a lower chart. The highest function returns the maximum high over a look‑back window; the lowest function returns the minimum low.
Concrete scenario: A day trader watches the 15‑minute chart of SPY but wants to confirm a bearish block that originated on the daily chart. The script calls security with the daily resolution, extracts the daily highest high of the last five bars, and compares it to the current 15‑minute low. If the 15‑minute low breaches that daily high, the detector flags a bearish block on the intraday chart, aligning a short‑term entry with a higher‑timeframe supply zone.
Creating dynamic alerts and visual cues with alertcondition and plotshape — mechanism explained
Once a block is identified, the script must inform the trader without constant visual scanning. Pine Script’s alertcondition creates a custom alert that can be sent to email, phone, or webhook. plotshape draws a triangle or square on the chart at the breakout bar, making the block instantly recognizable.
Concrete scenario: After the EUR/USD bullish block is plotted, the script triggers an alertcondition named “Bullish Breaker Block”. The trader receives a push notification on their phone at the exact moment the breakout candle closes, allowing immediate order execution before the price moves away.
Core Concepts
Breaker block detection rests on three pillars: swing identification, multi‑timeframe confirmation, and risk‑management overlay.
* Swing identification relies on a look‑back window of three to five bars. The script records the highest high and lowest low within that window, then checks whether the current close breaches those extremes.
* Multi‑timeframe confirmation uses security to pull swing data from a higher resolution—daily, weekly, or even monthly—while the chart displays a lower resolution. This hierarchy filters out noise that often plagues single‑timeframe approaches.
* Risk‑management overlay adds a horizontal line at the opposite edge of the block, providing a natural stop level. A target line can be set as a fixed percentage of the block’s height or as a multiple of the risk amount, giving traders a quick visual of the risk‑reward ratio.
Understanding how these elements interact is essential before writing a single line of code.
Step‑by‑Step Guide
## Step 1 — Define swing‑high and swing‑low criteria
Begin by setting the look‑back length for swing identification, typically three to five bars. Use the highest function to capture the maximum high over that window and the lowest function for the minimum low. Store these values in variables called swingHigh and swingLow.
pinescript
lookBack = 5
swingHigh = ta.highest(high, lookBack)
swingLow = ta.lowest(low, lookBack)
Step 2 — Detect breakout and block formation across timeframes
lookBack = 5
swingHigh = ta.highest(high, lookBack)
swingLow = ta.lowest(low, lookBack)
Call the security function to fetch swingHigh and swingLow from the chosen higher timeframe (for example, daily while charting 4‑hour). Compare the current bar’s close to those values:
* For a bullish block, the close must rise above swingHigh after a series of lower lows.
* For a bearish block, the close must fall below swingLow after a series of higher highs.
When the condition is met, assign the block’s top and bottom to variables blockTop and blockBottom.
pinescript
[htSwingHigh, htSwingLow] = request.security(syminfo.tickerid, "D", [swingHigh, swingLow])
bullish = close > htSwingHigh and low[1] < low[2] and low[2] < low[3]
bearish = close < htSwingLow and high[1] > high[2] and high[2] > high[3]
blockTop = bullish ? close : bearish ? htSwingLow : na
blockBottom= bullish ? htSwingLow : bearish ? close : na
Step 3 — Plot the block and generate alerts
Use plotshape to draw a visual marker at the breakout bar: a green upward‑pointing triangle for bullish blocks, a red downward‑pointing triangle for bearish blocks. Then create two alertcondition statements—one for each block type—so TradingView can fire a real‑time notification.
pinescript
plotshape(bullish, style=shape.triangleup, location=location.abovebar, color=color.green, size=size.small, title="Bullish Block")
plotshape(bearish, style=shape.triangledown, location=location.belowbar, color=color.red, size=size.small, title="Bearish Block")
alertcondition(bullish, title="Bullish Breaker Block", message="Bullish breaker block formed")
alertcondition(bearish, title="Bearish Breaker Block", message="Bearish breaker block formed")
Step 4 — Add risk‑management overlays
Overlay a horizontal line at blockBottom for bullish blocks (the stop level) and at blockTop for bearish blocks. Optionally, plot a target line based on a fixed percentage—say 1.5 × the block’s height—or a risk‑adjusted multiple.
pinescript
stopLine = bullish ? blockBottom : bearish ? blockTop : na
targetLine = stopLine + (blockTop - blockBottom) * (bullish ? 1.5 : -1.5)
hline(stopLine, "Stop", color=color.gray, linestyle=hline.style_dotted)
hline(targetLine, "Target", color=color.blue, linestyle=hline.style_dashed)
Step 5 — Backtest the detector on historical data
Switch the chart to “Bar Replay” mode or use TradingView’s strategy tester. Write a simple strategy that enters on the alertcondition trigger, sets the stop at the opposite block edge, and exits at the target line or on a trailing stop. Review the equity curve, maximum drawdown, and win‑rate. Adjust the swing‑look‑back or the higher‑timeframe resolution if the backtest shows over‑fitting.
Key metrics to watch include:
* Profit factor – total gross profit divided by total gross loss.
* Sharpe ratio – excess return over the risk‑free rate, adjusted for volatility.
* Maximum adverse excursion – the deepest drawdown a trade experiences before hitting the stop.
If the profit factor stays above 1.5 and the Sharpe ratio exceeds 1.2 across at least three asset classes, the detector is likely robust enough for live use.
Step 6 — Deploy to live monitoring
Save the script as a public or private indicator, add it to your watchlist, and enable the alert with the “Once per bar close” option to avoid premature signals. Monitor the alerts during live sessions, and keep a journal of each trade to refine the parameters over time.
A disciplined journal should capture: entry time, entry price, stop level, target, actual exit price, and the reason the trade was taken (breaker block confirmation, volume spike, etc.). Over weeks, patterns will emerge that reveal whether the detector needs a tighter look‑back window or a different higher‑timeframe reference.
Practical Tips for Better Results
- Choose a higher‑timeframe that sits at least two steps above your trading chart; a 15‑minute trader benefits from a 4‑hour reference, while a daily swing trader may look to the weekly chart.
- Filter out low‑liquidity periods—avoid generating alerts during thin Asian forex sessions when spreads widen dramatically. The EUR/USD spread can jump from 1 pip to 3 pips during those hours, eroding the block’s edge.
- Combine the breaker block with a volume spike filter; a breakout on above‑average volume adds confirmation. On equities, a surge in the NYSE’s NYSE‑TR volume exceeding the 20‑day average by 30 % often validates the block.
- Set the alert’s expiration to the end of the current session to prevent stale signals from lingering overnight. An alert that fires at 23:55 GMT may be irrelevant once the New York open begins.
- When backtesting, incorporate realistic slippage: assume a half‑tick spread on equities and a 2‑pip slippage on major forex pairs. Ignoring slippage inflates win‑rate and masks true performance.
- Keep the look‑back window dynamic: increase it during low‑volatility regimes (for example, when the CBOE VIX sits below 15) to avoid false blocks that arise from minor price jitter.
- Use the built‑in
sessionfunction to disable the detector during major news releases that can invalidate price‑action patterns. A Federal Reserve rate decision, for instance, can cause price to swing 100 pips in seconds, rendering any block meaningless.
Common Mistakes to Avoid
- Hard‑coding a single timeframe – locks the detector to one market condition and reduces adaptability.
- Ignoring spread and slippage – leads to backtest results that look better than live performance.
- Triggering alerts on every breakout – creates noise; filter with a minimum price‑movement threshold, such as a 0.5 % move beyond the block edge.
- Setting stops exactly at the block edge – can be breached by market microstructure; add a buffer of one tick or pip to protect against whipsaws.
- Over‑optimizing swing length – produces curve‑fitting; stick to a range of 3‑5 bars and test across assets.
How do I code a breaker block detector in Pine Script?
Start by defining swing‑high and swing‑low using the
highestandlowestfunctions over a chosen look‑back. Pull those values from a higher timeframe with thesecurityfunction, then compare the current close to the fetched extremes. Plot the block withplotshapeand fire alerts usingalertcondition.What is a breaker block in TradingView?
A breaker block on TradingView is a visual rectangle that marks the price range between a prior swing extreme and the breakout level that reverses the prior trend. It appears as a colored shape on the chart and can be linked to custom alerts for real‑time monitoring.
Why use a custom breaker block detector instead of built‑in indicators?
Built‑in indicators often rely on lagging moving averages or generic volatility bands, which do not capture the precise supply‑demand zones that breaker blocks represent. A custom detector lets you define exact swing criteria, multi‑timeframe confirmation, and alert logic tailored to your trading style.
When should I trigger an alert on a breaker block?
Trigger the alert at the close of the breakout candle that confirms the block, not on the intrabar high or low. This reduces false signals caused by temporary spikes and aligns the alert with the point where a trader can safely place an order.
Can I backtest a breaker block strategy on TradingView?
Yes. Convert the detector into a strategy script, add entry and exit rules, and run the built‑in strategy tester. Remember to model realistic commissions, slippage, and spread, especially for forex pairs like EUR/USD or equity ETFs such as SPY.
Is a breaker block reliable for day trading?
Reliability improves when the block is confirmed on a higher timeframe and when volume or order‑flow data supports the breakout. In fast‑moving markets, such as during Federal Reserve announcements, liquidity can evaporate, making any breakout—including breaker blocks—riskier.
Conclusion
The single most valuable lesson is that a well‑coded breaker block detector turns a vague price‑action pattern into a concrete entry rule with defined risk. Your next step is to copy the script skeleton, adjust the swing‑look‑back and higher‑timeframe to match the asset you trade, and run a short backtest on the last three months of data.
Remember, no detector guarantees success. Size positions so that a single block loss does not exceed 1‑2 % of your account, and be prepared for false breakouts during low‑liquidity periods. Trade responsibly.
—
This article is for educational purposes only and does not constitute investment advice. Trading and investing carry risk of loss; never invest more than you can afford to lose.
Last reviewed August 2026
Last reviewed: August 2026