Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

BuyTheDip

A Pine Script v4 strategy built on SMA or EMA or HMA or RMA or VWMA or WMA (source, length), ATR (22) and Highest (maAlignment, 30). It has 3 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.01% commission. 9 settings; defaults include Moving Average Type sma, Exit Strategy Signal and Lookback Period 30.

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 BuyTheDip repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
How did BuyTheDip do on BTCUSDT 1D with default settings?
+4.58%
From 26 Jan 2024 to 21 Oct 2026, over 2 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can BuyTheDip 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 BuyTheDip use a stop loss?
Yes
strategy.exit sets a stop on line 65.
Does BuyTheDip run in Zeal Terminal?
Yes
It compiles in 16 ms and runs 1,000 bars in 78 ms, in the browser.

BTCUSDT · 1D · default settings

  • 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 (9)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$10,458$20,253Equity from $10,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. The script plots nothing itself; the lines and the lower pane are its own calculations, drawn for reference.
Net profit
+4.58%
$457.96
Buy and hold
+102.5%
same period
Closed trades
2
2 won · 0 lost
Profitable
100.0%
of closed trades
Profit factor
—
gross profit ÷ gross loss
Max drawdown
8.29%
−$835.52

One run with the author's default settings, $10,000 starting capital, commission as the script sets it. 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

    1 setting does nothing

    “Trade Direction” is declared but never read.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    6 settings have no label

    In the settings dialog LookbackPeriod (line 7), BBStdDev (line 8), BBLength (line 9), atrLength (line 10), atrMult (line 11), backtestYears (line 13) show an empty name. The labels on this page come from the variable names.

  • 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 63, 64, 65. The upgraded version below moves each call inside an if block.

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames sma → ta.sma, ema → ta.ema, hma → ta.hma, rma → ta.rma, vwma → ta.vwma, wma → ta.wma, max → math.max, atr → ta.atr, highest → ta.highest, bb → ta.bb, crossover → ta.crossover, crossunder → ta.crossunder.
  • 3 strategy calls use the when = argument (line 63, 64, 65). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

Same 2 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 3: //@version=4 → //@version=5
  • Line 16: sma → ta.sma
  • Line 18: ema → ta.ema
  • Line 20: hma → ta.hma
  • Line 22: rma → ta.rma
  • Line 24: vwma → ta.vwma
8 more edits
  • Line 26: wma → ta.wma
  • Line 30: max → math.max
  • Line 57: atr → ta.atr
  • Line 59: highest → ta.highest
  • Line 60: bb → ta.bb
  • Line 61: crossover → ta.crossover
  • Line 61: crossover → ta.crossover
  • Line 62: crossunder → ta.crossunder
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("BuyTheDip", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯f_getMovingAverage(source, MAType, length)=>-    ma = sma(source, length)+    ma = ta.sma(source, length)    if(MAType == "ema")-        ma := ema(source,length)+        ma := ta.ema(source,length)    if(MAType == "hma")-        ma := hma(source,length)+        ma := ta.hma(source,length)    if(MAType == "rma")-        ma := rma(source,length)+        ma := ta.rma(source,length)    if(MAType == "vwma")-        ma := vwma(source,length)+        ma := ta.vwma(source,length)    if(MAType == "wma")-        ma := wma(source,length)+        ma := ta.wma(source,length)    ma⋯    stop = close - atrMult*atr-    stop := strategy.position_size > 0 ? max(stop, stop[1]) : stop+    stop := strategy.position_size > 0 ? math.max(stop, stop[1]) : stop    stop⋯maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)-atr = atr(atrLength)+atr = ta.atr(atrLength)trailingStop = f_getTrailingStop(atr, atrMult)-maAligned = highest(maAlignment,LookbackPeriod)+maAligned = ta.highest(maAlignment,LookbackPeriod)-[middle, upper, lower] = bb(close, BBLength, BBStdDev)+[middle, upper, lower] = ta.bb(close, BBLength, BBStdDev)-buyCondition = maAligned == 1 and (crossover(close, lower) or crossover(close, middle))+buyCondition = maAligned == 1 and (ta.crossover(close, lower) or ta.crossover(close, middle))-buyExitCondition = crossunder(close, upper)+buyExitCondition = ta.crossunder(close, upper)strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)⋯

Clean v5

VerifiedDownload the v5 script

Same 2 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 5: input() → input.string()
  • Line 6: input() → input.string()
  • Line 7: input() → input.int()
  • Line 8: input() → input.int()
  • Line 9: input() → input.int()
  • Line 10: input() → input.int()
5 more edits
  • Line 11: input() → input.int()
  • Line 13: input() → input.int()
  • Line 63: when = buyCondition and inDateRange → if block
  • Line 64: when = buyExitCondition and exitBySignal → if block
  • Line 65: when = exitByTrailingStop → if block
⋯strategy("BuyTheDip", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)-MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+MAType = input.string(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-exitType = input(title="Exit Strategy", defval="Signal", options=["Signal", "TrailingStop", "Both"])+exitType = input.string(title="Exit Strategy", defval="Signal", options=["Signal", "TrailingStop", "Both"])-LookbackPeriod = input(30, minval=10,step=10)+LookbackPeriod = input.int(30, minval=10,step=10)-BBStdDev = input(2, minval=1, maxval=10, step=0.5)+BBStdDev = input.int(2, minval=1, maxval=10, step=0.5)-BBLength = input(60, minval=5, step=5)+BBLength = input.int(60, minval=5, step=5)-atrLength = input(22)+atrLength = input.int(22)-atrMult = input(6)+atrMult = input.int(6)tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])-backtestYears = input(10, minval=1, step=1)+backtestYears = input.int(10, minval=1, step=1)includePartiallyAligned = true⋯buyExitCondition = ta.crossunder(close, upper)-strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)+if buyCondition and inDateRange+    strategy.entry("Buy", strategy.long, oca_name="oca_buy", oca_type=strategy.oca.none)-strategy.close("Buy", when=buyExitCondition and exitBySignal)+if buyExitCondition and exitBySignal+    strategy.close("Buy")-strategy.exit("ExitBuy", "Buy", stop = trailingStop, when=exitByTrailingStop )+if exitByTrailingStop+    strategy.exit("ExitBuy", "Buy", stop = trailingStop )

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: 2 before, 3 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © HeWhoMustNotBeNamed-//@version=5+//@version=6strategy("BuyTheDip", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Moving Average Typesmastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]ma5 ma10 ma20 ma30 ma50 ma100 ma200 maAlignment line 17 line 19 line 21 line 23 line 25
Exit StrategySignalstring · options ["Signal", "TrailingStop", "Both"]exitBySignal exitByTrailingStop
Lookback Period (no label in the script)30int · min 10 · step 10maAligned
BBStd Dev (no label in the script)2int · min 1 · max 10 · step 0.5middle upper lower
BBLength (no label in the script)60int · min 5 · step 5middle upper lower
ATR Length (no label in the script)22intatr
ATR Mult (no label in the script)6intstop trailingStop
Trade Directionstrategy.direction.allvalue · options [strategy.direction.all, strategy.direction.long, strategy.direction.short]unused
Backtest Years (no label in the script)10int · min 1 · step 1inDateRange

What it calculates

  • SMA / EMA / HMA / RMA / VWMA / WMA (sma, ta.sma in v5)source, lengthma · line 16
  • ATR (atr, ta.atr in v5)ATR Length (22)atr · line 57
  • Highest (highest, ta.highest in v5)maAlignment, Lookback Period (30)maAligned · line 59
  • BB (bb, ta.bb in v5)close, BBLength (60), BBStd Dev (2)middle · line 60
  • BB (bb, ta.bb in v5)close, BBLength (60), BBStd Dev (2)upper · line 60
  • BB (bb, ta.bb in v5)close, BBLength (60), BBStd Dev (2)lower · line 60
  • Crossunder (crossunder, ta.crossunder in v5)close, upperbuyExitCondition · line 62

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.

high · low · closehigh · low · closeprice dataatrLengthATR Lengthsetting · 22LookbackPeriodLookback Periodsetting · 30closecloseprice dataBBLengthBBLengthsetting · 60BBStdDevBBStd Devsetting · 2atrMultATR Multsetting · 6MATypeMoving Average Typesetting · smaexitTypeExit Strategysetting · Signaltimetimeprice databacktestYearsBacktest Yearssetting · 10maSMA / EMA / HMA / RMA /…→ maatrATR→ atrmaAlignedHighest→ maAlignedmiddleBB→ middleupperBB→ upperlowerBB→ lowerbuyExitConditionCrossunder→ buyExitConditionstopstopvaluema5, ma10, ma20, ma30, ma50, ma100, ma200ma5 · ma10 +57 valuesupwardScoreupwardScorevaluemaAlignmentmaAlignmentvaluetrailingStoptrailingStopvalueexitByTrailingStopexitByTrailingStopconditionupwards, downwardsupwards · downwards2 conditionsinDateRangeinDateRangeconditionexitBySignalexitBySignalconditionbuyConditionbuyConditionconditionentry:BuyOpen Buystrategy.entryclose:BuyClose Buystrategy.closeexit:ExitBuyexit ExitBuystrategy.exit

Order rules

OrderFires whenBy defaultLine
Open Buy longbuyCondition and inDateRangeOn63
Close BuybuyExitCondition and exitBySignalOn64
Exit ExitBuy stopexitByTrailingStopexitType == "TrailingStop" or exitType == "Both"On65

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.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+4.6%+102.5%2100%—8.3%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−0.0%+5.5%00%0.003.2%8 May 2026 – 21 Oct 2026
ETHUSDT 1D0.0%+9.8%00%—0.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+11.8%+8.4%3100%1,053.2614.2%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−45.7%+16.7%20%0.0056.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+5.6%+21.5%1100%528.5015.4%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−0.0%+148.3%00%0.000.3%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+4.2%+17.1%2100%—3.6%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market1100%$80.99
Sideways market1100%$376.97
Falling market0—$0.00

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

0.0%

The 95th percentile of the worst drawdown when the same 2 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 0.0% to 0.0%; the tick is what actually happened, 0.0%. Order luck alone moves it this much.

0%1%
All 2 trades
SideEntryExitBarsP&L
long16 Jan 2025 100,497.0020 Jan 2025 101,332.004$80.99
long23 Aug 2025 116,936.008 Oct 2025 121,333.0046$376.97

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
BuyTheDip this page—v4 strategy+4.6%28.3%
Multi MA Trend Following Strategy Template by TradeAutomationema hma rma sma vwma wma atr highestv5 strategy+12.3%326.9%
Ultra Moving Average Rating Trend Strategy by exlux99ema wma highest sma rma vwma hmav5 strategy+2.8%52.4%
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST by TraderHalaisma ema hma vwma rmav5 strategy+1.3%1135.6%
VCP pivot buy by perrycc007sma ema rma vwma wma highestv4 strategydoes not run in Zeal Terminal
Multi Trend Cross Strategy Template by TradeAutomationema hma rma sma vwma wma highestv5 strategy+33.0%37.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 16 msYes 1,000 bars in 78 msNot measured
PineTSNo v5 and v6 only—Not measured

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © HeWhoMustNotBeNamed//@version=4strategy("BuyTheDip", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])exitType = input(title="Exit Strategy", defval="Signal", options=["Signal", "TrailingStop", "Both"])LookbackPeriod = input(30, minval=10,step=10)BBStdDev = input(2, minval=1, maxval=10, step=0.5)BBLength = input(60, minval=5, step=5)atrLength = input(22)atrMult = input(6)tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])backtestYears = input(10, minval=1, step=1)includePartiallyAligned = truef_getMovingAverage(source, MAType, length)=>    ma = sma(source, length)    if(MAType == "ema")        ma := ema(source,length)    if(MAType == "hma")        ma := hma(source,length)    if(MAType == "rma")        ma := rma(source,length)    if(MAType == "vwma")        ma := vwma(source,length)    if(MAType == "wma")        ma := wma(source,length)    maf_getTrailingStop(atr, atrMult)=>    stop = close - atrMult*atr    stop := strategy.position_size > 0 ? max(stop, stop[1]) : stop    stopf_getMaAlignment(MAType, includePartiallyAligned)=>    ma5 = f_getMovingAverage(close,MAType,5)    ma10 = f_getMovingAverage(close,MAType,10)    ma20 = f_getMovingAverage(close,MAType,20)    ma30 = f_getMovingAverage(close,MAType,30)    ma50 = f_getMovingAverage(close,MAType,50)    ma100 = f_getMovingAverage(close,MAType,100)    ma200 = f_getMovingAverage(close,MAType,200)    upwardScore = 0    upwardScore := close > ma5? upwardScore+1:upwardScore    upwardScore := ma5 > ma10? upwardScore+1:upwardScore    upwardScore := ma10 > ma20? upwardScore+1:upwardScore    upwardScore := ma20 > ma30? upwardScore+1:upwardScore    upwardScore := ma30 > ma50? upwardScore+1:upwardScore    upwardScore := ma50 > ma100? upwardScore+1:upwardScore    upwardScore := ma100 > ma200? upwardScore+1:upwardScore        upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200    downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200    upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0    inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)exitBySignal = exitType == "Signal" or exitType == "Both"exitByTrailingStop = exitType == "TrailingStop" or exitType == "Both"maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)atr = atr(atrLength)trailingStop = f_getTrailingStop(atr, atrMult)maAligned = highest(maAlignment,LookbackPeriod)[middle, upper, lower] = bb(close, BBLength, BBStdDev)buyCondition = maAligned == 1 and (crossover(close, lower) or crossover(close, middle))buyExitCondition = crossunder(close, upper)strategy.entry("Buy", strategy.long, when=buyCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)strategy.close("Buy", when=buyExitCondition and exitBySignal)strategy.exit("ExitBuy", "Buy", stop = trailingStop, when=exitByTrailingStop )