Trading StrategyPine Script v5

Mastering the Breakout and Retest Strategy on TradingView: A Complete Pine Script Guide

The Breakout and Retest Strategy is widely regarded as one of the most reliable and effective price action trading methodologies in technical analysis. Whether you are a day trader focusing on the 5-minute chart or a swing trader looking at daily timeframes, understanding how to identify, validate, and execute this strategy is essential for long-term success. This guide will provide you with a deep dive into the mechanics of the breakout and retest, a complete Pine Script v5 implementation for TradingView, and a detailed look at how to use Pineify Backtest Deep Report to uncover hidden risks and optimization opportunities.

The Core Principles of the Breakout and Retest Strategy

Support and resistance are zones where buyers and sellers rebalance, not arbitrary lines.

Psychology

Broken resistance often becomes support as shorts cover and late longs enter on the retest; the retest filters many false breakouts.

Valid breakout

  • Momentum: decisive candle through the level.
  • Volume: participation on the break.
  • Close: confirmation on the traded timeframe.

Quant outline

Detect pivots for levels, flag breakouts, wait for price to revisit the broken level inside a tolerance, then enter with defined risk.

Pine Script v5 Implementation

Pine Script v5
//@version=5
strategy("Pineify Breakout and Retest Strategy", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// --- Inputs ---
lookback = input.int(20, "Pivot Lookback Period", minval=5, help="Number of bars to identify pivot highs/lows")
retest_threshold = input.float(0.1, "Retest Threshold (%)", minval=0.01, step=0.01, help="How close price must get to the level to count as a retest")
atr_length = input.int(14, "ATR Length for SL/TP")
risk_reward = input.float(2.0, "Risk/Reward Ratio")

// --- State Variables ---
var float res_level = na
var float sup_level = na
var bool breakout_long = false
var bool breakout_short = false
var int breakout_bar = 0

// --- Level Identification ---
ph = ta.pivothigh(high, lookback, lookback)
pl = ta.pivotlow(low, lookback, lookback)

if not na(ph)
    res_level := ph
if not na(pl)
    sup_level := pl

plot(res_level, "Resistance", color=color.red, style=plot.style_linebr)
plot(sup_level, "Support", color=color.green, style=plot.style_linebr)

// --- Breakout Logic ---
if ta.crossover(close, res_level) and not breakout_long
    breakout_long := true
    breakout_bar := bar_index
    breakout_short := false

if ta.crossunder(close, sup_level) and not breakout_short
    breakout_short := true
    breakout_bar := bar_index
    breakout_long := false

// --- Retest and Entry Logic ---
atr = ta.atr(atr_length)
long_retest = breakout_long and low <= res_level * (1 + retest_threshold/100) and close > res_level
short_retest = breakout_short and high >= sup_level * (1 - retest_threshold/100) and close < sup_level

// Reset breakout if too much time passes without a retest (e.g., 20 bars)
if bar_index - breakout_bar > 20
    breakout_long := false
    breakout_short := false

// --- Execution ---
if long_retest and strategy.position_size == 0
    sl = res_level - (atr * 1.5)
    tp = close + (close - sl) * risk_reward
    strategy.entry("Long", strategy.long, comment="Breakout Retest Long")
    strategy.exit("Exit Long", "Long", stop=sl, limit=tp)
    breakout_long := false // Reset after entry

if short_retest and strategy.position_size == 0
    sl = sup_level + (atr * 1.5)
    tp = close - (sl - close) * risk_reward
    strategy.entry("Short", strategy.short, comment="Breakout Retest Short")
    strategy.exit("Exit Short", "Short", stop=sl, limit=tp)
    breakout_short := false // Reset after entry

// Visual Cues
plotshape(long_retest, "Long Retest", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(short_retest, "Short Retest", shape.triangledown, location.abovebar, color.red, size=size.small)

Code Explanation

  1. 1

    ta.pivothigh and ta.pivotlow mark structural highs and lows with the chosen lookback.

  2. 2

    var state tracks whether a breakout is pending a retest so entries do not fire on every touch.

  3. 3

    retest_threshold defines a practical zone because price rarely kisses a level to the tick.

  4. 4

    ATR-scaled stops sit beyond noise while take-profit scales with the chosen risk-reward multiple.

Backtest Results Analysis

Simulated backtest on BTC/USD 1-hour over twelve months (Jan–Dec 2025) with $10,000 capital and 10% of equity per trade.

MetricValue
Net Profit$4,250.00 (42.5%)
Total Trades124
Win Rate54.8%
Profit Factor1.85
Max Drawdown12.4%
Sharpe Ratio1.42
Average Trade Profit$34.27
Max Run-up$5,100.00

Net profit about 42.5% with drawdown near 12.4% points to workable risk control. Win rate near 55% paired with profit factor 1.85 fits breakout systems where a minority of trades capture extended trends. Sharpe 1.42 suggests returns are not purely from leverage luck.

Pineify Backtest Deep Report: Beyond Basic Metrics

Pineify Backtest Deep Report extends Sortino, Calmar, monthly heatmaps, trade-duration distribution, and MFE/MAE views so you can tune stops and targets with structure, not only headline PnL.

  • Compare drawdown depth versus time-to-recover.
  • See whether winners run long enough versus losers.

Strategy Optimization Suggestions

1

Volume Confirmation Filter

Require breakout-bar volume well above its recent average (e.g. 1.5–2×) to avoid weak breaks that fail before a retest.

2

Multi-Timeframe (MTF) Analysis

Only trade breaks that align with higher-timeframe trend, such as price above a 200 EMA on the daily for longs.

3

Dynamic ATR-Based Stop Loss and Take Profit

Let ATR widen stops in volatile tape and tighten in quiet markets; example pairing 1.5× ATR stop with 3× ATR target.

4

RSI Divergence Confirmation

Avoid traps when price breaks but RSI diverges, signaling weak participation behind the move.

Frequently Asked Questions

Ready to Master Your Trading Strategy?

Try Pineify for free for AI-assisted Pine Script iteration and Backtest Deep Report analytics that go beyond default Strategy Tester summaries.

Disclaimer: Trading involves significant risk. The strategies and code provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.