Pine Script v4 · Strategy
VWMA with kNN Machine Learning- MFI-ADX
A Pine Script v4 strategy built on VWMA (open, 13), Change (high) and Crossover (fastMA, slowMA). It has 2 order rules, 2 entries among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade commits 100% of equity and pays no commission. 9 settings; defaults include Source open, Fast Length 13 and Slow Length 19.
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 VWMA with kNN Machine Learning- MFI-ADX repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did VWMA with kNN Machine Learning- MFI-ADX do on BTCUSDT 1D with default settings?
- −98.76%
- From 26 Jan 2024 to 21 Oct 2026, over 3 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can VWMA with kNN Machine Learning- MFI-ADX be converted to Pine Script v5?
- No
- The automatic step from v4 to v5 changes the results, so no v5 download is offered; the edits are shown below.
- Does VWMA with kNN Machine Learning- MFI-ADX use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
- Does VWMA with kNN Machine Learning- MFI-ADX run in Zeal Terminal?
- Yes
- It compiles in 19 ms and runs 1,000 bars in 192 ms, in the browser.
BTCUSDT · 1D · default settings
- Plot
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −98.76%
- −$98,763.30
- Buy and hold
- +102.5%
- same period
- Closed trades
- 3
- 0 won · 3 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- 0.00
- gross profit ÷ gross loss
- Max drawdown
- 106.19%
- −$106,193.00
One run with the author's default settings, $100,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
No stop loss
Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.
-
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
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 min → math.min, sqrt → math.sqrt, pow → math.pow, vwma → ta.vwma, change → ta.change, abs → math.abs, sum → math.sum, crossover → ta.crossover, crossunder → ta.crossunder.
v4 → v5
DiffersTrades differ: 3 before, 3 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 31: min → math.min
- Line 43: sqrt → math.sqrt
- Line 43: pow → math.pow
- Line 43: pow → math.pow
- Line 53: input(type = input.source) → input.source()
18 more edits
- Line 54: input(type = input.integer) → input.int()
- Line 55: input(type = input.integer) → input.int()
- Line 57: input(type = input.integer) → input.int()
- Line 58: input(type = input.integer) → input.int()
- Line 60: input(type = input.integer) → input.int()
- Line 61: input(type = input.integer) → input.int()
- Line 66: vwma → ta.vwma
- Line 67: vwma → ta.vwma
- Line 77: change → ta.change
- Line 78: change → ta.change
- Line 81: tr → ta.tr
- Line 85: abs → math.abs
- Line 98: sum → math.sum
- Line 98: change → ta.change
- Line 99: sum → math.sum
- Line 99: change → ta.change
- Line 104: crossover → ta.crossover
- Line 105: crossunder → ta.crossunder
⋯// © lastguru-//@version=4+//@version=5strategy(title="VWMA with kNN Machine Learning: MFI/ADX by lastguru", shorttitle="VWMA + kNN: MFI/ADX", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)⋯ array.sort(sarr)- ss = array.slice(sarr, 0, min(k, array.size(sarr)))+ ss = array.slice(sarr, 0, math.min(k, array.size(sarr))) m = array.max(ss)⋯ for i = 0 to n- d = sqrt( pow(p1 - array.get(knn1, i), 2) + pow(p2 - array.get(knn2, i), 2) )+ d = math.sqrt( math.pow(p1 - array.get(knn1, i), 2) + math.pow(p2 - array.get(knn2, i), 2) ) array.push(dist, d)⋯////////////-SRC = input(title="Source", type=input.source, defval=open)+SRC = input.source(title="Source", defval=open)-FAST = input(title="Fast Length", type=input.integer, defval=13)+FAST = input.int(title="Fast Length", defval=13)-SLOW = input(title="Slow Length", type=input.integer, defval=19)+SLOW = input.int(title="Slow Length", defval=19)APPLY = input(title = "Apply kNN filter", defval=true)-FILTER = input(title="Filter Length", type=input.integer, defval=13)+FILTER = input.int(title="Filter Length", defval=13)-SMOOTH = input(title="Filter Smoothing", type=input.integer, defval=6)+SMOOTH = input.int(title="Filter Smoothing", defval=6)// When DIST is 0, KNN default was 23-KNN = input(title="kNN nearest neighbors (k)", type=input.integer, defval=45)+KNN = input.int(title="kNN nearest neighbors (k)", defval=45)-DIST = input(title="kNN minimum difference", type=input.integer, defval=2)+DIST = input.int(title="kNN minimum difference", defval=2)BACKGROUND = input(title = "Draw background", defval=false)⋯////////-fastMA = vwma(SRC, FAST)+fastMA = ta.vwma(SRC, FAST)-slowMA = vwma(SRC, SLOW)+slowMA = ta.vwma(SRC, SLOW)/////////⋯_dmi (len, smooth) =>- up = change(high)+ up = ta.change(high)- down = -change(low)+ down = -ta.change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)- trur = _rma(tr, len)+ trur = _rma(ta.tr, len) plus = fixnan(100 * _rma(plusDM, len) / trur)⋯ sum = plus + minus- adx = 100 * _rma(abs(plus - minus) / (sum == 0 ? 1 : sum), smooth)+ adx = 100 * _rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), smooth) [plus, minus, adx]⋯ 100.0 - (100.0 / (1.0 + upper / lower))-mfiUp = sum(volume * (change(ohlc4) <= 0 ? 0 : ohlc4), FILTER)+mfiUp = math.sum(volume * (ta.change(ohlc4) <= 0 ? 0 : ohlc4), FILTER)-mfiDown = sum(volume * (change(ohlc4) >= 0 ? 0 : ohlc4), FILTER)+mfiDown = math.sum(volume * (ta.change(ohlc4) >= 0 ? 0 : ohlc4), FILTER)mfi = _rsi(mfiUp, mfiDown)⋯////////////-longCondition = crossover(fastMA, slowMA)+longCondition = ta.crossover(fastMA, slowMA)-shortCondition = crossunder(fastMA, slowMA)+shortCondition = ta.crossunder(fastMA, slowMA)if (longCondition or shortCondition)⋯Clean v5
VerifiedSame 3 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 56: input() → input.bool()
- Line 62: input() → input.bool()
⋯SLOW = input.int(title="Slow Length", defval=19)-APPLY = input(title = "Apply kNN filter", defval=true)+APPLY = input.bool(title = "Apply kNN filter", defval=true)FILTER = input.int(title="Filter Length", defval=13)⋯DIST = input.int(title="kNN minimum difference", defval=2)-BACKGROUND = input(title = "Draw background", defval=false)+BACKGROUND = input.bool(title = "Draw background", defval=false)////////⋯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: 3 before, 5 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.
⋯// © lastguru-//@version=5+//@version=6strategy(title="VWMA with kNN Machine Learning: MFI/ADX by lastguru", shorttitle="VWMA + kNN: MFI/ADX", overlay=true, 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Source | open | source | fastMA slowMA line 107 |
| Fast Length | 13 | int (written input.integer) | fastMA |
| Slow Length | 19 | int (written input.integer) | slowMA |
| Apply kNN filter | true | bool | entry Long entry Short line 115 line 117 |
| Filter Length | 13 | int (written input.integer) | adx diplus diminus mfiUp mfiDown |
| Filter Smoothing | 6 | int (written input.integer) | adx diplus diminus |
| kNN nearest neighbors (k) | 45 | int (written input.integer) | filter |
| kNN minimum difference | 2 | int (written input.integer) | entry Long entry Short line 115 line 117 |
| Draw background | false | bool | bgcolor |
What it calculates
- VWMA (
vwma,ta.vwmain v5)Source (open), Fast Length (13)fastMA · line 66 - VWMA (
vwma,ta.vwmain v5)Source (open), Slow Length (19)slowMA · line 67 - Change (
change,ta.changein v5)highup · line 77 - Change (
change,ta.changein v5)lowdown · line 78 - Change (
change,ta.changein v5)ohlc4mfiUp · line 98 - Change (
change,ta.changein v5)ohlc4mfiDown · line 99 - Crossover (
crossover,ta.crossoverin v5)fastMA, slowMAlongCondition · line 104 - Crossunder (
crossunder,ta.crossunderin v5)fastMA, slowMAshortCondition · line 105
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 | (longCondition and (not APPLY or filter >= DIST)) | On | 116 |
| Open Short short | (shortCondition and (not APPLY or filter <= -DIST)) | On | 118 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | −98.8% | +102.5% | 3 | 0% | 0.00 | 106.2% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −11.1% | +5.5% | 1 | 0% | 0.00 | 15.5% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −39.1% | +9.8% | 1 | 0% | 0.00 | 109.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | 0.0% | +8.4% | 0 | 0% | — | 42.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −79.8% | +16.7% | 3 | 33% | 0.02 | 92.5% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +48.5% | +21.5% | 2 | 50% | 40.77 | 13.5% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | 0.0% | +148.3% | 0 | 0% | — | 30.8% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −21.1% | +17.1% | 2 | 0% | 0.00 | 23.8% | 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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 2 | 0% | −$18,060.10 |
| Sideways market | 0 | — | $0.00 |
| Falling market | 1 | 0% | −$80,703.20 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
98.8%
The 95th percentile of the worst drawdown when the same 3 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 98.8% to 98.8%; the tick is what actually happened, 98.8%. Order luck alone moves it this much.
All 3 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 3 Apr 2024 65,464.00 | 7 Sep 2024 53,963.00 | 157 | −$17,568.50 |
| short | 7 Sep 2024 53,963.00 | 17 Jun 2025 106,795.00 | 283 | −$80,703.20 |
| long | 17 Jun 2025 106,795.00 | 18 Sep 2026 76,417.00 | 458 | −$491.61 |
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 |
|---|---|---|---|---|---|
| VWMA with kNN Machine Learning- MFI-ADX this page | — | v4 strategy | −98.8% | 3 | 106.2% |
| Profitable Contrarian scalping by Jaerevan47 | vwma | v5 strategy | −48.2% | 7 | 60.2% |
| Rolling VWAP by Zeal Terminal | vwma | v5 indicator | indicator | ||
| Swing Trading SPX Correlation by exlux99 | vwma | v5 strategy | No trades on this market | ||
| Volume fight strategy by Shuttle_Club | vwma | v5 strategy | +92.0% | 45 | 24.6% |
| Volume Weighted Moving Average by Zeal Terminal | vwma | v5 indicator | indicator | ||
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 19 ms | Yes 1,000 bars in 192 ms | 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/// © lastguru//@version=4strategy(title="VWMA with kNN Machine Learning: MFI/ADX by lastguru", shorttitle="VWMA + kNN: MFI/ADX", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)/////////// kNN ///////////// Define storage arrays for: parameter 1, parameter 2, price, result (up = 1; down = -1)var knn1 = array.new_float(1, 0)var knn2 = array.new_float(1, 0)var knnp = array.new_float(1, 0)var knnr = array.new_float(1, 0)// Store the previous trade; buffer the current one until results are in_knnStore (p1, p2, src) => var prevp1 = 0.0 var prevp2 = 0.0 var prevsrc = 0.0 array.push(knn1, prevp1) array.push(knn2, prevp2) array.push(knnp, prevsrc) array.push(knnr, src >= prevsrc ? 1 : -1) prevp1 := p1 prevp2 := p2 prevsrc := src// Get neighbours by getting k smallest distances from the distance array, and then getting all results with these distances_knnGet(arr1, arr2, k) => sarr = array.copy(arr1) array.sort(sarr) ss = array.slice(sarr, 0, min(k, array.size(sarr))) m = array.max(ss) out = array.new_float(0) for i = 0 to array.size(arr1) - 1 if (array.get(arr1, i) <= m) array.push(out, array.get(arr2, i)) out// Create a distance array from the two given parameters_knnDistance(p1, p2) => dist = array.new_float(0) n = array.size(knn1) - 1 for i = 0 to n d = sqrt( pow(p1 - array.get(knn1, i), 2) + pow(p2 - array.get(knn2, i), 2) ) array.push(dist, d) dist// Make a prediction, finding k nearest neighbours_knn(p1, p2, k) => slice = _knnGet(_knnDistance(p1, p2), array.copy(knnr), k) knn = array.sum(slice)////////////// Inputs //////////////SRC = input(title="Source", type=input.source, defval=open)FAST = input(title="Fast Length", type=input.integer, defval=13)SLOW = input(title="Slow Length", type=input.integer, defval=19)APPLY = input(title = "Apply kNN filter", defval=true)FILTER = input(title="Filter Length", type=input.integer, defval=13)SMOOTH = input(title="Filter Smoothing", type=input.integer, defval=6)// When DIST is 0, KNN default was 23KNN = input(title="kNN nearest neighbors (k)", type=input.integer, defval=45)DIST = input(title="kNN minimum difference", type=input.integer, defval=2)BACKGROUND = input(title = "Draw background", defval=false)////////// MA //////////fastMA = vwma(SRC, FAST)slowMA = vwma(SRC, SLOW)/////////// DMI ///////////// Wilder's Smoothing (Running Moving Average)_rma(src, length) => out = 0.0 out := ((length - 1) * nz(out[1]) + src) / length// DMI (Directional Movement Index)_dmi (len, smooth) => up = change(high) down = -change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) trur = _rma(tr, len) plus = fixnan(100 * _rma(plusDM, len) / trur) minus = fixnan(100 * _rma(minusDM, len) / trur) sum = plus + minus adx = 100 * _rma(abs(plus - minus) / (sum == 0 ? 1 : sum), smooth) [plus, minus, adx][diplus, diminus, adx] = _dmi(FILTER, SMOOTH)/////////// MFI ///////////// common RSI function_rsi(upper, lower) => if lower == 0 100 if upper == 0 0 100.0 - (100.0 / (1.0 + upper / lower))mfiUp = sum(volume * (change(ohlc4) <= 0 ? 0 : ohlc4), FILTER)mfiDown = sum(volume * (change(ohlc4) >= 0 ? 0 : ohlc4), FILTER)mfi = _rsi(mfiUp, mfiDown)////////////// Filter //////////////longCondition = crossover(fastMA, slowMA)shortCondition = crossunder(fastMA, slowMA)if (longCondition or shortCondition) _knnStore(adx, mfi, SRC)filter = _knn(adx, mfi, KNN)/////////////// Actions ///////////////bgcolor(BACKGROUND ? filter >= 0 ? color.green : color.red : na)plot(fastMA, color=color.red)plot(slowMA, color=color.green)if (longCondition and (not APPLY or filter >= DIST)) strategy.entry("Long", strategy.long)if (shortCondition and (not APPLY or filter <= -DIST)) strategy.entry("Short", strategy.short)