Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Function Polynomial Regression Strategy

A Pine Script v4 strategy with no technical-analysis calculation. It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 100% of equity and pays 0.0025% commission. 17 settings; defaults include Length 59, Pr mid col color.blue and Pr std col color.aqua.

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 Function Polynomial Regression Strategy repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 2 of 2 trades.
How did Function Polynomial Regression Strategy do on BTCUSDT 1D with default settings?
+26.34%
From 26 Jan 2024 to 21 Oct 2026, over 10 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Function Polynomial Regression Strategy be converted to Pine Script v5?
Yes
The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
Does Function Polynomial Regression Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 227, 229.
Does Function Polynomial Regression Strategy run in Zeal Terminal?
Yes
It compiles in 60 ms and runs 1,000 bars in 1,083 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • Plot
  • 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 (17)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOctPlot$5,751$10,126Equity from $5,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. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep. Zeal Terminal's engine currently reads an order side written as false, true as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 174, 182) so the engine trades the way the script says.
Net profit
+26.34%
$1,317.05
Buy and hold
+102.5%
same period
Closed trades
10
5 won · 5 lost
Profitable
50.0%
of closed trades
Profit factor
1.48
gross profit ÷ gross loss
Max drawdown
64.61%
−$3,889.56

One run with the author's default settings, $5,000 starting capital, commission as the script sets it. A short position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

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

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    4 settings have no label

    In the settings dialog length (line 72), _pr_mid_col (line 92), _pr_std_col (line 93), _pr_max_col (line 94) 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.

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 pow → math.pow, abs → math.abs, pivothigh → ta.pivothigh, pivotlow → ta.pivotlow, max → math.max, barssince → ta.barssince, crossunder → ta.crossunder, crossover → ta.crossover, min → math.min.

v4 → v5

Verified

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

  • Line 4: //@version=4 → //@version=5
  • Line 27: pow → math.pow
  • Line 28: pow → math.pow
  • Line 29: pow → math.pow
  • Line 30: pow → math.pow
  • Line 31: pow → math.pow
19 more edits
  • Line 64: abs → math.abs
  • Line 75: pivothigh → ta.pivothigh
  • Line 80: pivotlow → ta.pivotlow
  • Line 125: max → math.max
  • Line 147: barssince → ta.barssince
  • Line 148: barssince → ta.barssince
  • Line 149: input(type = input.bool) → input.bool()
  • Line 150: input(type = input.bool) → input.bool()
  • Line 151: input(type = input.bool) → input.bool()
  • Line 152: input(type = input.bool) → input.bool()
  • Line 172: crossunder → ta.crossunder
  • Line 174: strategy.entry(…, false) → strategy.entry(…, strategy.short)
  • Line 180: crossover → ta.crossover
  • Line 182: strategy.entry(…, true) → strategy.entry(…, strategy.long)
  • Line 199: input(type = input.bool) → input.bool()
  • Line 200: input(type = input.float) → input.float()
  • Line 202: input(type = input.float) → input.float()
  • Line 209: max → math.max
  • Line 215: min → math.min
⋯// © X11joe for strategy using it.-//@version=4+//@version=5strategy(title="Function Polynomial Regression Strategy", overlay=false, precision=2,commission_value=0.0025,commission_type=strategy.commission.percent, initial_capital=5000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100)⋯            _meanXY := _meanXY + (_Xi * _Yi)-            _meanY2 := _meanY2 + pow(_Yi, 2)+            _meanY2 := _meanY2 + math.pow(_Yi, 2)-            _meanX2 := _meanX2 + pow(_Xi, 2)+            _meanX2 := _meanX2 + math.pow(_Xi, 2)-            _meanX3 := _meanX3 + pow(_Xi, 3)+            _meanX3 := _meanX3 + math.pow(_Xi, 3)-            _meanX4 := _meanX4 + pow(_Xi, 4)+            _meanX4 := _meanX4 + math.pow(_Xi, 4)-            _meanX2Y := _meanX2Y + pow(_Xi, 2) * _Yi+            _meanX2Y := _meanX2Y + math.pow(_Xi, 2) * _Yi        _meanXY := _meanXY / _sizeX⋯            _min_dev := _diff-        _stdev := _stdev + abs(_diff)+        _stdev := _stdev + math.abs(_diff)//| Output:⋯var int[] indices = array.new_int(size=length, initial_value=0)-if pivothigh(2, 2)+if ta.pivothigh(2, 2)    e = array.pop(id=prices)⋯    array.insert(id=indices, index=0, value=bar_index[2])-if pivotlow(2, 2)+if ta.pivotlow(2, 2)    e = array.pop(id=prices)⋯int pr_size = array.size(id=P)-int pr_step = max(pr_size / pr_fractions, 1)+int pr_step = math.max(pr_size / pr_fractions, 1)for _i = 0 to pr_size - pr_step - 1 by pr_step⋯var inShort = false-sinceShort = barssince(inLong == true)+sinceShort = ta.barssince(inLong == true)-sinceLong = barssince(inShort == true)+sinceLong = ta.barssince(inShort == true)-allowLongs = input(title="Allow Longs",type=input.bool,defval=true)+allowLongs = input.bool(title="Allow Longs",defval=true)-allowShorts = input(title="Allow Shorts",type=input.bool,defval=true)+allowShorts = input.bool(title="Allow Shorts",defval=true)-closeNoShort = input(title="Close instead of Short", type=input.bool, defval=false)+closeNoShort = input.bool(title="Close instead of Short", defval=false)-closeNoLong = input(title="Close instead of Long", type=input.bool, defval=false)+closeNoLong = input.bool(title="Close instead of Long", defval=false)// === INPUT BACKTEST RANGE ===⋯if(window()==true)-    if(crossunder(close,maxval))+    if(ta.crossunder(close,maxval))        if(closeNoShort==false and allowShorts==true)-            strategy.entry("short",false)+            strategy.entry("short",strategy.short)            inShort := true⋯            inLong := false-    if(crossover(close,minval))+    if(ta.crossover(close,minval))        if(closeNoLong==false and allowLongs==true)-            strategy.entry("long",true)+            strategy.entry("long",strategy.long)            inLong := true⋯//TRAILING STOP LOSS ------------------------------------------------------------useTrailing = input(title="Use Trailing Stop Losses",type=input.bool,defval=false)+useTrailing = input.bool(title="Use Trailing Stop Losses",defval=false)-longTrailPerc = input(title="Trail Long Loss (%)",-     type=input.float, minval=0.0, step=0.1, defval=10) * 0.01+longTrailPerc = input.float(title="Trail Long Loss (%)", minval=0.0, step=0.1, defval=10) * 0.01-shortTrailPerc = input(title="Trail Short Loss (%)",-     type=input.float, minval=0.0, step=0.1, defval=4.6) * 0.01+shortTrailPerc = input.float(title="Trail Short Loss (%)", minval=0.0, step=0.1, defval=4.6) * 0.01// Create the variables that keep track of the stop price for being short or long.  These values are always changing in a trailing stop loss based on if the bar is higher or lower than the previous.⋯    stopValue = close * (1 - longTrailPerc)-    max(stopValue, longStopPrice[1])+    math.max(stopValue, longStopPrice[1])else⋯    stopValue = close * (1 + shortTrailPerc)-    min(stopValue, shortStopPrice[1])+    math.min(stopValue, shortStopPrice[1])else⋯

Clean v5

VerifiedDownload the v5 script

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

  • Line 72: input() → input.int()
  • Line 92: input() → input.color()
  • Line 93: input() → input.color()
  • Line 94: input() → input.color()
  • Line 154: input() → input.int()
  • Line 155: input() → input.int()
4 more edits
  • Line 156: input() → input.int()
  • Line 157: input() → input.int()
  • Line 158: input() → input.int()
  • Line 159: input() → input.int()
⋯    [_predictions, _max_dev, _min_dev, _stdev/_sizeX]-int length = input(59)+int length = input.int(59)var float[] prices = array.new_float(size=length, initial_value=open)⋯//|----------------------------------------------------------------------------||-color _pr_mid_col = input(color.blue)+color _pr_mid_col = input.color(color.blue)-color _pr_std_col = input(color.aqua)+color _pr_std_col = input.color(color.aqua)-color _pr_max_col = input(color.purple)+color _pr_max_col = input.color(color.purple)f_init_mid()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_mid_col, style=line.style_solid, width=2)⋯// === INPUT BACKTEST RANGE ===-FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)+FromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)-FromDay   = input(defval = 1, title = "From Day", minval = 1, maxval = 31)+FromDay   = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)-FromYear  = input(defval = 1980, title = "From Year", minval = 1980)+FromYear  = input.int(defval = 1980, title = "From Year", minval = 1980)-ToMonth   = input(defval = 1, title = "To Month", minval = 1, maxval = 12)+ToMonth   = input.int(defval = 1, title = "To Month", minval = 1, maxval = 12)-ToDay     = input(defval = 1, title = "To Day", minval = 1, maxval = 31)+ToDay     = input.int(defval = 1, title = "To Day", minval = 1, maxval = 31)-ToYear    = input(defval = 9999, title = "To Year", minval = 2017)+ToYear    = input.int(defval = 9999, title = "To Year", minval = 2017)start     = timestamp(FromYear, FromMonth, FromDay, 00, 00)  // backtest start window⋯

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 10 before, 22 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © X11joe for strategy using it.-//@version=5+//@version=6strategy(title="Function Polynomial Regression Strategy", overlay=false, precision=2,commission_value=0.0025,commission_type=strategy.commission.percent, initial_capital=5000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100)⋯

Settings

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

SettingDefaultType and rangeFeeds
Length (no label in the script)59intprices indices
Pr mid col (no label in the script)color.bluevalueline 95
Pr std col (no label in the script)color.aquavalueline 96
Pr max col (no label in the script)color.purplevalueline 97
Allow Longstrueboolentry long close short line 181 line 185
Allow Shortstrueboolentry short close long line 173 line 177
Close instead of Shortfalseboolentry short close long line 173 line 177
Close instead of Longfalseboolentry long close short line 181 line 185
From Month1int · min 1 · max 12start
From Day1int · min 1 · max 31start
From Year1980int · min 1980start
To Month1int · min 1 · max 12finish
To Day1int · min 1 · max 31finish
To Year9999int · min 2017finish
Use Trailing Stop Lossesfalseboolexit TS X Long exit TS X Short line 226 line 228
Trail Long Loss (%)10float · min 0.0 · step 0.1longStopPrice stopValue
Trail Short Loss (%)4.6float · min 0.0 · step 0.1shortStopPrice stopValue

What it calculates

No technical-analysis calculation: the script works on prices and settings directly.

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.

openopenprice datalengthLengthsetting · 59FromYearFrom Yearsetting · 1980FromMonthFrom Monthsetting · 1FromDayFrom Daysetting · 1ToYearTo Yearsetting · 9999ToMonthTo Monthsetting · 1ToDayTo Daysetting · 1closecloseprice datashortTrailPercTrail Short Loss (%)setting · 4.6longTrailPercTrail Long Loss (%)setting · 10_sizeY, _sizeX, _Xi, _Yi_sizeY · _sizeX +24 values_meanX, _meanY_meanX · _meanY2 values_meanXY_meanXYvalue_meanY2_meanY2value_meanX2_meanX2value_meanX3_meanX3value_meanX4_meanX4value_meanX2Y_meanX2Yvalue_sXX_sXXvalue_sXY_sXYvalue_sXX2_sXX2value_sX2X2_sX2X2value_sX2Y_sX2Yvalue_b, _c_b · _c2 values_a_avalue_max_dev, _min_dev_max_dev · _min_dev2 values_stdev_stdevvalue_vector_vectorvalue_diff_diffvaluepricespricesvalueindicesindicesvalueeevalueiivalueP, Pmax, Pmin, PstdevP · Pmax +24 valuespr_sizepr_sizevaluepr_step, minval, maxvalpr_step · minval +13 values_next_step_index, _line_next_step_index · _line2 valuesstartstartvaluefinishfinishvaluestopValuestopValuevaluesinceShort, sinceLongsinceShort · sinceLong2 conditionslongStopPricelongStopPriceconditionshortStopPriceColourshortStopPriceentry:shortOpen shortstrategy.entryclose:longClose longstrategy.closeentry:longOpen longstrategy.entryclose:shortClose shortstrategy.closeexit:TS X Longexit TS X Longstrategy.exitexit:TS X Shortexit TS X Shortstrategy.exitplot:142plotplotplot:143plotplotplot:144plotplot

Order rules

OrderFires whenBy defaultLine
Open short short(closeNoShort==false and allowShorts==true)On174
Close long(closeNoShort==true and allowShorts==false)On178
Open long long(closeNoLong==false and allowLongs==true)On182
Close short(closeNoLong==true and allowLongs==false)On186
Exit TS X Long stop(strategy.position_size > 0 and useTrailing==true)On227
Exit TS X Short stop(strategy.position_size < 0 and useTrailing==true)On229

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, and the live replay matched history.

2/2trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.

The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.

Other markets

The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+26.3%+102.5%1050%1.4864.6%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−19.8%+5.5%1060%0.5340.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−80.8%+9.8%967%0.4095.7%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−50.9%+8.4%650%0.1765.9%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+68.6%+16.7%978%1.4569.5%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−45.7%+21.5%838%0.3565.6%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−28.8%+148.3%633%0.6366.9%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−4.4%+17.1%1155%0.8330.2%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 market617%−$1,742.18
Sideways market3100%$2,708.23
Falling market1100%$351.15

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

How bad could the drawdown be?

45.6%

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

0%53%
All 10 trades
SideEntryExitBarsP&L
short18 Feb 2024 51,642.6026 Feb 2024 51,728.808−$8.60
long26 Feb 2024 51,728.802 Mar 2024 62,387.905$1,028.23
short2 Mar 2024 62,387.9018 Mar 2024 68,393.5016−$579.78
long18 Mar 2024 68,393.5024 May 2024 67,969.7067−$33.98
short24 May 2024 67,969.7012 Jan 2025 94,600.00233−$2,118.33
long12 Jan 2025 94,600.0028 Apr 2025 93,749.30106−$29.73
short28 Apr 2025 93,749.3024 Nov 2025 86,830.00210$240.29
long24 Nov 2025 86,830.0017 Jan 2026 95,550.9054$351.15
short17 Jan 2026 95,550.908 Jun 2026 63,332.00142$1,297.78
long8 Jun 2026 63,332.0024 Aug 2026 77,734.0077$1,170.16

Similar scripts

No other indicator or strategy here shares enough of its calculations.

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 60 msWith a workaround 1,000 bars in 1,083 msNot measured
PineTSNo v5 and v6 only—Not measured

Zeal Terminal's engine currently reads an order side written as false, true as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 174, 182) so the engine trades the way the script says.

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

Source

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

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © Credit for polynomial linear regression to RicardoSantos! Great work!// © X11joe for strategy using it.//@version=4strategy(title="Function Polynomial Regression Strategy", overlay=false, precision=2,commission_value=0.0025,commission_type=strategy.commission.percent, initial_capital=5000, currency=currency.USD, default_qty_type=strategy.percent_of_equity, default_qty_value=100)f_array_polyreg(_X, _Y)=>//{//| Returns a polynomial regression channel using (X,Y) vector points.//| Resources://|     language D: https://rosettacode.org/wiki/Polynomial_regression    int _sizeY = array.size(id=_Y)    int _sizeX = array.size(id=_X)    //    float _meanX = array.sum(id=_X) / _sizeX    float _meanY = array.sum(id=_Y) / _sizeX    float _meanXY = 0.0    float _meanY2 = 0.0    float _meanX2 = 0.0    float _meanX3 = 0.0    float _meanX4 = 0.0    float _meanX2Y = 0.0    if _sizeY == _sizeX        for _i = 0 to _sizeY - 1            float _Xi = array.get(id=_X, index=_i)            float _Yi = array.get(id=_Y, index=_i)            _meanXY := _meanXY + (_Xi * _Yi)            _meanY2 := _meanY2 + pow(_Yi, 2)            _meanX2 := _meanX2 + pow(_Xi, 2)            _meanX3 := _meanX3 + pow(_Xi, 3)            _meanX4 := _meanX4 + pow(_Xi, 4)            _meanX2Y := _meanX2Y + pow(_Xi, 2) * _Yi        _meanXY := _meanXY / _sizeX        _meanY2 := _meanY2 / _sizeX        _meanX2 := _meanX2 / _sizeX        _meanX3 := _meanX3 / _sizeX        _meanX4 := _meanX4 / _sizeX        _meanX2Y := _meanX2Y / _sizeX    //-----------|covs    float _sXX = _meanX2 - _meanX * _meanX    float _sXY = _meanXY - _meanX * _meanY    float _sXX2 = _meanX3 - _meanX * _meanX2    float _sX2X2 = _meanX4 - _meanX2 * _meanX2    float _sX2Y = _meanX2Y - _meanX2 * _meanY    //-----------|    float _b = (_sXY * _sX2X2 - _sX2Y * _sXX2) / (_sXX * _sX2X2 - _sXX2 * _sXX2)    float _c = (_sX2Y * _sXX - _sXY * _sXX2) / (_sXX * _sX2X2 - _sXX2 * _sXX2)    float _a = _meanY - _b * _meanX - _c * _meanX2    //-----------|    float[] _predictions = array.new_float(size=0, initial_value=0.0)    float _max_dev = 0.0    float _min_dev = 0.0    float _stdev = 0.0    for _i = 0 to _sizeX - 1        float _Xi = array.get(id=_X, index=_i)        float _vector = _a + _b * _Xi + _c * _Xi * _Xi        array.push(id=_predictions, value=_vector)        //        float _Yi = array.get(id=_Y, index=_i)        float _diff = _Yi - _vector        if _diff > _max_dev            _max_dev := _diff        if _diff < _min_dev            _min_dev := _diff        _stdev := _stdev + abs(_diff)//| Output://|     _predictions:   Array with adjusted _Y values.//|     _max_dev:       Max deviation from the mean.//|     _min_dev:       Min deviation from the mean.//|     _stdev/_sizeX:  Average deviation from the mean.//}    [_predictions, _max_dev, _min_dev, _stdev/_sizeX]int length = input(59)var float[] prices = array.new_float(size=length, initial_value=open)var int[] indices = array.new_int(size=length, initial_value=0)if pivothigh(2, 2)    e = array.pop(id=prices)    i = array.pop(id=indices)    array.insert(id=prices, index=0, value=high[2])    array.insert(id=indices, index=0, value=bar_index[2])if pivotlow(2, 2)    e = array.pop(id=prices)    i = array.pop(id=indices)    array.insert(id=prices, index=0, value=low[2])    array.insert(id=indices, index=0, value=bar_index[2])[P, Pmax, Pmin, Pstdev] = f_array_polyreg(indices, prices)//|----------------------------------------------------------------------------||//|----------------------------------------------------------------------------||//|----------------------------------------------------------------------------||//|----------------------------------------------------------------------------||//|----------------------------------------------------------------------------||//|----------------------------------------------------------------------------||color _pr_mid_col = input(color.blue)color _pr_std_col = input(color.aqua)color _pr_max_col = input(color.purple)f_init_mid()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_mid_col, style=line.style_solid, width=2)f_init_std()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_std_col, style=line.style_dashed, width=1)f_init_max()=>line.new(x1=bar_index, y1=0.0, x2=bar_index, y2=0.0, color=_pr_max_col, style=line.style_dotted, width=1)var line pr_mid00 = f_init_mid(), var line pr_min00 = f_init_max(), var line pr_max00 = f_init_max()var line pr_mid01 = f_init_mid(), var line pr_min01 = f_init_max(), var line pr_max01 = f_init_max()var line pr_mid02 = f_init_mid(), var line pr_min02 = f_init_max(), var line pr_max02 = f_init_max()var line pr_mid03 = f_init_mid(), var line pr_min03 = f_init_max(), var line pr_max03 = f_init_max()var line pr_mid04 = f_init_mid(), var line pr_min04 = f_init_max(), var line pr_max04 = f_init_max()var line pr_mid05 = f_init_mid(), var line pr_min05 = f_init_max(), var line pr_max05 = f_init_max()var line pr_mid06 = f_init_mid(), var line pr_min06 = f_init_max(), var line pr_max06 = f_init_max()var line pr_mid07 = f_init_mid(), var line pr_min07 = f_init_max(), var line pr_max07 = f_init_max()var line pr_mid08 = f_init_mid(), var line pr_min08 = f_init_max(), var line pr_max08 = f_init_max()var line pr_mid09 = f_init_mid(), var line pr_min09 = f_init_max(), var line pr_max09 = f_init_max()var line pr_lower00 = f_init_std(), var line pr_upper00 = f_init_std()var line pr_lower01 = f_init_std(), var line pr_upper01 = f_init_std()var line pr_lower02 = f_init_std(), var line pr_upper02 = f_init_std()var line pr_lower03 = f_init_std(), var line pr_upper03 = f_init_std()var line pr_lower04 = f_init_std(), var line pr_upper04 = f_init_std()var line pr_lower05 = f_init_std(), var line pr_upper05 = f_init_std()var line pr_lower06 = f_init_std(), var line pr_upper06 = f_init_std()var line pr_lower07 = f_init_std(), var line pr_upper07 = f_init_std()var line pr_lower08 = f_init_std(), var line pr_upper08 = f_init_std()var line pr_lower09 = f_init_std(), var line pr_upper09 = f_init_std()f_pr_mid_line_selector(_i)=>(_i==0?pr_mid00:(_i==1?pr_mid01:(_i==2?pr_mid02:(_i==3?pr_mid03:(_i==4?pr_mid04:(_i==5?pr_mid05:(_i==6?pr_mid06:(_i==7?pr_mid07:(_i==8?pr_mid08:(_i==9?pr_mid09:pr_mid00))))))))))f_pr_max_line_selector(_i)=>(_i==0?pr_max00:(_i==1?pr_max01:(_i==2?pr_max02:(_i==3?pr_max03:(_i==4?pr_max04:(_i==5?pr_max05:(_i==6?pr_max06:(_i==7?pr_max07:(_i==8?pr_max08:(_i==9?pr_max09:pr_max00))))))))))f_pr_min_line_selector(_i)=>(_i==0?pr_min00:(_i==1?pr_min01:(_i==2?pr_min02:(_i==3?pr_min03:(_i==4?pr_min04:(_i==5?pr_min05:(_i==6?pr_min06:(_i==7?pr_min07:(_i==8?pr_min08:(_i==9?pr_min09:pr_min00))))))))))f_pr_upper_line_selector(_i)=>(_i==0?pr_upper00:(_i==1?pr_upper01:(_i==2?pr_upper02:(_i==3?pr_upper03:(_i==4?pr_upper04:(_i==5?pr_upper05:(_i==6?pr_upper06:(_i==7?pr_upper07:(_i==8?pr_upper08:(_i==9?pr_upper09:pr_upper00))))))))))f_pr_lower_line_selector(_i)=>(_i==0?pr_lower00:(_i==1?pr_lower01:(_i==2?pr_lower02:(_i==3?pr_lower03:(_i==4?pr_lower04:(_i==5?pr_lower05:(_i==6?pr_lower06:(_i==7?pr_lower07:(_i==8?pr_lower08:(_i==9?pr_lower09:pr_lower00))))))))))int pr_fractions = 10int pr_size = array.size(id=P)int pr_step = max(pr_size / pr_fractions, 1)for _i = 0 to pr_size - pr_step - 1 by pr_step    int _next_step_index = _i + pr_step    int _line = _i / pr_step    line.set_xy1(id=f_pr_mid_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i))    line.set_xy2(id=f_pr_mid_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step))    line.set_xy1(id=f_pr_max_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) + Pmax)    line.set_xy2(id=f_pr_max_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) + Pmax)    line.set_xy1(id=f_pr_min_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) + Pmin)    line.set_xy2(id=f_pr_min_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) + Pmin)    line.set_xy1(id=f_pr_upper_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) + Pstdev)    line.set_xy2(id=f_pr_upper_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) + Pstdev)    line.set_xy1(id=f_pr_lower_line_selector(_line), x=array.get(id=indices, index=_i), y=array.get(id=P, index=_i) - Pstdev)    line.set_xy2(id=f_pr_lower_line_selector(_line), x=array.get(id=indices, index=_i + pr_step), y=array.get(id=P, index=_i + pr_step) - Pstdev)//@JA - Code from below was my strategy edits.minval = line.get_y1(f_pr_min_line_selector(pr_size))maxval = line.get_y1(f_pr_max_line_selector(pr_size))plot(minval,color=color.green)plot(maxval,color=color.red)plot(close,color=color.yellow)var inLong = falsevar inShort = falsesinceShort = barssince(inLong == true)sinceLong = barssince(inShort == true)allowLongs = input(title="Allow Longs",type=input.bool,defval=true)allowShorts = input(title="Allow Shorts",type=input.bool,defval=true)closeNoShort = input(title="Close instead of Short", type=input.bool, defval=false)closeNoLong = input(title="Close instead of Long", type=input.bool, defval=false)// === INPUT BACKTEST RANGE ===FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)FromDay   = input(defval = 1, title = "From Day", minval = 1, maxval = 31)FromYear  = input(defval = 1980, title = "From Year", minval = 1980)ToMonth   = input(defval = 1, title = "To Month", minval = 1, maxval = 12)ToDay     = input(defval = 1, title = "To Day", minval = 1, maxval = 31)ToYear    = input(defval = 9999, title = "To Year", minval = 2017)start     = timestamp(FromYear, FromMonth, FromDay, 00, 00)  // backtest start windowfinish    = timestamp(ToYear, ToMonth, ToDay, 23, 59)        // backtest finish windowwindow()  => time >= start and time <= finish ? true : false // create function "within window of time"// -- END BACKTEST RANGE --//@JA - This is required so it works the first time onward//plot(sinceLong,color=color.green)//plot(sinceShort,color=color.red)// avgLong = ema(sinceLong,length*10)// avgShort = ema(sinceShort,length*10)//plot(avgLong,color=color.green)//plot(avgShort,color=color.red)if(window()==true)    if(crossunder(close,maxval))        if(closeNoShort==false and allowShorts==true)            strategy.entry("short",false)            inShort := true            inLong := false        if(closeNoShort==true and allowShorts==false)            strategy.close("long") //@JA - Then close the strategy instead of going into short            inLong := false    if(crossover(close,minval))        if(closeNoLong==false and allowLongs==true)            strategy.entry("long",true)            inLong := true            inShort := false        if(closeNoLong==true and allowLongs==false)            strategy.close("short") //@JA - Then close the strategy instead of going into short            inShort := false// //@JA - If going long and a long cross shows again and the minimum time for long has elapsed.// if( strategy.position_size > 0 and crossunder(close,minval) and sinceLong>=10 )//     strategy.entry("short cancel",false)//     inShort := true//     inLong := false    // if( strategy.position_size < 0 and crossover(close,maxval) and sinceShort>=10 )//     strategy.entry("long cancel",true)//     inLong := true    //TRAILING STOP LOSS -----------------------------------------------------------useTrailing = input(title="Use Trailing Stop Losses",type=input.bool,defval=false)longTrailPerc = input(title="Trail Long Loss (%)",     type=input.float, minval=0.0, step=0.1, defval=10) * 0.01shortTrailPerc = input(title="Trail Short Loss (%)",     type=input.float, minval=0.0, step=0.1, defval=4.6) * 0.01// Create the variables that keep track of the stop price for being short or long.  These values are always changing in a trailing stop loss based on if the bar is higher or lower than the previous.longStopPrice = 0.0, shortStopPrice = 0.0//Calculate the LONG stop price accounting for the percentagelongStopPrice := if (strategy.position_size > 0)    stopValue = close * (1 - longTrailPerc)    max(stopValue, longStopPrice[1])else    0//Calculate the SHORT stop price accounting for the percentageshortStopPrice := if (strategy.position_size < 0)    stopValue = close * (1 + shortTrailPerc)    min(stopValue, shortStopPrice[1])else    999999// Plot stop loss values for confirmation// plot(series=(strategy.position_size > 0) ? longStopPrice : na,//      color=color.green, style=plot.style_cross,//      linewidth=2, title="Long Trail Stop")// plot(series=(strategy.position_size < 0) ? shortStopPrice : na,//      color=color.red, style=plot.style_cross,//      linewidth=2, title="Short Trail Stop")//Exit if trailing stop loss conditions met to lock in profits.if (strategy.position_size > 0 and useTrailing==true)    strategy.exit(id="TS X Long", stop=longStopPrice)if (strategy.position_size < 0 and useTrailing==true)    strategy.exit(id="TS X Short", stop=shortStopPrice)//END TRAILING STOP LOSS --------------------------------------------------------