Pine Script v4 · Strategy
Trendlines Strategy
A Pine Script v4 strategy built on Lowest (10), Highest (10) and Valuewhen (bought, LL). It has 10 order rules, 8 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays 0.04 commission. 16 settings; defaults include Strategy Direction 0, Pivot Detection: Left Bars 100 and Pivot Detection: Right Bars 15.
Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.
- Does Trendlines Strategy repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 1 of 1 trades.
- How did Trendlines Strategy do on BTCUSDT 1D with default settings?
- +69.02%
- From 26 Jan 2024 to 21 Oct 2026, over 4 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can Trendlines Strategy be converted to Pine Script v5?
- Yes
- The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
- Does Trendlines Strategy use a stop loss?
- Yes
- strategy.exit sets a stop on line 203, 204.
- Does Trendlines Strategy run in Zeal Terminal?
- Yes
- It compiles in 47 ms and runs 1,000 bars in 143 ms, in the browser.
BTCUSDT · 1D · default settings
- Pivot High
- Pivot Low
- Plot
- Plot
- Resistance Trendline
- Support Trendline
- Long Break
- Short Break
- SL
- SSL
- TP
- STP
- Bullish Setup
- Bearish Setup
- Winning trade
- Losing trade
- Net profit
- +69.02%
- $6,902.14
- Buy and hold
- +102.5%
- same period
- Closed trades
- 4
- 3 won · 1 lost
- Profitable
- 75.0%
- of closed trades
- Profit factor
- 3.85
- gross profit ÷ gross loss
- Max drawdown
- 16.71%
- −$2,601.08
One run with the author's default settings, $10,000 starting capital, commission as the script sets it. A short position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
3 settings do nothing
“-----------------Strategy Inputs-------------------”, “Plot Pivots”, “-----------------General Inputs-------------------” are declared but never read.
-
Check
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
Uses an argument v6 removed
when = on line 189, 190, 192, 193, 196, 197, 199, 200. The upgraded version below moves each call inside an if block.
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames lowest → ta.lowest, highest → ta.highest, valuewhen → ta.valuewhen, atr → ta.atr, pivothigh → ta.pivothigh, pivotlow → ta.pivotlow, crossover → ta.crossover, crossunder → ta.crossunder.
- 8 strategy calls use the when = argument (line 189, 190, 192, 193, 196, 197, 199, 200). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 4 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 16: //@version=4 → //@version=5
- Line 25: input(type = input.integer) → input.int()
- Line 51: lowest → ta.lowest
- Line 52: highest → ta.highest
- Line 53: valuewhen → ta.valuewhen
- Line 54: valuewhen → ta.valuewhen
17 more edits
- Line 62: atr → ta.atr
- Line 65: valuewhen → ta.valuewhen
- Line 66: valuewhen → ta.valuewhen
- Line 82: valuewhen → ta.valuewhen
- Line 94: valuewhen → ta.valuewhen
- Line 114: pivothigh → ta.pivothigh
- Line 115: pivotlow → ta.pivotlow
- Line 116: valuewhen → ta.valuewhen
- Line 117: valuewhen → ta.valuewhen
- Line 118: valuewhen → ta.valuewhen
- Line 119: valuewhen → ta.valuewhen
- Line 120: valuewhen → ta.valuewhen
- Line 121: valuewhen → ta.valuewhen
- Line 122: valuewhen → ta.valuewhen
- Line 123: valuewhen → ta.valuewhen
- Line 172: crossover → ta.crossover
- Line 173: crossunder → ta.crossunder
⋯// trade-off you need to come to terms with and decide what the best settings are for you."-//@version=4+//@version=5strategy("Trendlines Strategy", ⋯ slippage=0)-direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)+direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : ⋯SwingStopProfit() =>- LL=(lowest(i_SPL))*(1-i_PercIncrement)+ LL=(ta.lowest(i_SPL))*(1-i_PercIncrement)- HH=(highest(i_SPL))*(1+i_PercIncrement)+ HH=(ta.highest(i_SPL))*(1+i_PercIncrement)- LL_price = valuewhen(bought, LL, 0)+ LL_price = ta.valuewhen(bought, LL, 0)- HH_price = valuewhen(bought, HH, 0)+ HH_price = ta.valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na ⋯ATRStop() =>- ATR=atr(i_ATR)*i_ATRMult+ ATR=ta.atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR- ATRLongStop = valuewhen(bought, ATRLong, 0)+ ATRLongStop = ta.valuewhen(bought, ATRLong, 0)- ATRShortStop = valuewhen(bought, ATRShort, 0)+ ATRShortStop = ta.valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ⋯TrailingStop(SL,SSL) =>- dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))+ dif=(ta.valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price⋯ var Ststop = float(na)- Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 + Sdif=strategy.position_avg_price-(ta.valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0))⋯// Pivots-ph = pivothigh(high, leftbars, rightbars)+ph = ta.pivothigh(high, leftbars, rightbars)-pl = pivotlow(low, leftbars, rightbars)+pl = ta.pivotlow(low, leftbars, rightbars)-phv1 = valuewhen(ph, high[rightbars], 0)+phv1 = ta.valuewhen(ph, high[rightbars], 0)-phb1 = valuewhen(ph, bar_index[rightbars], 0)+phb1 = ta.valuewhen(ph, bar_index[rightbars], 0)-phv2 = valuewhen(ph, high[rightbars], 1)+phv2 = ta.valuewhen(ph, high[rightbars], 1)-phb2 = valuewhen(ph, bar_index[rightbars], 1)+phb2 = ta.valuewhen(ph, bar_index[rightbars], 1)-plv1 = valuewhen(pl, low[rightbars], 0)+plv1 = ta.valuewhen(pl, low[rightbars], 0)-plb1 = valuewhen(pl, bar_index[rightbars], 0)+plb1 = ta.valuewhen(pl, bar_index[rightbars], 0)-plv2 = valuewhen(pl, low[rightbars], 1)+plv2 = ta.valuewhen(pl, low[rightbars], 1)-plb2 = valuewhen(pl, bar_index[rightbars], 1)+plb2 = ta.valuewhen(pl, bar_index[rightbars], 1) ⋯// Breaks-long_break = crossover(close, res_y)+long_break = ta.crossover(close, res_y)-short_break = crossunder(close, sup_y)+short_break = ta.crossunder(close, sup_y)plotshape(long_break, style=shape.triangleup, color=color.green, size=size.tiny, location=location.belowbar, title='Long Break')⋯Same 4 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 32: input() → input.bool()
- Line 33: input() → input.int()
- Line 34: input() → input.int()
- Line 35: input() → input.bool()
- Line 37: input() → input.bool()
- Line 39: input() → input.bool()
17 more edits
- Line 40: input() → input.bool()
- Line 41: input() → input.string()
- Line 42: input() → input.int()
- Line 43: input() → input.int()
- Line 44: input() → input.int()
- Line 45: input() → input.int()
- Line 46: input() → input.int()
- Line 47: input() → input.bool()
- Line 48: input() → input.bool()
- Line 189: when = SELL and strategy.position_size == 0 → if block
- Line 190: when = BUY and strategy.position_size == 0 → if block
- Line 192: when = SELL → if block
- Line 193: when = BUY → if block
- Line 196: when = BUY and strategy.position_size == 0 → if block
- Line 197: when = SELL and strategy.position_size == 0 → if block
- Line 199: when = BUY → if block
- Line 200: when = SELL → if block
⋯/////////////////////// STRATEGY INPUTS ////////////////////////////////////////-title1=input(true, "-----------------Strategy Inputs-------------------") +title1=input.bool(true, "-----------------Strategy Inputs-------------------") -leftbars = input(100, minval=1, title='Pivot Detection: Left Bars')+leftbars = input.int(100, minval=1, title='Pivot Detection: Left Bars')-rightbars = input(15, minval=1, title='Pivot Detection: Right Bars')+rightbars = input.int(15, minval=1, title='Pivot Detection: Right Bars')-plotpivots = input(true, title='Plot Pivots')+plotpivots = input.bool(true, title='Plot Pivots')/////////////////////// BACKTESTER /////////////////////////////////////////////-title2=input(true, "-----------------General Inputs-------------------") +title2=input.bool(true, "-----------------General Inputs-------------------") // Backtester General Inputs-i_SL=input(true, title="Use Stop Loss and Take Profit")+i_SL=input.bool(true, title="Use Stop Loss and Take Profit")-TS=input(false, title="Use Trailing Stop")+TS=input.bool(false, title="Use Trailing Stop")-i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])+i_SLType=input.string(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])-i_SPL=input(defval=10, title="Swing Point Lookback")+i_SPL=input.int(defval=10, title="Swing Point Lookback")-i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01+i_PercIncrement=input.int(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01-i_ATR = input(14, title="ATR Length")+i_ATR = input.int(14, title="ATR Length")-i_ATRMult = input(4, step=.1, title="ATR Multiple")+i_ATRMult = input.int(4, step=.1, title="ATR Multiple")-i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio")+i_TPRRR = input.int(2, step=.1, title="Take Profit Risk Reward Ratio")-DPR=input(true, "Allow Direct Position Reverse")+DPR=input.bool(true, "Allow Direct Position Reverse")-reverse=input(true, "Reverse Trades")+reverse=input.bool(true, "Reverse Trades")// Swing Points Stop and Take Profit⋯ if not DPR- strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)+ if SELL and strategy.position_size == 0+ strategy.entry("long", strategy.long)- strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)+ if BUY and strategy.position_size == 0+ strategy.entry("short", strategy.short) else - strategy.entry("long", strategy.long, when=SELL)+ if SELL+ strategy.entry("long", strategy.long)- strategy.entry("short", strategy.short, when=BUY)+ if BUY+ strategy.entry("short", strategy.short)else if not DPR - strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)+ if BUY and strategy.position_size == 0+ strategy.entry("long", strategy.long)- strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)+ if SELL and strategy.position_size == 0+ strategy.entry("short", strategy.short) else- strategy.entry("long", strategy.long, when=BUY)+ if BUY+ strategy.entry("long", strategy.long)- strategy.entry("short", strategy.short, when=SELL)+ if SELL+ strategy.entry("short", strategy.short)// Exits⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 4 before, 5 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// trade-off you need to come to terms with and decide what the best settings are for you."-//@version=5+//@version=6strategy("Trendlines Strategy", ⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Strategy Direction | 0 | int (written input.integer) · min -1 · max 1 | line 26 line 27 |
| -----------------Strategy Inputs------------------- | true | bool | unused |
| Pivot Detection: Left Bars | 100 | int · min 1 | ph pl |
| Pivot Detection: Right Bars | 15 | int · min 1 | ph pl phv1 phb1 phv2 phb2 plv1 plb1 plv2 plb2 Pivot High Pivot Low plot |
| Plot Pivots | true | bool | unused |
| -----------------General Inputs------------------- | true | bool | unused |
| Use Stop Loss and Take Profit | true | bool | exit TP & SL exit TP & SL line 202 SL SSL TP STP |
| Use Trailing Stop | false | bool | exit TP & SL SL SSL |
| Type Of Stop | ATR Stop | string · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"] | SL SSL TP STP |
| Swing Point Lookback | 10 | int | LL HH |
| Swing Point SL Perc Increment | 3 | int · step .1 | LL HH |
| ATR Length | 14 | int | ATR |
| ATR Multiple | 4 | int · step .1 | ATR |
| Take Profit Risk Reward Ratio | 2 | int · step .1 | tp stp ATRtp ATRstp |
| Allow Direct Position Reverse | true | bool | entry long entry short entry long entry short entry long entry short entry long entry short line 188 line 195 |
| Reverse Trades | true | bool | line 187 |
What it calculates
- Lowest (
lowest,ta.lowestin v5)Swing Point Lookback (10)LL · line 51 - Highest (
highest,ta.highestin v5)Swing Point Lookback (10)HH · line 52 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, LL, 0LL_price · line 53 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, HH, 0HH_price · line 54 - ATR (
atr,ta.atrin v5)ATR Length (14)ATR · line 62 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRLong, 0ATRLongStop · line 65 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRShort, 0ATRShortStop · line 66 - Pivothigh (
pivothigh,ta.pivothighin v5)high, Pivot Detection: Left Bars (100), Pivot Detection: Right Bars (15)ph · line 114 - Pivotlow (
pivotlow,ta.pivotlowin v5)low, Pivot Detection: Left Bars (100), Pivot Detection: Right Bars (15)pl · line 115 - Valuewhen (
valuewhen,ta.valuewhenin v5)ph, high[rightbars], 0phv1 · line 116 - Valuewhen (
valuewhen,ta.valuewhenin v5)ph, bar_index[rightbars], 0phb1 · line 117 - Valuewhen (
valuewhen,ta.valuewhenin v5)ph, high[rightbars], 1phv2 · line 118 - Valuewhen (
valuewhen,ta.valuewhenin v5)ph, bar_index[rightbars], 1phb2 · line 119 - Valuewhen (
valuewhen,ta.valuewhenin v5)pl, low[rightbars], 0plv1 · line 120 - Valuewhen (
valuewhen,ta.valuewhenin v5)pl, bar_index[rightbars], 0plb1 · line 121 - Valuewhen (
valuewhen,ta.valuewhenin v5)pl, low[rightbars], 1plv2 · line 122 - Valuewhen (
valuewhen,ta.valuewhenin v5)pl, bar_index[rightbars], 1plb2 · line 123 - Crossover (
crossover,ta.crossoverin v5)close, res_ylong_break · line 172 - Crossunder (
crossunder,ta.crossunderin v5)close, sup_yshort_break · line 173
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
The script has 75 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | SELL and strategy.position_size == 0 | On | 189 |
| Open short short | BUY and strategy.position_size == 0 | On | 190 |
| Open long long | SELL | On | 192 |
| Open short short | BUY | On | 193 |
| Open long long | BUY and strategy.position_size == 0 | On | 196 |
| Open short short | SELL and strategy.position_size == 0 | On | 197 |
| Open long long | BUY | On | 199 |
| Open short short | SELL | On | 200 |
| Exit TP & SL stop and limit | i_SL | On “Use Stop Loss and Take Profit” | 203 |
| Exit TP & SL stop and limit | i_SL | On “Use Stop Loss and Take Profit” | 204 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
No
No repainting patterns in the source, and the live replay matched history.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +69.0% | +102.5% | 4 | 75% | 3.85 | 16.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +8.9% | +5.5% | 4 | 75% | 2.04 | 10.4% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −12.3% | +9.8% | 3 | 33% | 0.75 | 35.9% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −1.4% | +8.4% | 3 | 33% | 0.88 | 13.5% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +0.2% | +16.7% | 3 | 33% | 1.00 | 51.1% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +9.1% | +21.5% | 3 | 67% | 3.27 | 10.5% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −54.8% | +148.3% | 7 | 14% | 0.06 | 55.4% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −8.4% | +17.1% | 2 | 0% | 0.00 | 9.6% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 1 | 100% | $1,720.96 |
| Sideways market | 2 | 50% | $1,342.71 |
| Falling market | 1 | 100% | $3,845.23 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
15.5%
The 95th percentile of the worst drawdown when the same 4 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 15.5% to 15.5%; the tick is what actually happened, 15.5%. Order luck alone moves it this much.
All 4 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 7 Apr 2025 78,430.00 | 21 May 2025 108,675.00 | 44 | $3,845.23 |
| short | 11 Jul 2025 116,010.00 | 5 Nov 2025 101,497.00 | 117 | $1,720.96 |
| long | 5 Nov 2025 101,497.00 | 21 Nov 2025 85,851.00 | 16 | −$2,410.88 |
| long | 1 Jul 2026 58,624.70 | 21 Aug 2026 75,412.30 | 51 | $3,753.59 |
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Trendlines Strategy this page | — | v4 strategy | +69.0% | 4 | 16.7% |
| Qullamaggie Breakout by millerrh | atr pivothigh pivotlow valuewhen lowest | v4 strategy | +61.3% | 25 | 20.2% |
| Positive Bars - Strategy by tweakerID | lowest highest valuewhen atr | v4 strategy | −40.3% | 7 | 54.7% |
| Big Bar Strategy by tweakerID | lowest highest valuewhen atr | v4 strategy | −56.6% | 13 | 57.1% |
| SuperTrend Multi Time Frame Long and Short Trading Strategy by ranga_technologies | atr highest lowest valuewhen | v5 strategy | No trades on this market | ||
| Inside Bar Strategy w- SL by tweakerID | lowest highest valuewhen atr | v4 strategy | −61.3% | 25 | 65.0% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 47 ms | Yes 1,000 bars in 143 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © tweakerID and © BacktestRookies// Using the clever calculations and code by BacktestRookies, here is a strategy that buys // when the price breaks above a trendline and sells (or shorts) when it crosses below. // This logic can be reversed, which seems to work better with recent market conditions.// "A general explanation of the indicator would be a good place to start. In it, we plot two // trend lines at any given time. A resistance trend line and a support trend line. The resistance // trend is shown with red circles and is created by joining swing highs together. The second is a // support trend which is created by joining swing lows.// Since we need swings to make the trend, the trend line code contains code for the swing detection. // You can play around with the swing detection to alter how frequently new trend lines are detected. // Relying on swings also means that there will be some delay in trend detection depending on how you // configure the swing detection. The higher you set rightbars, the more lag you will have before a trend // is detected. However, at the same time the quality of the pivots found will increase. So it is a // trade-off you need to come to terms with and decide what the best settings are for you."//@version=4strategy("Trendlines Strategy", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, initial_capital=10000, commission_value=0.04, calc_on_every_tick=false, slippage=0)direction = input(0, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))// Bought and Sold Boolean Signalbought = strategy.position_size > strategy.position_size[1] or strategy.position_size < strategy.position_size[1]/////////////////////// STRATEGY INPUTS ////////////////////////////////////////title1=input(true, "-----------------Strategy Inputs-------------------") leftbars = input(100, minval=1, title='Pivot Detection: Left Bars')rightbars = input(15, minval=1, title='Pivot Detection: Right Bars')plotpivots = input(true, title='Plot Pivots')/////////////////////// BACKTESTER /////////////////////////////////////////////title2=input(true, "-----------------General Inputs-------------------") // Backtester General Inputsi_SL=input(true, title="Use Stop Loss and Take Profit")TS=input(false, title="Use Trailing Stop")i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])i_SPL=input(defval=10, title="Swing Point Lookback")i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01i_ATR = input(14, title="ATR Length")i_ATRMult = input(4, step=.1, title="ATR Multiple")i_TPRRR = input(2, step=.1, title="Take Profit Risk Reward Ratio")DPR=input(true, "Allow Direct Position Reverse")reverse=input(true, "Reverse Trades")// Swing Points Stop and Take ProfitSwingStopProfit() => LL=(lowest(i_SPL))*(1-i_PercIncrement) HH=(highest(i_SPL))*(1+i_PercIncrement) LL_price = valuewhen(bought, LL, 0) HH_price = valuewhen(bought, HH, 0) entry_LL_price = strategy.position_size > 0 ? LL_price : na entry_HH_price = strategy.position_size < 0 ? HH_price : na tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR [entry_LL_price, entry_HH_price, tp, stp]// ATR StopATRStop() => ATR=atr(i_ATR)*i_ATRMult ATRLong = ohlc4 - ATR ATRShort = ohlc4 + ATR ATRLongStop = valuewhen(bought, ATRLong, 0) ATRShortStop = valuewhen(bought, ATRShort, 0) LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] // Strategy StopStrategyStop(bought) => float LongStop = na float ShortStop = na float StratTP = na float StratSTP = na [LongStop, ShortStop, StratTP, StratSTP]//TrailingStopTrailingStop(SL,SSL) => dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0)) -strategy.position_avg_price trailOffset = strategy.position_avg_price - SL var tstop = float(na) if strategy.position_size > 0 tstop := high- trailOffset - dif if tstop<tstop[1] tstop:=tstop[1] else tstop := na StrailOffset = SSL - strategy.position_avg_price var Ststop = float(na) Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 and strategy.position_size[1]>=0, low,0)) if strategy.position_size < 0 Ststop := low+ StrailOffset + Sdif if Ststop>Ststop[1] Ststop:=Ststop[1] else Ststop := na [tstop, Ststop] //Stop Loss & Take Profit Switches SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) => SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP [SL, SSL, TP, STP]/////////////////////// STRATEGY LOGIC /////////////////////////////////////////// Pivotsph = pivothigh(high, leftbars, rightbars)pl = pivotlow(low, leftbars, rightbars)phv1 = valuewhen(ph, high[rightbars], 0)phb1 = valuewhen(ph, bar_index[rightbars], 0)phv2 = valuewhen(ph, high[rightbars], 1)phb2 = valuewhen(ph, bar_index[rightbars], 1)plv1 = valuewhen(pl, low[rightbars], 0)plb1 = valuewhen(pl, bar_index[rightbars], 0)plv2 = valuewhen(pl, low[rightbars], 1)plb2 = valuewhen(pl, bar_index[rightbars], 1) plotshape(ph, style=shape.circle, location=location.abovebar, color=color.orange, title='Pivot High', offset=-rightbars)plotshape(pl, style=shape.circle, location=location.belowbar, color=color.blue, title='Pivot Low', offset=-rightbars)plot(ph ? high[rightbars] : na, color=color.orange, offset=-rightbars)plot(pl ? low[rightbars] : na, color=color.purple, offset=-rightbars)// TRENDLINE CODE// --------------get_slope(x1,x2,y1,y2)=> m = (y2-y1)/(x2-x1) get_y_intercept(m, x1, y1)=> b=y1-m*x1get_y(m, b, ts)=> Y = m * ts + bint res_x1 = nafloat res_y1 = naint res_x2 = nafloat res_y2 = naint sup_x1 = nafloat sup_y1 = naint sup_x2 = nafloat sup_y2 = na// Resistanceres_x1 := ph ? phb1 : res_x1[1]res_y1 := ph ? phv1 : res_y1[1]res_x2 := ph ? phb2 : res_x2[1]res_y2 := ph ? phv2 : res_y2[1]res_m = get_slope(res_x1,res_x2,res_y1,res_y2)res_b = get_y_intercept(res_m, res_x1, res_y1)res_y = get_y(res_m, res_b, bar_index)// Supportsup_x1 := pl ? plb1 : sup_x1[1]sup_y1 := pl ? plv1 : sup_y1[1]sup_x2 := pl ? plb2 : sup_x2[1]sup_y2 := pl ? plv2 : sup_y2[1]sup_m = get_slope(sup_x1,sup_x2,sup_y1,sup_y2)sup_b = get_y_intercept(sup_m, sup_x1, sup_y1)sup_y = get_y(sup_m, sup_b, bar_index)// plot(line.get_y2(line1))plot(res_y, color=color.red, title='Resistance Trendline', linewidth=2, style=plot.style_circles)plot(sup_y, color=color.lime, title='Support Trendline', linewidth=2, style=plot.style_circles)if ph line.new(phb1,phv1, bar_index, res_y, style=line.style_dashed, color=color.blue) if pl line.new(plb1,plv1, bar_index, sup_y, style=line.style_dashed, color=color.blue) // Breakslong_break = crossover(close, res_y)short_break = crossunder(close, sup_y)plotshape(long_break, style=shape.triangleup, color=color.green, size=size.tiny, location=location.belowbar, title='Long Break')plotshape(short_break, style=shape.triangledown, color=color.red, size=size.tiny, location=location.abovebar, title='Short Break')BUY=long_breakSELL=short_break/////////////////////// FUNCTION CALLS /////////////////////////////////////////// Stops and Profits[entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit()[LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop()[LongStop, ShortStop, StratTP, StratSTP] = StrategyStop(bought)[SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp)[tstop, Ststop] = TrailingStop(SL,SSL)// Entriesif reverse if not DPR strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0) strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=SELL) strategy.entry("short", strategy.short, when=BUY)else if not DPR strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0) strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0) else strategy.entry("long", strategy.long, when=BUY) strategy.entry("short", strategy.short, when=SELL)// Exitsif i_SL strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL) strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL)/////////////////////// PLOTS //////////////////////////////////////////////////plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red)plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red)plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green)plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green)// Draw price action setup arrowsplotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup", size=size.auto)plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar, color=color.red, title="Bearish Setup", size=size.auto)