ML Pivots Breakouts for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
t0zuehh.png


Limited nearest neighbor up to 13 only!
Author Message:
'Machine Learning Breakouts (from Pivots)' indicator to revolutionize the way we detect breakout opportunities and follow trend, harnessing the power of pivot points and machine learning. This tool integrates the k-Nearest Neighbors (k-NN) method with the Euclidean distance algorithm, meticulously analyzing pivot points to accurately forecast multiple breakout paths/zones. "ML Pivots Breakouts" is designed to identify and visually alert traders on bullish breakouts above high lines and bearish breakouts below low lines, offering essential insights for breakout and trend follower traders.

CODE:

CSS:
# https://www.tradingview.com/v/3ve5wjun/
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © tkarolak
#// Description //
#// "ML Pivots Breakouts" identifies multiple breakout zones through kNN ML prediction from pivot points,
#// offering essential insights for breakout and trend follower traders. It visually alerts on bullish breakouts above high lines and
#// bearish breakouts below low lines, designed for both long and short strategies, adapting to volatility and market shifts.
#indicator("Machine Learning Breakouts (from Pivots)", shorttitle="ML Pivots Breakouts", overlay=true, precision=4,
# Converted and mod by Sam4Cok@Samer800 - 02/2024, (Limited Number of Neighbors)

input colorBars = no;
input fastMode = no;
input ShowPivotsLabel = no; #,"Show/Hide Pivots"
input showCloud = yes;
input DistanceCalcMethod = {Default "Nearest Neighbors", "Lorentzian", "Euclidean", "Cosine similarity"};
input source = close;
input pivotBars = 20;      # "Pivot Bars"
input NumberOfNeighbors = 5;    # "Number of Neighbors (k)"
input predictionSmoothing = 20; # "Prediction Smoothing"

def na = Double.NaN;
def last = isNaN(close);
def rightBar = if fastMode then floor(pivotBars/2) else pivotBars;
#-- Colors
DefineGlobalColor("up", CreateColor(33,150,243));
DefineGlobalColor("dn", CreateColor(255,82,82));
DefineGlobalColor("dup",CreateColor(7,76,132));
DefineGlobalColor("ddn",CreateColor(141,0,0));

def k = Min(Max(NumberOfNeighbors, 1), 13);
script Pivots {
    input series    = close;
    input leftBars  = 10;
    input rightBars = 10;
    input isHigh = yes;
    def na = Double.NaN;
    def HH = series == Highest(series, leftBars + 1);
    def LL = series == Lowest(series, leftBars + 1);
    def pivotRange = (leftBars + rightBars + 1);
    def leftEdgeValue = if series[pivotRange] == 0 then na else series[pivotRange];
    def pvtCond = !IsNaN(series) and leftBars > 0 and rightBars > 0 and !IsNaN(leftEdgeValue);
    def barIndexH = if pvtCond then
                    fold i = 1 to rightBars + 1 with p=1 while p do
                    series > GetValue(series, - i) else na;
    def barIndexL = if pvtCond then
                    fold j = 1 to rightBars + 1 with q=1 while q do
                    series < GetValue(series, - j) else na;
    def PivotPoint;def cond;
    if isHigh {
        cond = HH and barIndexH;
        PivotPoint = if cond then series else na;
    } else {
        cond = LL and barIndexL;
        PivotPoint = if cond then series else na;
    }
    plot pvt = PivotPoint;
}
script Ranking {
    input i0 = 0;
    input i1 = 0;
    input i2 = 0;
    input i3 = 0;
    input i4 = 0;
    input i5 = 0;
    input i6 = 0;
    input i7 = 0;
    input i8 = 0;
    input i9 = 0;
    input i10 = 0;
    input i11 = 0;
    input i12 = 0;
    def v0 = if IsNaN(i0) then Double.POSITIVE_INFINITY else i0;
    def v1 = if IsNaN(i1) then Double.POSITIVE_INFINITY else i1;
    def v2 = if IsNaN(i2) then Double.POSITIVE_INFINITY else i2;
    def v3 = if IsNaN(i3) then Double.POSITIVE_INFINITY else i3;
    def v4 = if IsNaN(i4) then Double.POSITIVE_INFINITY else i4;
    def v5 = if IsNaN(i5) then Double.POSITIVE_INFINITY else i5;
    def v6 = if IsNaN(i6) then Double.POSITIVE_INFINITY else i6;
    def v7 = if IsNaN(i7) then Double.POSITIVE_INFINITY else i7;
    def v8 = if IsNaN(i8) then Double.POSITIVE_INFINITY else i8;
    def v9 = if IsNaN(i9) then Double.POSITIVE_INFINITY else i9;
    def v10 = if IsNaN(i10) then Double.POSITIVE_INFINITY else i10;
    def v11 = if IsNaN(i11) then Double.POSITIVE_INFINITY else i11;
    def v12 = if IsNaN(i12) then Double.POSITIVE_INFINITY else i12;
    def r1 = v0 < v1;
    def r2 = v0 < v2;
    def r3 = v0 < v3;
    def r4 = v0 < v4;
    def r5 = v0 < v5;
    def r6 = v0 < v6;
    def r7 = v0 < v7;
    def r8 = v0 < v8;
    def r9 = v0 < v9;
    def r10 = v0 < v10;
    def r11 = v0 < v11;
    def r12 = v0 < v12;
    plot result = r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10+ r11+ r12;
}
Script knn_distance {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def knn_distance = Sqrt(Sqr(currentPar1 - param1) + Sqr(currentPar2 - param2));
    plot out = if isNaN(knn_distance) then Double.POSITIVE_INFINITY else knn_distance;
}
Script lorentzian_distance {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def lorentzian_distance = log(1 + AbsValue(currentPar1 - param1)) + log(1 + AbsValue(currentPar2 - param2));
    plot out = if isNaN(lorentzian_distance) then Double.POSITIVE_INFINITY else lorentzian_distance;
}
Script euclidean_distance {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def euclidean_distance = Sqr(currentPar1 - param1) + Sqr(currentPar2 - param2);
    plot out = if isNaN(euclidean_distance) then Double.POSITIVE_INFINITY else euclidean_distance;
}
Script cosine_similarity {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def dotProduct = (currentPar1 * param1) + (currentPar2 * param2);
    def magnitudeSeries = (Sqr(currentPar1) + Sqr(currentPar2));
    def magnitudeArray = (Sqr(param1) + Sqr(param2));
    def cosine_similarity = dotProduct / (magnitudeSeries * magnitudeArray);
    plot out = if isNaN(cosine_similarity) then Double.POSITIVE_INFINITY else cosine_similarity;
}
Script DistanceCalculation {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input type = "Nearest Neighbors";
input nzPar1 = 1;
input naPar2 = 1;
    def knn        = knn_distance(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def Lorentzian = lorentzian_distance(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def Euclidean  = euclidean_distance(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def Cosine     = cosine_similarity(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def calc = if type == "Nearest Neighbors" then knn else
               if type == "Lorentzian" then Lorentzian else
               if type == "Euclidean" then Euclidean else
               if type == "Cosine similarity" then Cosine else knn;
    plot out = if isNaN(calc) then Double.POSITIVE_INFINITY else calc;
}
#/ @return float: Predicted pivot price based on nearest neighbors.
Script Prediction {
input currentPrice = close;
input ph = high;
input pl = low;
input pivotBars = 20;
input k = 10;
input isHigh = yes;
input type = yes;
    def time = GetTime();
    def preBar = time - ((time - time[1]) * pivotBars);
    def src; def preSrc; def pvtDetected;
    if isHigh {
        pvtDetected = !isNaN(ph);
        src = high;
        preSrc = highest(src, pivotBars);
    } else {
        pvtDetected = !isNaN(pl);
        src = low;
        preSrc = lowest(src, pivotBars);
    }
    def ph0; def ph1; def ph2; def ph3; def ph4; def ph5; def ph6; def ph7; def ph8; def ph9; def ph10;
    def ph11; def ph12;
    def xh0; def xh1; def xh2; def xh3; def xh4; def xh5; def xh6; def xh7; def xh8; def xh9;def xh10;
    def xh11;def xh12;
    if pvtDetected {
    ph12 = ph11[1];
    ph11 = ph10[1];
    ph10 = ph9[1];
    ph9 = ph8[1];
    ph8 = ph7[1];
    ph7 = ph6[1];
    ph6 = ph5[1];
    ph5 = ph4[1];
    ph4 = ph3[1];
    ph3 = ph2[1];
    ph2 = ph1[1];
    ph1 = ph0[1];
    ph0 = src;
    xh12 = xh11[1];
    xh11 = xh10[1];
    xh10 = xh9[1];
    xh9 = xh8[1];
    xh8 = xh7[1];
    xh7 = xh6[1];
    xh6 = xh5[1];
    xh5 = xh4[1];
    xh4 = xh3[1];
    xh3 = xh2[1];
    xh2 = xh1[1];
    xh1 = xh0[1];
    xh0 = time;
    } else {
    ph12 = if ph12[1]==0 then preSrc[12] else ph12[1];
    ph11 = if ph11[1]==0 then preSrc[11] else ph11[1];
    ph10 = if ph10[1]==0 then preSrc[10] else ph10[1];
    ph9 = if ph9[1]==0 then preSrc[9] else ph9[1];
    ph8 = if ph8[1]==0 then preSrc[8] else ph8[1];
    ph7 = if ph7[1]==0 then preSrc[7] else ph7[1];
    ph6 = if ph6[1]==0 then preSrc[6] else ph6[1];
    ph5 = if ph5[1]==0 then preSrc[5] else ph5[1];
    ph4 = if ph4[1]==0 then preSrc[4] else ph4[1];
    ph3 = if ph3[1]==0 then preSrc[3] else ph3[1];
    ph2 = if ph2[1]==0 then preSrc[2] else ph2[1];
    ph1 = if ph1[1]==0 then preSrc[1] else ph1[1];
    ph0 = if ph0[1]==0 then preSrc[0] else ph0[1];
    xh12 = if xh12[1]==0 then preBar[12] else xh12[1];
    xh11 = if xh11[1]==0 then preBar[11] else xh11[1];
    xh10 = if xh10[1]==0 then preBar[10] else xh10[1];
    xh9 = if xh9[1]==0 then preBar[9] else xh9[1];
    xh8 = if xh8[1]==0 then preBar[8] else xh8[1];
    xh7 = if xh7[1]==0 then preBar[7] else xh7[1];
    xh6 = if xh6[1]==0 then preBar[6] else xh6[1];
    xh5 = if xh5[1]==0 then preBar[5] else xh5[1];
    xh4 = if xh4[1]==0 then preBar[4] else xh4[1];
    xh3 = if xh3[1]==0 then preBar[3] else xh3[1];
    xh2 = if xh2[1]==0 then preBar[2] else xh2[1];
    xh1 = if xh1[1]==0 then preBar[1] else xh1[1];
    xh0 = if xh0[1]==0 then preBar[0] else xh0[1];
}
    def dist0 = DistanceCalculation(currentPrice, ph0, time, xh0, type, preSrc[0], preBar[0]);
    def dist1 = DistanceCalculation(currentPrice, ph1, time, xh1, type, preSrc[1], preBar[1]);
    def dist2 = DistanceCalculation(currentPrice, ph2, time, xh2, type, preSrc[2], preBar[2]);
    def dist3 = DistanceCalculation(currentPrice, ph3, time, xh3, type, preSrc[3], preBar[3]);
    def dist4 = DistanceCalculation(currentPrice, ph4, time, xh4, type, preSrc[4], preBar[4]);
    def dist5 = DistanceCalculation(currentPrice, ph5, time, xh5, type, preSrc[5], preBar[5]);
    def dist6 = DistanceCalculation(currentPrice, ph6, time, xh6, type, preSrc[6], preBar[6]);
    def dist7 = DistanceCalculation(currentPrice, ph7, time, xh7, type, preSrc[7], preBar[7]);
    def dist8 = DistanceCalculation(currentPrice, ph8, time, xh8, type, preSrc[8], preBar[8]);
    def dist9 = DistanceCalculation(currentPrice, ph9, time, xh9, type, preSrc[9], preBar[9]);
    def dist10 = DistanceCalculation(currentPrice, ph10, time, xh10, type, preSrc[10], preBar[10]);
    def dist11 = DistanceCalculation(currentPrice, ph11, time, xh11, type, preSrc[11], preBar[11]);
    def dist12 = DistanceCalculation(currentPrice, ph12, time, xh12, type, preSrc[12], preBar[12]);

    def h0p = 13 - Ranking(dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist10, dist11, dist12);
    def h1p = 13 - Ranking(dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist10, dist11, dist12);
    def h2p = 13 - Ranking(dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist10, dist11, dist12);
    def h3p = 13 - Ranking(dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist10, dist11, dist12);
    def h4p = 13 - Ranking(dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist10, dist11, dist12);
    def h5p = 13 - Ranking(dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist10, dist11, dist12);
    def h6p = 13 - Ranking(dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist10, dist11, dist12);
    def h7p = 13 - Ranking(dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist10, dist11, dist12);
    def h8p = 13 - Ranking(dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist10, dist11, dist12);
    def h9p = 13 - Ranking(dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist10, dist11, dist12);
    def h10p = 13 - Ranking(dist10, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist11, dist12);
    def h11p = 13 - Ranking(dist11, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist10, dist12);
    def h12p = 13 - Ranking(dist12, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist10, dist11);
    def maxH1 = if h0p == 1 then ph0 else
                if h1p == 1 then ph1 else
                if h2p == 1 then ph2 else
                if h3p == 1 then ph3 else
                if h4p == 1 then ph4 else
                if h5p == 1 then ph5 else
                if h6p == 1 then ph6 else
                if h7p == 1 then ph7 else
                if h8p == 1 then ph8 else
                if h9p == 1 then ph9 else
                if h10p == 1 then ph10 else
                if h11p == 1 then ph11 else ph12;
    def maxH2 = if h0p == 2 then ph0 else
                if h1p == 2 then ph1 else
                if h2p == 2 then ph2 else
                if h3p == 2 then ph3 else
                if h4p == 2 then ph4 else
                if h5p == 2 then ph5 else
                if h6p == 2 then ph6 else
                if h7p == 2 then ph7 else
                if h8p == 2 then ph8 else
                if h9p == 2 then ph9 else
                if h10p == 2 then ph10 else
                if h11p == 2 then ph11 else ph12;
    def maxH3 = if h0p == 3 then ph0 else
                if h1p == 3 then ph1 else
                if h2p == 3 then ph2 else
                if h3p == 3 then ph3 else
                if h4p == 3 then ph4 else
                if h5p == 3 then ph5 else
                if h6p == 3 then ph6 else
                if h7p == 3 then ph7 else
                if h8p == 3 then ph8 else
                if h9p == 3 then ph9 else
                if h10p == 3 then ph10 else
                if h11p == 3 then ph11 else ph12;
    def maxH4 = if h0p == 4 then ph0 else
                if h1p == 4 then ph1 else
                if h2p == 4 then ph2 else
                if h3p == 4 then ph3 else
                if h4p == 4 then ph4 else
                if h5p == 4 then ph5 else
                if h6p == 4 then ph6 else
                if h7p == 4 then ph7 else
                if h8p == 4 then ph8 else
                if h9p == 4 then ph9 else
                if h10p == 4 then ph10 else
                if h11p == 4 then ph11 else ph12;
    def maxH5 = if h0p == 5 then ph0 else
                if h1p == 5 then ph1 else
                if h2p == 5 then ph2 else
                if h3p == 5 then ph3 else
                if h4p == 5 then ph4 else
                if h5p == 5 then ph5 else
                if h6p == 5 then ph6 else
                if h7p == 5 then ph7 else
                if h8p == 5 then ph8 else
                if h9p == 5 then ph9 else
                if h10p == 5 then ph10 else
                if h11p == 5 then ph11 else ph12;
    def maxH6 = if h0p == 6 then ph0 else
                if h1p == 6 then ph1 else
                if h2p == 6 then ph2 else
                if h3p == 6 then ph3 else
                if h4p == 6 then ph4 else
                if h5p == 6 then ph5 else
                if h6p == 6 then ph6 else
                if h7p == 6 then ph7 else
                if h8p == 6 then ph8 else
                if h9p == 6 then ph9 else
                if h10p == 6 then ph10 else
                if h11p == 6 then ph11 else ph12;
    def maxH7 = if h0p == 7 then ph0 else
                if h1p == 7 then ph1 else
                if h2p == 7 then ph2 else
                if h3p == 7 then ph3 else
                if h4p == 7 then ph4 else
                if h5p == 7 then ph5 else
                if h6p == 7 then ph6 else
                if h7p == 7 then ph7 else
                if h8p == 7 then ph8 else
                if h9p == 7 then ph9 else
                if h10p == 7 then ph10 else
                if h11p == 7 then ph11 else ph12;
    def maxH8 = if h0p == 8 then ph0 else
                if h1p == 8 then ph1 else
                if h2p == 8 then ph2 else
                if h3p == 8 then ph3 else
                if h4p == 8 then ph4 else
                if h5p == 8 then ph5 else
                if h6p == 8 then ph6 else
                if h7p == 8 then ph7 else
                if h8p == 8 then ph8 else
                if h9p == 8 then ph9 else
                if h10p == 8 then ph10 else
                if h11p == 8 then ph11 else ph12;
    def maxH9 = if h0p == 9 then ph0 else
                if h1p == 9 then ph1 else
                if h2p == 9 then ph2 else
                if h3p == 9 then ph3 else
                if h4p == 9 then ph4 else
                if h5p == 9 then ph5 else
                if h6p == 9 then ph6 else
                if h7p == 9 then ph7 else
                if h8p == 9 then ph8 else
                if h9p == 9 then ph9 else
                if h10p == 9 then ph10 else
                if h11p == 9 then ph11 else ph12;
    def maxH10 = if h0p == 10 then ph0 else
                 if h1p == 10 then ph1 else
                 if h2p == 10 then ph2 else
                 if h3p == 10 then ph3 else
                 if h4p == 10 then ph4 else
                 if h5p == 10 then ph5 else
                 if h6p == 10 then ph6 else
                 if h7p == 10 then ph7 else
                 if h8p == 10 then ph8 else
                 if h9p == 10 then ph9 else
                 if h10p == 10 then ph10 else
                 if h11p == 10 then ph11 else ph12;
    def maxH11 = if h0p == 11 then ph0 else
                 if h1p == 11 then ph1 else
                 if h2p == 11 then ph2 else
                 if h3p == 11 then ph3 else
                 if h4p == 11 then ph4 else
                 if h5p == 11 then ph5 else
                 if h6p == 11 then ph6 else
                 if h7p == 11 then ph7 else
                 if h8p == 11 then ph8 else
                 if h9p == 11 then ph9 else
                 if h10p == 11 then ph10 else
                 if h11p == 11 then ph11 else ph12;
    def maxH12 = if h0p == 12 then ph0 else
                 if h1p == 12 then ph1 else
                 if h2p == 12 then ph2 else
                 if h3p == 12 then ph3 else
                 if h4p == 12 then ph4 else
                 if h5p == 12 then ph5 else
                 if h6p == 12 then ph6 else
                 if h7p == 12 then ph7 else
                 if h8p == 12 then ph8 else
                 if h9p == 12 then ph9 else
                 if h10p == 12 then ph10 else
                 if h11p == 12 then ph11 else ph12;
    def maxH13 = if h0p == 13 then ph0 else
                 if h1p == 13 then ph1 else
                 if h2p == 13 then ph2 else
                 if h3p == 13 then ph3 else
                 if h4p == 13 then ph4 else
                 if h5p == 13 then ph5 else
                 if h6p == 13 then ph6 else
                 if h7p == 13 then ph7 else
                 if h8p == 13 then ph8 else
                 if h9p == 13 then ph9 else
                 if h10p == 13 then ph10 else
                 if h11p == 13 then ph11 else ph12;
    def sort1 = if k >= 1 then maxH1 else 0;
    def sort2 = if k >= 2 then maxH2 else 0;
    def sort3 = if k >= 3 then maxH3 else 0;
    def sort4 = if k >= 4 then maxH4 else 0;
    def sort5 = if k >= 5 then maxH5 else 0;
    def sort6 = if k >= 6 then maxH6 else 0;
    def sort7 = if k >= 7 then maxH7 else 0;
    def sort8 = if k >= 8 then maxH8 else 0;
    def sort9 = if k >= 9 then maxH9 else 0;
    def sort10 = if k >= 10 then maxH10 else 0;
    def sort11 = if k >= 11 then maxH11 else 0;
    def sort12 = if k >= 12 then maxH12 else 0;
    def sort13 = if k >= 13 then maxH13 else 0;
    def avg = (sort1 + sort2 + sort3 + sort4 + sort5 + sort6 + sort7 + sort8 + sort9 + sort10 + sort11 + sort12 + sort13) / k;
    plot val1 = Average(avg[pivotBars], 1);
}
def ph = Pivots(high, pivotBars, rightBar, yes);
def pl = Pivots(low, pivotBars, rightBar, no);
def higherBand = Prediction(source, ph, pl, pivotBars, k, yes, DistanceCalcMethod);
def lowerBand  = Prediction(source, ph, pl, pivotBars, k, no, DistanceCalcMethod);
def hiWMA = WMA(higherBand, predictionSmoothing);
def loWMA = WMA(lowerBand, predictionSmoothing);
def midWMA = (hiWMA + loWMA) / 2;
def touchUp = if (source Crosses hiWMA within k bars) then 1 else 0;
def touchDn = if (source Crosses loWMA within k bars) then 1 else 0;
def touchMd = if (source Crosses midWMA within k bars) then 1 else 0;

plot UpBand = if !last and hiWMA then hiWMA else na;
plot LoBand = if !last and loWMA then loWMA else na;
plot midBand = if !last and midWMA then midWMA else na;
UpBand.AssignValueColor(if touchUp>0 then Color.YELLOW else GlobalColor("dup"));
LoBand.AssignValueColor(if touchDn>0 then Color.YELLOW else GlobalColor("ddn"));
midBand.AssignValueColor(if touchMd>0 then Color.WHITE else Color.DARK_GRAY);

#-- bar color
def extUp = source > UpBand and UpBand > LoBand;
def weakUp = source > UpBand;
def extDn = source < LoBand and LoBand < UpBand;
def weakDn = source < LoBand;

AssignPriceColor(if !colorBars then Color.CURRENT else
                 if extUp then GlobalColor("up") else
                 if weakUp then GlobalColor("dup") else
                 if extDn then GlobalColor("dn") else
                 if weakDn then GlobalColor("ddn") else Color.GRAY);

#-- Clouds and Label
def ohlc = ohlc4;
AddCloud(if showCloud and weakUp then ohlc else na, UpBand, GlobalColor("dup"));
AddCloud(if showCloud and weakDn then LoBand else na, ohlc, GlobalColor("ddn"));
AddCloud(if showCloud then UpBand else na, LoBand, Color.DARK_GRAY, Color.DARK_GRAY);

AddChartBubble(ShowPivotsLabel and ph, high, "HH", GlobalColor("dn"));
AddChartBubble(ShowPivotsLabel and pl, low, "LL", GlobalColor("up"), no);

#-- END of CODE
 
This is a good effort but this is not KNN. You can get the same exact results averaging the last 13 data points.

It’s not though because it just looks at the last 13 data points and if k = 13 then you are literally just taking an average of the last 13 datapoints. As you increase k in your algo it just converges to an SMA. A true knn algorithm using 13 wild rank the entire data set and get the closest 13 data points in the entire dataset. Given pivots are sparse in your algo you might not even have enough data in your window to even classify correctly.

It’s not though because it just looks at the last 13 data points and if k = 13 then you are literally just taking an average of the last 13 datapoints. As you increase k in your algo it just converges to an SMA. A true knn algorithm using 13 wild rank the entire data set and get the closest 13 data points in the entire dataset. Given pivots are sparse in your algo you might not even have enough data in your window to even classify correctly.
 
This is a good effort but this is not KNN. You can get the same exact results averaging the last 13 data points.
it is a KNN algo but ThinkScript can't handle much of data point to have better results.
I may add another dimension apart of the price and time and evaluate the results.
 
Last edited:
what label is your indicator giving a pivot? when it is red or blue?
@bigworm, The calculations can be found in the code above.
@samer800 did not create this code.
He ported it over from Tradingview. He is not the author!

If you want to have an extended discussion on why the Tradingview OP used the words "machine learning" in describing his code. You need to take that discussion over to the comment section of his code:
https://www.tradingview.com/script/3ve5wjun-Machine-Learning-Breakouts-from-Pivots/

For the record, this script is quickly becoming my go-to favorite for detecting trend.
 
mod note:
This is a MTF script so it repaints

I improved this study with some labels


Code:
# https://www.tradingview.com/v/3ve5wjun/
#// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
#// © tkarolak
#// Description //
#// "ML Pivots Breakouts" identifies multiple breakout zones through kNN ML prediction from pivot points,
#// offering essential insights for breakout and trend follower traders. It visually alerts on bullish breakouts above high lines and
#// bearish breakouts below low lines, designed for both long and short strategies, adapting to volatility and market shifts.
#indicator("Machine Learning Breakouts (from Pivots)", shorttitle="ML Pivots Breakouts", overlay=true, precision=4,
# Converted and mod by Sam4Cok@Samer800 - 02/2024, (Limited Number of Neighbors)

input colorBars = no;
input fastMode = no;
input ShowPivotsLabel = no; #,"Show/Hide Pivots"
input showCloud = yes;
input DistanceCalcMethod = {Default "Nearest Neighbors", "Lorentzian", "Euclidean", "Cosine similarity"};
input source = close;
input pivotBars = 20;      # "Pivot Bars"
input NumberOfNeighbors = 5;    # "Number of Neighbors (k)"
input predictionSmoothing = 20; # "Prediction Smoothing"

def na = Double.NaN;
def last = isNaN(close);
def rightBar = if fastMode then floor(pivotBars/2) else pivotBars;
#-- Colors
DefineGlobalColor("up", Color.white);
DefineGlobalColor("dn", CreateColor(255,82,82));
DefineGlobalColor("dup",CreateColor(255, 95, 95));
DefineGlobalColor("ddn",Color.ORANGE);

def k = Min(Max(NumberOfNeighbors, 1), 13);
script Pivots {
    input series    = close;
    input leftBars  = 10;
    input rightBars = 10;
    input isHigh = yes;
    def na = Double.NaN;
    def HH = series == Highest(series, leftBars + 1);
    def LL = series == Lowest(series, leftBars + 1);
    def pivotRange = (leftBars + rightBars + 1);
    def leftEdgeValue = if series[pivotRange] == 0 then na else series[pivotRange];
    def pvtCond = !IsNaN(series) and leftBars > 0 and rightBars > 0 and !IsNaN(leftEdgeValue);
    def barIndexH = if pvtCond then
                    fold i = 1 to rightBars + 1 with p=1 while p do
                    series > GetValue(series, - i) else na;
    def barIndexL = if pvtCond then
                    fold j = 1 to rightBars + 1 with q=1 while q do
                    series < GetValue(series, - j) else na;
    def PivotPoint;def cond;
    if isHigh {
        cond = HH and barIndexH;
        PivotPoint = if cond then series else na;
    } else {
        cond = LL and barIndexL;
        PivotPoint = if cond then series else na;
    }
    plot pvt = PivotPoint;
}
script Ranking {
    input i0 = 0;
    input i1 = 0;
    input i2 = 0;
    input i3 = 0;
    input i4 = 0;
    input i5 = 0;
    input i6 = 0;
    input i7 = 0;
    input i8 = 0;
    input i9 = 0;
    input i10 = 0;
    input i11 = 0;
    input i12 = 0;
    def v0 = if IsNaN(i0) then Double.POSITIVE_INFINITY else i0;
    def v1 = if IsNaN(i1) then Double.POSITIVE_INFINITY else i1;
    def v2 = if IsNaN(i2) then Double.POSITIVE_INFINITY else i2;
    def v3 = if IsNaN(i3) then Double.POSITIVE_INFINITY else i3;
    def v4 = if IsNaN(i4) then Double.POSITIVE_INFINITY else i4;
    def v5 = if IsNaN(i5) then Double.POSITIVE_INFINITY else i5;
    def v6 = if IsNaN(i6) then Double.POSITIVE_INFINITY else i6;
    def v7 = if IsNaN(i7) then Double.POSITIVE_INFINITY else i7;
    def v8 = if IsNaN(i8) then Double.POSITIVE_INFINITY else i8;
    def v9 = if IsNaN(i9) then Double.POSITIVE_INFINITY else i9;
    def v10 = if IsNaN(i10) then Double.POSITIVE_INFINITY else i10;
    def v11 = if IsNaN(i11) then Double.POSITIVE_INFINITY else i11;
    def v12 = if IsNaN(i12) then Double.POSITIVE_INFINITY else i12;
    def r1 = v0 < v1;
    def r2 = v0 < v2;
    def r3 = v0 < v3;
    def r4 = v0 < v4;
    def r5 = v0 < v5;
    def r6 = v0 < v6;
    def r7 = v0 < v7;
    def r8 = v0 < v8;
    def r9 = v0 < v9;
    def r10 = v0 < v10;
    def r11 = v0 < v11;
    def r12 = v0 < v12;
    plot result = r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10+ r11+ r12;
}
Script knn_distance {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def knn_distance = Sqrt(Sqr(currentPar1 - param1) + Sqr(currentPar2 - param2));
    plot out = if isNaN(knn_distance) then Double.POSITIVE_INFINITY else knn_distance;
}
Script lorentzian_distance {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def lorentzian_distance = log(1 + AbsValue(currentPar1 - param1)) + log(1 + AbsValue(currentPar2 - param2));
    plot out = if isNaN(lorentzian_distance) then Double.POSITIVE_INFINITY else lorentzian_distance;
}
Script euclidean_distance {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def euclidean_distance = Sqr(currentPar1 - param1) + Sqr(currentPar2 - param2);
    plot out = if isNaN(euclidean_distance) then Double.POSITIVE_INFINITY else euclidean_distance;
}
Script cosine_similarity {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input nzPar1 = 1;
input naPar2 = 1;
    def param1 = if !isNaN(arrayPar1) then arrayPar1 else nzPar1;
    def param2 = if !isNaN(arrayPar2) then arrayPar2 else naPar2;
    def dotProduct = (currentPar1 * param1) + (currentPar2 * param2);
    def magnitudeSeries = (Sqr(currentPar1) + Sqr(currentPar2));
    def magnitudeArray = (Sqr(param1) + Sqr(param2));
    def cosine_similarity = dotProduct / (magnitudeSeries * magnitudeArray);
    plot out = if isNaN(cosine_similarity) then Double.POSITIVE_INFINITY else cosine_similarity;
}
Script DistanceCalculation {
input currentPar1 = 1;
input arrayPar1 = 1;
input currentPar2 = 1;
input arrayPar2 = 1;
input type = "Nearest Neighbors";
input nzPar1 = 1;
input naPar2 = 1;
    def knn        = knn_distance(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def Lorentzian = lorentzian_distance(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def Euclidean  = euclidean_distance(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def Cosine     = cosine_similarity(currentPar1, arrayPar1, currentPar2, arrayPar2, nzPar1, naPar2);
    def calc = if type == "Nearest Neighbors" then knn else
               if type == "Lorentzian" then Lorentzian else
               if type == "Euclidean" then Euclidean else
               if type == "Cosine similarity" then Cosine else knn;
    plot out = if isNaN(calc) then Double.POSITIVE_INFINITY else calc;
}
#/ @return float: Predicted pivot price based on nearest neighbors.
Script Prediction {
input currentPrice = close;
input ph = high;
input pl = low;
input pivotBars = 20;
input k = 10;
input isHigh = yes;
input type = yes;
    def time = GetTime();
    def preBar = time - ((time - time[1]) * pivotBars);
    def src; def preSrc; def pvtDetected;
    if isHigh {
        pvtDetected = !isNaN(ph);
        src = high;
        preSrc = highest(src, pivotBars);
    } else {
        pvtDetected = !isNaN(pl);
        src = low;
        preSrc = lowest(src, pivotBars);
    }
    def ph0; def ph1; def ph2; def ph3; def ph4; def ph5; def ph6; def ph7; def ph8; def ph9; def ph10;
    def ph11; def ph12;
    def xh0; def xh1; def xh2; def xh3; def xh4; def xh5; def xh6; def xh7; def xh8; def xh9;def xh10;
    def xh11;def xh12;
    if pvtDetected {
    ph12 = ph11[1];
    ph11 = ph10[1];
    ph10 = ph9[1];
    ph9 = ph8[1];
    ph8 = ph7[1];
    ph7 = ph6[1];
    ph6 = ph5[1];
    ph5 = ph4[1];
    ph4 = ph3[1];
    ph3 = ph2[1];
    ph2 = ph1[1];
    ph1 = ph0[1];
    ph0 = src;
    xh12 = xh11[1];
    xh11 = xh10[1];
    xh10 = xh9[1];
    xh9 = xh8[1];
    xh8 = xh7[1];
    xh7 = xh6[1];
    xh6 = xh5[1];
    xh5 = xh4[1];
    xh4 = xh3[1];
    xh3 = xh2[1];
    xh2 = xh1[1];
    xh1 = xh0[1];
    xh0 = time;
    } else {
    ph12 = if ph12[1]==0 then preSrc[12] else ph12[1];
    ph11 = if ph11[1]==0 then preSrc[11] else ph11[1];
    ph10 = if ph10[1]==0 then preSrc[10] else ph10[1];
    ph9 = if ph9[1]==0 then preSrc[9] else ph9[1];
    ph8 = if ph8[1]==0 then preSrc[8] else ph8[1];
    ph7 = if ph7[1]==0 then preSrc[7] else ph7[1];
    ph6 = if ph6[1]==0 then preSrc[6] else ph6[1];
    ph5 = if ph5[1]==0 then preSrc[5] else ph5[1];
    ph4 = if ph4[1]==0 then preSrc[4] else ph4[1];
    ph3 = if ph3[1]==0 then preSrc[3] else ph3[1];
    ph2 = if ph2[1]==0 then preSrc[2] else ph2[1];
    ph1 = if ph1[1]==0 then preSrc[1] else ph1[1];
    ph0 = if ph0[1]==0 then preSrc[0] else ph0[1];
    xh12 = if xh12[1]==0 then preBar[12] else xh12[1];
    xh11 = if xh11[1]==0 then preBar[11] else xh11[1];
    xh10 = if xh10[1]==0 then preBar[10] else xh10[1];
    xh9 = if xh9[1]==0 then preBar[9] else xh9[1];
    xh8 = if xh8[1]==0 then preBar[8] else xh8[1];
    xh7 = if xh7[1]==0 then preBar[7] else xh7[1];
    xh6 = if xh6[1]==0 then preBar[6] else xh6[1];
    xh5 = if xh5[1]==0 then preBar[5] else xh5[1];
    xh4 = if xh4[1]==0 then preBar[4] else xh4[1];
    xh3 = if xh3[1]==0 then preBar[3] else xh3[1];
    xh2 = if xh2[1]==0 then preBar[2] else xh2[1];
    xh1 = if xh1[1]==0 then preBar[1] else xh1[1];
    xh0 = if xh0[1]==0 then preBar[0] else xh0[1];
}
    def dist0 = DistanceCalculation(currentPrice, ph0, time, xh0, type, preSrc[0], preBar[0]);
    def dist1 = DistanceCalculation(currentPrice, ph1, time, xh1, type, preSrc[1], preBar[1]);
    def dist2 = DistanceCalculation(currentPrice, ph2, time, xh2, type, preSrc[2], preBar[2]);
    def dist3 = DistanceCalculation(currentPrice, ph3, time, xh3, type, preSrc[3], preBar[3]);
    def dist4 = DistanceCalculation(currentPrice, ph4, time, xh4, type, preSrc[4], preBar[4]);
    def dist5 = DistanceCalculation(currentPrice, ph5, time, xh5, type, preSrc[5], preBar[5]);
    def dist6 = DistanceCalculation(currentPrice, ph6, time, xh6, type, preSrc[6], preBar[6]);
    def dist7 = DistanceCalculation(currentPrice, ph7, time, xh7, type, preSrc[7], preBar[7]);
    def dist8 = DistanceCalculation(currentPrice, ph8, time, xh8, type, preSrc[8], preBar[8]);
    def dist9 = DistanceCalculation(currentPrice, ph9, time, xh9, type, preSrc[9], preBar[9]);
    def dist10 = DistanceCalculation(currentPrice, ph10, time, xh10, type, preSrc[10], preBar[10]);
    def dist11 = DistanceCalculation(currentPrice, ph11, time, xh11, type, preSrc[11], preBar[11]);
    def dist12 = DistanceCalculation(currentPrice, ph12, time, xh12, type, preSrc[12], preBar[12]);

    def h0p = 13 - Ranking(dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist10, dist11, dist12);
    def h1p = 13 - Ranking(dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist10, dist11, dist12);
    def h2p = 13 - Ranking(dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist10, dist11, dist12);
    def h3p = 13 - Ranking(dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist10, dist11, dist12);
    def h4p = 13 - Ranking(dist4, dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist10, dist11, dist12);
    def h5p = 13 - Ranking(dist5, dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist10, dist11, dist12);
    def h6p = 13 - Ranking(dist6, dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist10, dist11, dist12);
    def h7p = 13 - Ranking(dist7, dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist10, dist11, dist12);
    def h8p = 13 - Ranking(dist8, dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist10, dist11, dist12);
    def h9p = 13 - Ranking(dist9, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist10, dist11, dist12);
    def h10p = 13 - Ranking(dist10, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist11, dist12);
    def h11p = 13 - Ranking(dist11, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist10, dist12);
    def h12p = 13 - Ranking(dist12, dist0, dist1, dist2, dist3, dist4, dist5, dist6, dist7, dist8, dist9, dist10, dist11);
    def maxH1 = if h0p == 1 then ph0 else
                if h1p == 1 then ph1 else
                if h2p == 1 then ph2 else
                if h3p == 1 then ph3 else
                if h4p == 1 then ph4 else
                if h5p == 1 then ph5 else
                if h6p == 1 then ph6 else
                if h7p == 1 then ph7 else
                if h8p == 1 then ph8 else
                if h9p == 1 then ph9 else
                if h10p == 1 then ph10 else
                if h11p == 1 then ph11 else ph12;
    def maxH2 = if h0p == 2 then ph0 else
                if h1p == 2 then ph1 else
                if h2p == 2 then ph2 else
                if h3p == 2 then ph3 else
                if h4p == 2 then ph4 else
                if h5p == 2 then ph5 else
                if h6p == 2 then ph6 else
                if h7p == 2 then ph7 else
                if h8p == 2 then ph8 else
                if h9p == 2 then ph9 else
                if h10p == 2 then ph10 else
                if h11p == 2 then ph11 else ph12;
    def maxH3 = if h0p == 3 then ph0 else
                if h1p == 3 then ph1 else
                if h2p == 3 then ph2 else
                if h3p == 3 then ph3 else
                if h4p == 3 then ph4 else
                if h5p == 3 then ph5 else
                if h6p == 3 then ph6 else
                if h7p == 3 then ph7 else
                if h8p == 3 then ph8 else
                if h9p == 3 then ph9 else
                if h10p == 3 then ph10 else
                if h11p == 3 then ph11 else ph12;
    def maxH4 = if h0p == 4 then ph0 else
                if h1p == 4 then ph1 else
                if h2p == 4 then ph2 else
                if h3p == 4 then ph3 else
                if h4p == 4 then ph4 else
                if h5p == 4 then ph5 else
                if h6p == 4 then ph6 else
                if h7p == 4 then ph7 else
                if h8p == 4 then ph8 else
                if h9p == 4 then ph9 else
                if h10p == 4 then ph10 else
                if h11p == 4 then ph11 else ph12;
    def maxH5 = if h0p == 5 then ph0 else
                if h1p == 5 then ph1 else
                if h2p == 5 then ph2 else
                if h3p == 5 then ph3 else
                if h4p == 5 then ph4 else
                if h5p == 5 then ph5 else
                if h6p == 5 then ph6 else
                if h7p == 5 then ph7 else
                if h8p == 5 then ph8 else
                if h9p == 5 then ph9 else
                if h10p == 5 then ph10 else
                if h11p == 5 then ph11 else ph12;
    def maxH6 = if h0p == 6 then ph0 else
                if h1p == 6 then ph1 else
                if h2p == 6 then ph2 else
                if h3p == 6 then ph3 else
                if h4p == 6 then ph4 else
                if h5p == 6 then ph5 else
                if h6p == 6 then ph6 else
                if h7p == 6 then ph7 else
                if h8p == 6 then ph8 else
                if h9p == 6 then ph9 else
                if h10p == 6 then ph10 else
                if h11p == 6 then ph11 else ph12;
    def maxH7 = if h0p == 7 then ph0 else
                if h1p == 7 then ph1 else
                if h2p == 7 then ph2 else
                if h3p == 7 then ph3 else
                if h4p == 7 then ph4 else
                if h5p == 7 then ph5 else
                if h6p == 7 then ph6 else
                if h7p == 7 then ph7 else
                if h8p == 7 then ph8 else
                if h9p == 7 then ph9 else
                if h10p == 7 then ph10 else
                if h11p == 7 then ph11 else ph12;
    def maxH8 = if h0p == 8 then ph0 else
                if h1p == 8 then ph1 else
                if h2p == 8 then ph2 else
                if h3p == 8 then ph3 else
                if h4p == 8 then ph4 else
                if h5p == 8 then ph5 else
                if h6p == 8 then ph6 else
                if h7p == 8 then ph7 else
                if h8p == 8 then ph8 else
                if h9p == 8 then ph9 else
                if h10p == 8 then ph10 else
                if h11p == 8 then ph11 else ph12;
    def maxH9 = if h0p == 9 then ph0 else
                if h1p == 9 then ph1 else
                if h2p == 9 then ph2 else
                if h3p == 9 then ph3 else
                if h4p == 9 then ph4 else
                if h5p == 9 then ph5 else
                if h6p == 9 then ph6 else
                if h7p == 9 then ph7 else
                if h8p == 9 then ph8 else
                if h9p == 9 then ph9 else
                if h10p == 9 then ph10 else
                if h11p == 9 then ph11 else ph12;
    def maxH10 = if h0p == 10 then ph0 else
                 if h1p == 10 then ph1 else
                 if h2p == 10 then ph2 else
                 if h3p == 10 then ph3 else
                 if h4p == 10 then ph4 else
                 if h5p == 10 then ph5 else
                 if h6p == 10 then ph6 else
                 if h7p == 10 then ph7 else
                 if h8p == 10 then ph8 else
                 if h9p == 10 then ph9 else
                 if h10p == 10 then ph10 else
                 if h11p == 10 then ph11 else ph12;
    def maxH11 = if h0p == 11 then ph0 else
                 if h1p == 11 then ph1 else
                 if h2p == 11 then ph2 else
                 if h3p == 11 then ph3 else
                 if h4p == 11 then ph4 else
                 if h5p == 11 then ph5 else
                 if h6p == 11 then ph6 else
                 if h7p == 11 then ph7 else
                 if h8p == 11 then ph8 else
                 if h9p == 11 then ph9 else
                 if h10p == 11 then ph10 else
                 if h11p == 11 then ph11 else ph12;
    def maxH12 = if h0p == 12 then ph0 else
                 if h1p == 12 then ph1 else
                 if h2p == 12 then ph2 else
                 if h3p == 12 then ph3 else
                 if h4p == 12 then ph4 else
                 if h5p == 12 then ph5 else
                 if h6p == 12 then ph6 else
                 if h7p == 12 then ph7 else
                 if h8p == 12 then ph8 else
                 if h9p == 12 then ph9 else
                 if h10p == 12 then ph10 else
                 if h11p == 12 then ph11 else ph12;
    def maxH13 = if h0p == 13 then ph0 else
                 if h1p == 13 then ph1 else
                 if h2p == 13 then ph2 else
                 if h3p == 13 then ph3 else
                 if h4p == 13 then ph4 else
                 if h5p == 13 then ph5 else
                 if h6p == 13 then ph6 else
                 if h7p == 13 then ph7 else
                 if h8p == 13 then ph8 else
                 if h9p == 13 then ph9 else
                 if h10p == 13 then ph10 else
                 if h11p == 13 then ph11 else ph12;
    def sort1 = if k >= 1 then maxH1 else 0;
    def sort2 = if k >= 2 then maxH2 else 0;
    def sort3 = if k >= 3 then maxH3 else 0;
    def sort4 = if k >= 4 then maxH4 else 0;
    def sort5 = if k >= 5 then maxH5 else 0;
    def sort6 = if k >= 6 then maxH6 else 0;
    def sort7 = if k >= 7 then maxH7 else 0;
    def sort8 = if k >= 8 then maxH8 else 0;
    def sort9 = if k >= 9 then maxH9 else 0;
    def sort10 = if k >= 10 then maxH10 else 0;
    def sort11 = if k >= 11 then maxH11 else 0;
    def sort12 = if k >= 12 then maxH12 else 0;
    def sort13 = if k >= 13 then maxH13 else 0;
    def avg = (sort1 + sort2 + sort3 + sort4 + sort5 + sort6 + sort7 + sort8 + sort9 + sort10 + sort11 + sort12 + sort13) / k;
    plot val1 = Average(avg[pivotBars], 1);
}
def ph = Pivots(high, pivotBars, rightBar, yes);
def pl = Pivots(low, pivotBars, rightBar, no);
def higherBand = Prediction(source, ph, pl, pivotBars, k, yes, DistanceCalcMethod);
def lowerBand  = Prediction(source, ph, pl, pivotBars, k, no, DistanceCalcMethod);
def hiWMA = WMA(higherBand, predictionSmoothing);
def loWMA = WMA(lowerBand, predictionSmoothing);
def midWMA = (hiWMA + loWMA) / 2;
def touchUp = if (source Crosses hiWMA within k bars) then 1 else 0;
def touchDn = if (source Crosses loWMA within k bars) then 1 else 0;
def touchMd = if (source Crosses midWMA within k bars) then 1 else 0;

plot UpBand = if !last and hiWMA then hiWMA else na;
plot LoBand = if !last and loWMA then loWMA else na;
plot midBand = if !last and midWMA then midWMA else na;


UpBand.AssignValueColor(if touchUp>0 then Color.cyan else GlobalColor("dup"));
LoBand.AssignValueColor(if touchDn>0 then Color.cyan else GlobalColor("ddn"));
midBand.AssignValueColor(if touchMd>0 then Color.cyan else Color.white);

#-- bar color
def extUp = source > UpBand and UpBand > LoBand;
def weakUp = source > UpBand;
def extDn = source < LoBand and LoBand < UpBand;
def weakDn = source < LoBand;

AssignPriceColor(if !colorBars then Color.CURRENT else
                 if extUp then GlobalColor("up") else
                 if weakUp then GlobalColor("dup") else
                 if extDn then GlobalColor("dn") else
                 if weakDn then GlobalColor("ddn") else Color.GRAY);

#-- Clouds and Label
def ohlc = ohlc4;
AddCloud(if showCloud and weakUp then ohlc else na, UpBand, GlobalColor("dup"));
AddCloud(if showCloud and weakDn then LoBand else na, ohlc, GlobalColor("ddn"));
AddCloud(if showCloud then UpBand else na, LoBand, Color.white, Color.white);

AddChartBubble(ShowPivotsLabel and ph, high, "HH", GlobalColor("dn"));
AddChartBubble(ShowPivotsLabel and pl, low, "LL", GlobalColor("up"), no);

#-- END of CODE




#            ______________________
#           /\  __________________ \
#          /xx\ \________________/\ \
#         /x/\x\ \            /x/\x\ \
#        /x/ /\x\ \          /x/ /\x\ \
#       /x/ /  \x\ \________/x/ /__\_\ \____________________
#      /x/ /    \x\________/x/ /_______  __________________ \
#     /x/ /     /x/ ______/x/ /_______/\ \________________/\ \
#    /x/ /_____/_/_/_____/x/ /_____/_/\_\_\____        /x/\x\ \
#   /x/_/________________\/_/_________________ \      /x/ /\x\ \
#   \x\ \________________/\ \________________/\ \____/x/ /__\_\ \
#    \x\ \  /x/ /     /x/\x\ \  /x/ /    \/x/\x\ \__/x/ /________\
#     \x\ \/x/ /     /x/ /\x\_\/x/ /    _/x/ /\x\ \/x/ /_______  /
#      \x\/x/ /_____/x/ /__\_\/x/_/_____/x/ /__\_\_\/ /     /x/ /
#       \xx/_/_____/x/ /______\/_/_____/x/ /______\/_/     /x/ /
#       /xx\ \____/x/ /_______/\ \____/x/ /______ /\ \    /x/ /
#      /x/\x\ \  /x/ /_____/_/\_\_\__/x/ /     /x/\x\ \  /x/ /
#     /x/ /\x\ \/x/_/________________\/_/     /x/ /\x\ \/x/ /
#    /x/ /  \x\ \x\_\________________/\ \____/x/_/__\_\/x/ /
#   /x/ /    \x\_\x\_\__/x/_/______\/\x\_\__/x/ /______\/ /
#  /x/ /     /x/ _\x\_\/x/_/_______  _\x\_\/x/ /_________/
# /x/ /_____/_/_/__\_\/x/ /_____/_/_/__\_\/x/ /
#/x/_/________________\/_/________________\/ /
#\x\ \________________/\ \__________________/
# \x\ \  /x/ /        \x\ \  /x/ /
#  \x\ \/x/ /          \x\ \/x/ /
#   \x\/x/ /____________\_\/x/ /
#    \xx/ /________________\/ /
#     \/_____________________/



########################################################### Formula for mode of indicator ############################################################################
########################################################### Formula for mode of indicator ############################################################################
########################################################### Formula for mode of indicator ############################################################################
########################################################### Formula for mode of indicator ############################################################################
########################################################### Formula for mode of indicator ############################################################################


# Custom study mode menu
Input strategy_mode = { default "Labels","plot_lines","Labels_and_plot_lines"};

input Set_the_width_of_VWAP_bands_to_standard_width = yes;


########################################################### Standard Config ##########################################################################################
########################################################### Standard Config ##########################################################################################
########################################################### Standard Config ##########################################################################################
########################################################### Standard Config ##########################################################################################
########################################################### Standard Config ###########################################################################################


#input timeFrame = {default year,month,Week,day};
input Budget = 5000;
input basic_budget_labels = yes;
input Standard_VWAP_and_the_Deviation_Band_functionality = yes; # Vwap + quad band and their assoicated labels.
input Label_dividers = no;


########################################################### Formula for Labels that count the of candles ###################################################################
########################################################### Formula for Labels that count the of candles ###################################################################
########################################################### Formula for Labels that count the of candles ###################################################################
########################################################### Formula for Labels that count the of candles ###################################################################
########################################################### Formula for Labels that count the of candles ###################################################################


def bn = BarNumber();
script Candles_since {
    input Condition = 0;
    def Candles_since = if Condition then 1 else Candles_since[1] + 1;
    plot return = Candles_since;}


########################################################### Forumula to Calculate current_price and Share_Quantity_purchase_limit ##################################
########################################################### Forumula to Calculate current_price and Share_Quantity_purchase_limit ##################################
########################################################### Forumula to Calculate current_price and Share_Quantity_purchase_limit ##################################
########################################################### Forumula to Calculate current_price and Share_Quantity_purchase_limit ##################################
########################################################### Forumula to Calculate current_price and Share_Quantity_purchase_limit ##################################


def current_price = close;
def Share_Quantity_purchase_limit = Budget / current_price;


########################################################### Share purchase budget label #########################################################
########################################################### Share purchase budget label #########################################################
########################################################### Share purchase budget label ########################################################
########################################################### Share purchase budget label #########################################################
########################################################### Share purchase budget label #########################################################


# Custom study that displays a label when two inputs are toggled "on."
def basic_budget_labels_Show_and_hide_Condition = strategy_mode == strategy_mode."Labels";# or strategy_mode == strategy_mode."plots"
def show_the_basic_budget_label = basic_budget_labels_Show_and_hide_Condition and basic_budget_labels;

# Add the label only once
AddLabel(show_the_basic_budget_label, Concat("current price shares = ", Round(Share_Quantity_purchase_limit)), Color.ORANGE);


########################################################### Calculate VWAP Bands ###########################################################
########################################################### Calculate VWAP Bands ###########################################################
########################################################### Calculate VWAP Bands ###########################################################
########################################################### Calculate VWAP Bands ###########################################################
########################################################### Calculate VWAP Bands ###########################################################


def Standard_VWAP_and_the_Deviation_Band_functionality_show_and_hide_condition = strategy_mode == strategy_mode."Labels";#or strategy_mode."Label_and_plot_line";
def show_the_Standard_VWAP_and_the_Deviation_Band_functionality =  Standard_VWAP_and_the_Deviation_Band_functionality_show_and_hide_condition and Standard_VWAP_and_the_Deviation_Band_functionality;


def Share_Quantity_purchase_limit_at_the_Current_Upper_band_price =  Budget / UpBand;
def Share_Quantity_purchase_limit_at_the_Current_Mid_band_price =  Budget /midBand;
def Share_Quantity_purchase_limit_at_the_Current_lower_band_price =  Budget / LoBand;


### ### ### upper band  ### ### ###
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat(" Upper Band price = ",  Round (UpBand)), (CreateColor(255, 95, 95)));
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat(" Quanity of shares you can purchase at the Upper Band price = ",  Round (Share_Quantity_purchase_limit_at_the_Current_Upper_band_price)), (CreateColor(255, 95, 95)));
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat("Current price shares profit @ Upper Band = ", Round( Share_Quantity_purchase_limit  * UpBand - Budget )), (CreateColor(255, 95, 95)));
### ### ### upper band  ### ### ###

### ### ### Mid band ### ### ###
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat(" Mid Upper Band price = ",  Round (midBand)), (CreateColor(255, 255, 255)));
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat(" Quanity of shares you can purchase at the mid Band price = ",  Round (Share_Quantity_purchase_limit_at_the_Current_Mid_band_price)), (CreateColor(255, 255, 255)));
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat("Current price shares profit @ mid Band = ", Round( Share_Quantity_purchase_limit  *  midBand - Budget )), (CreateColor(255, 255, 255)));
### ### ### Mid band ### ### ###

### ### ###  Lower Band ### ### ###
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat(" Lower band price = ",  Round (LoBand)), Color.ORANGE);
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat(" Quanity of shares you can purchase at the  lower Band price = ",  Round (Share_Quantity_purchase_limit_at_the_Current_lower_band_price)), Color.ORANGE);
AddLabel(show_the_Standard_VWAP_and_the_Deviation_Band_functionality, Concat("Current price shares profit @ lower Band = ", Round( Share_Quantity_purchase_limit  * LoBand - Budget )), Color.ORANGE);
### ### ###  Lower Band ### ### ###



#            ______________________
#           /\  __________________ \
#          /xx\ \________________/\ \
#         /x/\x\ \            /x/\x\ \
#        /x/ /\x\ \          /x/ /\x\ \
#       /x/ /  \x\ \________/x/ /__\_\ \____________________
#      /x/ /    \x\________/x/ /_______  __________________ \
#     /x/ /     /x/ ______/x/ /_______/\ \________________/\ \
#    /x/ /_____/_/_/_____/x/ /_____/_/\_\_\____        /x/\x\ \
#   /x/_/________________\/_/_________________ \      /x/ /\x\ \
#   \x\ \________________/\ \________________/\ \____/x/ /__\_\ \
#    \x\ \  /x/ /     /x/\x\ \  /x/ /    \/x/\x\ \__/x/ /________\
#     \x\ \/x/ /     /x/ /\x\_\/x/ /    _/x/ /\x\ \/x/ /_______  /
#      \x\/x/ /_____/x/ /__\_\/x/_/_____/x/ /__\_\_\/ /     /x/ /
#       \xx/_/_____/x/ /______\/_/_____/x/ /______\/_/     /x/ /
#       /xx\ \____/x/ /_______/\ \____/x/ /______ /\ \    /x/ /
#      /x/\x\ \  /x/ /_____/_/\_\_\__/x/ /     /x/\x\ \  /x/ /
#     /x/ /\x\ \/x/_/________________\/_/     /x/ /\x\ \/x/ /
#    /x/ /  \x\ \x\_\________________/\ \____/x/_/__\_\/x/ /
#   /x/ /    \x\_\x\_\__/x/_/______\/\x\_\__/x/ /______\/ /
#  /x/ /     /x/ _\x\_\/x/_/_______  _\x\_\/x/ /_________/
# /x/ /_____/_/_/__\_\/x/ /_____/_/_/__\_\/x/ /
#/x/_/________________\/_/________________\/ /
#\x\ \________________/\ \__________________/
# \x\ \  /x/ /        \x\ \  /x/ /
#  \x\ \/x/ /          \x\ \/x/ /
#   \x\/x/ /____________\_\/x/ /
#    \xx/ /________________\/ /
#     \/_____________________/
 

Attachments

  • grfwsnkmlsfolp;msedfl;kmcds.png
    grfwsnkmlsfolp;msedfl;kmcds.png
    261.6 KB · Views: 57
Last edited by a moderator:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
409 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top