Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (9)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,095$202,527Equity from $100,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.
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

Differs

Trades 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

Verified

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

SettingDefaultType and rangeFeeds
SourceopensourcefastMA slowMA line 107
Fast Length13int (written input.integer)fastMA
Slow Length19int (written input.integer)slowMA
Apply kNN filtertrueboolentry Long entry Short line 115 line 117
Filter Length13int (written input.integer)adx diplus diminus mfiUp mfiDown
Filter Smoothing6int (written input.integer)adx diplus diminus
kNN nearest neighbors (k)45int (written input.integer)filter
kNN minimum difference2int (written input.integer)entry Long entry Short line 115 line 117
Draw backgroundfalseboolbgcolor

What it calculates

  • VWMA (vwma, ta.vwma in v5)Source (open), Fast Length (13)fastMA · line 66
  • VWMA (vwma, ta.vwma in v5)Source (open), Slow Length (19)slowMA · line 67
  • Change (change, ta.change in v5)highup · line 77
  • Change (change, ta.change in v5)lowdown · line 78
  • Change (change, ta.change in v5)ohlc4mfiUp · line 98
  • Change (change, ta.change in v5)ohlc4mfiDown · line 99
  • Crossover (crossover, ta.crossover in v5)fastMA, slowMAlongCondition · line 104
  • Crossunder (crossunder, ta.crossunder in 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.

openopenprice dataFASTFast Lengthsetting · 13SLOWSlow Lengthsetting · 19highhighprice datalowlowprice dataohlc4ohlc4price datavolumevolumeprice dataFILTERFilter Lengthsetting · 13SMOOTHFilter Smoothingsetting · 6KNNkNN nearest neighbors (…setting · 45DISTkNN minimum differencesetting · 2fastMAVWMA→ fastMAslowMAVWMA→ slowMAupChange→ updownChange→ downmfiUpChange→ mfiUpmfiDownChange→ mfiDownlongConditionCrossover→ longConditionshortConditionCrossunder→ shortConditionprevp1, prevp2, prevsrc, sarr, n, d, slice, trurprevp1 · prevp2 +68 valuesssssvaluemmvalueoutoutvalueknnknnvalueplusDM, minusDMplusDM · minusDM2 valuesplusplusvalueminusminusvaluesumsumvalueadx, diplus, diminusadx · diplus +13 valuesmfimfivaluefilterfiltervalueentry:LongOpen Longstrategy.entryentry:ShortOpen Shortstrategy.entrybgcolor:112bgcolorbgcolorplot:113plotplotplot:114plotplot

Order rules

OrderFires whenBy defaultLine
Open Long long(longCondition and (not APPLY or filter >= DIST))On116
Open Short short(shortCondition and (not APPLY or filter <= -DIST))On118

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.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • 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−98.8%+102.5%30%0.00106.2%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−11.1%+5.5%10%0.0015.5%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−39.1%+9.8%10%0.00109.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h0.0%+8.4%00%—42.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−79.8%+16.7%333%0.0292.5%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+48.5%+21.5%250%40.7713.5%8 May 2026 – 21 Oct 2026
BNBUSDT 1D0.0%+148.3%00%—30.8%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−21.1%+17.1%20%0.0023.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 barsTradesWonP&L
Rising market20%−$18,060.10
Sideways market0—$0.00
Falling market10%−$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.

0%114%
All 3 trades
SideEntryExitBarsP&L
long3 Apr 2024 65,464.007 Sep 2024 53,963.00157−$17,568.50
short7 Sep 2024 53,963.0017 Jun 2025 106,795.00283−$80,703.20
long17 Jun 2025 106,795.0018 Sep 2026 76,417.00458−$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.

ScriptSharesTypeNetTradesMax drawdown
VWMA with kNN Machine Learning- MFI-ADX this page—v4 strategy−98.8%3106.2%
Profitable Contrarian scalping by Jaerevan47vwmav5 strategy−48.2%760.2%
Rolling VWAP by Zeal Terminalvwmav5 indicatorindicator
Swing Trading SPX Correlation by exlux99vwmav5 strategyNo trades on this market
Volume fight strategy by Shuttle_Clubvwmav5 strategy+92.0%4524.6%
Volume Weighted Moving Average by Zeal Terminalvwmav5 indicatorindicator

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 19 msYes 1,000 bars in 192 msNot measured
PineTSNo v5 and v6 only—Not measured

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

Source

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

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © 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)