---
title: Trendline Breakout Strategy
slug: trendline-breakout-strategy
date: 2025-12-11
modified: 2026-08-27
author: PickMyTrade
excerpt: ""
meta_description: "Our trendline breakout strategy turns an open-source Pine Script into a fully automated, risk-managed TradingView system, with real backtest results."
focus_keyword: trendline breakout strategy
canonical_url: "https://blog.pickmytrade.trade/trendline-breakout-strategy/"
og_title: Trendline Breakout Strategy
og_description: "Our trendline breakout strategy turns an open-source Pine Script into a fully automated, risk-managed TradingView system, with real backtest results."
og_image: "https://blog.pickmytrade.trade/wp-content/uploads/2025/12/20251211_1457_Fintech-Trading-Innovation_simple_compose_01kc6bpksde06stbenb5kcqr0c-1024x683.avif"
schema_type: Article
categories:
  - algorithm trading
  - Automated Trading
tags:
  - Trading
  - Trading Strategies
  - TradingView
reading_time: 15
word_count: 3587
robots: "index, follow"
lang: en-US
---

# Trendline Breakout Strategy: How We Turned an Open-Source Trend Script into a Professional Long-Only System

If you like clean price action, you’re going to like this one.

Table of Contents

1. [From Trendline Indicator to Complete Strategy](https://blog.pickmytrade.trade/#from-trendline-indicator-to-complete-strategy)
2. [Original Idea (by @crazyrabbitheart)](https://blog.pickmytrade.trade/#original-idea-by-crazyrabbitheart)
3. [What We Added](https://blog.pickmytrade.trade/#what-we-added)
4. [Understanding Profit Factor (Again)](https://blog.pickmytrade.trade/#understanding-profit-factor-again)
5. [Backtest Results: Stocks, Crypto, Forex &amp; Futures](https://blog.pickmytrade.trade/#backtest-results-stocks-crypto-forex-futures)
6. [AAPL – 5 Minute (NASDAQ)](https://blog.pickmytrade.trade/#aapl-5-minute-nasdaq)
7. [SOLUSDT – 1 Hour (Binance)](https://blog.pickmytrade.trade/#solusdt-1-hour-binance)
8. [EURUSD – 15 Minute (Tickmill)](https://blog.pickmytrade.trade/#eurusd-15-minute-tickmill)
9. [MNQ – 5 Minute (Micro Nasdaq Futures, CME)](https://blog.pickmytrade.trade/#mnq-5-minute-micro-nasdaq-futures-cme)
10. [Key Takeaways from the Tests](https://blog.pickmytrade.trade/#key-takeaways-from-the-tests)
11. [How the Trendline Strategy Actually Works](https://blog.pickmytrade.trade/#how-the-trendline-strategy-actually-works)
12. [1. Pivot Detection &amp; Trendline Building](https://blog.pickmytrade.trade/#1-pivot-detection-trendline-building)
13. [2. Entry: Breakout Above a Valid Trendline](https://blog.pickmytrade.trade/#2-entry-breakout-above-a-valid-trendline)
14. [3. Stop Loss: Pivot-Based](https://blog.pickmytrade.trade/#3-stop-loss-pivot-based)
15. [4. Position Sizing: Dollar Risk Model](https://blog.pickmytrade.trade/#4-position-sizing-dollar-risk-model)
16. [5. Take Profit Options](https://blog.pickmytrade.trade/#5-take-profit-options)
17. [6. Trailing Stop (Optional)](https://blog.pickmytrade.trade/#6-trailing-stop-optional)
18. [7. Session Control](https://blog.pickmytrade.trade/#7-session-control)
19. [The Actual Strategy Code (Pine Script v5)](https://blog.pickmytrade.trade/#the-actual-strategy-code-pine-script-v5)
20. [Automate It with PickMyTrade](https://blog.pickmytrade.trade/#automate-it-with-pickmytrade)
21. [Final Thoughts &amp; Disclaimers](https://blog.pickmytrade.trade/#final-thoughts-disclaimers)
22. [You may also like:](https://blog.pickmytrade.trade/#you-may-also-like)

The **PickMyTrade Advanced Trend Following Strategy** is built on top of an excellent open-source Pine Script by **@crazyrabbitheart** that automatically draws and trades off trendlines. We took that script, wrapped it into a complete TradingView strategy, and added professional-grade risk and trade management so it’s ready for both backtesting and full automation.

Just like in our MACD + ADX post, the idea is simple:

&gt; An indicator shows you what _might_ be a trade.  
&gt; A strategy decides **when to enter, how much to risk, where to exit, and when to stand aside.**

In this post we’ll walk through:

- How the trendline breakout logic actually works
- The risk and position-sizing engine we added
- Real backtest performance across **stocks, crypto, forex, and futures**
- How to automate everything with **PickMyTrade**

## From Trendline Indicator to Complete Strategy {#from-trendline-indicator-to-complete-strategy}

### Original Idea (by @crazyrabbitheart) {#original-idea-by-crazyrabbitheart}

The original script focuses on one thing and does it very well:

- Automatically detecting **downtrend resistance lines**
- Validating them using multiple touches
- Entering long when price **breaks above** that trendline

It’s pure price action – no oscillators, no lagging filters. Great for visual discretionary trading and semi-automated entries.

### What We Added {#what-we-added}

We turned it into a full TradingView **strategy** with automation-grade features:

**Trend &amp; Entry Logic (core kept from original)**

- Automatic detection of downtrend lines using pivot highs
- Configurable **pivot length** for trend detection
- **Touch count** requirement (e.g., 3 touches) to validate the trendline
- Optional extra pivot validation for stricter trendlines
- Session filter so the system only trades during specific hours

**Risk &amp; Position Management (our enhancements)**

- Fixed **dollar-based risk per trade** (default: $100)
- Automatic **position sizing** based on stop distance
- Pivot-based stop loss with optional buffer
- Three different take-profit modes:
  - Risk/Reward ratio (e.g., 1.5R)
  - Lookback-based exits
  - Fibonacci extension targets (multi-level scaling)
- Optional trailing stop using new pivot lows
- Multi-trend mode so it can track and trade multiple simultaneous breakouts

With that, you get a pure price-action strategy that:

- Only buys **strong, confirmed breakouts**
- Sizes each trade based on risk, not emotion
- Handles exits mechanically from start to finish

## Understanding Profit Factor (Again) {#understanding-profit-factor-again}

Just like in the MACD article, one of the key metrics here is **Profit Factor**:

&gt; **Profit Factor = Gross Profit ÷ Gross Loss**

- PF &gt; 1.0 → profitable
- PF &gt; 1.5 → solid
- PF &gt; 2.0 → excellent

In a trend strategy like this, we care less about being right on every trade and more about:

- Cutting losers at logical pivots
- Letting winners run into clean trend legs

So Profit Factor and average R:R tell us more than raw win rate.

## Backtest Results: Stocks, Crypto, Forex &amp; Futures {#backtest-results-stocks-crypto-forex-futures}

All tests use the **same default parameters** (3 touches, risk–reward 1.5R, $100 risk per trade, session 09:00–18:00 where applicable).

&gt; Numbers are from TradingView Strategy Tester using the script below.

### AAPL – 5 Minute (NASDAQ) {#aapl-5-minute-nasdaq}

![AAPL ](https://blog.pickmytrade.trade/wp-content/uploads/2025/12/AAPL-5min-1024x497.avif)

- **Total P&amp;L:** **+$3,229.90**
- **Max Equity Drawdown:** **$869.47**
- **Total Trades:** **106**
- **Win Rate:** **50.00%** (53 / 106)
- **Profit Factor:** **1.572**

**Comment:**  
Even with very conservative dollar risk, AAPL shows a **strong profit factor and a clean equity curve**, with half the trades profitable and losers capped by pivot-based stops.

### SOLUSDT – 1 Hour (Binance) {#solusdt-1-hour-binance}

![SOLUSDT](https://blog.pickmytrade.trade/wp-content/uploads/2025/12/solusdt-1hour-1024x498.avif)

- **Total P&amp;L:** **+3,108.37 USDT**
- **Max Equity Drawdown:** **592.72 USDT**
- **Total Trades:** **118**
- **Win Rate:** **50.85%** (60 / 118)
- **Profit Factor:** **1.55**

**Comment:**  
SOL is a volatile trending crypto, and the strategy handles it nicely – profit factor stays around **1.5** with a drawdown that is small relative to total movement. Trendline breakouts really shine on coins that trend hard after consolidation.

### EURUSD – 15 Minute (Tickmill) {#eurusd-15-minute-tickmill}

![EURUSD ](https://blog.pickmytrade.trade/wp-content/uploads/2025/12/eurusd-15min-1024x517.avif)

- **Total P&amp;L:** **+1,438.57 USD**
- **Max Equity Drawdown:** **$839.54**
- **Total Trades:** **98**
- **Win Rate:** **46.94%** (46 / 98)
- **Profit Factor:** **1.263**

**Comment:**  
FX is choppier, so the win rate dips just under 50%, but the strategy is still comfortably profitable. This is where **touch count and session filtering** help filter noisy London/NY overlaps.

### MNQ – 5 Minute (Micro Nasdaq Futures, CME) {#mnq-5-minute-micro-nasdaq-futures-cme}

![MNQ ](https://blog.pickmytrade.trade/wp-content/uploads/2025/12/mnq-5min-1024x497.avif)

- **Total P&amp;L:** **+$189.00 USD**
- **Max Equity Drawdown:** **$443.00**
- **Total Trades:** **35**
- **Win Rate:** **42.86%** (15 / 35)
- **Profit Factor:** **1.106**

**Comment:**  
Short test window and a volatile index future, yet still positive with PF &gt; 1.0. Tightening parameters (higher touch count, enabling extra pivot validation) usually improves PF here.

## Key Takeaways from the Tests {#key-takeaways-from-the-tests}

1. **Consistent Profit Factor Across Markets**  
Stocks, crypto, FX, and futures all show **PF &gt; 1.1**, with the best performers (AAPL &amp; SOL) around **1.55–1.57** using the same default settings.
2. **You Don’t Need a Huge Win Rate**  
Win rates hover around **45–51%**, yet the strategies remain profitable. The edge comes from **logical stops + asymmetric targets**, not trying to be right all the time.
3. **Trend Markets Reward the Strategy Most**  
SOLUSDT and AAPL – both capable of strong, clean trends – deliver the best numbers. Exactly what you’d expect from a trendline breakout system.
4. **Risk Is Contained by Construction**  
Every trade starts with:
  - Pre-defined dollar risk
  - Stop loss at a structural pivot low
  - Optional buffer and trailing stop  
Drawdowns in the tests stay modest relative to the number of trades taken.
5. **One Strategy, Many Markets**  
With no indicator soup and no asset-specific config, this is a good “core” system you can apply across **stocks, crypto, FX and index futures** with only minor tuning (timeframe, touch count, session hours).

## How the Trendline Strategy Actually Works {#how-the-trendline-strategy-actually-works}

Here’s the high-level logic behind the Pine Script you shared.

### 1. Pivot Detection &amp; Trendline Building {#1-pivot-detection-trendline-building}

- The script finds **pivot highs** using a configurable length (`pivotLength`, default 15).
- When a new pivot high forms **below** the previous pivot high, it assumes a **downtrend** and draws a line between them.
- It then checks how many candles:
  - Touch or slightly pierce that line
  - Or come within a small **percentage buffer** (`valid`)

If the number of touches is ≥ `touchNum` (default 3), the line is considered a **valid downtrend resistance**.

Optional: a second pivot length (`plen`) can be used to demand an extra confirming swing between those two highs – a stricter filter for “real” trendlines.

### 2. Entry: Breakout Above a Valid Trendline {#2-entry-breakout-above-a-valid-trendline}

A **long entry** is triggered when:

- The current bar closes **above** the validated downtrend line
- The bar is within your active **session** (if the session filter is enabled)
- The maximum allowed number of open positions (`posNum`) has not been reached

In multi-trend mode, this can happen on **any** active trendline. In single-trend mode, it only tracks one main line at a time.

### 3. Stop Loss: Pivot-Based {#3-stop-loss-pivot-based}

To place the stop:

- The script searches backward through recent **pivot lows** (`plenforsl`)
- It finds the most recent low that makes sense as structural support
- Optional **offset** (`offsetForSL`) is subtracted to add a safety buffer
- The stop is never allowed above the bar’s low (basic sanity check)

This gives you **market-based** stops instead of random fixed ticks.

### 4. Position Sizing: Dollar Risk Model {#4-position-sizing-dollar-risk-model}

Once entry and stop are known:

```
Risk per trade = riskAmount   (e.g., $100)

Qty = floor( riskAmount / |Entry - Stop| / syminfo.pointvalue )
```

- If calculated size is ≤ 0 (risk too small vs. stop distance) → no trade,  
unless you enable **Default Contract Size**, in which case it forces 1 unit.

This keeps risk consistent across markets and volatility regimes.

### 5. Take Profit Options {#5-take-profit-options}

You can choose 1 of 3 TP styles:

#### a) Risk/Reward Ratio (default)

- TP = Entry + (Entry − Stop) × `riskAwardRatio` (1.5R by default)
- A simple, robust rule that works across most instruments.

#### b) Lookback-Based Exit

- No fixed TP limit – only a stop.
- The strategy closes all positions when:
  - Price makes the **lowest low (or close)** of the last `lookBackCandles` bars in a long trade.
- Great for **swing trading**, letting winners run until structure breaks.

#### c) Fibonacci Extensions

- It finds a swing high (`phFib`) above the trade and calculates:
  - 0.618, 1.0, 1.312, 1.618 extensions between that high and your stop.
- As price breaks above these levels, it marks them as **triggered**.
- When price later closes back **below the highest triggered level**, the strategy exits.

This effectively creates a **tiered TP system**, letting you hold into strong trends while still banking gains.

### 6. Trailing Stop (Optional) {#6-trailing-stop-optional}

When enabled:

- If a new pivot low (`plsl`) forms **above** your original stop level,
- And price then drops back below that pivot,
- The strategy exits the trade.

That turns newly formed higher lows into **dynamic trailing stops**.

### 7. Session Control {#7-session-control}

For intraday traders:

- You can specify a session (e.g. `"0900-1800"`)
- The strategy will:
  - Only open trades during those hours
  - Optionally **close all positions at session end**

Great if you want to avoid overnight gaps or news.

## The Actual Strategy Code (Pine Script v5) {#the-actual-strategy-code-pine-script-v5}

Here’s the complete script, including original license and credit:

```
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © crazyrabbitheart

//@version=5
strategy("[PickMyTrade] Trend strategy for Long", overlay = true, pyramiding = 1000, process_orders_on_close = true, calc_on_every_tick = true, max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500)

pivotLength = input.int(15, title = "pivot Length For Trend")
touchNum = input.int(3, title = "Touch Number")
valid = input.float(0.1, title = "valid percentage")
enablePivotToCheck = input.bool(false, title = "Enable Pivot To Valid")
plen = input.int(5, title = "pivot Length For valid")

isMulti = input.bool(true, title = "Enable Multi Trend")
posNum = input.int(1, title = "position number")

riskAmount = input.int(defval = 100, title = "Risk Amount", group = "strategy", minval = 1)
EnableContractSizeByDefault = input.bool(false, title = "Enable Default Contract Size")
setMethodForTP = input.string(defval = "RiskAwardRatio", title = "Set TP Method", options = ["RiskAwardRatio", "LookBackCandles", "Fibonacci"])
riskAwardRatio = input.float(defval = 1.5, title = "riskAwardRatio", group = "strategy", minval = 1.0)
lookBackCandles = input.int(defval = 10, title = "Look Back Candles", minval =1)
// nextCandles = input.int(1, title = "candles to check breakout")
sourceForTP = input.string(defval = "Close", title = "Source for TP", options = ["Close", "High/Low"])
enabledSL = input.bool(true, title = "Turn On/Off SL")
plenforsl = input.int(3, title = "pivot length for sl")
offsetForSL = input.float(0.0, title = "Buffer For SL", minval = 0.0)
enabledTrailing = input.bool(false, title = "Turn On/Off trailing stop")

lengthForFib = input.int(15, title = "Pivot length for Fibonacci", group = "Fibonacci")
// isFib1 = input.bool(true, title = "", group = "Fibonacci", inline = "Fibonacci1")
fibLevel1 = input.float(0.618, title = "Pivot length for Fibonacci", group = "Fibonacci", inline = "Fibonacci1")
// isFib2 = input.bool(false, title = "", group = "Fibonacci", inline = "Fibonacci2")
fibLevel2 = input.float(1, title = "Pivot length for Fibonacci", group = "Fibonacci", inline = "Fibonacci2")
// isFib3 = input.bool(false, title = "", group = "Fibonacci", inline = "Fibonacci3")
fibLevel3 = input.float(1.312, title = "Pivot length for Fibonacci", group = "Fibonacci", inline = "Fibonacci3")
// isFib4 = input.bool(false, title = "", group = "Fibonacci", inline = "Fibonacci4")
fibLevel4 = input.float(1.618, title = "Pivot length for Fibonacci", group = "Fibonacci", inline = "Fibonacci4")

enabledSession = input.bool(false, title = "", group = "Session", inline = "Session")
i_sess = input.session("0900-1800", "Session", group = "Session", inline = "Session")

t = time(timeframe.period, i_sess)
bgcolor(time == t and enabledSession ? color.new(color.white, 95) : na)

ph = ta.pivothigh(high, pivotLength, pivotLength)
pl = ta.pivotlow(low, pivotLength, pivotLength)

var phh = 0.0
var pll = 0.0

phh := na(ph) ? phh[1] : ph     //pivot high value
pll := na(pl) ? pll[1] : pl     //pivot low value

var phbar = 0
var plbar = 0

phbar := na(ph) ? phbar[1] : bar_index - pivotLength    // pivot high bar_index
plbar := na(pl) ? plbar[1] : bar_index - pivotLength    // pivot low bar_index

phbar := na(phbar) ? 0 : phbar
plbar := na(plbar) ? 0 : plbar

pph = ta.pivothigh(high, plen, plen)    // pivot high for valid
ppl = ta.pivotlow(low, plen, plen)      // pivot low for valid

var pphbar = 0
var pplbar = 0

pphbar := na(pph) ? pphbar[1] : bar_index - plen    // pivot high bar_index for valid
pplbar := na(ppl) ? pplbar[1] : bar_index - plen    // pivot low bar_index for valid

h = ta.pivothigh(high, plenforsl, plenforsl)        //pivot high for SL
l = ta.pivotlow(low, plenforsl, plenforsl)          //pivot low for SL

var phsl = 0.
var plsl = 0.

phsl := na(h) ? phsl[1] : h
plsl := na(l) ? plsl[1] : l

h := ta.pivothigh(high, lengthForFib, lengthForFib)
l := ta.pivotlow(low, lengthForFib, lengthForFib)

var phFib = 0.
var plFib = 0.

phFib := na(h) ? phFib[1] : h
plFib := na(l) ? plFib[1] : l

// ------------- Multi-trend mode -------------
if isMulti
    var line[] trendline = array.new_line()
    var int[] distance = array.new_int()
    var float[] stepY = array.new_float()
    var int[] startPointX = array.new_int()
    var float[] startPointY = array.new_float()

    if not na(ph) and phh  pricen
                n := n + 1
            else
                if (pricen - high[i]) = touchNum ? true : false

        if enablePivotToCheck
            isValidLine := isValidLine and (pphbar[bar_index - phbar]  phbar[1]) ? true : false

        if isValidLine
            array.push(trendline, line.new(phbar[1], phh[1], bar_index, y, xloc = xloc.bar_index))
            array.push(distance, dis)
            array.push(stepY, step)
            array.push(startPointX, phbar[1])
            array.push(startPointY, phh[1])

    var string[] entryId = array.new_string()
    var float[] slPerEntry = array.new_float()
    var string[] fibLevel = array.new_string()
    var float[] isFibTriggered = array.new_float()

    i = 0
    for tline in trendline
        y2 = array.get(startPointY, i) - array.get(stepY, i) * (bar_index - array.get(startPointX, i))    
        line.set_xy2(tline, bar_index, y2)
        if close &gt; y2 and ((timeframe.isintraday and time == t and enabledSession) or not timeframe.isintraday or not enabledSession)
            if strategy.opentrades &lt; posNum
                j = 0
                minl = plsl
                while close  0 ? minl - offsetForSL : minl
                minl := low &gt; minl ? minl : low
                qtyLong = math.floor((riskAmount / math.abs(close - minl)) / syminfo.pointvalue)        
                if (not EnableContractSizeByDefault and qtyLong &lt;= 1) or qtyLong &lt; 0
                    qtyLong := 0
                else if EnableContractSizeByDefault and qtyLong  phFib[k]
                        k := k + 1
                        q := phFib[k]
                        if k == 1000
                            q := close
                            break

                    l1 = (q - minl) * fibLevel1 + minl
                    l2 = (q - minl) * fibLevel2 + minl
                    l3 = (q - minl) * fibLevel3 + minl
                    l4 = (q - minl) * fibLevel4 + minl

                    fl1 = line.new(x1=bar_index, y1=l1, x2=bar_index + 10, y2=l1, color=color.green, width=1)
                    fl2 = line.new(x1=bar_index, y1=l2, x2=bar_index + 10, y2=l2, color=color.green, width=1)
                    fl3 = line.new(x1=bar_index, y1=l3, x2=bar_index + 10, y2=l3, color=color.green, width=1)
                    fl4 = line.new(x1=bar_index, y1=l4, x2=bar_index + 10, y2=l4, color=color.green, width=1)
                    
                    strlvl = str.tostring(l1) + "," + str.tostring(l2) + "," + str.tostring(l3) + "," + str.tostring(l4)
                    array.push(fibLevel, strlvl)
                    array.push(isFibTriggered, 0.0)

                if enabledSL
                    if setMethodForTP == "RiskAwardRatio" or setMethodForTP == "Fibonacci"
                        strategy.exit("TP/SL" + str.tostring(bar_index), entryId_, stop=minl, limit=takeProfitLong)
                    else if setMethodForTP == "LookBackCandles"
                        strategy.exit("TP/SL" + str.tostring(bar_index), entryId_, stop=minl)
                        
                array.push(slPerEntry, minl)

            array.remove(trendline, i)
            array.remove(distance, i)
            array.remove(stepY, i)
            array.remove(startPointX, i)
            array.remove(startPointY, i)
        i := i + 1

    exitLongCondition = false
    exitShortCondition = false

    if sourceForTP == "Close"
        exitLongCondition := close == ta.lowest(close, lookBackCandles+1) and open &gt; close
        exitShortCondition := close == ta.highest(close, lookBackCandles+1) and open  close
        exitShortCondition := high == ta.highest(high, lookBackCandles+1) and open  0 and exitLongCondition) or (strategy.position_size  0 and close &lt; isTrig and open  0
                for k = 0 to array.size(a) - 1
                    if close &gt; str.tonumber(array.get(a, k)) and array.get(isFibTriggered, i)  slPerEntry_ and close &lt; plsl
                strategy.close(array.get(entryId, i))
                array.remove(entryId, i)
                array.remove(slPerEntry, i)
                array.remove(fibLevel , i)
                array.remove(isFibTriggered, i)
            i := i + 1

    if na(t) and enabledSession
        strategy.close_all()
        array.clear(entryId)
        array.clear(slPerEntry)
        array.clear(fibLevel)
        array.clear(isFibTriggered)

// ------------- Single-trend mode -------------
else
    var line line1 = na
    var hvalid = false
    var distanceh = 0
    var steph = 0.
    var startLineXPointh = 0
    var startLineYPointh = 0.

    if not na(ph) and phh  pricen
                n := n + 1
            else
                if (pricen - high[i]) = touchNum ? true : false

        if enablePivotToCheck
            hvalid := hvalid and (pphbar[bar_index - phbar]  phbar[1]) ? true : false
    else
        distanceh := distanceh[1]
        steph := steph[1]
        startLineXPointh := startLineXPointh[1]
        startLineYPointh := startLineYPointh[1]    
        hvalid := hvalid[1]

    var entryIndexh = 0
    var entrySl = 0.
    var fibLevel = ""
    var isFibTriggered = 0.

    if hvalid
        y2 = startLineYPointh - steph * (bar_index - startLineXPointh)
        line.set_xy2(line1, bar_index, y2)    
        if close &gt; y2 and ((timeframe.isintraday and time == t and enabledSession) or not timeframe.isintraday or not enabledSession) 
            if strategy.opentrades &lt;= posNum
                j = 0
                minl = plsl
                while close  0 ? minl - offsetForSL : minl
                minl := low &gt; minl ? minl : low
                qtyLong = math.floor((riskAmount / math.abs(close - minl)) / syminfo.pointvalue)
                if (not EnableContractSizeByDefault and qtyLong &lt;= 1) or qtyLong &lt; 0
                    qtyLong := 0
                else if EnableContractSizeByDefault and qtyLong  phFib[k]
                        k := k + 1
                        q := phFib[k]
                        if k == 1000
                            q := close
                            break

                    l1 = (q - minl) * fibLevel1 + minl
                    l2 = (q - minl) * fibLevel2 + minl
                    l3 = (q - minl) * fibLevel3 + minl
                    l4 = (q - minl) * fibLevel4 + minl

                    fl1 = line.new(x1=bar_index, y1=l1, x2=bar_index + 10, y2=l1, color=color.green, width=2)
                    fl2 = line.new(x1=bar_index, y1=l2, x2=bar_index + 10, y2=l2, color=color.green, width=2)
                    fl3 = line.new(x1=bar_index, y1=l3, x2=bar_index + 10, y2=l3, color=color.green, width=2)
                    fl4 = line.new(x1=bar_index, y1=l4, x2=bar_index + 10, y2=l4, color=color.green, width=2)
                    
                    fibLevel := str.tostring(l1) + "," + str.tostring(l2) + "," + str.tostring(l3) + "," + str.tostring(l4)
                    isFibTriggered := 0.

                if enabledSL        
                    if setMethodForTP == "RiskAwardRatio" or setMethodForTP =="Fibonacci"
                        strategy.exit("TP/SL" + str.tostring(bar_index), "long"+str.tostring(bar_index), stop=minl, limit=takeProfitLong)
                    else if setMethodForTP == "LookBackCandles"
                        strategy.exit("TP/SL" + str.tostring(bar_index), "long"+str.tostring(bar_index), stop=minl)
            hvalid := false

    exitLongCondition = false
    exitShortCondition = false

    if sourceForTP == "Close"
        exitLongCondition := close == ta.lowest(close, lookBackCandles+1) and open &gt; close
        exitShortCondition := close == ta.highest(close, lookBackCandles+1) and open  close
        exitShortCondition := high == ta.highest(high, lookBackCandles+1) and open  entryIndexh
        if (strategy.position_size &gt; 0 and exitLongCondition)
            strategy.close_all()

        if (strategy.position_size &lt; 0 and exitShortCondition)
            strategy.close_all()

    if setMethodForTP == &quot;Fibonacci&quot;
        if close &lt; isFibTriggered and open  0
            for k = 0 to array.size(a) - 1
                if close &gt; str.tonumber(array.get(a, k)) and isFibTriggered  entrySl and close &lt; plsl
            strategy.close_all()

    if na(t) and enabledSession
        strategy.close_all()
```

## Automate It with PickMyTrade {#automate-it-with-pickmytrade}

Backtesting is great. Automation is better.

Because this is written as a TradingView **strategy**, you can:

1. Turn it into alerts
2. Use [**PickMyTrade**](https://pickmytrade.io/)to convert those alerts into **live orders** on your broker

Typical workflow:

1. **Add the strategy** to your chart and adjust settings (risk, TP method, time window).
2. In TradingView, create an alert based on “**strategy order fills**”.
3. Point the alert to your **PickMyTrade webhook URL**.
4. In PickMyTrade, map that alert to:
  - Your broker &amp; symbol
  - Order type, quantity mode, etc.

From there:

- Every trendline breakout the strategy takes on TradingView becomes a **live trade** on your broker.
- Stops and targets are pre-defined in the script.
- You’re no longer glued to the screen waiting for the perfect breakout candle.

(Always start on demo / paper trading first.)

## Final Thoughts &amp; Disclaimers {#final-thoughts-disclaimers}

We’ve taken a smart, open-source trendline concept by **@crazyrabbitheart** and wrapped it into a risk-controlled, automation-ready TradingView strategy that:

- Waits for **confirmed** multi-touch trendlines
- Enters only when price **decisively breaks out**
- Sizes positions by **fixed dollar risk**
- Manages exits with **R:R, lookback, or Fibonacci**
- Plays well across **stocks, crypto, FX and futures**

Still, the usual reminders apply:

- Backtests are historical, not guarantees.
- Live execution includes slippage, commissions, and human error.
- Markets evolve – no strategy works in every condition forever.

Use it as a **framework**, not a magic box:

- Risk 1–2% per trade
- Test per market and timeframe
- Demo first, real money later

## You may also like: {#you-may-also-like}

[UT Bot Indicators: Futures Trading Strategy](https://blog.pickmytrade.trade/ut-bot-indicators-futures-trading-strategy-2025/)  
[TradingView Alert Enhancement: Tools &amp; Indicators](https://blog.pickmytrade.trade/boost-tradingview-alerts-custom-tools-webhooks-2025/)

For AI tools &amp; developers:[View Markdown →](https://blog.pickmytrade.trade/trendline-breakout-strategy.md)