Pine Script v5 · Strategy
Qullamaggie Breakout V2
A Pine Script v5 strategy built on SMA (21), Pivothigh (high, lbHigh) and Pivotlow (low, lbLow). It has 2 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss. Each trade commits 100% of equity and pays 0.1% commission. 21 settings; defaults include Timeframe of Moving Averages D, Moving Average Type SMA and 1st Moving Average: Length 10.
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 Qullamaggie Breakout V2 repaint?
- Yes
- At least one pattern in the source can repaint: higher-timeframe data, intrabar recalculation.
- How did Qullamaggie Breakout V2 do on BTCUSDT 1D with default settings?
- +35.43%
- From 26 Jan 2024 to 21 Oct 2026, over 33 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Does Qullamaggie Breakout V2 run in Pine Script v6?
- Yes
- Same 33 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
- Does Qullamaggie Breakout V2 use a stop loss?
- Yes
- strategy.exit sets a stop on line 162.
- Does Qullamaggie Breakout V2 run in Zeal Terminal?
- Yes
- It compiles in 69 ms and runs 1,000 bars in 194 ms, in the browser.
BTCUSDT · 1D · default settings
- MA1
- MA2
- MA3
- Historical Stop Levels
- Historical Trail Stop Levels
- Winning trade
- Losing trade
- Equity
- Buy and hold
| 2.52% ADR | 5.40% Range |
- Net profit
- +35.43%
- $35,428.10
- Buy and hold
- +102.5%
- same period
- Closed trades
- 33
- 15 won · 18 lost
- Profitable
- 45.5%
- of closed trades
- Profit factor
- 1.56
- gross profit ÷ gross loss
- Max drawdown
- 16.88%
- −$16,881.90
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A long 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
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 160. The upgraded version below moves each call inside an if block.
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 |
|---|---|---|---|
| backtest window and pivot history | |||
| Backtest Start Date | timestamp("01 Jan 2019 06:00 +0000") | time | buyConditions |
| Backtest End Date | timestamp("01 Jan 2100 00:00 +0000") | time | buyConditions |
| Show Historical Pivot Points?Toggle this on to see the historical pivot points that were used. Change the Lookback Periods to adjust the frequency of these points. | false | bool | Top Levels Top Levels 2 Bottom Levels Bottom Levels 2 Ma Stop Levels |
| moving averages | |||
| Timeframe of Moving AveragesAllows you to set a different time frame for the moving averages and your trailing stop. The default behavior is to identify good tightening setups on a larger timeframe (like daily) and enter the trade on a breakout occuring on a smaller timeframe, using the moving averages of the larger timeframe to trail your stop. | D | timeframe | ma1 ma2 ma3 crossTF |
| Moving Average Type | SMA | string · options ["EMA", "SMA"] | ma1 ma2 ma3 line 50 |
| 1st Moving Average: Length | 10 | int · min 1 | ma1 |
| Color | color.new(color.purple, 60) | color | MA1 |
| 2nd Moving Average: Length | 20 | int · min 1 | ma2 |
| Color | color.new(color.yellow, 60) | color | MA2 |
| 3rd Moving Average: Length | 50 | int · min 1 | ma3 |
| Color | color.new(color.white, 60) | color | MA3 |
| Use 3rd Moving Average for Filtering?Signals will be ignored when price is under this slowest moving average. The intent is to keep you out of bear periods and only buying when price is showing strength or trading with the longer term trend. | true | bool | buyConditions |
| stops | |||
| Trailing StopInitial stops after entry follow the range lows. Once in profit, the trade gets more wiggle room and stops will be trailed when price breaches this moving average. | 1st Moving Average | string · options ["1st Moving Average", "2nd Moving Average"] | trailMa |
| Trailing Stop TimeframeOnce price breaches the trail stop moving average, the stop will be raised to the low of that candle that breached. You can choose to use the chart timeframe's candles breaching or use the same timeframe the moving averages use. (i.e. if daily, you wait for the daily bar to close before setting your new stop level.) | Same as Moving Averages | string · options ["Same as Moving Averages", "Same as Chart"] | crossTF |
| Current Range S/R Colors: Support | color.new(color.orange,50) | color | lowLine |
| Resistance | color.new(color.blue,50) | color | highLine |
| Stop Colors: Initial | color.new(color.orange,50) | color | Historical Stop Levels |
| Moving Average Trailing | color.new(color.blue,50) | color | Historical Trail Stop Levels |
| adr filtering | |||
| Use ADR for Filtering?Signals will be ignored if the distance between support and resistance is larger than a user-defined percentage of ADR (or monthly volatility in the stock screener). This allows the user to ensure they are not buying something that is too extended and instead focus on names that are consolidating more. | false | bool | buyConditions |
| % of ADR Value | 120 | int · min 1 | adrCompare |
| ADR Table VisibilityPlace ADR table on the top of the pane, the bottom of the pane, or off. | Bottom | string · options ["Top", "Bottom"] | tablePos |
What it calculates
- SMA(high-low)/math.abs(low) * 100, 21
adrValue · line 66 - Pivothighhigh, lbHigh, lbHigh
ph · line 69 - Pivotlowlow, lbLow, lbLow
pl · line 70 - Valuewhenph, high[lbHigh], 0
highLevel · line 71 - Valuewhenpl, low[lbLow], 0
lowLevel · line 72 - Barssinceph
barsSinceHigh · line 73 - Barssincepl
barsSinceLow · line 74 - Valuewhenph, high[lbHigh], 0
buyLevel · line 88 - Valuewhenpl, low[lbLow], 0
stopDefine · line 109 - BarssincenotInPosition
inPositionBars · line 116 - BarssincemaCrossEvent
maCrossBars · line 117
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 65 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 Buy long | buyConditions | On | 160 |
| Exit Sell stop | every bar | On | 162 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
The script reads request.security() at the chart's own timeframe, which Zeal Terminal's engine answers one bar late in live mode but not in history, so this replay cannot tell repainting from that engine issue.
- CheckHigher-timeframe data5 request.security call(s) use lookahead_on (line 51, 52, 53, 66, 104). Without a [1] offset this reads future bars in history.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- CheckIntrabar recalculationcalc_on_every_tick = true. Live values can differ from history.
- 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 | +35.4% | +102.5% | 33 | 45% | 1.56 | 16.9% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −7.1% | +5.5% | 17 | 29% | 0.74 | 13.4% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +66.8% | +9.8% | 25 | 40% | 1.47 | 19.7% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +3.6% | +8.4% | 17 | 24% | 1.14 | 12.8% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +16.7% | +16.7% | 29 | 38% | 1.14 | 41.7% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +6.3% | +21.5% | 18 | 22% | 1.16 | 15.8% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −59.4% | +148.3% | 36 | 22% | 0.35 | 63.4% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +25.5% | +17.1% | 13 | 54% | 4.83 | 4.5% | 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 | 13 | 38% | $10,210.40 |
| Sideways market | 16 | 50% | $14,059.50 |
| Falling market | 4 | 50% | $11,293.60 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
28.5%
The 95th percentile of the worst drawdown when the same 33 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 12.8% to 28.5%; the tick is what actually happened, 14.8%. Order luck alone moves it this much.
All 33 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 16 Mar 2024 69,499.80 | 2 Apr 2024 68,062.90 | 17 | −$2,263.27 |
| long | 8 Apr 2024 71,769.50 | 10 Apr 2024 68,210.00 | 2 | −$5,033.02 |
| long | 15 May 2024 65,500.00 | 29 May 2024 68,128.00 | 14 | $3,526.83 |
| long | 4 Jun 2024 70,687.60 | 11 Jun 2024 69,130.20 | 7 | −$2,308.09 |
| long | 19 Jul 2024 63,987.90 | 25 Jul 2024 65,111.00 | 6 | $1,457.52 |
| long | 27 Jul 2024 68,474.60 | 30 Jul 2024 66,428.00 | 3 | −$3,035.57 |
| long | 23 Aug 2024 62,745.10 | 28 Aug 2024 58,034.00 | 5 | −$7,104.20 |
| long | 17 Sep 2024 60,625.00 | 1 Oct 2024 62,856.30 | 14 | $2,960.68 |
| long | 14 Oct 2024 64,478.20 | 23 Oct 2024 66,571.40 | 9 | $2,681.42 |
| long | 24 Oct 2024 66,668.60 | 3 Nov 2024 68,820.10 | 10 | $2,745.46 |
| long | 6 Nov 2024 73,620.10 | 26 Nov 2024 92,600.20 | 20 | $23,903.00 |
| long | 4 Dec 2024 98,620.00 | 5 Dec 2024 90,791.10 | 1 | −$9,546.29 |
| long | 6 Dec 2024 98,620.00 | 19 Dec 2024 100,000.00 | 13 | $1,292.28 |
| long | 6 Jan 2025 99,963.70 | 8 Jan 2025 96,181.80 | 2 | −$4,344.30 |
| long | 17 Jan 2025 102,724.00 | 27 Jan 2025 102,520.00 | 10 | −$417.56 |
| long | 21 Apr 2025 86,496.40 | 5 May 2025 94,151.40 | 14 | $9,022.29 |
| long | 8 May 2025 97,895.70 | 28 May 2025 107,517.00 | 20 | $10,908.90 |
| long | 9 Jun 2025 106,795.00 | 13 Jun 2025 105,672.00 | 4 | −$1,554.58 |
| long | 2 Jul 2025 108,952.00 | 7 Jul 2025 107,800.00 | 5 | −$1,542.74 |
| long | 9 Jul 2025 110,529.00 | 25 Jul 2025 116,813.00 | 16 | $6,642.43 |
| long | 11 Aug 2025 119,800.00 | 15 Aug 2025 117,180.00 | 4 | −$3,049.27 |
| long | 18 Sep 2025 117,429.00 | 22 Sep 2025 114,384.00 | 4 | −$3,483.03 |
| long | 1 Oct 2025 117,900.00 | 10 Oct 2025 119,651.00 | 9 | $1,558.06 |
| long | 2 Jan 2026 90,406.10 | 20 Jan 2026 89,311.00 | 18 | −$1,732.90 |
| long | 16 Mar 2026 74,050.00 | 19 Mar 2026 70,500.00 | 3 | −$6,045.14 |
| long | 6 Apr 2026 69,310.00 | 20 Apr 2026 73,762.90 | 14 | $7,158.62 |
| long | 22 Apr 2026 78,333.00 | 28 Apr 2026 76,459.60 | 6 | −$3,165.88 |
| long | 4 May 2026 79,485.70 | 13 May 2026 79,843.60 | 9 | $297.61 |
| long | 14 Jul 2026 64,692.80 | 24 Jul 2026 64,650.00 | 10 | −$317.80 |
| long | 9 Aug 2026 65,409.60 | 11 Aug 2026 63,806.30 | 2 | −$3,154.40 |
| long | 19 Aug 2026 65,474.50 | 1 Sep 2026 76,888.00 | 13 | $19,958.80 |
| long | 3 Sep 2026 81,478.90 | 8 Sep 2026 78,680.00 | 5 | −$4,934.69 |
| long | 18 Sep 2026 79,890.00 | 8 Oct 2026 82,787.30 | 20 | $4,482.33 |
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 |
|---|---|---|---|---|---|
| Qullamaggie Breakout V2 this page | — | v5 strategy | +35.4% | 33 | 16.9% |
| Alert(), alertcondition() or strategy alerts- by Peter_O | sma pivothigh pivotlow valuewhen | v4 strategy | +7,640,000.0% | 191 | 919.9% |
| Quantitative Trend Strategy- Uptrend long by CheatCode1 | sma pivothigh pivotlow valuewhen | v5 strategy | +5.9% | 28 | 32.8% |
| Moving Stop-Loss mechanism + alerts to MT4-MT5 by Peter_O | sma pivothigh pivotlow valuewhen | v5 strategy | −9,857,600.0% | 191 | 4,436.8% |
| TradingView Alerts to MT4 MT5 - Forex, indices, commodities by Peter_O | sma pivothigh pivotlow valuewhen | v4 strategy | −699,283.0% | 382 | 3,138.7% |
| TradePro's 2 EMA + Stoch RSI + ATR Strategy by PtGambler | sma pivothigh pivotlow valuewhen | v5 strategy | −2.7% | 18 | 22.0% |
Upgrade and export
Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.
- 1 strategy call uses the when = argument (line 160). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
- No v6-only features. v6 is not needed to run this script.
Same 33 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 160: when = buyConditions → if block
⋯// == STRATEGY ENTRY AND EXIT ==-strategy.entry("Buy", strategy.long, stop = buyLevel, when = buyConditions)+if buyConditions+ strategy.entry("Buy", strategy.long, stop = buyLevel)stop = stopLevel > trailStopLevel ? stopLevel : close[1] > trailStopLevel and close[1] > trailMa ? trailStopLevel : stopLevel⋯Does it run in Pine Script v6?
Yes
Same 33 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.
⋯// original by incorporating some of what I learned in the Breakout Trend Follower script.-//@version=5+//@version=6strategy("Qullamaggie Breakout V2", overlay=true, initial_capital=100000, currency='USD', calc_on_every_tick = true,⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 69 ms | Yes 1,000 bars in 194 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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/// © millerrh// The intent of this strategy is to buy breakouts with a tight stop on smaller timeframes in the direction of the longer term trend.// Then use a trailing stop of a close below either the 10 MA or 20 MA (user choice) on that larger timeframe as the position // moves in your favor (i.e. whenever position price rises above the MA).// Option of using daily ADR as a measure of finding contracting ranges and ensuring a decent risk/reward.// (If the difference between the breakout point and your stop level is below a certain % of ATR, it could possibly find those consolidating periods.)// V2 - updates code of original Qullamaggie Breakout to optimize and debug it a bit - the goal is to remove some of the whipsaw and poor win rate of the // original by incorporating some of what I learned in the Breakout Trend Follower script.//@version=5strategy("Qullamaggie Breakout V2", overlay=true, initial_capital=100000, currency='USD', calc_on_every_tick = true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1) // === BACKTEST RANGE ===Start = input.time(defval = timestamp("01 Jan 2019 06:00 +0000"), title = "Backtest Start Date", group = "backtest window and pivot history")Finish = input.time(defval = timestamp("01 Jan 2100 00:00 +0000"), title = "Backtest End Date", group = "backtest window and pivot history")// InputsshowPivotPoints = input.bool(title = "Show Historical Pivot Points?", defval = false, group = "backtest window and pivot history", tooltip = "Toggle this on to see the historical pivot points that were used. Change the Lookback Periods to adjust the frequency of these points.")htf = input.timeframe(defval="D", title="Timeframe of Moving Averages", group = "moving averages", tooltip = "Allows you to set a different time frame for the moving averages and your trailing stop. The default behavior is to identify good tightening setups on a larger timeframe (like daily) and enter the trade on a breakout occuring on a smaller timeframe, using the moving averages of the larger timeframe to trail your stop.")maType = input.string(defval="SMA", options=["EMA", "SMA"], title = "Moving Average Type", group = "moving averages")ma1Length = input.int(defval = 10, title = "1st Moving Average: Length", minval = 1, group = "moving averages", inline = "1ma")ma1Color = input.color(color.new(color.purple, 60), title = " Color", group = "moving averages", inline = "1ma")ma2Length = input.int(defval = 20, title = "2nd Moving Average: Length", minval = 1, group = "moving averages", inline = "2ma")ma2Color = input.color(color.new(color.yellow, 60), title = " Color", group = "moving averages", inline = "2ma")ma3Length = input.int(defval = 50, title = "3rd Moving Average: Length", minval = 1, group = "moving averages", inline = "3ma")ma3Color = input.color(color.new(color.white, 60), title = " Color", group = "moving averages", inline = "3ma")useMaFilter = input.bool(title = "Use 3rd Moving Average for Filtering?", defval = true, group = "moving averages", tooltip = "Signals will be ignored when price is under this slowest moving average. The intent is to keep you out of bear periods and only buying when price is showing strength or trading with the longer term trend.")trailMaInput = input.string(defval="1st Moving Average", options=["1st Moving Average", "2nd Moving Average"], title = "Trailing Stop", group = "stops", tooltip = "Initial stops after entry follow the range lows. Once in profit, the trade gets more wiggle room and stops will be trailed when price breaches this moving average.")trailMaTF = input.string(defval="Same as Moving Averages", options=["Same as Moving Averages", "Same as Chart"], title = "Trailing Stop Timeframe", group = "stops", tooltip = "Once price breaches the trail stop moving average, the stop will be raised to the low of that candle that breached. You can choose to use the chart timeframe's candles breaching or use the same timeframe the moving averages use. (i.e. if daily, you wait for the daily bar to close before setting your new stop level.)")currentColorS = input.color(color.new(color.orange,50), title = "Current Range S/R Colors: Support", group = "stops", inline = "lineColor")currentColorR = input.color(color.new(color.blue,50), title = " Resistance", group = "stops", inline = "lineColor")colorStop = input.color(color.new(color.orange,50), title = "Stop Colors: Initial", group = "stops", inline = "stopColor")colorTrail = input.color(color.new(color.blue,50), title = " Moving Average Trailing", group = "stops", inline = "stopColor")// Pivot lookbacklbHigh = 3lbLow = 3// MA Calculations (can likely move this to a tuple for a single security call!!)ma(maType, src, length) => maType == "EMA" ? ta.ema(src, length) : ta.sma(src, length) //Ternary Operator (if maType equals EMA, then do ema calc, else do sma calc)ma1 = request.security(syminfo.tickerid, htf, ma(maType, close, ma1Length), barmerge.gaps_off, barmerge.lookahead_on)ma2 = request.security(syminfo.tickerid, htf, ma(maType, close, ma2Length), barmerge.gaps_off, barmerge.lookahead_on)ma3 = request.security(syminfo.tickerid, htf, ma(maType, close, ma3Length), barmerge.gaps_off, barmerge.lookahead_on)plot(ma1, color=ma1Color, style=plot.style_line, title="MA1", linewidth=2)plot(ma2, color=ma2Color, style=plot.style_line, title="MA2", linewidth=2)plot(ma3, color=ma3Color, style=plot.style_line, title="MA3", linewidth=2)// === USE ADR FOR FILTERING ===// The idea here is that you want to buy in a consolodating range for best risk/reward. So here you can compare the current distance between // support/resistance vs. the ADR and make sure you aren't buying at a point that is too extended.useAdrFilter = input.bool(title = "Use ADR for Filtering?", defval = false, group = "adr filtering", tooltip = "Signals will be ignored if the distance between support and resistance is larger than a user-defined percentage of ADR (or monthly volatility in the stock screener). This allows the user to ensure they are not buying something that is too extended and instead focus on names that are consolidating more.")adrPerc = input.int(defval = 120, title = "% of ADR Value", minval = 1, group = "adr filtering")tableLocation = input.string(defval="Bottom", options=["Top", "Bottom"], title = "ADR Table Visibility", group = "adr filtering", tooltip = "Place ADR table on the top of the pane, the bottom of the pane, or off.")adrValue = request.security(syminfo.tickerid, "D", ta.sma((high-low)/math.abs(low) * 100, 21), barmerge.gaps_off, barmerge.lookahead_on) // Monthly Volatility in Stock Screener (also ADR)adrCompare = (adrPerc * adrValue) / 100// === PLOT SWING HIGH/LOW AND MOST RECENT LOW TO USE AS STOP LOSS EXIT POINT ===ph = ta.pivothigh(high, lbHigh, lbHigh)pl = ta.pivotlow(low, lbLow, lbLow)highLevel = ta.valuewhen(ph, high[lbHigh], 0)lowLevel = ta.valuewhen(pl, low[lbLow], 0)barsSinceHigh = ta.barssince(ph) + lbHighbarsSinceLow = ta.barssince(pl) + lbLowtimeSinceHigh = time[barsSinceHigh]timeSinceLow = time[barsSinceLow]//Removes color when there is a change to ensure only the levels are shown (i.e. no diagonal lines connecting the levels)pvthis = fixnan(ph)pvtlos = fixnan(pl)hipc = ta.change(pvthis) != 0 ? na : color.new(color.maroon, 0)lopc = ta.change(pvtlos) != 0 ? na : color.new(color.green, 0)// Display Pivot linesplot(showPivotPoints ? pvthis : na, color=hipc, linewidth=1, offset=-lbHigh, title="Top Levels")plot(showPivotPoints ? pvthis : na, color=hipc, linewidth=1, offset=0, title="Top Levels 2")plot(showPivotPoints ? pvtlos : na, color=lopc, linewidth=1, offset=-lbLow, title="Bottom Levels")plot(showPivotPoints ? pvtlos : na, color=lopc, linewidth=1, offset=0, title="Bottom Levels 2")// BUY AND SELL CONDITIONSbuyLevel = ta.valuewhen(ph, high[lbHigh], 0) //Buy level at Swing High// Conditions for entrystopLevel = float(na) // Define stop level here as "na" so that I can reference it in the ADR calculation before the stopLevel is actually defined.buyConditions = (useMaFilter ? buyLevel > ma3 : true) and (useAdrFilter ? (buyLevel - stopLevel[1]) < adrCompare : true) and time > Start and time < FinishbuySignal = ta.crossover(high, buyLevel) and buyConditions// Trailing stop points - when price punctures the moving average, move stop to the low of that candle - Define as function/tuple to only use one security calltrailMa = trailMaInput == "1st Moving Average" ? ma1 : ma2f_getCross() => maCrossEvent = ta.crossunder(low, trailMa) maCross = ta.valuewhen(maCrossEvent, low, 0) maCrossLevel = fixnan(maCross) maCrossPc = ta.change(maCrossLevel) != 0 ? na : color.new(color.blue, 0) //Removes color when there is a change to ensure only the levels are shown (i.e. no diagonal lines connecting the levels) [maCrossEvent, maCross, maCrossLevel, maCrossPc]crossTF = trailMaTF == "Same as Moving Averages" ? htf : ""[maCrossEvent, maCross, maCrossLevel, maCrossPc] = request.security(syminfo.tickerid, crossTF, f_getCross(), barmerge.gaps_off, barmerge.lookahead_on)plot(showPivotPoints ? maCrossLevel : na, color = maCrossPc, linewidth=1, offset=0, title="Ma Stop Levels")// == STOP AND PRICE LEVELS ==inPosition = strategy.position_size > 0buyLevel := inPosition ? buyLevel[1] : buyLevelstopDefine = ta.valuewhen(pl, low[lbLow], 0) //Stop Level at Swing LowinProfit = strategy.position_avg_price <= stopDefine[1]// stopLevel := inPosition ? stopLevel[1] : stopDefine // Set stop loss based on swing low and leave it therestopLevel := inPosition and not inProfit ? stopDefine : inPosition and inProfit ? stopLevel[1] : stopDefine // Trail stop loss until in profittrailStopLevel = float(na)// trying to figure out a better way for waiting on the trail stop - it can trigger if above the stopLevel even if the MA hadn't been breached since opening the tradenotInPosition = strategy.position_size == 0inPositionBars = ta.barssince(notInPosition)maCrossBars = ta.barssince(maCrossEvent)trailCross = inPositionBars > maCrossBars// trailCross = trailMa > stopLeveltrailStopLevel := inPosition and trailCross ? maCrossLevel : naplot(inPosition ? stopLevel : na, style=plot.style_linebr, color=colorStop, linewidth = 2, title = "Historical Stop Levels", trackprice=false)plot(inPosition ? trailStopLevel : na, style=plot.style_linebr, color=colorTrail, linewidth = 2, title = "Historical Trail Stop Levels", trackprice=false)// == PLOT SUPPORT/RESISTANCE LINES FOR CURRENT CHART TIMEFRAME ==// Use a function to define the linesf_line(x1, y1, y2, _color) => var line id = na line.delete(id) id := line.new(x1, y1, time, y2, xloc.bar_time, extend.right, _color)highLine = f_line(timeSinceHigh, highLevel, highLevel, currentColorR)lowLine = f_line(timeSinceLow, lowLevel, lowLevel, currentColorS)// == ADR TABLE ==tablePos = tableLocation == "Top" ? position.top_right : position.bottom_rightvar table adrTable = table.new(tablePos, 2, 1, border_width = 3)lightTransp = 90avgTransp = 80heavyTransp = 70posColor = color.rgb(38, 166, 154)negColor = color.rgb(240, 83, 80)volColor = color.new(#999999, 0)f_fillCellVol(_table, _column, _row, _value) => _transp = math.abs(_value) > 7 ? heavyTransp : math.abs(_value) > 4 ? avgTransp : lightTransp _cellText = str.tostring(_value, "0.00") + "%\n" + "ADR" table.cell(_table, _column, _row, _cellText, bgcolor = color.new(volColor, _transp), text_color = volColor, width = 6)srDistance = (highLevel - lowLevel)/highLevel * 100f_fillCellCalc(_table, _column, _row, _value) => _c_color = _value >= adrCompare ? negColor : posColor _transp = _value >= adrCompare*0.8 and _value <= adrCompare*1.2 ? lightTransp : _value >= adrCompare*0.5 and _value < adrCompare*0.8 ? avgTransp : _value < adrCompare*0.5 ? heavyTransp : _value > adrCompare*1.2 and _value <= adrCompare*1.5 ? avgTransp : _value > adrCompare*1.5 ? heavyTransp : na _cellText = str.tostring(_value, "0.00") + "%\n" + "Range" table.cell(_table, _column, _row, _cellText, bgcolor = color.new(_c_color, _transp), text_color = _c_color, width = 6)if barstate.islast f_fillCellVol(adrTable, 0, 0, adrValue) f_fillCellCalc(adrTable, 1, 0, srDistance) // f_fillCellVol(adrTable, 0, 0, inPositionBars) // f_fillCellCalc(adrTable, 1, 0, maCrossBars)// == STRATEGY ENTRY AND EXIT ==strategy.entry("Buy", strategy.long, stop = buyLevel, when = buyConditions)stop = stopLevel > trailStopLevel ? stopLevel : close[1] > trailStopLevel and close[1] > trailMa ? trailStopLevel : stopLevelstrategy.exit("Sell", from_entry = "Buy", stop=stop)