Strategy · Pine Script v5 · On the chart

Breakout Strategy

by Web3Degenerate

This strategy detects price breakouts beyond the high or low of a higher timeframe (default Daily) on an intraday chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code89
Settings4inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

89 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/6.Breakout-Strategy-Example.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

6.Breakout-Strategy-Example.pine
//Updated June 2023 to comply with https://www.tradingview.com/pine-script-docs/en/v5/concepts/Repainting.html#repainting-request-security-calls



// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
strategy(title="Breakout Strategy", overlay=true, currency="USD")

// Import ZenLibrary
import ZenAndTheArtOfTrading/ZenLibrary/5 as zen

// Get user input
res = input.timeframe(title="Timeframe", defval="D")
rr = input.float(title="Risk:Reward", defval=1.0)
stopMultiplier = input.float(title="Stop Multiplier", defval=1.0)
lookback = input.int(title="Stop Lookback", defval=1)

// Get highs and lows
dailyHigh = request.security(syminfo.tickerid, res, high[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]
dailyLow  = request.security(syminfo.tickerid, res, low[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]

// Detect unique breakout for today
var bullishBreakoutToday = false
var bearishBreakoutToday = false
newDay = ta.change(time("D"))
if newDay
    bullishBreakoutToday := false
    bearishBreakoutToday := false

// Get ATR
atr = ta.atr(14)

// Check for breakouts
bullishBO = close > dailyHigh and close[1] <= dailyHigh and not bullishBreakoutToday and not na(atr) and strategy.position_size == 0
bearishBO = close < dailyLow and close[1] >= dailyLow and not bearishBreakoutToday and not na(atr) and strategy.position_size == 0

// Get stops & targets
longStop  = ta.lowest(low, lookback) - (atr * stopMultiplier)
shortStop = ta.highest(high, lookback) + (atr * stopMultiplier)
longStopDist  = close - longStop
shortStopDist = shortStop - close
longTarget  = close + (longStopDist * rr)
shortTarget = close - (shortStopDist * rr)

// Save stop & target
var float t_stop = na
var float t_target = na

// If bullish breakout detected today, disable any future signals for today
if bullishBO
    bullishBreakoutToday := true
    t_stop := longStop
    t_target := longTarget
    stopLabelText = str.tostring(longStopDist / syminfo.mintick / 10, "#.#")
    strategy.entry(id="Long", direction=strategy.long, comment="Long (SL=" + stopLabelText + " pips)")

// If bearish breakout detected today, disable any future signals for today
if bearishBO
    bearishBreakoutToday := true
    t_stop := shortStop
    t_target := shortTarget
    stopLabelText = str.tostring(shortStopDist / syminfo.mintick / 10, "#.#")
    strategy.entry(id="Short", direction=strategy.short, comment="Short (SL=" + stopLabelText + " pips)")

// Check long stops & targets being hit
strategy.exit(id="Long Exit",
     from_entry="Long",
     limit=t_target,
     stop=t_stop,
     comment="Long Exit (Equity: " + str.tostring(strategy.equity, "###,###,###") + ")")

// Check short stops & targets being hit
strategy.exit(id="Short Exit",
     from_entry="Short",
     limit=t_target,
     stop=t_stop,
     comment="Short Exit (Equity: " + str.tostring(strategy.equity, "###,###,###") + ")")

// Draw highs and lows to the chart
plot(dailyHigh, color=color.red, linewidth=2)
plot(dailyLow, color=color.green, linewidth=2)

// Draw signals
plotshape(bearishBO, title="Bearish Breakout", style=shape.triangledown, location=location.abovebar, color=color.red)
plotshape(bullishBO, title="Bullish Breakout", style=shape.triangleup, location=location.belowbar, color=color.green)

// Draw stops & targets
plot(strategy.position_size != 0 ? t_stop : na, color=color.red, style=plot.style_linebr, title="Trade Stop")
plot(strategy.position_size != 0 ? t_target : na, color=color.green, style=plot.style_linebr, title="Trade Target")

Overview

When the close crosses above the higher-timeframe high or below its low, it enters long or short, limiting execution to one breakout per direction each day. Stop losses are calculated using swing extremes adjusted by an ATR multiplier, while profit targets are derived via a configurable risk-to-reward ratio. It overlays the breakout levels, trade signals, stop loss, and target levels directly on the price chart.

Details

Published by

Web3Degenerate on GitHub

Draws

On the price chart

Markets

Forex, Gold, Crypto, Stocks, Indices, Oil & commodities

Timeframes

M1-M5, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
TimeframetimeframeDres
Risk:Rewardfloat1.0rr
Stop Multiplierfloat1.0stopMultiplier
Stop Lookbackint1lookback
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 7 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint
16 stars

This strategy trades Donchian breakouts measured on weekly bars while orders execute on the chart timeframe. It allows long and short entries when price breaks the prior weekly channel and exits against the shorter weekly channel. Position size risks a set per

Strategy v6 TrendBreakout
Updated 12 months ago · None stated GitHub repository of Seykota Alt 4: Weekly Donchian
11 stars

Calculates upper and lower Donchian Channel bands over a customizable lookback length and plots them on the main price chart. At a specified exchange hour, the strategy places a long buy stop order at the upper Donchian Channel level. Unfilled pending orders a

Strategy v6 BreakoutSupport & resistance
Updated 5 months ago · Apache-2.0 GitHub repository of Estrategia Donchian Breakout
6 stars

This overlay strategy builds independent timed session ranges and marks range, trendline, mean, VWAP, and high-low levels when those displays are enabled. It enters on range breakouts and exits with strategy exits, choosing among range, ATR, fixed-point, and r

Strategy v5 Sessions & timeBreakout
Updated 7 months ago · None stated GitHub repository of MSG Enhanced LEGO System Strategy
3 stars

Donchian Channel Breakout is a Pine Script v5 strategy drawn on the price chart. It enters long when close crosses above the previous upper Donchian band and short when close crosses below the previous lower band, reversing with the opposite signal. An ATR tra

Strategy v5 BreakoutVolatility & bands
Updated 7 months ago · MIT GitHub repository of Donchian Channel Breakout

The Range Percent Breakout Strategy identifies range contraction and inside bar patterns where the current bar's range is within a specified percentage threshold of the previous bar. When this condition is met while flat, breakout levels are established above

Strategy v5 BreakoutVolatility & bands
Updated 5 months ago · None stated GitHub repository of Range Percent Breakout Strategy

More Breakout scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers