Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (14)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$135,998$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep.
Table drawn by the script, as it stood on the last bar
2.52% ADR5.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.

SettingDefaultType and rangeFeeds
backtest window and pivot history
Backtest Start Datetimestamp("01 Jan 2019 06:00 +0000")timebuyConditions
Backtest End Datetimestamp("01 Jan 2100 00:00 +0000")timebuyConditions
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.falseboolTop 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.Dtimeframema1 ma2 ma3 crossTF
Moving Average TypeSMAstring · options ["EMA", "SMA"]ma1 ma2 ma3 line 50
1st Moving Average: Length10int · min 1ma1
Colorcolor.new(color.purple, 60)colorMA1
2nd Moving Average: Length20int · min 1ma2
Colorcolor.new(color.yellow, 60)colorMA2
3rd Moving Average: Length50int · min 1ma3
Colorcolor.new(color.white, 60)colorMA3
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.trueboolbuyConditions
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 Averagestring · 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 Averagesstring · options ["Same as Moving Averages", "Same as Chart"]crossTF
Current Range S/R Colors: Supportcolor.new(color.orange,50)colorlowLine
Resistancecolor.new(color.blue,50)colorhighLine
Stop Colors: Initialcolor.new(color.orange,50)colorHistorical Stop Levels
Moving Average Trailingcolor.new(color.blue,50)colorHistorical 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.falseboolbuyConditions
% of ADR Value120int · min 1adrCompare
ADR Table VisibilityPlace ADR table on the top of the pane, the bottom of the pane, or off.Bottomstring · options ["Top", "Bottom"]tablePos

What it calculates

  • SMA(high-low)/math.abs(low) * 100, 21adrValue · line 66
  • Pivothighhigh, lbHigh, lbHighph · line 69
  • Pivotlowlow, lbLow, lbLowpl · line 70
  • Valuewhenph, high[lbHigh], 0highLevel · line 71
  • Valuewhenpl, low[lbLow], 0lowLevel · line 72
  • BarssincephbarsSinceHigh · line 73
  • BarssinceplbarsSinceLow · line 74
  • Valuewhenph, high[lbHigh], 0buyLevel · line 88
  • Valuewhenpl, low[lbLow], 0stopDefine · line 109
  • BarssincenotInPositioninPositionBars · line 116
  • BarssincemaCrossEventmaCrossBars · 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

OrderFires whenBy defaultLine
Open Buy longbuyConditionsOn160
Exit Sell stopevery barOn162

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.

9/10trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. On 18 of them the position changed while the bar was forming before it settled. Anyone watching live sees those changes; once the bar closes it matches history.

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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+35.4%+102.5%3345%1.5616.9%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−7.1%+5.5%1729%0.7413.4%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+66.8%+9.8%2540%1.4719.7%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+3.6%+8.4%1724%1.1412.8%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+16.7%+16.7%2938%1.1441.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+6.3%+21.5%1822%1.1615.8%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−59.4%+148.3%3622%0.3563.4%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+25.5%+17.1%1354%4.834.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 barsTradesWonP&L
Rising market1338%$10,210.40
Sideways market1650%$14,059.50
Falling market450%$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.

0%33%
All 33 trades
SideEntryExitBarsP&L
long16 Mar 2024 69,499.802 Apr 2024 68,062.9017−$2,263.27
long8 Apr 2024 71,769.5010 Apr 2024 68,210.002−$5,033.02
long15 May 2024 65,500.0029 May 2024 68,128.0014$3,526.83
long4 Jun 2024 70,687.6011 Jun 2024 69,130.207−$2,308.09
long19 Jul 2024 63,987.9025 Jul 2024 65,111.006$1,457.52
long27 Jul 2024 68,474.6030 Jul 2024 66,428.003−$3,035.57
long23 Aug 2024 62,745.1028 Aug 2024 58,034.005−$7,104.20
long17 Sep 2024 60,625.001 Oct 2024 62,856.3014$2,960.68
long14 Oct 2024 64,478.2023 Oct 2024 66,571.409$2,681.42
long24 Oct 2024 66,668.603 Nov 2024 68,820.1010$2,745.46
long6 Nov 2024 73,620.1026 Nov 2024 92,600.2020$23,903.00
long4 Dec 2024 98,620.005 Dec 2024 90,791.101−$9,546.29
long6 Dec 2024 98,620.0019 Dec 2024 100,000.0013$1,292.28
long6 Jan 2025 99,963.708 Jan 2025 96,181.802−$4,344.30
long17 Jan 2025 102,724.0027 Jan 2025 102,520.0010−$417.56
long21 Apr 2025 86,496.405 May 2025 94,151.4014$9,022.29
long8 May 2025 97,895.7028 May 2025 107,517.0020$10,908.90
long9 Jun 2025 106,795.0013 Jun 2025 105,672.004−$1,554.58
long2 Jul 2025 108,952.007 Jul 2025 107,800.005−$1,542.74
long9 Jul 2025 110,529.0025 Jul 2025 116,813.0016$6,642.43
long11 Aug 2025 119,800.0015 Aug 2025 117,180.004−$3,049.27
long18 Sep 2025 117,429.0022 Sep 2025 114,384.004−$3,483.03
long1 Oct 2025 117,900.0010 Oct 2025 119,651.009$1,558.06
long2 Jan 2026 90,406.1020 Jan 2026 89,311.0018−$1,732.90
long16 Mar 2026 74,050.0019 Mar 2026 70,500.003−$6,045.14
long6 Apr 2026 69,310.0020 Apr 2026 73,762.9014$7,158.62
long22 Apr 2026 78,333.0028 Apr 2026 76,459.606−$3,165.88
long4 May 2026 79,485.7013 May 2026 79,843.609$297.61
long14 Jul 2026 64,692.8024 Jul 2026 64,650.0010−$317.80
long9 Aug 2026 65,409.6011 Aug 2026 63,806.302−$3,154.40
long19 Aug 2026 65,474.501 Sep 2026 76,888.0013$19,958.80
long3 Sep 2026 81,478.908 Sep 2026 78,680.005−$4,934.69
long18 Sep 2026 79,890.008 Oct 2026 82,787.3020$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.

ScriptSharesTypeNetTradesMax drawdown
Qullamaggie Breakout V2 this page—v5 strategy+35.4%3316.9%
Alert(), alertcondition() or strategy alerts- by Peter_Osma pivothigh pivotlow valuewhenv4 strategy+7,640,000.0%191919.9%
Quantitative Trend Strategy- Uptrend long by CheatCode1sma pivothigh pivotlow valuewhenv5 strategy+5.9%2832.8%
Moving Stop-Loss mechanism + alerts to MT4-MT5 by Peter_Osma pivothigh pivotlow valuewhenv5 strategy−9,857,600.0%1914,436.8%
TradingView Alerts to MT4 MT5 - Forex, indices, commodities by Peter_Osma pivothigh pivotlow valuewhenv4 strategy−699,283.0%3823,138.7%
TradePro's 2 EMA + Stoch RSI + ATR Strategy by PtGamblersma pivothigh pivotlow valuewhenv5 strategy−2.7%1822.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.

Clean v5

VerifiedDownload the v5 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.

Download the v6 script

⋯// 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

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 69 msYes 1,000 bars in 194 msNot measured
PineTSNot testedNot testedNot 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)