Zeal Terminal Open Zeal Terminal

Pine Script v4 · Strategy

Correlation Strategy

A Pine Script v4 strategy built on Lowest (10), Highest (10) and Valuewhen (bought, LL). It has 11 order rules, 8 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays 0.04 commission. 34 settings; defaults include Strategy Direction 1, Correl Length 11 and Symbol BTCUSDTPERP.

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 Correlation Strategy repaint?
No
No repainting patterns were found in the source.
Can Correlation Strategy be converted to Pine Script v5?
Not tested
The steps are shown below, but the original does not run in Zeal Terminal's engine, so they could not be checked.
Does Correlation Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 206, 207.
Does Correlation Strategy run in Zeal Terminal?
No
Not yet: [Context.call] Execution error for ID "security@L172:C9": The provided reference is not a function. Check if the function exists in the stdlib.
Does not run in Zeal Terminal yet[Context.call] Execution error for ID "security@L172:C9": The provided reference is not a function. Check if the function exists in the stdlib. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • Check

    5 settings do nothing

    “-----------------Strategy Inputs-------------------”, “---------------Walk Forward Analysis----------------”, “1”, “2”, “-----------------General Inputs-------------------” are declared but never read.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    4 settings have no label

    In the settings dialog OS (line 37), OB (line 38), totalbars (line 45), WFA (line 78) show an empty name. The labels on this page come from the variable names.

  • Note

    Uses an argument v6 removed

    when = on line 192, 193, 195, 196, 199, 200, 202, 203, 209. The upgraded version below moves each call inside an if block.

  • Note

    Uses transp =, which v5 removed line 46

    transp = on line 46, 176. v5 folds the transparency into the colour with color.new(c, transp).

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 lowest → ta.lowest, highest → ta.highest, valuewhen → ta.valuewhen, atr → ta.atr, barssince → ta.barssince, security → request.security, correlation → ta.correlation, rsi → ta.rsi, sma → ta.sma.
  • 9 strategy calls use the when = argument (line 192, 193, 195, 196, 199, 200, 202, 203, 209). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Not verified

The v4 script does not run in Zeal Terminal's engine ([Context.call] Execution error for ID "security@L172:C9": The provided reference is not a function. Check if the function exists in the stdlib.), so this step could not be checked.

  • Line 16: //@version=4 → //@version=5
  • Line 25: input(type = input.integer) → input.int()
  • Line 34: input(type = input.symbol) → input.symbol()
  • Line 46: transp = 100 removed: the call sets no colour to fold it into, so its default colour loses the transparency
  • Line 62: input(type = input.string) → input.string()
  • Line 105: lowest → ta.lowest
15 more edits
  • Line 106: highest → ta.highest
  • Line 107: valuewhen → ta.valuewhen
  • Line 108: valuewhen → ta.valuewhen
  • Line 116: atr → ta.atr
  • Line 119: valuewhen → ta.valuewhen
  • Line 120: valuewhen → ta.valuewhen
  • Line 137: barssince → ta.barssince
  • Line 141: valuewhen → ta.valuewhen
  • Line 153: valuewhen → ta.valuewhen
  • Line 172: security → request.security
  • Line 173: correlation → ta.correlation
  • Line 175: rsi → ta.rsi
  • Line 176: transp = 100 removed: the call sets no colour to fold it into, so its default colour loses the transparency
  • Line 177: sma → ta.sma
  • Line 178: sma → ta.sma
⋯// More info on WFA: https://en.wikipedia.org/wiki/Walk_forward_optimization-//@version=4+//@version=5strategy("Correlation Strategy", ⋯     slippage=0)-direction = input(1, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)+direction = input.int(1, title = "Strategy Direction", minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : ⋯length=input(11, "Correl Length")-symbol=input("BTCUSDTPERP", "Symbol", type=input.symbol)+symbol=input.symbol("BTCUSDTPERP", "Symbol")i_smalen=input(14, "SMA Length")⋯totalbars=input(10000)-plot(bar_index, title="Current Bar", transp=100)+plot(bar_index, title="Current Bar")period1in_start=0⋯PreTrade=bar_index > (totalbars*pretrade_start) and bar_index < (totalbars*pretrade_end)-PeriodInTest = input(defval="1", type=input.string, title="Select In-Sample", options=['1', '2', 'PreTrade', 'All'])+PeriodInTest = input.string(defval="1", title="Select In-Sample", options=['1', '2', 'PreTrade', 'All'])WFAwindowSelector(_strat) =>⋯SwingStopProfit() =>-    LL=(lowest(i_SPL))*(1-i_PercIncrement)+    LL=(ta.lowest(i_SPL))*(1-i_PercIncrement)-    HH=(highest(i_SPL))*(1+i_PercIncrement)+    HH=(ta.highest(i_SPL))*(1+i_PercIncrement)-    LL_price = valuewhen(bought, LL, 0)+    LL_price = ta.valuewhen(bought, LL, 0)-    HH_price = valuewhen(bought, HH, 0)+    HH_price = ta.valuewhen(bought, HH, 0)    entry_LL_price = strategy.position_size > 0 ? LL_price : na ⋯ATRStop() =>-    ATR=atr(i_ATR)*i_ATRMult+    ATR=ta.atr(i_ATR)*i_ATRMult    ATRLong = ohlc4 - ATR    ATRShort = ohlc4 + ATR-    ATRLongStop = valuewhen(bought, ATRLong, 0)+    ATRLongStop = ta.valuewhen(bought, ATRLong, 0)-    ATRShortStop = valuewhen(bought, ATRShort, 0)+    ATRShortStop = ta.valuewhen(bought, ATRShort, 0)    LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na ⋯BoughtBarsCount(XBars) =>-    EnoughBars=barssince(bought)==XBars+    EnoughBars=ta.barssince(bought)==XBars    [EnoughBars]⋯TrailingStop(SL,SSL) =>-    dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))+    dif=(ta.valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))     -strategy.position_avg_price⋯    var Ststop = float(na)-    Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0 +    Sdif=strategy.position_avg_price-(ta.valuewhen(strategy.position_size<0      and strategy.position_size[1]>=0, low,0))⋯/////////////////////// STRATEGY LOGIC /////////////////////////////////////////-security=security(symbol,"", close)+security=request.security(symbol,"", close)-correl=correlation(security, close, length)*100+correl=ta.correlation(security, close, length)*100smalen= usesamelen ? length : i_smalen-rsi=rsi(close, usesamelen ? length : i_rsilen)+rsi=ta.rsi(close, usesamelen ? length : i_rsilen)-plot(correl, transp=100)+plot(correl)-BUY=correl < i_correl and (useRSI? rsi < OS : close < sma(close, smalen))+BUY=correl < i_correl and (useRSI? rsi < OS : close < ta.sma(close, smalen))-SELL=correl < i_correl and (useRSI? rsi > OB : close > sma(close, smalen))+SELL=correl < i_correl and (useRSI? rsi > OB : close > ta.sma(close, smalen))/////////////////////// FUNCTION CALLS /////////////////////////////////////////⋯

Clean v5

Not verified

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 32: input() → input.bool()
  • Line 33: input() → input.int()
  • Line 35: input() → input.int()
  • Line 36: input() → input.int()
  • Line 37: input() → input.int()
  • Line 38: input() → input.int()
34 more edits
  • Line 39: input() → input.bool()
  • Line 40: input() → input.int()
  • Line 41: input() → input.bool()
  • Line 43: input() → input.bool()
  • Line 45: input() → input.int()
  • Line 78: input() → input.bool()
  • Line 81: input() → input.bool()
  • Line 82: input() → input.int()
  • Line 83: input() → input.int()
  • Line 85: input() → input.bool()
  • Line 86: input() → input.int()
  • Line 87: input() → input.int()
  • Line 89: input() → input.bool()
  • Line 91: input() → input.bool()
  • Line 92: input() → input.bool()
  • Line 93: input() → input.string()
  • Line 94: input() → input.int()
  • Line 95: input() → input.int()
  • Line 96: input() → input.int()
  • Line 97: input() → input.int()
  • Line 98: input() → input.int()
  • Line 99: input() → input.bool()
  • Line 100: input() → input.bool()
  • Line 101: input() → input.bool()
  • Line 102: input() → input.int()
  • Line 192: when = SELL and strategy.position_size == 0 → if block
  • Line 193: when = BUY and strategy.position_size == 0 → if block
  • Line 195: when = SELL → if block
  • Line 196: when = BUY → if block
  • Line 199: when = BUY and strategy.position_size == 0 → if block
  • Line 200: when = SELL and strategy.position_size == 0 → if block
  • Line 202: when = BUY → if block
  • Line 203: when = SELL → if block
  • Line 209: when = EnoughBars → if block
⋯/////////////////////// STRATEGY INPUTS ////////////////////////////////////////-title1=input(true, "-----------------Strategy Inputs-------------------")  +title1=input.bool(true, "-----------------Strategy Inputs-------------------")  -length=input(11, "Correl Length")+length=input.int(11, "Correl Length")symbol=input.symbol("BTCUSDTPERP", "Symbol")-i_smalen=input(14, "SMA Length")+i_smalen=input.int(14, "SMA Length")-i_rsilen=input(14, "RSI Length")+i_rsilen=input.int(14, "RSI Length")-OS=input(30)+OS=input.int(30)-OB=input(70)+OB=input.int(70)-useRSI=input(false, "Use RSI instead of SMA")+useRSI=input.bool(false, "Use RSI instead of SMA")-i_correl=input(20, "Correlation Threshold", step=10)+i_correl=input.int(20, "Correlation Threshold", step=10)-usesamelen=input(true, "Use Correl Length as SMA/RSI Length")+usesamelen=input.bool(true, "Use Correl Length as SMA/RSI Length")///////////////////WALK FORWARD ANALYSIS////////////////////////////////////////-title3=input(true, "---------------Walk Forward Analysis----------------") +title3=input.bool(true, "---------------Walk Forward Analysis----------------") //Total Bars Calc-totalbars=input(10000)+totalbars=input.int(10000)plot(bar_index, title="Current Bar")⋯        [na]-WFA=input(false)+WFA=input.bool(false)if WFA    if Period1In or Period1Out-        p1=input(false, title="1")+        p1=input.bool(false, title="1")-        length:=input(11, "Correl Length")+        length:=input.int(11, "Correl Length")-        i_correl:=input(20, "Correlation Threshold", step=10)+        i_correl:=input.int(20, "Correlation Threshold", step=10)    if Period2Out-        p2=input(false, title="2")+        p2=input.bool(false, title="2")-        length:=input(11, "Correl Length")+        length:=input.int(11, "Correl Length")-        i_correl:=input(20, "Correlation Threshold", step=10)+        i_correl:=input.int(20, "Correlation Threshold", step=10)/////////////////////// BACKTESTER /////////////////////////////////////////////-title2=input(true, "-----------------General Inputs-------------------")  +title2=input.bool(true, "-----------------General Inputs-------------------")  // Backtester General Inputs-i_SL=input(true, title="Use Stop Loss and Take Profit")+i_SL=input.bool(true, title="Use Stop Loss and Take Profit")-TS=input(false, title="Use Trailing Stop")+TS=input.bool(false, title="Use Trailing Stop")-i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])+i_SLType=input.string(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])-i_SPL=input(defval=10, title="Swing Point Lookback")+i_SPL=input.int(defval=10, title="Swing Point Lookback")-i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01+i_PercIncrement=input.int(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01-i_ATR = input(14, title="ATR Length")+i_ATR = input.int(14, title="ATR Length")-i_ATRMult = input(2, step=.1, title="ATR Multiple")+i_ATRMult = input.int(2, step=.1, title="ATR Multiple")-i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio")+i_TPRRR = input.int(1, step=.1, title="Take Profit Risk Reward Ratio")-DPR=input(true, "Allow Stop and Reverse")+DPR=input.bool(true, "Allow Stop and Reverse")-reverse=input(false, "Reverse Trades")+reverse=input.bool(false, "Reverse Trades")-BarsExit=input(false, "Use X Bars Exit")+BarsExit=input.bool(false, "Use X Bars Exit")-XBars=input(1, minval=1, maxval=50, title="X Bars")+XBars=input.int(1, minval=1, maxval=50, title="X Bars")// Swing Points Stop and Take Profit⋯    if not DPR and window-        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)+        if SELL and strategy.position_size == 0+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)+        if BUY and strategy.position_size == 0+            strategy.entry("short", strategy.short)    else if window     -        strategy.entry("long", strategy.long, when=SELL)+        if SELL+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=BUY)+        if BUY+            strategy.entry("short", strategy.short)else    if not DPR and window-        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)+        if BUY and strategy.position_size == 0+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)+        if SELL and strategy.position_size == 0+            strategy.entry("short", strategy.short)    else if window-        strategy.entry("long", strategy.long, when=BUY)+        if BUY+            strategy.entry("long", strategy.long)-        strategy.entry("short", strategy.short, when=SELL)+        if SELL+            strategy.entry("short", strategy.short)// Exits⋯if BarsExit and not i_SL-    strategy.close_all(when=EnoughBars)+    if EnoughBars+        strategy.close_all()/////////////////////// PLOTS //////////////////////////////////////////////////⋯

Does it run in Pine Script v6?

Not tested

Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// More info on WFA: https://en.wikipedia.org/wiki/Walk_forward_optimization-//@version=5+//@version=6strategy("Correlation Strategy", ⋯

Settings

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

SettingDefaultType and rangeFeeds
Strategy Direction1int (written input.integer) · min -1 · max 1line 26 line 27
-----------------Strategy Inputs-------------------trueboolunused
Correl Length11intcorrel smalen rsi
SymbolBTCUSDTPERPsymbolsecurity
SMA Length14intsmalen
RSI Length14intrsi
OS (no label in the script)30intBUY
OB (no label in the script)70intSELL
Use RSI instead of SMAfalseboolBUY SELL
Correlation Threshold20int · step 10BUY SELL
Use Correl Length as SMA/RSI Lengthtrueboolsmalen rsi
---------------Walk Forward Analysis----------------trueboolunused
Totalbars (no label in the script)10000intPeriod1In Period1Out Period2In Period2Out PreTrade all
Select In-Sample1string · options ['1', '2', 'PreTrade', 'All']window
WFA (no label in the script)falseboolline 79
1falseboolunused
Correl Length11intcorrel smalen rsi
Correlation Threshold20int · step 10BUY SELL
2falseboolunused
Correl Length11intcorrel smalen rsi
Correlation Threshold20int · step 10BUY SELL
-----------------General Inputs-------------------trueboolunused
Use Stop Loss and Take Profittrueboolexit TP & SL exit TP & SL close_all line 205 line 208 SL SSL TP STP
Use Trailing Stopfalseboolexit TP & SL SL SSL
Type Of StopATR Stopstring · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"]SL SSL TP STP
Swing Point Lookback10intLL HH
Swing Point SL Perc Increment3int · step .1LL HH
ATR Length14intATR
ATR Multiple2int · step .1ATR
Take Profit Risk Reward Ratio1int · step .1tp stp ATRtp ATRstp
Allow Stop and Reversetrueboolentry long entry short entry long entry short line 191 line 198
Reverse Tradesfalseboolline 190
Use X Bars Exitfalseboolexit TP & SL exit TP & SL close_all line 205 line 208
X Bars1int · min 1 · max 50EnoughBars

What it calculates

  • Lowest (lowest, ta.lowest in v5)Swing Point Lookback (10)LL · line 105
  • Highest (highest, ta.highest in v5)Swing Point Lookback (10)HH · line 106
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, LL, 0LL_price · line 107
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, HH, 0HH_price · line 108
  • ATR (atr, ta.atr in v5)ATR Length (14)ATR · line 116
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, ATRLong, 0ATRLongStop · line 119
  • Valuewhen (valuewhen, ta.valuewhen in v5)bought, ATRShort, 0ATRShortStop · line 120
  • Correlation (correlation, ta.correlation in v5)security, close, Correl Length (11)correl · line 173
  • RSI (rsi, ta.rsi in v5)close, usesamelen ? length : i_rsilenrsi · line 175
  • SMA (sma, ta.sma in v5)close, smalenBUY · line 177
  • SMA (sma, ta.sma in v5)close, smalenSELL · line 178

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.

i_SPLSwing Point Lookbacksetting · 10i_PercIncrementSwing Point SL Perc Inc…setting · 3high · low · closehigh · low · closeprice datai_ATRATR Lengthsetting · 14i_ATRMultATR Multiplesetting · 2closecloseprice datalengthCorrel Lengthsetting · 11i_rsilenRSI Lengthsetting · 14i_correlCorrelation Thresholdsetting · 20OSOSsetting · 30OBOBsetting · 70ohlc4ohlc4price dataXBarsX Barssetting · 1symbolSymbolsetting · BTCUSDTPERPi_smalenSMA Lengthsetting · 14PeriodInTestSelect In-Samplesetting · 1totalbarsTotalbarssetting · 10000highhighprice datalowlowprice dataLLLowest→ LLHHHighest→ HHLL_priceValuewhen→ LL_priceHH_priceValuewhen→ HH_priceATRATR→ ATRATRLongStopValuewhen→ ATRLongStopATRShortStopValuewhen→ ATRShortStopcorrelCorrelation→ correlrsiRSI→ rsiBUYSMA→ BUYSELLSMA→ SELLATRLong, ATRShortATRLong · ATRShort2 valuesEnoughBarsEnoughBarsvaluetrailOffsettrailOffsetvaluetstop, Ststoptstop · Ststop2 valuesStrailOffsetStrailOffsetvalueSL, SSL, TP, STPSL · SSL +24 valuessecuritysecurityvaluesmalensmalenvaluewindowwindowvalueboughtboughtconditionPeriod1In, Period1Out, Period2In, Period2Out, PreTrade, allPeriod1In · Period1Out …6 conditionsdifdifconditionSdifSdifconditionentry:longOpen longstrategy.entryentry:shortOpen shortstrategy.entryexit:TP & SLexit TP & SLstrategy.exitclose_all:close_all strategy.close_allplot:46Current Barplotplot:176plotplotplot:211SLplotplot:213SSLplotplot:215TPplotplot:216STPplotplotshape:218Bullish Setupplotshapeplotshape:220Bearish Setupplotshape

Order rules

OrderFires whenBy defaultLine
Open long longSELL and strategy.position_size == 0On192
Open short shortBUY and strategy.position_size == 0On193
Open long longSELLOn195
Open short shortBUYOn196
Open long longBUY and strategy.position_size == 0On199
Open short shortSELL and strategy.position_size == 0On200
Open long longBUYOn202
Open short shortSELLOn203
Exit TP & SL stop and limiti_SL and not BarsExitOn206
Exit TP & SL stop and limiti_SL and not BarsExitOn207
Close EnoughBarsOn209

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.

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 data1 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.

ScriptSharesTypeNetTradesMax drawdown
Delayed RSI Strategy by tweakerIDlowest highest valuewhen atr rsiv4 strategy−40.4%742.2%
Stochastic RSI + WMA + SMA strat by tweakerIDrsi sma lowest highest valuewhenv4 strategy−11.9%437.9%
Money Flow Index 5 min Strategy by tweakerIDlowest highest valuewhen atr smav4 strategy−6.8%1828.4%
Double Bollinger Strategy by tweakerIDlowest highest valuewhen atr rsiv4 strategy−29.6%6150.1%
MA Bollinger Bands + RSI by LucasViviensma rsi atr lowest highestv5 strategy−73.9%477.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No [Context.call] Execution error for ID "security@L172:C9": The provided reference is not a function. Check if the function exists in the stdlib.Not 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/// © tweakerID// This is strategy determines a level (expressed in a scale from 1 to 100) of correlation// between security A (user defined) and security B (used on the chart) closing prices. If the correlation// is less than the user defined threshold, a buy signal will be possible. To determine the direction// of the trade we can choose between a Simple Moving Average or a Relative Strength Index indicator,// both with user defined lengths.// WFA Explained// This strategy includes a simple Walk Forward Optimization, which is a technique used to evaluate the robustness// of the strategy. The "in-sample" period is where you should optimize the values of the Strategy Inputs that match the ones in the WFA. // Default value is 1 (or 1/3 of all the candles in the chart). After optimizing the first period, the "All" period can be chosen to evaluate the results of // our "in-sample" optimization in an "out-of-sample" period (="All"-"1"). It is also possible and recommended to optimize// each period (1 and 2) independently and then replace the corresponding values in the WFA section of the inputs panel.// The WFA input is used to make those values effective in their corresponding periods. // More info on WFA: https://en.wikipedia.org/wiki/Walk_forward_optimization//@version=4strategy("Correlation Strategy",      overlay=true,      default_qty_type=strategy.percent_of_equity,      default_qty_value=100,      initial_capital=10000,      commission_value=0.04,      calc_on_every_tick=false,      slippage=0)direction = input(1, title = "Strategy Direction", type=input.integer, minval=-1, maxval=1)strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all :  (direction < 0 ? strategy.direction.short : strategy.direction.long))// Bought and Sold Boolean Signalbought = strategy.position_size > strategy.position_size[1]  or strategy.position_size < strategy.position_size[1]/////////////////////// STRATEGY INPUTS ////////////////////////////////////////title1=input(true, "-----------------Strategy Inputs-------------------")  length=input(11, "Correl Length")symbol=input("BTCUSDTPERP", "Symbol", type=input.symbol)i_smalen=input(14, "SMA Length")i_rsilen=input(14, "RSI Length")OS=input(30)OB=input(70)useRSI=input(false, "Use RSI instead of SMA")i_correl=input(20, "Correlation Threshold", step=10)usesamelen=input(true, "Use Correl Length as SMA/RSI Length")///////////////////WALK FORWARD ANALYSIS////////////////////////////////////////title3=input(true, "---------------Walk Forward Analysis----------------") //Total Bars Calctotalbars=input(10000)plot(bar_index, title="Current Bar", transp=100)period1in_start=0period1in_end=0.5period1out_start=0.5period1out_end=0.75period2in_start=0.25period2in_end=0.75period2out_start=0.75period2out_end=1pretrade_start=0.5pretrade_end=1Period1In=bar_index > (totalbars*period1in_start) and bar_index < (totalbars*period1in_end)Period1Out=bar_index > (totalbars*period1out_start) and bar_index < (totalbars*period1out_end)Period2In=bar_index > (totalbars*period2in_start) and bar_index < (totalbars*period2in_end)Period2Out=bar_index > (totalbars*period2out_start) and bar_index < (totalbars*period2out_end)PreTrade=bar_index > (totalbars*pretrade_start) and bar_index < (totalbars*pretrade_end)PeriodInTest = input(defval="1", type=input.string, title="Select In-Sample", options=['1', '2', 'PreTrade', 'All'])WFAwindowSelector(_strat) =>    if _strat == '1'        Period1In               [Period1In]    else if _strat == '2'        Period2In               [Period2In]    else if _strat == 'PreTrade'        PreTrade              [PreTrade]    else if _strat == 'All'        all=bar_index > 0 and bar_index < (totalbars + 1)        [all]    else        [na]WFA=input(false)if WFA    if Period1In or Period1Out        p1=input(false, title="1")        length:=input(11, "Correl Length")        i_correl:=input(20, "Correlation Threshold", step=10)    if Period2Out        p2=input(false, title="2")        length:=input(11, "Correl Length")        i_correl:=input(20, "Correlation Threshold", step=10)/////////////////////// BACKTESTER /////////////////////////////////////////////title2=input(true, "-----------------General Inputs-------------------")  // Backtester General Inputsi_SL=input(true, title="Use Stop Loss and Take Profit")TS=input(false, title="Use Trailing Stop")i_SLType=input(defval="ATR Stop", title="Type Of Stop", options=["Strategy Stop", "Swing Lo/Hi", "ATR Stop"])i_SPL=input(defval=10, title="Swing Point Lookback")i_PercIncrement=input(defval=3, step=.1, title="Swing Point SL Perc Increment")*0.01i_ATR = input(14, title="ATR Length")i_ATRMult = input(2, step=.1, title="ATR Multiple")i_TPRRR = input(1, step=.1, title="Take Profit Risk Reward Ratio")DPR=input(true, "Allow Stop and Reverse")reverse=input(false, "Reverse Trades")BarsExit=input(false, "Use X Bars Exit")XBars=input(1, minval=1, maxval=50, title="X Bars")// Swing Points Stop and Take ProfitSwingStopProfit() =>    LL=(lowest(i_SPL))*(1-i_PercIncrement)    HH=(highest(i_SPL))*(1+i_PercIncrement)    LL_price = valuewhen(bought, LL, 0)    HH_price = valuewhen(bought, HH, 0)    entry_LL_price = strategy.position_size > 0 ? LL_price : na     entry_HH_price = strategy.position_size < 0 ? HH_price : na     tp=strategy.position_avg_price + (strategy.position_avg_price - entry_LL_price)*i_TPRRR    stp=strategy.position_avg_price - (entry_HH_price - strategy.position_avg_price)*i_TPRRR    [entry_LL_price, entry_HH_price, tp, stp]// ATR StopATRStop() =>    ATR=atr(i_ATR)*i_ATRMult    ATRLong = ohlc4 - ATR    ATRShort = ohlc4 + ATR    ATRLongStop = valuewhen(bought, ATRLong, 0)    ATRShortStop = valuewhen(bought, ATRShort, 0)    LongSL_ATR_price = strategy.position_size > 0 ? ATRLongStop : na     ShortSL_ATR_price = strategy.position_size < 0 ? ATRShortStop : na     ATRtp=strategy.position_avg_price + (strategy.position_avg_price - LongSL_ATR_price)*i_TPRRR    ATRstp=strategy.position_avg_price - (ShortSL_ATR_price - strategy.position_avg_price)*i_TPRRR    [LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp]    // Strategy StopStrategyStop() =>    float LongStop = na    float ShortStop = na    float StratTP = na    float StratSTP = na    [LongStop, ShortStop, StratTP, StratSTP]    // Random ExitBoughtBarsCount(XBars) =>    EnoughBars=barssince(bought)==XBars    [EnoughBars]//TrailingStopTrailingStop(SL,SSL) =>    dif=(valuewhen(strategy.position_size>0 and strategy.position_size[1]<=0, high,0))     -strategy.position_avg_price    trailOffset     = strategy.position_avg_price - SL    var tstop = float(na)    if strategy.position_size > 0        tstop := high- trailOffset - dif        if tstop<tstop[1]            tstop:=tstop[1]    else        tstop := na    StrailOffset     = SSL - strategy.position_avg_price    var Ststop = float(na)    Sdif=strategy.position_avg_price-(valuewhen(strategy.position_size<0      and strategy.position_size[1]>=0, low,0))    if strategy.position_size < 0        Ststop := low+ StrailOffset + Sdif        if Ststop>Ststop[1]            Ststop:=Ststop[1]    else        Ststop := na    [tstop, Ststop]  //Stop Loss & Take Profit Switches  SLTPLogic(LongStop, ShortStop, StratTP, StratSTP, LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp) =>    SL= i_SLType == "Swing Lo/Hi" ? entry_LL_price : i_SLType == "ATR Stop" ? LongSL_ATR_price : LongStop    SSL= i_SLType == "Swing Lo/Hi" ? entry_HH_price : i_SLType == "ATR Stop" ? ShortSL_ATR_price : ShortStop    TP= i_SLType == "Swing Lo/Hi" ? tp : i_SLType == "ATR Stop" ? ATRtp : StratTP    STP= i_SLType == "Swing Lo/Hi" ? stp : i_SLType == "ATR Stop" ? ATRstp : StratSTP    [SL, SSL, TP, STP]/////////////////////// STRATEGY LOGIC /////////////////////////////////////////security=security(symbol,"", close)correl=correlation(security, close, length)*100smalen= usesamelen ? length : i_smalenrsi=rsi(close, usesamelen ? length : i_rsilen)plot(correl, transp=100)BUY=correl < i_correl and (useRSI? rsi < OS : close < sma(close, smalen))SELL=correl < i_correl and (useRSI? rsi > OB : close > sma(close, smalen))/////////////////////// FUNCTION CALLS /////////////////////////////////////////// Stops and Profits[entry_LL_price, entry_HH_price, tp, stp] = SwingStopProfit()[LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp] = ATRStop()[LongStop, ShortStop, StratTP, StratSTP] = StrategyStop()[SL, SSL, TP, STP] = SLTPLogic(LongStop, ShortStop, StratTP, StratSTP,  LongSL_ATR_price, ShortSL_ATR_price, ATRtp, ATRstp, entry_LL_price, entry_HH_price, tp, stp)[tstop, Ststop] = TrailingStop(SL,SSL)[window] = WFAwindowSelector(PeriodInTest)  [EnoughBars] = BoughtBarsCount(XBars)// Entriesif reverse    if not DPR and window        strategy.entry("long", strategy.long, when=SELL and strategy.position_size == 0)        strategy.entry("short", strategy.short, when=BUY and strategy.position_size == 0)    else if window             strategy.entry("long", strategy.long, when=SELL)        strategy.entry("short", strategy.short, when=BUY)else    if not DPR and window        strategy.entry("long", strategy.long, when=BUY and strategy.position_size == 0)        strategy.entry("short", strategy.short, when=SELL and strategy.position_size == 0)    else if window        strategy.entry("long", strategy.long, when=BUY)        strategy.entry("short", strategy.short, when=SELL)// Exitsif i_SL and not BarsExit    strategy.exit("TP & SL", "long", limit=TP, stop=TS? tstop : SL)    strategy.exit("TP & SL", "short", limit=STP, stop=TS? Ststop : SSL)if BarsExit and not i_SL    strategy.close_all(when=EnoughBars)/////////////////////// PLOTS //////////////////////////////////////////////////plot(i_SL and strategy.position_size > 0 and not TS ? SL : i_SL and  strategy.position_size > 0 and TS ? tstop : na , title='SL', style=plot.style_cross, color=color.red)plot(i_SL and strategy.position_size < 0 and not TS ? SSL : i_SL and  strategy.position_size < 0 and TS ? Ststop : na , title='SSL', style=plot.style_cross, color=color.red)plot(i_SL and strategy.position_size > 0 ? TP : na, title='TP', style=plot.style_cross, color=color.green)plot(i_SL and strategy.position_size < 0 ? STP : na, title='STP', style=plot.style_cross, color=color.green)// Draw price action setup arrowsplotshape(BUY ? 1 : na, style=shape.triangleup, location=location.belowbar,  color=color.green, title="Bullish Setup", size=size.auto)plotshape(SELL ? 1 : na, style=shape.triangledown, location=location.abovebar,  color=color.red, title="Bearish Setup", size=size.auto)