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.
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 verifiedThe 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 verifiedNeither 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Strategy Direction | 1 | int (written input.integer) · min -1 · max 1 | line 26 line 27 |
| -----------------Strategy Inputs------------------- | true | bool | unused |
| Correl Length | 11 | int | correl smalen rsi |
| Symbol | BTCUSDTPERP | symbol | security |
| SMA Length | 14 | int | smalen |
| RSI Length | 14 | int | rsi |
| OS (no label in the script) | 30 | int | BUY |
| OB (no label in the script) | 70 | int | SELL |
| Use RSI instead of SMA | false | bool | BUY SELL |
| Correlation Threshold | 20 | int · step 10 | BUY SELL |
| Use Correl Length as SMA/RSI Length | true | bool | smalen rsi |
| ---------------Walk Forward Analysis---------------- | true | bool | unused |
| Totalbars (no label in the script) | 10000 | int | Period1In Period1Out Period2In Period2Out PreTrade all |
| Select In-Sample | 1 | string · options ['1', '2', 'PreTrade', 'All'] | window |
| WFA (no label in the script) | false | bool | line 79 |
| 1 | false | bool | unused |
| Correl Length | 11 | int | correl smalen rsi |
| Correlation Threshold | 20 | int · step 10 | BUY SELL |
| 2 | false | bool | unused |
| Correl Length | 11 | int | correl smalen rsi |
| Correlation Threshold | 20 | int · step 10 | BUY SELL |
| -----------------General Inputs------------------- | true | bool | unused |
| Use Stop Loss and Take Profit | true | bool | exit TP & SL exit TP & SL close_all line 205 line 208 SL SSL TP STP |
| Use Trailing Stop | false | bool | exit TP & SL SL SSL |
| Type Of Stop | ATR Stop | string · options ["Strategy Stop", "Swing Lo/Hi", "ATR Stop"] | SL SSL TP STP |
| Swing Point Lookback | 10 | int | LL HH |
| Swing Point SL Perc Increment | 3 | int · step .1 | LL HH |
| ATR Length | 14 | int | ATR |
| ATR Multiple | 2 | int · step .1 | ATR |
| Take Profit Risk Reward Ratio | 1 | int · step .1 | tp stp ATRtp ATRstp |
| Allow Stop and Reverse | true | bool | entry long entry short entry long entry short line 191 line 198 |
| Reverse Trades | false | bool | line 190 |
| Use X Bars Exit | false | bool | exit TP & SL exit TP & SL close_all line 205 line 208 |
| X Bars | 1 | int · min 1 · max 50 | EnoughBars |
What it calculates
- Lowest (
lowest,ta.lowestin v5)Swing Point Lookback (10)LL · line 105 - Highest (
highest,ta.highestin v5)Swing Point Lookback (10)HH · line 106 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, LL, 0LL_price · line 107 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, HH, 0HH_price · line 108 - ATR (
atr,ta.atrin v5)ATR Length (14)ATR · line 116 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRLong, 0ATRLongStop · line 119 - Valuewhen (
valuewhen,ta.valuewhenin v5)bought, ATRShort, 0ATRShortStop · line 120 - Correlation (
correlation,ta.correlationin v5)security, close, Correl Length (11)correl · line 173 - RSI (
rsi,ta.rsiin v5)close, usesamelen ? length : i_rsilenrsi · line 175 - SMA (
sma,ta.smain v5)close, smalenBUY · line 177 - SMA (
sma,ta.smain 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | SELL and strategy.position_size == 0 | On | 192 |
| Open short short | BUY and strategy.position_size == 0 | On | 193 |
| Open long long | SELL | On | 195 |
| Open short short | BUY | On | 196 |
| Open long long | BUY and strategy.position_size == 0 | On | 199 |
| Open short short | SELL and strategy.position_size == 0 | On | 200 |
| Open long long | BUY | On | 202 |
| Open short short | SELL | On | 203 |
| Exit TP & SL stop and limit | i_SL and not BarsExit | On | 206 |
| Exit TP & SL stop and limit | i_SL and not BarsExit | On | 207 |
| Close | EnoughBars | On | 209 |
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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Delayed RSI Strategy by tweakerID | lowest highest valuewhen atr rsi | v4 strategy | −40.4% | 7 | 42.2% |
| Stochastic RSI + WMA + SMA strat by tweakerID | rsi sma lowest highest valuewhen | v4 strategy | −11.9% | 4 | 37.9% |
| Money Flow Index 5 min Strategy by tweakerID | lowest highest valuewhen atr sma | v4 strategy | −6.8% | 18 | 28.4% |
| Double Bollinger Strategy by tweakerID | lowest highest valuewhen atr rsi | v4 strategy | −29.6% | 61 | 50.1% |
| MA Bollinger Bands + RSI by LucasVivien | sma rsi atr lowest highest | v5 strategy | −73.9% | 4 | 77.3% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | No [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 | |
| PineTS | No 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)