Pine Script v4 · Strategy
LPB MicroCycles Strategy
A Pine Script v4 strategy built on ATR (14), Change (start) and Crossover (av, ohlc4). It has 2 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays no commission. 15 settings; defaults include Start Date 1, Start Month 1 and Start Year 2010.
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 LPB MicroCycles Strategy repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
- How did LPB MicroCycles Strategy do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
- Can LPB MicroCycles Strategy be converted to Pine Script v5?
- Not tested
- The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
- What alerts does LPB MicroCycles Strategy have?
- 1
- Long Detected.
- Does LPB MicroCycles Strategy use a stop loss?
- Yes
- strategy.exit sets a stop on line 156.
BTCUSDT · 1D · default settings
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
Needs BINANCE:BTCUSDT 1 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Values that depend on it are empty on this chart.
| Total Trades: 0 | Starting: $10000 | Return: $0 | Return: 0% |
| Win Rate: NaN% | Ending: $10000 | Pips: 0 | Max DD: 0% |
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 0.00%
- $0.00
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Check
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
1 setting has no label
In the settings dialog TimeFrame (line 92) shows an empty name. The labels on this page come from the variable names.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 145, 156. The upgraded version below moves each call inside an if block.
-
Note
Uses iff(), which v5 removed line 95
iff() on line 95, 98, 100, 102. v5 writes it as the ternary c ? a : b.
-
Note
Uses long =, which v5 renamed line 145
long = on line 145. v5 writes it as direction = strategy.long or strategy.short.
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 atr → ta.atr, security → request.security, change → ta.change, sqrt → math.sqrt, max → math.max, pow → math.pow, crossover → ta.crossover, crossunder → ta.crossunder, tostring → str.tostring, abs → math.abs.
- 2 strategy calls use the when = argument (line 145, 156). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 3: //@version=4 → //@version=5
- Line 5: input(type = input.integer) → input.int()
- Line 7: input(type = input.integer) → input.int()
- Line 9: input(type = input.integer) → input.int()
- Line 11: input(type = input.integer) → input.int()
- Line 13: input(type = input.integer) → input.int()
35 more edits
- Line 15: input(type = input.integer) → input.int()
- Line 27: input(type = input.float) → input.float()
- Line 28: input(type = input.float) → input.float()
- Line 31: input(type = input.float) → input.float()
- Line 32: input(type = input.float) → input.float()
- Line 33: input(type = input.bool) → input.bool()
- Line 35: input(type = input.float) → input.float()
- Line 36: input(type = input.integer) → input.int()
- Line 38: atr → ta.atr
- Line 92: input(type = input.resolution) → input.timeframe()
- Line 93: security → request.security
- Line 95: iff(c, a, b) → (c ? a : b)
- Line 95: change → ta.change
- Line 98: iff(c, a, b) → (c ? a : b)
- Line 100: iff(c, a, b) → (c ? a : b)
- Line 102: iff(c, a, b) → (c ? a : b)
- Line 104: sqrt → math.sqrt
- Line 104: max → math.max
- Line 107: input(type = input.bool) → input.bool()
- Line 111: return is reserved in v5: renamed return_
- Line 121: pow → math.pow
- Line 124: crossover → ta.crossover
- Line 125: crossunder → ta.crossunder
- Line 145: long = strategy.long → direction = strategy.long
- Line 145: tostring → str.tostring
- Line 178: abs → math.abs
- Line 186: abs → math.abs
- Line 205: tostring → str.tostring
- Line 206: tostring → str.tostring
- Line 207: tostring → str.tostring
- Line 208: tostring → str.tostring
- Line 209: tostring → str.tostring
- Line 210: tostring → str.tostring
- Line 211: tostring → str.tostring
- Line 212: tostring → str.tostring
⋯// © tathal animouse hajixde-//@version=4+//@version=5strategy("LPB MicroCycles Strategy", "HPVWAP", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, max_bars_back=5000)-startDate = input(title="Start Date", type=input.integer,+startDate = input.int(title="Start Date", defval=1, minval=1, maxval=31)-startMonth = input(title="Start Month", type=input.integer,+startMonth = input.int(title="Start Month", defval=1, minval=1, maxval=12)-startYear = input(title="Start Year", type=input.integer,+startYear = input.int(title="Start Year", defval=2010, minval=1800, maxval=2100)-endDate = input(title="End Date", type=input.integer,+endDate = input.int(title="End Date", defval=31, minval=1, maxval=31)-endMonth = input(title="End Month", type=input.integer,+endMonth = input.int(title="End Month", defval=12, minval=1, maxval=12)-endYear = input(title="End Year", type=input.integer,+endYear = input.int(title="End Year", defval=2021, minval=1800, maxval=2100)⋯var g_strategy = "Strategy Settings"-stopMultiplier = input(title="Stop Loss ATR", type=input.float, defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")+stopMultiplier = input.float(title="Stop Loss ATR", defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")-rr = input(title="R:R", type=input.float, defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")+rr = input.float(title="R:R", defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")/// Backtester Settingsvar g_tester = "Backtester Settings"-startBalance = input(title="Starting Balance", type=input.float, defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")+startBalance = input.float(title="Starting Balance", defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")-riskPerTrade = input(title="Risk Per Trade", type=input.float, defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")+riskPerTrade = input.float(title="Risk Per Trade", defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")-drawTester = input(title="Draw Backtester", type=input.bool, defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")+drawTester = input.bool(title="Draw Backtester", defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")////////////////INPUTS///////////////////-lambda = input(defval = 1000, type = input.float, title = "Smoothing Factor (Lambda)", minval = 1)+lambda = input.float(defval = 1000, title = "Smoothing Factor (Lambda)", minval = 1)-leng = input(defval = 100, type = input.integer, title = "Filter Length", minval = 1)+leng = input.int(defval = 100, title = "Filter Length", minval = 1)src = ohlc4-atr = atr(14)+atr = ta.atr(14)///////////Construct Arrays///////////////⋯///////////////Custom VWAP////////////////////////-TimeFrame = input('1', type=input.resolution)+TimeFrame = input.timeframe('1')-start = security(syminfo.tickerid, TimeFrame, time)+start = request.security(syminfo.tickerid, TimeFrame, time)//-------------------------------------------------newSession = iff(change(start), 1, 0)+newSession = (ta.change(start) ? 1 : 0)//------------------------------------------------vwapsum = 0.0-vwapsum := iff(newSession, HP*volume, vwapsum[1]+HP*volume)+vwapsum := (newSession ? HP*volume : vwapsum[1]+HP*volume)volumesum = 0.0-volumesum := iff(newSession, volume, volumesum[1]+volume)+volumesum := (newSession ? volume : volumesum[1]+volume)v2sum = 0.0-v2sum := iff(newSession, volume*HP*HP, v2sum[1]+volume*HP*HP)+v2sum := (newSession ? volume*HP*HP : v2sum[1]+volume*HP*HP)myvwap = vwapsum/volumesum-dev = sqrt(max(v2sum/volumesum - myvwap*myvwap, 0))+dev = math.sqrt(math.max(v2sum/volumesum - myvwap*myvwap, 0))Coloring=close>myvwap?color.new(#81c784, 62):color.new(#c2185b, 38)av=myvwap-showBcol = input(true, type=input.bool, title="Show barcolors")+showBcol = input.bool(true, title="Show barcolors")///////////////Entry & Exit///////////////////⋯toWhole(number) =>- return = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number+ return_ = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number- return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return+ return_ := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return_ * 100 : return_ ⋯toPips(number) =>- return = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue)+ return_ = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue)- return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return / 100 : return+ return_ := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return_ / 100 : return_ ⋯truncate(_number, _decimalPlaces) =>- _factor = pow(10, _decimalPlaces)+ _factor = math.pow(10, _decimalPlaces) int(_number * _factor) / _factor///////////////Conditional Strategy Logic//////////////-Long = crossover(av, ohlc4)+Long = ta.crossover(av, ohlc4)-Sell = crossunder(av, ohlc4)+Sell = ta.crossunder(av, ohlc4)// Check if we have confirmation for our setup⋯ t_direction := 1- strategy.entry(id="Long", long=strategy.long, when=validLong, comment="(SL=" + tostring(truncate(toWhole(longStopDistance),2)) + " pips)")+ strategy.entry(id="Long", direction = strategy.long, when=validLong, comment="(SL=" + str.tostring(truncate(toWhole(longStopDistance),2)) + " pips)") // Fire alerts⋯ balance := balance + ((riskPerTrade / 100) * balance) * rr- totalPips := totalPips + abs(t_entry - t_target)+ totalPips := totalPips + math.abs(t_entry - t_target) totalWins := totalWins + 1⋯ balance := balance - ((riskPerTrade / 100) * balance)- totalPips := totalPips - abs(t_entry - t_stop)+ totalPips := totalPips - math.abs(t_entry - t_stop) totalLoss := totalLoss + 1⋯ dollarReturn = balance - startBalance- f_fillCell(testTable, 0, 0, "Total Trades:", tostring(strategy.closedtrades), bgcolor, color.white)+ f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)- f_fillCell(testTable, 0, 1, "Win Rate:", tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)+ f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white)- f_fillCell(testTable, 1, 0, "Starting:", "$" + tostring(startBalance), bgcolor, color.white)+ f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(startBalance), bgcolor, color.white)- f_fillCell(testTable, 1, 1, "Ending:", "$" + tostring(truncate(balance,2)), bgcolor, color.white)+ f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(truncate(balance,2)), bgcolor, color.white)- f_fillCell(testTable, 2, 0, "Return:", "$" + tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white)+ f_fillCell(testTable, 2, 0, "Return:", "$" + str.tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white)- f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white)+ f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + str.tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white)- f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)+ f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white)- f_fillCell(testTable, 3, 1, "Max DD:", tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)+ f_fillCell(testTable, 3, 1, "Max DD:", str.tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)// --- END TESTER CODE --- //Clean v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 145: when = validLong → if block
- Line 156: when = strategy.position_size > 0 → if block
⋯ t_direction := 1- strategy.entry(id="Long", direction = strategy.long, when=validLong, comment="(SL=" + str.tostring(truncate(toWhole(longStopDistance),2)) + " pips)")+ if validLong+ strategy.entry(id="Long", direction = strategy.long, comment="(SL=" + str.tostring(truncate(toWhole(longStopDistance),2)) + " pips)") // Fire alerts⋯// Exit trades whenever our stop or target is hit-strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0)+if strategy.position_size > 0+ strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop)// Draw trade data⋯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.
⋯// © tathal animouse hajixde-//@version=5+//@version=6strategy("LPB MicroCycles Strategy", "HPVWAP", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, max_bars_back=5000)⋯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 |
|---|---|---|---|
| Start Date | 1 | int (written input.integer) · min 1 · max 31 | inDateRange |
| Start Month | 1 | int (written input.integer) · min 1 · max 12 | inDateRange |
| Start Year | 2010 | int (written input.integer) · min 1800 · max 2100 | inDateRange |
| End Date | 31 | int (written input.integer) · min 1 · max 31 | inDateRange |
| End Month | 12 | int (written input.integer) · min 1 · max 12 | inDateRange |
| End Year | 2021 | int (written input.integer) · min 1800 · max 2100 | inDateRange |
| Smoothing Factor (Lambda) | 1000 | float · min 1 | line 50 line 52 line 53 line 54 line 55 line 56 line 57 line 58 line 59 line 60 line 61 line 62 line 63 |
| Filter Length | 100 | int (written input.integer) · min 1 | a b c d e f ll1 ll2 i x line 86 |
| Time Frame (no label in the script) | 1 | timeframe (written input.resolution) | start |
| Show barcolors | true | bool | barcolor |
| Strategy Settings | |||
| Stop Loss ATRStop loss multiplier (x ATR) | 1.0 | float | stopSize |
| R:RRisk:Reward profile | 1.0 | float | longTargetPrice balance |
| Backtester Settings | |||
| Starting BalanceYour starting balance for the custom inbuilt tester system | 10000.0 | float | balance dollarReturn line 207 line 211 |
| Risk Per TradeYour desired % risk per trade (as a whole number) | 1.0 | float | balance |
| Draw BacktesterTurn on/off inbuilt backtester display | true | bool | line 201 |
What it calculates
- ATR (
atr,ta.atrin v5)14atr · line 38 - Change (
change,ta.changein v5)startnewSession · line 95 - Crossover (
crossover,ta.crossoverin v5)av, ohlc4Long · line 124 - Crossunder (
crossunder,ta.crossunderin v5)av, ohlc4Sell · line 125
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
The script has 67 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | validLongLong and strategy.position_size == 0 and inDateRange and barstate.isconfirmed | On | 145 |
| Exit Long Exit stop and limit | strategy.position_size > 0 | On | 156 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | Long Detected | 147 |
Does it repaint?
No
No repainting patterns in the source.
- 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.
Other markets
Not run on other markets: the script requests BINANCE:BTCUSDT 1, and that data is not available here (a lower timeframe than the chart; the engine does not evaluate intrabar data). Its results would rest on empty values.
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| LPB MicroCycles Strategy this page | — | v4 strategy | 0.0% | 0 | 0.0% |
| SOJA PIVOT by ParaBellum68 | atr | v4 strategy | +3.3% | 9 | 18.2% |
| Volatility System by EduardoMattje | atr | v5 strategy | +150.2% | 2 | 21.5% |
| ATR Stop Buy Strategy by phobo3s | atr | v4 strategy | No trades on this market | ||
| VBand Strategy by Saravanan_Ragavan | atr | v4 strategy | No trades on this market | ||
| Volatility Breakout Strategy [Angel Algo] by AngelAlgo | atr | v5 strategy | +3.1% | 18 | 3.6% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 69 ms | With a workaround 1,000 bars in 2,101 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as long = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 145) 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/// © tathal animouse hajixde//@version=4strategy("LPB MicroCycles Strategy", "HPVWAP", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100, max_bars_back=5000)startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12)startYear = input(title="Start Year", type=input.integer, defval=2010, minval=1800, maxval=2100)endDate = input(title="End Date", type=input.integer, defval=31, minval=1, maxval=31)endMonth = input(title="End Month", type=input.integer, defval=12, minval=1, maxval=12)endYear = input(title="End Year", type=input.integer, defval=2021, minval=1800, maxval=2100) // STEP 2:// Look if the close time of the current bar// falls inside the date rangeinDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0)) and (time < timestamp(syminfo.timezone, endYear, endMonth, endDate, 0, 0))///// Strategy Settingsvar g_strategy = "Strategy Settings"stopMultiplier = input(title="Stop Loss ATR", type=input.float, defval=1.0, group=g_strategy, tooltip="Stop loss multiplier (x ATR)")rr = input(title="R:R", type=input.float, defval=1.0, group=g_strategy, tooltip="Risk:Reward profile")/// Backtester Settingsvar g_tester = "Backtester Settings"startBalance = input(title="Starting Balance", type=input.float, defval=10000.0, group=g_tester, tooltip="Your starting balance for the custom inbuilt tester system")riskPerTrade = input(title="Risk Per Trade", type=input.float, defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")drawTester = input(title="Draw Backtester", type=input.bool, defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")////////////////INPUTS///////////////////lambda = input(defval = 1000, type = input.float, title = "Smoothing Factor (Lambda)", minval = 1)leng = input(defval = 100, type = input.integer, title = "Filter Length", minval = 1)src = ohlc4atr = atr(14)///////////Construct Arrays///////////////a = array.new_float(leng, 0.0) b = array.new_float(leng, 0.0)c = array.new_float(leng, 0.0)d = array.new_float(leng, 0.0)e = array.new_float(leng, 0.0)f = array.new_float(leng, 0.0)/////////Initialize the Values///////////ll1 = leng-1ll2 = leng-2for i = 0 to ll1 array.set(a,i, lambda*(-4)) array.set(b,i, src[i]) array.set(c,i, lambda*(-4)) array.set(d,i, lambda*6 + 1) array.set(e,i, lambda) array.set(f,i, lambda)array.set(d, 0, lambda + 1.0)array.set(d, ll1, lambda + 1.0)array.set(d, 1, lambda * 5.0 + 1.0)array.set(d, ll2, lambda * 5.0 + 1.0)array.set(c, 0 , lambda * (-2.0))array.set(c, ll2, lambda * (-2.0))array.set(a, 0 , lambda * (-2.0))array.set(a, ll2, lambda * (-2.0))//////////////Solve the optimization issue/////////////////////float r = array.get(a, 0)float s = array.get(a, 1)float t = array.get(e, 0)float xmult = 0.0for i = 1 to ll2 xmult := r / array.get(d, i-1) array.set(d, i, array.get(d, i) - xmult * array.get(c, i-1)) array.set(c, i, array.get(c, i) - xmult * array.get(f, i-1)) array.set(b, i, array.get(b, i) - xmult * array.get(b, i-1)) xmult := t / array.get(d, i-1) r := s - xmult*array.get(c, i-1) array.set(d, i+1, array.get(d, i+1) - xmult * array.get(f, i-1)) array.set(b, i+1, array.get(b, i+1) - xmult * array.get(b, i-1)) s := array.get(a, i+1) t := array.get(e, i)xmult := r / array.get(d, ll2)array.set(d, ll1, array.get(d, ll1) - xmult * array.get(c, ll2))x = array.new_float(leng, 0) array.set(x, ll1, (array.get(b, ll1) - xmult * array.get(b, ll2)) / array.get(d, ll1))array.set(x, ll2, (array.get(b, ll2) - array.get(c, ll2) * array.get(x, ll1)) / array.get(d, ll2))for j = 0 to leng-3 i = leng-3 - j array.set(x, i, (array.get(b,i) - array.get(f,i)*array.get(x,i+2) - array.get(c,i)*array.get(x,i+1)) / array.get(d, i))//////////////Construct the output///////////////////HP = array.get(x,0)///////////////Custom VWAP////////////////////////TimeFrame = input('1', type=input.resolution)start = security(syminfo.tickerid, TimeFrame, time)//------------------------------------------------newSession = iff(change(start), 1, 0)//------------------------------------------------vwapsum = 0.0vwapsum := iff(newSession, HP*volume, vwapsum[1]+HP*volume)volumesum = 0.0volumesum := iff(newSession, volume, volumesum[1]+volume)v2sum = 0.0v2sum := iff(newSession, volume*HP*HP, v2sum[1]+volume*HP*HP)myvwap = vwapsum/volumesumdev = sqrt(max(v2sum/volumesum - myvwap*myvwap, 0))Coloring=close>myvwap?color.new(#81c784, 62):color.new(#c2185b, 38)av=myvwapshowBcol = input(true, type=input.bool, title="Show barcolors")///////////////Entry & Exit///////////////////// Custom function to convert pips into whole numberstoWhole(number) => return = atr < 1.0 ? (number / syminfo.mintick) / (10 / syminfo.pointvalue) : number return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return * 100 : return // Custom function to convert whole numbers back into pipstoPips(number) => return = atr >= 1.0 ? number : (number * syminfo.mintick) * (10 / syminfo.pointvalue) return := atr >= 1.0 and atr < 100.0 and syminfo.currency == "JPY" ? return / 100 : return // Custom function to truncate (cut) excess decimal placestruncate(_number, _decimalPlaces) => _factor = pow(10, _decimalPlaces) int(_number * _factor) / _factor///////////////Conditional Strategy Logic//////////////Long = crossover(av, ohlc4)Sell = crossunder(av, ohlc4)// Check if we have confirmation for our setupvalidLong = Long and strategy.position_size == 0 and inDateRange and barstate.isconfirmedvalidShort = Sell and strategy.position_size == 0 and inDateRange and barstate.isconfirmed// Calculate our stop distance & size for the current barstopSize = atr * stopMultiplierlongStopPrice = low < low[1] ? low - stopSize : low[1] - stopSizelongStopDistance = close - longStopPricelongTargetPrice = close + (longStopDistance * rr)// Save trade stop & target & position size if a valid setup is detectedvar t_entry = 0.0var t_stop = 0.0var t_target = 0.0var t_direction = 0// Detect valid long setups & trigger alertif validLong t_entry := close t_stop := longStopPrice t_target := longTargetPrice t_direction := 1 strategy.entry(id="Long", long=strategy.long, when=validLong, comment="(SL=" + tostring(truncate(toWhole(longStopDistance),2)) + " pips)") // Fire alerts alert(message="Long Detected", freq=alert.freq_once_per_bar_close) // Check if price has hit long stop loss or targetif t_direction == 1 and (low <= t_stop or high >= t_target) t_direction := 0// Check if price has hit short stop loss or targetif t_direction == -1 and (high >= t_stop or low <= t_target) t_direction := 0// Exit trades whenever our stop or target is hitstrategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0)// Draw trade dataplot(strategy.position_size != 0 or validLong? t_stop : na, title="Trade Stop Price", color=color.red, style=plot.style_linebr)plot(strategy.position_size != 0 or validLong? t_target : na, title="Trade Target Price", color=color.green, style=plot.style_linebr)/////////////////////Plotting//////////////////////////A=plot(av, color=Coloring, title="HP VWAP")barcolor(showBcol?Coloring:na)fill(A, plot(ohlc4), Coloring)// Draw price action setup arrowsplotshape(validLong ? 1 : na, style=shape.triangleup, location=location.belowbar, color=color.green, title="Bullish Setup")// --- BEGIN TESTER CODE --- //// Declare performance tracking variablesvar balance = startBalancevar drawdown = 0.0var maxDrawdown = 0.0var maxBalance = 0.0var totalPips = 0.0var totalWins = 0var totalLoss = 0// Detect winning tradesif strategy.wintrades != strategy.wintrades[1] balance := balance + ((riskPerTrade / 100) * balance) * rr totalPips := totalPips + abs(t_entry - t_target) totalWins := totalWins + 1 if balance > maxBalance maxBalance := balance // Detect losing tradesif strategy.losstrades != strategy.losstrades[1] balance := balance - ((riskPerTrade / 100) * balance) totalPips := totalPips - abs(t_entry - t_stop) totalLoss := totalLoss + 1 // Update drawdown drawdown := (balance / maxBalance) - 1 if drawdown < maxDrawdown maxDrawdown := drawdown // Prepare stats tablevar table testTable = table.new(position.top_right, 5, 2, border_width=1)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor) // Draw stats tablevar bgcolor = color.new(color.black,0)if drawTester if barstate.islastconfirmedhistory // Update table dollarReturn = balance - startBalance f_fillCell(testTable, 0, 0, "Total Trades:", tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(testTable, 0, 1, "Win Rate:", tostring(truncate((strategy.wintrades/strategy.closedtrades)*100,2)) + "%", bgcolor, color.white) f_fillCell(testTable, 1, 0, "Starting:", "$" + tostring(startBalance), bgcolor, color.white) f_fillCell(testTable, 1, 1, "Ending:", "$" + tostring(truncate(balance,2)), bgcolor, color.white) f_fillCell(testTable, 2, 0, "Return:", "$" + tostring(truncate(dollarReturn,2)), dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + tostring(truncate(toWhole(totalPips),2)), bgcolor, color.white) f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + tostring(truncate((dollarReturn / startBalance)*100,2)) + "%", dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 3, 1, "Max DD:", tostring(truncate(maxDrawdown*100,2)) + "%", color.red, color.white)// --- END TESTER CODE --- //