Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Nifty & BN 2 Candle Theory Back Testing and Alert Notification

A Pine Script v5 strategy built on EMA (close), RMA or Change (14) and SAR (0.02, 0.02). It has 6 order rules, 4 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. 31 settings; defaults include Session Timings(to avoid trades) 1430-1000, Risk to Reward 2.0 and Volume Cutoff 50000.

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 Nifty & BN 2 Candle Theory Back Testing and Alert Notification repaint?
No
No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
How did Nifty & BN 2 Candle Theory Back Testing and Alert Notification do on BTCUSDT 1D with default settings?
−1.87%
From 26 Jan 2024 to 21 Oct 2026, over 3 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
What alerts does Nifty & BN 2 Candle Theory Back Testing and Alert Notification have?
4
2 Candle Theorey Long Entry; 2 Candle Theorey Short Entry; Golden Cross Long Entry; Golden Cross Short Entry.
Does Nifty & BN 2 Candle Theory Back Testing and Alert Notification run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L101:C63: 'linewidth' must be at least 1 in Pine Script v6. The v6 version is shown for reference and is not offered as a download.
Does Nifty & BN 2 Candle Theory Back Testing and Alert Notification use a stop loss?
Yes
strategy.exit sets a stop on line 203, 206.

BTCUSDT · 1D · default settings

  • ParabolicSAR
  • Long Stop
  • Long Stop Start
  • Short Stop
  • VWMA
  • VWAP
  • Trade Stop Price
  • Trade Target Price
  • 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 (30)
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOct$981,296$2,025,273Equity from $1,000,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. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
Table drawn by the script, as it stood on the last bar
Backtester by EtherMatt BINANCE:BTCUSDTTotal Trades: 3Starting: $10000Profit Factor: 0Return: -2.97%
2 Candle Theory V2 DMWin Rate: 0%Ending: $9702.99Consec. Loss: 0Max DD: 0%
Net profit
−1.87%
−$18,703.70
Buy and hold
+102.5%
same period
Closed trades
3
0 won · 3 lost
Profitable
0.0%
of closed trades
Profit factor
0.00
gross profit ÷ gross loss
Max drawdown
1.87%
−$18,703.70

One run with the author's default settings, $1,000,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

    4 settings do nothing

    “BB StdDev”, “Show Buy/Sell Labels ?”, “Show VWAP”, “VWAP offset” are declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Note

    4 settings have no label

    In the settings dialog showsession (line 6), showVolumeColor (line 10), start0 (line 49), increment0 (line 50) 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 179, 185, 190, 196. 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
Timefilter
Showsession (no label in the script)falseboolsessioncond
Session Timings(to avoid trades)1430-1000sessionsession
Main Settings
Risk to RewardModify Risk to Reward for Take Profit2.0float · min 0.1 · max 10.0 · step 0.1tp balance
Volume CutoffModify Volume Cutoff ex: 2 Candles with Volume above 50k for Entry Condition50000float · min 10000 · max 1000000 · step 1000volumeFilter Big Volume Candles
Show Volume Color (no label in the script)trueboolBig Volume Candles
Show High Volume CandlesChange Canlde Color for Candles above Volume Cutoffcolor.new(color.yellow,20)colorBig Volume Candles
Filter Settings
EMA FilterEMA length to filter trades - set to zero to disable0intema emaFilterLong emaFilterShort EMA
Start Date FilterDate & time to begin trading fromtimestamp('01 Jan 2000 13:30 +0000')timedateFilter
End Date FilterDate & time to stop tradingtimestamp('1 Jan 2099 19:30 +0000')timedateFilter
Backtester Settings
Starting BalanceYour starting balance for the custom inbuilt tester system10000.0floatbalance initbalance dollarReturn line 265 line 269
Risk Per TradeYour desired % risk per trade (as a whole number)1.0floatbalance
Draw BacktesterTurn on/off inbuilt backtester displaytrueboolline 257
RSI Settings
RSI Length14int · min 1up0 down0
Sourceclosesourceup0 down0
MA TypeSMAstring · options ["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"]rsiMA isBB
MA Length14intrsiMA
BB StdDev2.0float · min 0.001 · max 50unused
Start0 (no label in the script)0.02floatout
Increment0 (no label in the script)0.02floatout
Max Value0.2floatout
Supertrend Settings
ATR Period10intatr
ATR Multiplier2float · step 0.1atr
SourceclosesourcelongStop shortStop
Take Wicks into Account ?trueboolhighPrice lowPrice
Show Buy/Sell Labels ?trueboolunused
Highlight State ?trueboollongFillColor shortFillColor
VMA Settings
Length20int · min 1mavma
Sourceclosesourcemavma
Offset0int · min -500 · max 500VWMA
VWAP Settings
Show VWAPtrueboolunused
VWAP offset0intunused

What it calculates

  • EMAclose, emaFilter == 0 ? 1 : emaFilterema · line 28
  • RMA / Changemath.max(ta.change(rsiSourceInput), 0), RSI Length (14)up0 · line 43
  • RMA / Change-math.min(ta.change(rsiSourceInput), 0), RSI Length (14)down0 · line 44
  • SARStart0 (0.02), Increment0 (0.02), Max Value (0.2)out · line 52
  • ATRATR Period (10)atr · line 61
  • VWMASource (close), Length (20)mavma · line 110
  • CrossoverlongStop, vwap_nowsupertrendCrossBull · line 166
  • CrossundershortStop, vwap_nowsupertrendCrossBear · line 167
  • Crossovermavma, vwap_nowvmaCrossBull · line 168
  • Crossundermavma, vwap_nowvmaCrossBear · line 169

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 108 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long Entry longvalidLongEntryvalidLongSetup and strategy.position_size == 0 and dateFilter and barstate.isconfirmedOn179
Open Short Entry shortvalidShortEntryvalidShortSetup and strategy.position_size == 0 and dateFilter and barstate.isconfirmedOn185
Open Golden Cross Long Entry longvalidGoldenCrossBullSetupsupertrendCrossBull and vmaCrossBull and volumeLongEntry and rsiFilterLongOn190
Open Golden Cross Short Entry shortvalidGoldenCrossBearSetupsupertrendCrossBear and vmaCrossBear and volumeShortEntry and rsiFilterShortOn196
Exit Exit stop and limitstrategy.position_size > 0On203
Exit Exit stop and limitstrategy.position_size < 0On206

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Alerts

AlertCallMessageLine
(no title)alert2 Candle Theorey Long Entry182
(no title)alert2 Candle Theorey Short Entry188
(no title)alertGolden Cross Long Entry193
(no title)alertGolden Cross Short Entry199

Does it repaint?

No

No repainting patterns in the source.

Not measuredAn engine gap, not the scriptThe script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script. The answer comes from the checks on the source alone.
  • ClearHigher-timeframe data1 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 timingprocess_orders_on_close = true: orders fill at the signal bar's close.

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−1.9%+102.5%30%0.001.9%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h0.0%+5.5%00%—0.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−0.1%+9.8%3429%0.890.4%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+0.0%+8.4%1638%1.160.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.0%+16.7%4432%0.990.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.0%+21.5%2544%1.640.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+0.0%+148.3%5040%1.240.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+0.0%+17.1%450%1.730.0%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 market20%−$10,413.10
Sideways market10%−$8,290.60
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?

1.9%

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

0%2%
All 3 trades
SideEntryExitBarsP&L
long7 Mar 2024 66,823.2019 Mar 2024 62,779.1012−$4,044.03
short1 May 2024 58,365.006 May 2024 64,734.005−$6,369.03
short26 Feb 2025 84,250.102 Mar 2025 92,540.704−$8,290.60

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
Nifty & BN 2 Candle Theory Back Testing and Alert Notification this page—v5 strategy−1.9%31.9%
KAMA Strategy - Kaufman's Adaptive Moving Average by BenHampsonema atr sarv5 strategy+51.1%2034.6%
888 BOT #backtest by UnknownUnicorn2151907ema rma sar atrv4 strategy+3.0%120.9%
Jigga - Survival Level by jigneshjcrma ema atrv5 strategyNo trades on this market
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST by TraderHalaiema vwma rmav5 strategy+1.3%1135.6%
Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] by myncryptoatr ema rmav5 strategyNo 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.

  • 4 strategy calls use the when = argument (line 179, 185, 190, 196). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • 11 settings use the untyped input() (line 49, 50, 51, 55, 57, 58, 59, 60, 109, 115, 116). It still compiles in v6; input.int, input.float or input.source state the type.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

VerifiedDownload the v5 script

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

  • Line 49: input() → input.float()
  • Line 50: input() → input.float()
  • Line 51: input() → input.float()
  • Line 55: input() → input.int()
  • Line 57: input() → input.source()
  • Line 58: input() → input.bool()
9 more edits
  • Line 59: input() → input.bool()
  • Line 60: input() → input.bool()
  • Line 109: input() → input.source()
  • Line 115: input() → input.bool()
  • Line 116: input() → input.int()
  • Line 179: when = validLongEntry → if block
  • Line 185: when = validShortEntry → if block
  • Line 190: when = validGoldenCrossBullSetup → if block
  • Line 196: when = validGoldenCrossBearSetup → if block
⋯//---------------------------------//PSAR Code\\---------------------------------\\-start0 = input(0.02)+start0 = input.float(0.02)-increment0 = input(0.02)+increment0 = input.float(0.02)-maximum0 = input(0.2, "Max Value")+maximum0 = input.float(0.2, "Max Value")out = ta.sar(start0, increment0, maximum0)⋯//---------------------------------//Supertrend Code\\---------------------------------\\-length = input(title='ATR Period', defval=10, group="Supertrend Settings")+length = input.int(title='ATR Period', defval=10, group="Supertrend Settings")mult = input.float(title='ATR Multiplier', step=0.1, defval=2, group="Supertrend Settings")-src = input(title='Source', defval=close, group="Supertrend Settings")+src = input.source(title='Source', defval=close, group="Supertrend Settings")-wicks = input(title='Take Wicks into Account ?', defval=true, group="Supertrend Settings")+wicks = input.bool(title='Take Wicks into Account ?', defval=true, group="Supertrend Settings")-showLabels = input(title='Show Buy/Sell Labels ?', defval=true, group="Supertrend Settings")+showLabels = input.bool(title='Show Buy/Sell Labels ?', defval=true, group="Supertrend Settings")-highlightState = input(title='Highlight State ?', defval=true, group="Supertrend Settings")+highlightState = input.bool(title='Highlight State ?', defval=true, group="Supertrend Settings")atr = mult * ta.atr(length)⋯lenvma = input.int(20, "Length", minval=1, group="VMA Settings")-srcvma = input(close, "Source", group="VMA Settings")+srcvma = input.source(close, "Source", group="VMA Settings")mavma = ta.vwma(srcvma, lenvma)⋯// Inputs-vwap_show = input(true, title='Show VWAP', group = "VWAP Settings")+vwap_show = input.bool(true, title='Show VWAP', group = "VWAP Settings")-vwapOffset = input(title='VWAP offset', defval=0, group = "VWAP Settings")+vwapOffset = input.int(title='VWAP offset', defval=0, group = "VWAP Settings")start = request.security(syminfo.tickerid, 'D', time)⋯if validLongEntry and strategy.position_size <= 0-    strategy.entry('Long Entry', strategy.long, when=validLongEntry)+    if validLongEntry+        strategy.entry('Long Entry', strategy.long)    sl := low[1]⋯if validShortEntry and strategy.position_size >= 0-    strategy.entry('Short Entry', strategy.short, when=validShortEntry)+    if validShortEntry+        strategy.entry('Short Entry', strategy.short)    sl := high[1]⋯if validGoldenCrossBullSetup and strategy.position_size <= 0-    strategy.entry('Golden Cross Long Entry', strategy.long, when=validGoldenCrossBullSetup)+    if validGoldenCrossBullSetup+        strategy.entry('Golden Cross Long Entry', strategy.long)    sl := low[1]⋯if validGoldenCrossBearSetup and strategy.position_size >= 0-    strategy.entry('Golden Cross Short Entry', strategy.short, when=validGoldenCrossBearSetup)+    if validGoldenCrossBearSetup+        strategy.entry('Golden Cross Short Entry', strategy.short)    sl := high[1]⋯

Does it run in Pine Script v6?

No

The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L101:C63: 'linewidth' must be at least 1 in Pine Script v6. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/-//@version=5+//@version=6//---------------------------//2 Candle Theorey + Golden Crossover\\------------------------------\\⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 79 msWith a workaround 1,000 bars in 189 msNot measured
PineTSNot testedNot testedNot measured

The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“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///@version=5//---------------------------//2 Candle Theorey + Golden Crossover\\------------------------------\\strategy('2 Candle Theorey V2', process_orders_on_close=true, overlay = true)//---------------------------------//Options\\---------------------------------\\showsession = input.bool(defval=false, title='', inline='Session', group='Timefilter')session2 = input.session(defval='1430-1000', title='Session Timings(to avoid trades)', inline='Session', group='Timefilter')profitMultiplier = input.float(defval=2.0, minval=0.1,step=0.1, maxval=10.0, title='Risk to Reward', group='Main Settings', tooltip='Modify Risk to Reward for Take Profit')volumecutoff = input.float(defval=50000, minval= 10000 , step= 1000, maxval=1000000, title='Volume Cutoff', tooltip='Modify Volume Cutoff ex: 2 Candles with Volume above 50k for Entry Condition', group='Main Settings')showVolumeColor = input.bool(defval=true,title='', group='Main Settings', inline='Color')color volumeColorInput = input.color(color.new(color.yellow,20), " Show High Volume Candles", group='Main Settings', tooltip='Change Canlde Color for Candles above Volume Cutoff', inline='Color')var g_filter = 'Filter Settings'emaFilter = input.int(title='EMA Filter', defval=0, group=g_filter, tooltip='EMA length to filter trades - set to zero to disable')i_startTime = input.time(title='Start Date Filter', defval=timestamp('01 Jan 2000 13:30 +0000'), group=g_filter, tooltip='Date & time to begin trading from')i_endTime = input.time(title='End Date Filter', defval=timestamp('1 Jan 2099 19:30 +0000'), group=g_filter, tooltip='Date & time to stop trading')// Backtester Settingsvar g_tester = 'Backtester Settings'startBalance = input.float(title='Starting Balance', defval=10000.0, group=g_tester, tooltip='Your starting balance for the custom inbuilt tester system')riskPerTrade = input.float(title='Risk Per Trade', defval=1.0, group=g_tester, tooltip='Your desired % risk per trade (as a whole number)')drawTester = input.bool(title='Draw Backtester', defval=true, group=g_tester, tooltip='Turn on/off inbuilt backtester display')//-----------------------------// Custom Functions \\---------------------------------\\    // Custom function to truncate (cut) excess decimal placestruncate(_number, _decimalPlaces) =>    _factor = math.pow(10, _decimalPlaces)    int(_number * _factor) / _factor//---------------------------------//EMA Filter\\---------------------------------\\ema = ta.ema(close, emaFilter == 0 ? 1 : emaFilter)//---------------------------------//RSI Code\\---------------------------------\\marsi(sourcersi, lengthrsi, typersi) =>    switch typersi        "SMA" => ta.sma(sourcersi, lengthrsi)        "Bollinger Bands" => ta.sma(sourcersi, lengthrsi)        "EMA" => ta.ema(sourcersi, lengthrsi)        "SMMA (RMA)" => ta.rma(sourcersi, lengthrsi)        "WMA" => ta.wma(sourcersi, lengthrsi)        "VWMA" => ta.vwma(sourcersi, lengthrsi)rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")rsiSourceInput = input.source(close, "Source", group="RSI Settings")maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="RSI Settings")maLengthInput = input.int(14, title="MA Length", group="RSI Settings")bbMultInput = input.float(2.0, minval=0.001, maxval=50, title="BB StdDev", group="RSI Settings")up0 = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)down0 = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)rsi = down0 == 0 ? 100 : up0 == 0 ? 0 : 100 - (100 / (1 + up0 / down0))rsiMA = marsi(rsi, maLengthInput, maTypeInput)isBB = maTypeInput == "Bollinger Bands"//---------------------------------//PSAR Code\\---------------------------------\\start0 = input(0.02)increment0 = input(0.02)maximum0 = input(0.2, "Max Value")out = ta.sar(start0, increment0, maximum0)plot(out, "ParabolicSAR", style=plot.style_cross, color=#2962FF)//---------------------------------//Supertrend Code\\---------------------------------\\length = input(title='ATR Period', defval=10, group="Supertrend Settings")mult = input.float(title='ATR Multiplier', step=0.1, defval=2, group="Supertrend Settings")src = input(title='Source', defval=close, group="Supertrend Settings")wicks = input(title='Take Wicks into Account ?', defval=true, group="Supertrend Settings")showLabels = input(title='Show Buy/Sell Labels ?', defval=true, group="Supertrend Settings")highlightState = input(title='Highlight State ?', defval=true, group="Supertrend Settings")atr = mult * ta.atr(length)highPrice = wicks ? high : closelowPrice = wicks ? low : closedoji4price = open == close and open == low and open == highlongStop = src - atrlongStopPrev = nz(longStop[1], longStop)if longStop > 0    if doji4price        longStop := longStopPrev        longStop    else        longStop := lowPrice[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop        longStopelse    longStop := longStopPrev    longStopshortStop = src + atrshortStopPrev = nz(shortStop[1], shortStop)if shortStop > 0    if doji4price        shortStop := shortStopPrev        shortStop    else        shortStop := highPrice[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop        shortStopelse    shortStop := shortStopPrev    shortStopvar int dir = 1dir := dir == -1 and highPrice > shortStopPrev ? 1 : dir == 1 and lowPrice < longStopPrev ? -1 : dirvar color longColor = color.greenvar color shortColor = color.redlongStopPlot = plot(dir == 1 ? longStop : na, title='Long Stop', style=plot.style_linebr, linewidth=2, color=color.new(longColor, 0))buySignal = dir == 1 and dir[1] == -1plotshape(buySignal ? longStop : na, title='Long Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(longColor, 0))//plotshape(buySignal and showLabels ? longStop : na, title='Buy Label', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(longColor, 0), textcolor=color.new(color.white, 0))shortStopPlot = plot(dir == 1 ? na : shortStop, title='Short Stop', style=plot.style_linebr, linewidth=2, color=color.new(shortColor, 0))sellSignal = dir == -1 and dir[1] == 1//plotshape(sellSignal ? shortStop : na, title='Short Stop Start', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(shortColor, 0))//plotshape(sellSignal and showLabels ? shortStop : na, title='Sell Label', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(shortColor, 0), textcolor=color.new(color.white, 0))midPricePlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none, editable=false)longFillColor = highlightState ? dir == 1 ? longColor : na : nashortFillColor = highlightState ? dir == -1 ? shortColor : na : na//fill(midPricePlot, longStopPlot, title='Long State Filling', color=longFillColor, transp=90)//fill(midPricePlot, shortStopPlot, title='Short State Filling', color=shortFillColor, transp=90)changeCond = dir != dir[1]//---------------------------------//VMA Code\\---------------------------------\\lenvma = input.int(20, "Length", minval=1, group="VMA Settings")srcvma = input(close, "Source", group="VMA Settings")mavma = ta.vwma(srcvma, lenvma)offsetvma = input.int(0, "Offset", minval = -500, maxval = 500, group="VMA Settings")plot(mavma, title="VWMA", color=#2962FF, offset = offsetvma)//---------------------------------//VWAP Code\\---------------------------------\\// Inputsvwap_show = input(true, title='Show VWAP', group = "VWAP Settings")vwapOffset = input(title='VWAP offset', defval=0, group = "VWAP Settings")start = request.security(syminfo.tickerid, 'D', time)newSession = start > start[1] ? 1 : 0vwapsum = 0.0volumesum = 0.0vwapsum := newSession[1] ? hlc3 * volume : vwapsum[1] + hlc3 * volumevolumesum := newSession[1] ? volume : volumesum[1] + volumevwap_now = vwapsum / volumesumplot(vwap_now, color=color.new(color.white, 0), title='VWAP')//---------------------------------//Logic\\---------------------------------\\// Check Sessions to avoid tradessession = time('1', session2 + string(':1234567'), str.tostring(syminfo.timezone))//'GMT+5:30')sessioncond = showsession ? not session : true// See if this bar's time happened within date filterdateFilter = time >= i_startTime and time <= i_endTime// Check EMA FilteremaFilterLong = emaFilter == 0 or close > emaemaFilterShort = emaFilter == 0 or close < ema// Check RSIrsiFilterLong = rsi > 50 and rsi <= 80rsiFilterShort = rsi < 40 and rsi >= 20// Check VWAPvwapFilterLong = close > vwap_nowvwapFilterShort = close < vwap_now// Check SupertrendsupertrendFilterLong = close > longStopsupertrendFilterShort = close < shortStop// Check VMAvmaFilterLong = close > mavmavmaFilterShort = close < mavma// Check PSARpsarFilterLong = close > outpsarFilterShort = close < out// Check Volume volumeFilter = volume[1] > volumecutoff and volume > volumecutoff //and barColor == barColor[1]volumeLongCond = close > open and close[1] > open[1]volumeShortCond = close < open and close[1] < open[1]volumeLongEntry = volumeFilter and volumeLongCondvolumeShortEntry = volumeFilter and volumeShortCond // Determine if we have a valid setupvalidLongSetup = rsiFilterLong and vwapFilterLong and supertrendFilterLong and vmaFilterLong and psarFilterLong and volumeFilter and volumeLongCond and emaFilterLong and sessioncondvalidShortSetup = rsiFilterShort and vwapFilterShort and supertrendFilterShort and vmaFilterShort and psarFilterShort and volumeFilter and volumeShortCond and emaFilterShort and sessioncond// Check if we have confirmation for our setupvalidLongEntry = validLongSetup and strategy.position_size == 0 and dateFilter and barstate.isconfirmedvalidShortEntry = validShortSetup and strategy.position_size == 0 and dateFilter and barstate.isconfirmed// Highlight candles above Volume Cutoff if truebarcolor(showVolumeColor? volume>volumecutoff ? volumeColorInput : na : na, title='Big Volume Candles')    //---------------------------------// Golden Cross Code\\---------------------------\\// Golden Cross ConditionssupertrendCrossBull = ta.crossover(longStop,vwap_now)supertrendCrossBear = ta.crossunder(shortStop,vwap_now)vmaCrossBull = ta.crossover(mavma,vwap_now)vmaCrossBear = ta.crossunder(mavma,vwap_now)// Golden Cross validGoldenCrossBullSetup = supertrendCrossBull and vmaCrossBull and volumeLongEntry and rsiFilterLong//and validLongEntry validGoldenCrossBearSetup = supertrendCrossBear and vmaCrossBear and volumeShortEntry and rsiFilterShort//and validShortEntry//---------------------------------// Strategy Execution \\-------------------------\\float sl = nafloat tp = nasl := nz(sl[1], 0.0)tp := nz(tp[1], 0.0)if validLongEntry and strategy.position_size <= 0    strategy.entry('Long Entry', strategy.long, when=validLongEntry)    sl := low[1]    sl    alert(message= "2 Candle Theorey Long Entry", freq=alert.freq_once_per_bar_close)    if validShortEntry and strategy.position_size >= 0    strategy.entry('Short Entry', strategy.short, when=validShortEntry)    sl := high[1]    sl    alert(message= "2 Candle Theorey Short Entry", freq=alert.freq_once_per_bar_close)if validGoldenCrossBullSetup and strategy.position_size <= 0    strategy.entry('Golden Cross Long Entry', strategy.long, when=validGoldenCrossBullSetup)    sl := low[1]    sl    alert(message= "Golden Cross Long Entry", freq=alert.freq_once_per_bar_close)    if validGoldenCrossBearSetup and strategy.position_size >= 0    strategy.entry('Golden Cross Short Entry', strategy.short, when=validGoldenCrossBearSetup)    sl := high[1]    sl    alert(message= "Golden Cross Short Entry", freq=alert.freq_once_per_bar_close)if sl != 0.0    if strategy.position_size > 0        tp := strategy.position_avg_price + (strategy.position_avg_price - sl) * profitMultiplier        strategy.exit(id='Exit', limit=tp, stop=sl)    if strategy.position_size < 0        tp := strategy.position_avg_price - (sl - strategy.position_avg_price) * profitMultiplier        strategy.exit(id='Exit', limit=tp, stop=sl)//---------------------------------//Plots\\---------------------------------\\// Draw trade dataplot(validLongEntry or validShortEntry ? sl : na, title='Trade Stop Price', color=color.new(color.red, 0), style=plot.style_linebr)plot(validLongEntry or validShortEntry ? tp : na, title='Trade Target Price', color=color.new(color.green, 0), style=plot.style_linebr)// Draw EMA if it's enabledplot(emaFilter == 0 ? na : ema, color=emaFilterLong ? color.green : color.red, linewidth=2, title='EMA')// Draw Golden Cross Setupsplotchar(validGoldenCrossBullSetup,"Bull Golden Cross",'🚀',location.abovebar,offset=0,size=size.small)plotchar(validGoldenCrossBearSetup,"Bear Golden Cross",'🚀',location.belowbar,offset=0,size=size.small)//---------------------------------//Dashbaord\\---------------------------------\\// --- BEGIN TESTER CODE --- //// Declare performance tracking variablesvar balance = startBalancevar drawdown = 0.0var maxDrawdown = 0.0var maxBalance = 0.0var totalPips = 0.0var totalWins = 0var totalLoss = 0// Detect winning tradesif strategy.wintrades != strategy.wintrades[1]    balance += riskPerTrade / 100 * balance * profitMultiplier    //totalPips += math.abs(t_entry - t_target)    totalWins += 1    if balance > maxBalance        maxBalance := balance        maxBalance// Detect losing tradesif strategy.losstrades != strategy.losstrades[1]    balance -= riskPerTrade / 100 * balance    //totalPips -= math.abs(t_entry - t_stop)    totalLoss += 1    // Update drawdown    drawdown := balance / maxBalance - 1    if drawdown < maxDrawdown        maxDrawdown := drawdown        maxDrawdown        // ProfitFactor returns the strategy's current profit factor,ProfitFactor = strategy.grossprofit / strategy.grosslossmaxloss = math.round(maxDrawdown*(-100))winrate = (strategy.wintrades / strategy.closedtrades) * 100initbalance = startBalance// Prepare stats tablevar table testTable = table.new(position.bottom_right, 5, 3, border_width=1)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>    _cellText = _title + '\n' + _value    table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)// Draw stats tablevar bgcolor = color.new(color.black, 0)if drawTester    if barstate.islastconfirmedhistory        // Update table        dollarReturn = balance - startBalance        f_fillCell(testTable, 0, 0, 'Backtester by EtherMatt', str.tostring(syminfo.tickerid) , color.blue, color.white)        f_fillCell(testTable, 0, 1, '2 Candle Theory V2', str.tostring(timeframe.period) + 'M' , color.blue, color.white)        f_fillCell(testTable, 1, 0, 'Total Trades:', str.tostring(strategy.closedtrades), bgcolor, color.white)        f_fillCell(testTable, 1, 1, 'Win Rate:', str.tostring(truncate(winrate, 2)) + '%', winrate > 40 ? color.green : color.red, color.white)// bgcolor, color.white)        f_fillCell(testTable, 2, 0, 'Starting:', '$' + str.tostring(startBalance), bgcolor, color.white)        f_fillCell(testTable, 2, 1, 'Ending:', '$' + str.tostring(truncate(balance, 2)), balance > initbalance ? color.green : color.red, color.white)        f_fillCell(testTable, 3, 0, 'Profit Factor:', str.tostring(truncate(ProfitFactor, 2)), ProfitFactor > 0 ? color.green : color.red, color.white)        f_fillCell(testTable, 3, 1, 'Consec. Loss:', str.tostring(maxloss), maxloss <= 5 ? color.green : color.red, color.white)//color.new(color.red,50), bgcolor, color.white)        f_fillCell(testTable, 4, 0, 'Return:', (dollarReturn > 0 ? '+' : '') + str.tostring(truncate(dollarReturn / startBalance * 100, 2)) + '%', dollarReturn > 0 ? color.green : color.red, color.white)        f_fillCell(testTable, 4, 1, 'Max DD:', str.tostring(truncate(maxDrawdown * 100, 2)) + '%', color.red, color.white)