Pine Script v5 · Strategy
AVWAP Strategy
A Pine Script v5 strategy built on Crossover (out, sig), Crossunder (out, sig) and RSI (hlc3, 64). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 36 settings; defaults include Heikin-Ashi Better Caculation Type Kaufman, Source Close and AMA Period 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 AVWAP Strategy repaint?
- No
- No repainting patterns were found in the source.
- What alerts does AVWAP Strategy have?
- 5
- Long; Short; Breakout (▲▼); Resistance Broken ▲; and more.
- Does AVWAP Strategy run in Pine Script v6?
- Not tested
- The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L7:C0: no source was supplied for the library 'loxx/loxxexpandedsourcetypes/4'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
- Does AVWAP Strategy use a stop loss?
- Yes
- strategy.exit sets a stop on line 292, 295.
- Does AVWAP Strategy run in Zeal Terminal?
- No
- Not yet: it imports the library loxx/loxxexpandedsourcetypes/4, whose source is not available here, so it does not run here
Review
What a careful reader of this script would point out, found by checking the source.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
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 |
|---|---|---|---|
| Source Settings | |||
| Heikin-Ashi Better Caculation Type | Kaufman | string · options ["AMA", "T3", "Kaufman"] | src |
| Source | Close | string · options ["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)", "HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)", "HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"] | src |
| Basic Settings | |||
| AMA Period | 10 | int | out |
| Fast-End | 2 | int | out |
| Slow-End | 20 | int | out |
| Smooth Power | 2 | int | out |
| Jurik Fractal Dimension Adaptive? | false | bool | out |
| Filter Settings | |||
| Filter Options | Both | string · options ["Price", "JFDAGKYZFKAMA", "Both", "None"] | out src |
| Filter Multiple | 0.5 | float · min 0 | out filtdev src |
| Filter Period | 15 | int · min 0 | out src |
| UI Options | |||
| Color bars? | true | bool | barcolor |
| Show Signals? | true | bool | Long Short |
| Moving Average Inputs | |||
| * Kaufman's Adaptive MA (KAMA) Only - Fast End | 0.666 | float | src |
| * Kaufman's Adaptive MA (KAMA) Only - Slow End | 0.0645 | float | src |
| * Adaptive Moving Average (AMA) Only - Fast | 2 | int | src |
| * Adaptive Moving Average (AMA) Only - Slow | 30 | int | src |
| Coloring | |||
| Colour Candles to Trade Order state | true | bool | bclr |
| Anchored VWAP | |||
| Use High/Low instead of HLC3When true, high and low values are used to caclulate the value of each AVWAP instead of HLC3. | true | bool | vwapHi vwapLo |
| Use open instead of close for alerts.Using the open instead of the close is more confirmative of a breakout as live values are based upon the close value and could be transient. | true | bool | alertValue |
| Stochastic RSI | |||
| K Mode | WMA | string · options [SMA, EMA, WMA, VWMA, VAWMA] | k |
| Source | hlc3 | source | sum rsi1 |
| K | 4 | int · min 1 | k |
| D | 4 | int · min 1 | d |
| stdev filter | 5 | int | buy sell Low Below loAVWAP Arrow |
| Use Percentage for Stop Loss | true | bool | stopLossPricebuy stopLossPricesell |
| Use Percentage for Take Profit | true | bool | takeProfitPricebuy takeProfitPricesell |
| Stop Loss (%) | 0.15 | float · step 0.1 | stopLossPricebuy stopLossPricesell |
| Take Profit (%) | 0.5 | float · step 0.1 | takeProfitPricebuy takeProfitPricesell |
| Stop Loss (Points) | 10 | float · step 1 | stopLossPricebuy stopLossPricesell |
| Take Profit (Points) | 15 | float · step 1 | takeProfitPricebuy takeProfitPricesell |
| Lengths | |||
| RSI | 64 | int · min 1 | rsi1 |
| Stochastic | 48 | int · min 1 | stoch |
| Band | |||
| Lower | 20 | int · min 0 · max 50 | line 210 line 240 |
| Upper | 80 | int · min 50 · max 100 | line 215 line 243 |
| Reversal | |||
| LowerThe level that if broken (down) signfies a reversal has begun/occured.\nDefault represents the lower band. | 20 | int · min 0 · max 100 | line 246 |
| UpperThe level that if broken (up) signfies a reversal has begun/occured.\nDefault represents the upper band. | 80 | int · min 0 · max 100 | line 251 |
What it calculates
- Crossoverout, sig
goLong_pre · line 132 - Crossunderout, sig
goShort_pre · line 133 - RSISource (hlc3), RSI (64)
rsi1 · line 190 - Stochrsi1, rsi1, rsi1, Stochastic (48)
stoch · line 191 - SMAk, D (4)
d · line 193 - Changek
k_c · line 194 - Changed
d_c · line 195 - Stdevclose, 50
bbwidth · line 264
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 119 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 | buy | On | 291 |
| Exit Take Profit/Stop Loss stop and limit | buy | On | 292 |
| Open Sell short | sell | On | 294 |
| Exit Take Profit/Stop Loss stop and limit | sell | On | 295 |
| Close SellToExit | strategy.position_size > 0 and selltoexit | On | 298 |
| Close BuyToExit | strategy.position_size < 0 and buytoexit | On | 300 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| Long | alertcondition | JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}} | 144 |
| Short | alertcondition | JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}} | 145 |
| Breakout (▲▼) | alertcondition | Breakout ({{ticker}} {{interval}}) | 272 |
| Resistance Broken ▲ | alertcondition | Resistance Broken ▲ ({{ticker}} {{interval}}) | 273 |
| Support Broken ▼ | alertcondition | Support Broken ▼ ({{ticker}} {{interval}}) | 274 |
Does it repaint?
No
No repainting patterns in the source.
The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.
- ClearHigher-timeframe data8 request.security call(s), none with lookahead on.
- 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.
Similar scripts
Indicators and strategies built from the same calculations.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Bottom catch strategy by footlz | sma stdev rsi | v4 strategy | +3.9% | 3 | 7.1% |
| Madri by Mdemoio | rsi sma stdev | v4 strategy | +25.0% | 4 | 36.4% |
| Bollinger Bands and RSI Short Selling (by Coinrule) by Coinrule | sma stdev rsi | v5 strategy | +7.6% | 3 | 4.3% |
| Shorting when Bollinger Band Above Price with RSI (by Coinrule) by Coinrule | sma stdev rsi | v5 strategy | No trades on this market | ||
| RSI_Boll-TP-SL by BigCoinHunter | sma stdev rsi | v5 strategy | No trades on this market | ||
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.
- No v6-only features. v6 is not needed to run this script.
Clean v5
VerifiedNothing to change.
Does it run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L7:C0: no source was supplied for the library 'loxx/loxxexpandedsourcetypes/4'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © loxx-//@version=5+//@version=6strategy("AVWAP Stragey",⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | No It imports the library loxx/loxxexpandedsourcetypes/4, whose source is not available here, so it does not run here | 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/// © loxx//@version=5strategy("AVWAP Stragey", shorttitle = "AVWAP Strategy", overlay = true)import loxx/loxxexpandedsourcetypes/4 as loxxexpandedsourcetypesgreencolor = #2DD204redcolor = #D2042D fdRange(int size)=> out = math.max(nz(close[size]), ta.highest(high, size)) - math.min(nz(close[size]), ta.lowest(low, size)) out jurikFractalDimension(int size, int count)=> int window1 = size * (count - 1) int window2 = size * count float smlRange = 0 float smlSumm = 0 smlRange := fdRange(size) smlSumm := nz(smlSumm[1]) + smlRange smlSumm -= nz(smlRange[window1]) out = 2.0 - math.log(fdRange(window2) / (smlSumm / window1)) / math.log(count) outkama(float src, int period, float fast, float slow, float power, bool JurikFD)=> float fastend = (2.0 / (fast + 1)) float slowend = (2.0 / (slow + 1)) float efratio = 0 float diff = 0 float signal = 0 float noise = 0 float fract = jurikFractalDimension(period, 2) if (JurikFD) efratio := math.min(2.0 - fract, 1.0) else signal := math.abs(src - nz(src[period])) diff := math.abs(src - nz(src[1])) for k = 0 to period - 1 noise += nz(diff[k]) if (noise != 0) efratio := signal / noise else efratio := 1 float smooth = math.pow(efratio * (fastend - slowend) + slowend, power) float kama = src kama := nz(kama[1]) + smooth * (src - nz(kama[1])) kamagkyzvol(int per)=> float gzkylog = math.log(open / nz(close[1])) float pklog = math.log(high / low) float gklog = math.log(close / open) float garmult = (2 * math.log(2) - 1) float gkyzsum = 1 / per * math.sum(math.pow(gzkylog, 2), per) float parkinsonsum = 1 / (2 * per) * math.sum(math.pow(pklog, 2), per) float garmansum = garmult / per * math.sum(math.pow(gklog, 2), per) float sum = gkyzsum + parkinsonsum - garmansum float devpercent = math.sqrt(sum) devpercentgkyzFilter(float src, int len, float filter)=> float price = src float filtdev = filter * gkyzvol(len) * src price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price pricesmthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")srcin = input.string("Close", "Source", group= "Source Settings", options = ["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)", "HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)", "HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])AmaPeriod = input.int(10, "AMA Period", group = "Basic Settings")FastEnd = input.int(2, "Fast-End", group = "Basic Settings")SlowEnd = input.int(20, "Slow-End", group = "Basic Settings")SmoothPower = input.int(2, "Smooth Power", group = "Basic Settings")JurikFDAdaptive = input.bool(false, "Jurik Fractal Dimension Adaptive?", group = "Basic Settings")filterop = input.string("Both", "Filter Options", options = ["Price", "JFDAGKYZFKAMA", "Both", "None"], group= "Filter Settings")filter = input.float(0.5, "Filter Multiple", minval = 0, group= "Filter Settings")filterperiod = input.int(15, "Filter Period", minval = 0, group= "Filter Settings")colorbars = input.bool(true, "Color bars?", group= "UI Options")showSigs = input.bool(true, "Show Signals?", group = "UI Options")kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)float src = switch srcin "Close" => loxxexpandedsourcetypes.rclose() "Open" => loxxexpandedsourcetypes.ropen() "High" => loxxexpandedsourcetypes.rhigh() "Low" => loxxexpandedsourcetypes.rlow() "Median" => loxxexpandedsourcetypes.rmedian() "Typical" => loxxexpandedsourcetypes.rtypical() "Weighted" => loxxexpandedsourcetypes.rweighted() "Average" => loxxexpandedsourcetypes.raverage() "Average Median Body" => loxxexpandedsourcetypes.ravemedbody() "Trend Biased" => loxxexpandedsourcetypes.rtrendb() "Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext() "HA Close" => loxxexpandedsourcetypes.haclose(haclose) "HA Open" => loxxexpandedsourcetypes.haopen(haopen) "HA High" => loxxexpandedsourcetypes.hahigh(hahigh) "HA Low" => loxxexpandedsourcetypes.halow(halow) "HA Median" => loxxexpandedsourcetypes.hamedian(hamedian) "HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical) "HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted) "HA Average" => loxxexpandedsourcetypes.haaverage(haaverage) "HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen) "HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow) "HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow) "HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl) "HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl) "HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl) "HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl) "HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl) "HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl) "HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl) "HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl) "HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl) "HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl) "HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl) => haclose src := filterop == "Both" or filterop == "Price" and filter > 0 ? gkyzFilter(src, filterperiod, filter) : srcout = kama(src, AmaPeriod, FastEnd, SlowEnd, SmoothPower, JurikFDAdaptive)out := filterop == "Both" or filterop == "JFDAGKYZFKAMA" and filter > 0 ? gkyzFilter(out, filterperiod, filter) : outsig = out[1]goLong_pre = ta.crossover(out, sig)goShort_pre = ta.crossunder(out, sig)contSwitch = 0contSwitch := nz(contSwitch[1])contSwitch := goLong_pre ? 1 : goShort_pre ? -1 : contSwitchgoLong = goLong_pre and ta.change(contSwitch)goShort = goShort_pre and ta.change(contSwitch)colorout = contSwitch == 1 ? greencolor : redcolorbarcolor(colorbars ? colorout : na)plot(out, "JFDAGKYZFKAMA", color = colorout, linewidth = 3)plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)alertcondition(goLong, title="Long", message="JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")alertcondition(goShort, title="Short", message="JFD-Adaptive, GKYZ-Filtered KAMA [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")//@version=5// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © Electrified (electrifiedtrading)kcolor = #0094FFdcolor = #FF6A00WMA = 'WMA'EMA = 'EMA'SMA = 'SMA'VWMA = 'VWMA'VAWMA = 'VAWMA'///////////////////////////////////////////////////// InputclrBars = input.bool(true, title='Colour Candles to Trade Order state', group='Coloring')useHiLow = input.bool(true, 'Use High/Low instead of HLC3', group='Anchored VWAP', tooltip='When true, high and low values are used to caclulate the value of each AVWAP instead of HLC3.')useOpen = input.bool(true, 'Use open instead of close for alerts.', group='Anchored VWAP', tooltip='Using the open instead of the close is more confirmative of a breakout as live values are based upon the close value and could be transient.')k_mode = input.string(WMA, 'K Mode', group='Stochastic RSI', inline='Source', options=[SMA, EMA, WMA, VWMA, VAWMA])src1 = input.source(hlc3, 'Source', group='Stochastic RSI', inline='Source')smoothK = input.int(4, 'K', group='Stochastic RSI', inline='Values', minval=1)smoothD = input.int(4, 'D', group='Stochastic RSI', inline='Values', minval=1)stdevfilter = input.int(5, "stdev filter", inline='Values')lengthRSI = input.int(64, 'RSI', group='Lengths', inline='Lengths', minval=1)lengthStoch = input.int(48, 'Stochastic', group='Lengths', inline='Lengths', minval=1)lowerBand = input.int(20, 'Lower', group='Band', inline='Band', maxval=50, minval=0)upperBand = input.int(80, 'Upper', group='Band', inline='Band', minval=50, maxval=100)lowerReversal = input.int(20, 'Lower', group='Reversal', inline='Reversal', maxval=100, minval=0, tooltip='The level that if broken (down) signfies a reversal has begun/occured.\nDefault represents the lower band.')upperReversal = input.int(80, 'Upper', group='Reversal', inline='Reversal', minval=0, maxval=100, tooltip='The level that if broken (up) signfies a reversal has begun/occured.\nDefault represents the upper band.')///////////////////////////////////////////////////// Functionsvawma(src1, len) => sum = 0.0 vol = 0.0 for m = 1 to len by 1 // m = triangular multiple i = len - m v = volume[i] * m vol += v sum += src1[i] * v sum sum / vol////getMA(series, mode, len) => mode == WMA ? ta.wma(series, len) : mode == EMA ? ta.ema(series, len) : mode == VWMA ? ta.vwma(series, len) : mode == VAWMA ? vawma(series, len) : ta.sma(series, len)///////////////////////////////////////////////////////// Calculationrsi1 = ta.rsi(src1, lengthRSI)stoch = ta.stoch(rsi1, rsi1, rsi1, lengthStoch)k = getMA(stoch, k_mode, smoothK)d = ta.sma(k, smoothD)k_c = ta.change(k)d_c = ta.change(d)kd = k - dvar hi = highvar lo = lowvar phi = highvar plo = lowvar state = 0var float hiAVWAP_s = 0var float loAVWAP_s = 0var float hiAVWAP_v = 0var float loAVWAP_v = 0var float hiAVWAP_s_next = 0var float loAVWAP_s_next = 0var float hiAVWAP_v_next = 0var float loAVWAP_v_next = 0if d < lowerBand or high > phi phi := high hiAVWAP_s_next := 0 hiAVWAP_v_next := 0 hiAVWAP_v_nextif d > upperBand or low < plo plo := low loAVWAP_s_next := 0 loAVWAP_v_next := 0 loAVWAP_v_nextif high > hi hi := high hiAVWAP_s := 0 hiAVWAP_v := 0 hiAVWAP_vif low < lo lo := low loAVWAP_s := 0 loAVWAP_v := 0 loAVWAP_vvwapHi = useHiLow ? high : hlc3vwapLo = useHiLow ? low : hlc3hiAVWAP_s += vwapHi * volumeloAVWAP_s += vwapLo * volumehiAVWAP_v += volumeloAVWAP_v += volumehiAVWAP_s_next += vwapHi * volumeloAVWAP_s_next += vwapLo * volumehiAVWAP_v_next += volumeloAVWAP_v_next += volumeif state != -1 and d < lowerBand state := -1 stateelse if state != +1 and d > upperBand state := +1 stateif hi > phi and state == +1 and k < d and k < lowerReversal hi := phi hiAVWAP_s := hiAVWAP_s_next hiAVWAP_v := hiAVWAP_v_next hiAVWAP_vif lo < plo and state == -1 and k > d and k > upperReversal lo := plo loAVWAP_s := loAVWAP_s_next loAVWAP_v := loAVWAP_v_next loAVWAP_vhiAVWAP = hiAVWAP_s / hiAVWAP_vloAVWAP = loAVWAP_s / loAVWAP_vhiAVWAP_next = hiAVWAP_s_next / hiAVWAP_v_nextloAVWAP_next = loAVWAP_s_next / loAVWAP_v_nextplot(hiAVWAP_next, 'High Next', color.new(color.red, 75), 1, style=plot.style_circles)plot(loAVWAP_next, 'Low Next', color.new(color.green, 75), 1, style=plot.style_circles)plot(hiAVWAP, 'High', color.new(color.red, 50), 2, style=plot.style_circles)plot(loAVWAP, 'Low', color.new(color.green, 50), 2, style=plot.style_circles)bbwidth = ta.stdev(close, 50)alertValue = useOpen ? open : closeresistance = alertValue - hiAVWAPsupport = alertValue - loAVWAPbuy = low < loAVWAP and close > loAVWAP and bbwidth >= stdevfilter and colorout == greencolor and colorout[1] == coloroutsell = high > hiAVWAP and close < hiAVWAP and bbwidth >= stdevfilter and colorout == redcolor and colorout[1] == coloroutbuytoexit = low < loAVWAP and close > loAVWAP and colorout == greencolorselltoexit = high > hiAVWAP and close < hiAVWAP and colorout == redcoloralertcondition(resistance > 0 or support < 0, title='Breakout (▲▼)', message='Breakout ({{ticker}} {{interval}})')alertcondition(resistance > 0, title='Resistance Broken ▲', message='Resistance Broken ▲ ({{ticker}} {{interval}})')alertcondition(support < 0, title='Support Broken ▼', message='Support Broken ▼ ({{ticker}} {{interval}})')plotarrow(low < loAVWAP and close > loAVWAP and bbwidth >= stdevfilter and colorout == greencolor and colorout[1] == colorout ? 1 : na, title='Low Below loAVWAP Arrow', colorup=color.new(color.green, 35), offset=-1)plotarrow(high > hiAVWAP and close < hiAVWAP and bbwidth >= stdevfilter and colorout == redcolor and colorout[1] == colorout ? 1 : na, title='Low Below loAVWAP Arrow', colorup=color.new(color.red, 35), offset=-1)// Input options for stop loss and take profitusePercentSL = input.bool(true, "Use Percentage for Stop Loss")usePercentTP = input.bool(true, "Use Percentage for Take Profit")stopLossPercent = input.float(0.15, "Stop Loss (%)", step = 0.1)takeProfitPercent = input.float(0.5, "Take Profit (%)", step = 0.1)stopLossPoints = input.float(10, "Stop Loss (Points)", step = 1)takeProfitPoints = input.float(15, "Take Profit (Points)", step = 1)// Calculate stop loss and take profit levelsstopLossPricebuy = usePercentSL ? strategy.position_avg_price * (1 - stopLossPercent / 100) : strategy.position_avg_price - stopLossPointstakeProfitPricebuy = usePercentTP ? strategy.position_avg_price * (1 + takeProfitPercent / 100) : strategy.position_avg_price + takeProfitPointsstopLossPricesell = usePercentSL ? strategy.position_avg_price * (1 + stopLossPercent / 100) : strategy.position_avg_price + stopLossPointstakeProfitPricesell = usePercentTP ? strategy.position_avg_price * (1 - takeProfitPercent / 100) : strategy.position_avg_price - takeProfitPoints// Strategy logicif buy strategy.entry("Buy", strategy.long,alert_message="buy SPX500 q=0.5") strategy.exit("Take Profit/Stop Loss", from_entry = "Buy", limit = takeProfitPricebuy, stop = stopLossPricebuy, alert_message="close SPX500 long t=1")if sell strategy.entry("Sell", strategy.short,alert_message="sell SPX500 q=0.5") strategy.exit("Take Profit/Stop Loss", from_entry = "Sell", limit = takeProfitPricesell, stop = stopLossPricesell, alert_message="close SPX500 short t=1") if strategy.position_size > 0 and selltoexit strategy.close("SellToExit", alert_message="close SPX500 long t=2")if strategy.position_size < 0 and buytoexit strategy.close("BuyToExit", alert_message="close SPX500 short t=2")// Plot the bars with trade highlightingbclr = not clrBars ? na : strategy.position_size == 0 ? color.gray : buy ? color.lime : sell ? color.red : color.gray