Pine Script v4 · Strategy
Volatility Bands Reversal Strategy [Long Only]
A Pine Script v4 strategy built on EMA (deviation, 8) and SMA (medianAvg, 8). It has 4 order rules, 1 entry among them, and trades long only with the default settings. Exits wait for a signal; there is no stop loss. Each trade commits 20% of equity and pays no commission. 7 settings; defaults include Band Average 8, Volatility Period 13 and Deviation Factor 3.33.
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 Volatility Bands Reversal Strategy [Long Only] repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did Volatility Bands Reversal Strategy [Long Only] do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings; it opened a long position that was still open on the last bar, so there is no result to report. On ETHUSDT 1D it did trade; that row of the markets table below has its figures. A backtest, not investment advice.
- Can Volatility Bands Reversal Strategy [Long Only] 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 Volatility Bands Reversal Strategy [Long Only] use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
- Does Volatility Bands Reversal Strategy [Long Only] run in Zeal Terminal?
- Yes
- It compiles in 16 ms and runs 1,000 bars in 54 ms, in the browser.
BTCUSDT · 1D · default settings
- UpperBand
- LowerBand
- MidLine
- BuyLine
- ema 50
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 69.48%
- −$6,948.09
One run with the author's default settings, $10,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.
-
Likely bug
ema(hlc3, 50) ignores the settings line 32
Line 32 hard-codes 50 where line 19 uses “Band Average”. Changing those settings moves one band but not this one.
ema(hlc3,50)ema(hlc3, av) -
Check
No stop loss
Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.
-
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.
-
Note
Uses an argument v6 removed
when = on line 66, 72, 74, 76. The upgraded version below moves each call inside an if block.
-
Note
Uses long =, which v5 renamed line 66
long = on line 66. v5 writes it as direction = strategy.long or strategy.short.
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 sum → math.sum, ema → ta.ema, sma → ta.sma, tostring → str.tostring, abs → math.abs, crossover → ta.crossover.
- 4 strategy calls use the when = argument (line 66, 72, 74, 76). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 3 trades and the same P&L on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 4: //@version=4 → //@version=5
- Line 18: sum → math.sum
- Line 19: ema → ta.ema
- Line 21: ema → ta.ema
- Line 22: ema → ta.ema
- Line 25: sma → ta.sma
10 more edits
- Line 30: ema → ta.ema
- Line 31: ema → ta.ema
- Line 32: ema → ta.ema
- Line 66: long = true → direction = strategy.long
- Line 72: tostring → str.tostring
- Line 72: abs → math.abs
- Line 74: tostring → str.tostring
- Line 76: tostring → str.tostring
- Line 76: crossover → ta.crossover
- Line 76: crossover → ta.crossover
⋯//strategy logic has been borrowed from ceyhun and tweaked the settings for back testing-//@version=4+//@version=5//SPY 4 hrs settings 8, 13 , 3.33 , 0.9 on 4 hrs chart⋯typical = src >= src[1] ? src - low[1] : src[1] - low-deviation = sum( typical , vp )/ vp * df+deviation = math.sum( typical , vp )/ vp * df-devHigh = ema(deviation, av)+devHigh = ta.ema(deviation, av)devLow = lba * devHigh-medianAvg = ema(src, av)+medianAvg = ta.ema(src, av)-emaMediaAvg=ema(medianAvg, av)+emaMediaAvg=ta.ema(medianAvg, av)upperBandVal= emaMediaAvg + devHighlowerbandVal= emaMediaAvg - devLow-MidLineVal=sma(medianAvg, av)+MidLineVal=ta.sma(medianAvg, av)UpperBand = plot ( upperBandVal, color=#EE82EE, linewidth=2, title="UpperBand")⋯buyLine = plot ( (lowerbandVal + MidLineVal )/2 , color=color.blue, title="BuyLine")-up=ema(medianAvg, av) + devHigh+up=ta.ema(medianAvg, av) + devHigh-down=ema(medianAvg, av) - devLow+down=ta.ema(medianAvg, av) - devLow-ema50=ema(hlc3,50)+ema50=ta.ema(hlc3,50)plot ( ema50, color=color.orange, linewidth=2, title="ema 50")⋯qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1-strategy.entry(id="vbLE", long=true, qty=qty1, when=Buy)+strategy.entry(id="vbLE", direction = strategy.long, qty=qty1, when=Buy)bgcolor(strategy.position_size>=1 ? color.blue : na)⋯plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss") //, trackprice=true)-strategy.close(id="vbLE", comment="SL exit Loss is "+tostring(close - strategy.position_avg_price, "###.##") , when=abs(strategy.position_size)>=1 and close < stopLossVal ) +strategy.close(id="vbLE", comment="SL exit Loss is "+str.tostring(close - strategy.position_avg_price, "###.##") , when=math.abs(strategy.position_size)>=1 and close < stopLossVal ) //close on Sell_Signal-strategy.close(id="vbLE", comment="Profit is : "+tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell)+strategy.close(id="vbLE", comment="Profit is : "+str.tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell)//close on touch_upperband-strategy.close(id="vbLE", comment="Profit is : "+tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="touch_upperband" and (crossover(close, up) or crossover(high, up)))+strategy.close(id="vbLE", comment="Profit is : "+str.tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="touch_upperband" and (ta.crossover(close, up) or ta.crossover(high, up)))Same 3 trades and the same P&L on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 9: input() → input.int()
- Line 10: input() → input.int()
- Line 11: input() → input.float()
- Line 12: input() → input.float()
- Line 13: input() → input.int()
- Line 14: input() → input.int()
5 more edits
- Line 15: input() → input.string()
- Line 66: when = Buy → if block
- Line 72: when = math.abs(strategy.position_size)>=1 and close < stopLossVal → if block
- Line 74: when = strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell → if block
- Line 76: when = strategy.position_size>=1 and exitOn=="touch_upperband" and (ta.crossover(close, up) or ta.crossover(high, up)) → if block
⋯strategy(title="Volatility Bands Reversal Strategy", shorttitle="VolatilityBandReversal" , overlay=true, pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,-av = input(8, title="Band Average")+av = input.int(8, title="Band Average")-vp = input(13, title="Volatility Period")+vp = input.int(13, title="Volatility Period")-df = input(3.33,title="Deviation Factor",minval=0.1)+df = input.float(3.33,title="Deviation Factor",minval=0.1)-lba = input(0.9,title="Lower Band Adjustment",minval=0.1)+lba = input.float(0.9,title="Lower Band Adjustment",minval=0.1)-riskCapital = input(title="Risk % of capital", defval=10, minval=1)+riskCapital = input.int(title="Risk % of capital", defval=10, minval=1)-stopLoss=input(6,title="Stop Loss",minval=1)+stopLoss=input.int(6,title="Stop Loss",minval=1)-exitOn=input(title="Exit on", defval="touch_upperband", options=["Sell_Signal", "touch_upperband"])+exitOn=input.string(title="Exit on", defval="touch_upperband", options=["Sell_Signal", "touch_upperband"])src = hlc3⋯qty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1-strategy.entry(id="vbLE", direction = strategy.long, qty=qty1, when=Buy)+if Buy+ strategy.entry(id="vbLE", direction = strategy.long, qty=qty1)bgcolor(strategy.position_size>=1 ? color.blue : na)⋯plot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss") //, trackprice=true)-strategy.close(id="vbLE", comment="SL exit Loss is "+str.tostring(close - strategy.position_avg_price, "###.##") , when=math.abs(strategy.position_size)>=1 and close < stopLossVal ) +if math.abs(strategy.position_size)>=1 and close < stopLossVal+ strategy.close(id="vbLE", comment="SL exit Loss is "+str.tostring(close - strategy.position_avg_price, "###.##") ) //close on Sell_Signal-strategy.close(id="vbLE", comment="Profit is : "+str.tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell)+if strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell+ strategy.close(id="vbLE", comment="Profit is : "+str.tostring(close - strategy.position_avg_price, "###.##") )//close on touch_upperband-strategy.close(id="vbLE", comment="Profit is : "+str.tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="touch_upperband" and (ta.crossover(close, up) or ta.crossover(high, up)))+if strategy.position_size>=1 and exitOn=="touch_upperband" and (ta.crossover(close, up) or ta.crossover(high, up))+ strategy.close(id="vbLE", comment="Profit is : "+str.tostring(close - strategy.position_avg_price, "###.##") )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: 3 before, 2 after on ETHUSDT 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.
⋯//strategy logic has been borrowed from ceyhun and tweaked the settings for back testing-//@version=5+//@version=6//SPY 4 hrs settings 8, 13 , 3.33 , 0.9 on 4 hrs chart⋯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 |
|---|---|---|---|
| Band Average | 8 | int | devHigh medianAvg emaMediaAvg MidLineVal up down |
| Volatility Period | 13 | int | deviation |
| Deviation Factor | 3.33 | float · min 0.1 | deviation |
| Lower Band Adjustment | 0.9 | float · min 0.1 | devLow |
| Risk % of capital | 10 | int · min 1 | qty1 |
| Stop Loss | 6 | int · min 1 | qty1 stopLossVal |
| Exit on | touch_upperband | string · options ["Sell_Signal", "touch_upperband"] | close vbLE |
What it calculates
- EMA (
ema,ta.emain v5)deviation, Band Average (8)devHigh · line 19 - EMA (
ema,ta.emain v5)src, Band Average (8)medianAvg · line 21 - EMA (
ema,ta.emain v5)medianAvg, Band Average (8)emaMediaAvg · line 22 - SMA (
sma,ta.smain v5)medianAvg, Band Average (8)MidLineVal · line 25 - EMA (
ema,ta.emain v5)medianAvg, Band Average (8)up · line 30 - EMA (
ema,ta.emain v5)medianAvg, Band Average (8)down · line 31 - EMA (
ema,ta.emain v5)hlc3, 50ema50 · line 32
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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open vbLE long | Buyclose[2] < down[2] and close[1]>down[1] and close>close[1] | On | 66 |
| Close vbLE | abs(strategy.position_size)>=1 and close < stopLossVal | On | 72 |
| Close vbLE | strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell | On | 74 |
| Close vbLE | strategy.position_size>=1 and exitOn=="touch_upperband" and (crossover(close, up) or crossover(high, up)) | On | 76 |
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.
- 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 | 0.0% | +102.5% | 0 | 0% | — | 69.5% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 44.4% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −23.4% | +9.8% | 3 | 0% | 0.00 | 24.9% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −21.3% | +8.4% | 5 | 20% | 0.10 | 22.7% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −7.1% | +16.7% | 5 | 20% | 0.74 | 32.2% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −35.0% | +21.5% | 8 | 13% | 0.08 | 37.5% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −16.5% | +148.3% | 2 | 0% | 0.00 | 22.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +13.5% | +17.1% | 3 | 100% | — | 10.6% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
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 |
|---|---|---|---|---|---|
| Volatility Bands Reversal Strategy [Long Only] this page | — | v4 strategy | 0.0% | 0 | 69.5% |
| MACD Long Strat by TheGrindToday | ema sma | v4 strategy | +24.0% | 79 | 20.1% |
| Stock trending strategy by exlux99 | ema sma | v4 strategy | +35.3% | 21 | 14.7% |
| 4-Hour Stochastic EMA Trend by slymnturkoglu | ema sma | v4 strategy | No trades on this market | ||
| 4X EMA and volume strategy by SoftKill21 | ema sma | v4 strategy | +1.8% | 3 | 25.8% |
| Simple Momentum Strategy Based on SMA, EMA and Volume by slip_stream | sma ema | v4 strategy | +7.4% | 18 | 27.4% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 16 ms | With a workaround 1,000 bars in 54 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as long = true as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 66) so the engine trades the way the script says.
“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/// © ediks123//strategy logic has been borrowed from ceyhun and tweaked the settings for back testing//@version=4//SPY 4 hrs settings 8, 13 , 3.33 , 0.9 on 4 hrs chart//QQQ above settings is good , but 13, 13 has less number of bars //QQQ 4 hrs settings 13, 13 , 3.33 , 0.9 on 4 hrs chartstrategy(title="Volatility Bands Reversal Strategy", shorttitle="VolatilityBandReversal" , overlay=true, pyramiding=2, default_qty_type=strategy.percent_of_equity, default_qty_value=20, initial_capital=10000, currency=currency.USD) //default_qty_value=10, default_qty_type=strategy.fixed,av = input(8, title="Band Average")vp = input(13, title="Volatility Period")df = input(3.33,title="Deviation Factor",minval=0.1)lba = input(0.9,title="Lower Band Adjustment",minval=0.1)riskCapital = input(title="Risk % of capital", defval=10, minval=1)stopLoss=input(6,title="Stop Loss",minval=1)exitOn=input(title="Exit on", defval="touch_upperband", options=["Sell_Signal", "touch_upperband"])src = hlc3typical = src >= src[1] ? src - low[1] : src[1] - lowdeviation = sum( typical , vp )/ vp * dfdevHigh = ema(deviation, av)devLow = lba * devHighmedianAvg = ema(src, av)emaMediaAvg=ema(medianAvg, av)upperBandVal= emaMediaAvg + devHighlowerbandVal= emaMediaAvg - devLowMidLineVal=sma(medianAvg, av)UpperBand = plot ( upperBandVal, color=#EE82EE, linewidth=2, title="UpperBand")LowerBand = plot ( lowerbandVal , color=#EE82EE, linewidth=2, title="LowerBand")MidLine = plot (MidLineVal, color=color.blue, linewidth=2, title="MidLine")buyLine = plot ( (lowerbandVal + MidLineVal )/2 , color=color.blue, title="BuyLine")up=ema(medianAvg, av) + devHighdown=ema(medianAvg, av) - devLowema50=ema(hlc3,50)plot ( ema50, color=color.orange, linewidth=2, title="ema 50")//outer deviation//deviation1 = sum( typical , vp )/ vp * 4//devHigh1 = ema(deviation, av)//devLow1 = lba * devHigh//medianAvg1 = ema(src, av)//UpperBand1 = plot (emaMediaAvg + devHigh1, color=color.red, linewidth=3, title="UpperBand1")//LowerBand1 = plot (emaMediaAvg - devLow1, color=color.red, linewidth=3, title="LowerBand1")/////Entry Rules//1)First candle close below the Lower Band of the volatility Band//2)Second candle close above the lower band//3)Third Candle closes above previous candleBuy = close[2] < down[2] and close[1]>down[1] and close>close[1]//plotshape(Buy,color=color.blue,style=shape.arrowup,location=location.belowbar, text="Buy")//barcolor(close[2] < down[2] and close[1]>down[1] and close>close[1] ? color.blue :na )//bgcolor(close[2] < down[2] and close[1]>down[1] and close>close[1] ? color.green :na )///Exit Rules//1)One can have a static stops initially followed by an trailing stop based on the risk the people are willing to take//2)One can exit with human based decisions or predefined target exits. Choice of deciding the stop loss and profit targets are left to the readers.Sell = close[2] > up[2] and close[1]<up[1] and close<close[1]//plotshape(Sell,color=color.red,style=shape.arrowup,text="Sell")barcolor(close[2] > up[2] and close[1]<up[1] and close<close[1] ? color.yellow :na )bgcolor(close[2] > up[2] and close[1]<up[1] and close<close[1] ? color.red :na )//Buyer = crossover(close,Buy)//Seller = crossunder(close,Sell)//alertcondition(Buyer, title="Buy Signal", message="Buy")//alertcondition(Seller, title="Sell Signal", message="Sell")//Entry--//Echeck how many units can be purchased based on risk manage ment and stop lossqty1 = (strategy.equity * riskCapital / 100 ) / (close*stopLoss/100) //check if cash is sufficient to buy qty1 , if capital not available use the available capital onlyqty1:= (qty1 * close >= strategy.equity ) ? (strategy.equity / close) : qty1strategy.entry(id="vbLE", long=true, qty=qty1, when=Buy)bgcolor(strategy.position_size>=1 ? color.blue : na)// stop loss exitstopLossVal = strategy.position_size>=1 ? strategy.position_avg_price * ( 1 - (stopLoss/100) ) : 0.00//draw initil stop lossplot(strategy.position_size>=1 ? stopLossVal : na, color = color.purple , style=plot.style_linebr, linewidth = 2, title = "stop loss") //, trackprice=true)strategy.close(id="vbLE", comment="SL exit Loss is "+tostring(close - strategy.position_avg_price, "###.##") , when=abs(strategy.position_size)>=1 and close < stopLossVal ) //close on Sell_Signalstrategy.close(id="vbLE", comment="Profit is : "+tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="Sell_Signal" and Sell)//close on touch_upperbandstrategy.close(id="vbLE", comment="Profit is : "+tostring(close - strategy.position_avg_price, "###.##") , when=strategy.position_size>=1 and exitOn=="touch_upperband" and (crossover(close, up) or crossover(high, up)))