Mehdi 
2024-12-28
Category: None

//@version=5

//github & X :@aigptcode

indicator('AI GPT KNN Ultimate all in one Strategy @aigptcode' ,overlay=true, max_labels_count=300, format=format.price, precision=2, max_boxes_count=6)



//-- EMA Input Parameters

ema_short = input.int(51, title="Short EMA")

ema_mid1 = input.int(99, title="EMA")

ema_mid2 = input.int(200, title="EMA")

ema_long1 = input.int(396, title="EMA")

ema_long2 = input.int(796, title="EMA")



// MA Input Parameters

ma1 = input.int(100, title="MA")

ma2 = input.int(200, title="MA")

ma3 = input.int(400, title="MA")



// Plotting EMAs

plot(ta.ema(close, ema_short), color=#f1f17d, linewidth=1, title="EMA Short")

plot(ta.ema(close, ema_mid1), color=#dbcf1fa3, linewidth=2, title="EMA Mid 1")

plot(ta.ema(close, ema_mid2), color=color.rgb(252, 197, 48), linewidth=1, title="EMA Mid 2") 

plot(ta.ema(close, ema_long1), color=color.rgb(211, 106, 32), linewidth=1, title="EMA Long 1")

plot(ta.ema(close, ema_long2), color=#c54444, linewidth=1, title="EMA Long 2")



// Plotting MAs

plot(ta.sma(close, ma1), color=color.rgb(211, 15, 80), linewidth=1, title="MA 1", display = display.none)

plot(ta.sma(close, ma2), color=#d41b52, linewidth=1, title="MA 2", display = display.none)

plot(ta.sma(close, ma3), color=#b92456, linewidth=1, title="MA 3", display = display.none)



//-- Machine Learning Input Parameters

startDate = input.time(timestamp('01 Jan 2000 00:00:00 GMT+00'), 'Start Date')

stopDate = input.time(timestamp('31 Dec 2025 23:45:00 GMT+00'), 'Stop Date')

indicatorType = input.string('All', 'Indicator',  )

shortWindow = input.int(14, 'Short Period  ', 7)

longWindow = input.int(28, 'Long Period  ', 14)

baseK = input.int(20, 'Base No. of Neighbours (K)  ', 10)

filterEnabled = input.bool(true, 'Volatility Filter')

barsThreshold = input.int(300, 'Bar Threshold  ', 100)

atrPeriod = input.int(12, "ATR Length", minval=1, group="Supertrend", tooltip="ATR Length used to create the Supertrend.")

factor = input.float(2.61, "Factor", minval=0.01, step=0.01, group="Supertrend", tooltip="Multiplier used to create the Supertrend.")





//-- Constants

var int BUY = 1

var int SELL = -1

var int CLEAR = 0

var int k = math.floor(math.sqrt(baseK)) // k Value for kNN algo



//-- Variables

var array feature1 = array.new_float(0)

var array feature2 = array.new_float(0)

var array directions = array.new_int(0)

var array predictions = array.new_int(0)

var float prediction = 0.0

var array bars = array.new(1, 0)

var int signal = CLEAR



//-- Functions

minimax(float x, int p, float min, float max) =>

    float hi = ta.highest(x, p), float lo = ta.lowest(x, p)

    (max - min) * (x - lo) / (hi - lo) + min



cAqua(int g) => g > 9 ? #3cff00 : g > 8 ? color.rgb(150, 248, 155, 10) : g > 7 ? #0080FFcc : g > 6 ? #0080FFb2 : g > 5 ? #0080FF99 : g > 4 ? #0080FF7f : g > 3 ? #0080FF66 : g > 2 ? #0080FF4c : g > 1 ? #0080FF33 : #00C0FF19

cPink(int g) => g > 9 ? #ff0000 : g > 8 ? color.rgb(236, 110, 110, 10) : g > 7 ? #FF0080cc : g > 6 ? #FF0080b2 : g > 5 ? #FF008099 : g > 4 ? #FF00807f : g > 3 ? #FF008066 : g > 2 ? #FF00804c : g > 1 ? #FF008033 : #FF008019



inside_window(float start, float stop) =>

    time >= start and time <= stop ? true : false



bool window = inside_window(startDate, stopDate)



float rs = ta.rsi(close, longWindow), rf = ta.rsi(close, shortWindow)

float cs = ta.cci(close, longWindow), cf = ta.cci(close, shortWindow)

float os = ta.roc(close, longWindow), of = ta.roc(close, shortWindow)

float vs = minimax(volume, longWindow, 0, 99), vf = minimax(volume, shortWindow, 0, 99)



float f1 = switch indicatorType

    'RSI' => rs

    'CCI' => cs

    'ROC' => os

    'Volume' => vs

    => math.avg(rs, cs, os, vs)



float f2 = switch indicatorType

    'RSI' => rf

    'CCI' => cf

    'ROC' => of

    'Volume' => vf

    => math.avg(rf, cf, of, vf)



int class_label = int(math.sign(close  - close ))



if window

    array.push(feature1, f1)

    array.push(feature2, f2)

    array.push(directions, class_label)



int size = array.size(directions)

float maxdist = -999.0



for i = 0 to size - 1

    float d = math.sqrt(math.pow(f1 - array.get(feature1, i), 2) + math.pow(f2 - array.get(feature2, i), 2))

    if d > maxdist

        maxdist := d

        if array.size(predictions) >= k

            array.shift(predictions)

        array.push(predictions, array.get(directions, i))



prediction := array.sum(predictions)



bool filter = filterEnabled ? ta.atr(10) > ta.atr(40) : true



bool long = (prediction > 0) and filter

bool short = (prediction < 0) and filter

bool clear = not(long or short)



if array.get(bars, 0) == barsThreshold

    signal := CLEAR

    array.set(bars, 0, 0)

else

    array.set(bars, 0, array.get(bars, 0) + 1)



signal := long ? BUY : short ? SELL : clear ? CLEAR : nz(signal )



int changed = ta.change(signal)

bool startLongTrade = changed and (signal == BUY)

bool startShortTrade = changed and (signal == SELL)

bool clear_condition = changed and (signal == CLEAR)



// Plot buy/sell signals

plotshape(startLongTrade ? ta.lowest(low, 10) : na, 'Buy', shape.labelup, location.belowbar, color=cAqua(int(prediction * 5)), size=size.small)

plotshape(startShortTrade ? ta.highest(high, 10) : na, 'Sell', shape.labeldown, location.abovebar, color=cPink(int(-prediction * 5)), size=size.small)

plotshape(clear_condition ? close : na, 'ClearPos', color=color.yellow, size=size.small, style=shape.cross)





// First Approach (Array-Based)

var float  supertrend = array.new_float(1)

var float  direction = array.new_float(1)

var float  stoploss = array.new_float(1)



getSupertrend(factor, atrPeriod) =>

    float atr = ta.atr(atrPeriod)

    float up = hl2 - (factor * atr)

    float dn = hl2 + (factor * atr)

    if (close > array.get(supertrend, 0))

        array.set(direction, 0, 1)

        array.set(supertrend, 0, up)

    else

        array.set(direction, 0, -1)

        array.set(supertrend, 0, dn)

     



  = getSupertrend(factor, atrPeriod)



plot(supertrendValue1, title="Supertrend (Array-Based)", color=color.rgb(168, 166, 166, 36), linewidth=1)



// Second Approach (Direct Calculation)

float atrST = ta.atr(atrPeriod)

float upperBandST = ta.ema(close, atrPeriod) + factor * atrST

float lowerBandST = ta.ema(close, atrPeriod) - factor * atrST



bool isUpTrend = na

float supertrendValue2 = na



if close > upperBandST 

    supertrendValue2 := lowerBandST

    isUpTrend := true

else if close < lowerBandST 

    supertrendValue2 := upperBandST

    isUpTrend := false



plot(supertrendValue2, title="Supertrend (Direct Calculation)", color=isUpTrend ? color.rgb(79, 248, 0, 31) : color.rgb(255, 0, 0, 15), linewidth=2)



//ichimoku

conversionPeriods = input.int(9, minval=1, title="Conversion Line Length")

basePeriods = input.int(26, minval=1, title="Base Line Length")

laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length")

displacement = input.int(26, minval=1, title="Lagging Span")

donchian(len) => math.avg(ta.lowest(len), ta.highest(len))

conversionLine = donchian(conversionPeriods)

baseLine = donchian(basePeriods)

leadLine1 = math.avg(conversionLine, baseLine)

leadLine2 = donchian(laggingSpan2Periods) 

p1 = plot(leadLine1, offset = displacement - 1, display = display.none)

p2 = plot(leadLine2, offset = displacement - 1, display = display.none)

fill(p1, p2, color = leadLine1 > leadLine2 ? color.new(color.green, 90) : color.new(color.red, 90), title = "Kumo Cloud")





// The Real Shark 32 Pattern

command1 = low  < low  and low  < low and high  > high  and high  > high

plotshape(command1, title="Shark-32 Pattern Top", color=color.rgb(254, 255, 254), style=shape.cross,size = size.tiny, location=location.belowbar)





//next

zigzagBool = input.bool(false, "Show Market Structure",group = "Price Action Toolkit Settings")

zigzagLen = input.int(9, "ZigZag Length",group = "Price Action Toolkit Settings")

liquidityBool = input.bool(false, "Show Liquidity Sweeps",group = "Liquidity Settings")

liquidity_len = input.int(30, "Liquidity Length",minval = 5,group = "Liquidity Settings")

orderblockBool = input.bool(true, "Show Order Blocks",group = "Order Block Settings")

numberObShow = input.int(2,"Number of Order Blocks to Show",group = "Order Block Settings",minval = 1,maxval = 10)

upColor = input.color(color.new(color.teal,15),title = "Market/Liquidity Colors" ,group = "Visual Settings",inline = "1")

downColor = input.color(color.new(color.red,15),title = " ",group = "Visual Settings",inline = "1")

bearishOrderblockColor = input.color(color.new(color.red,80),title = "Order Block Colors ",group = "Visual Settings",inline = "2")

bullishOrderblockColor = input.color(color.new(color.teal,80),title = " ",group = "Visual Settings",inline = "2")





type orderblock

    float value

    int barStart

    int barEnd

    box block

    bool broken



type liquidity

    float value

    int barStart

    int barEnd

    line liquidityLine

    bool broken

    label sweep



type zone

    float value

    int barStart

    int barEnd

    box block

    string zoneType







var array bullishOrderblock = array.new()

var array bearishOrderblock = array.new()

var array bullishLiquidity = array.new()

var array bearishLiquidity = array.new()

var array highValIndex = array.new()

var array lowValIndex = array.new()

var array highVal = array.new_float()

var array lowVal = array.new_float()



var bool drawUp = na

var bool drawDown = na

var string lastState = na

var bool to_up = na

var bool to_down = na

var int trend = 1

var float fibTopVal = na

var int fibTopIndex = na

var float fibBotVal = na

var int fibBotIndex = na

var float premiumVal = na

var float discountVal = na

var int premiumValIndex = na

var int discountValIndex = na

var box premiumBox = na

var box discountBox = na

var label premiumLabel = na

var label discountLabel = na

var string textOfPremium = na

var string textOfDiscount = na

var line newBearishTrendline = na

var line newBullishTrendline = na



atr = ta.atr(14)



to_up := high  >= ta.highest(high,zigzagLen)

to_down := low  <= ta.lowest(low,zigzagLen)



trend := trend == 1 and to_down ? -1 : trend == -1 and to_up ? 1 : trend



drawZigzag(x1,y1,x2,y2) =>

    line.new(x1=x1,y1=y1,x2=x2,y2=y2,xloc = xloc.bar_time,width = 1)



if ta.change(trend) != 0 and trend ==1

    array.push(highValIndex,time )

    array.push(highVal,high )

    if array.size(lowVal) > 1

        lastLowVal= array.get(lowVal,array.size(lowVal)-1)

        lastLowIndex =  array.get(lowValIndex,array.size(lowValIndex)-1)

        lastHighIndex=  array.get(highValIndex,array.size(highValIndex)-1)

        lastHighVal =  array.get(highVal,array.size(highVal)-1)

        if zigzagBool

            drawZigzag(x1=lastLowIndex,y1=lastLowVal,x2=lastHighIndex,y2=lastHighVal)

        drawUp := false

    fibTopIndex := time 

    fibTopVal :=high 

    

if ta.change(trend) != 0 and trend == -1

    array.push(lowValIndex,time )

    array.push(lowVal,low )

    if array.size(highVal) > 1

        lastHighVal= array.get(highVal,array.size(highVal)-1)

        lastHighIndex =  array.get(highValIndex,array.size(highValIndex)-1)

        lastLowIndex =  array.get(lowValIndex,array.size(lowValIndex)-1)

        lastLowVal =  array.get(lowVal,array.size(lowVal)-1)

        if zigzagBool

            drawZigzag(x1=lastHighIndex,y1=lastHighVal,x2=lastLowIndex,y2=lastLowVal)

        drawDown := false

    fibBotIndex := time 

    fibBotVal :=low 

    

if array.size(lowVal) > 1 and drawDown == false

    if close < array.get(lowVal,array.size(lowVal)-1)

        

        

        drawDown := true

        lastState := "down"

        if orderblockBool

            orderblock newOrderblock = orderblock.new()

            float max = 0

            int bar = na

            for i = (time - array.get(lowValIndex,array.size(lowValIndex)-1)-(time-time ))/(time-time ) to 0

                if high  > max

                    max := high 

                    bar := time 

            newOrderblock.barStart := bar

            newOrderblock.barEnd := time

            newOrderblock.broken :=false

            newOrderblock.value := max

            newOrderblock.block := box.new(left = newOrderblock.barStart ,top = newOrderblock.value-atr ,right= newOrderblock.barEnd,bottom=newOrderblock.value,xloc=xloc.bar_time,bgcolor = bearishOrderblockColor,border_width = 1,border_color = bearishOrderblockColor)

            array.push(bearishOrderblock,newOrderblock)

            if array.size(bearishOrderblock) > 33

                array.shift(bearishOrderblock)



if array.size(highVal) > 1 and drawUp == false

    if close > array.get(highVal,array.size(highVal)-1)

        

       

        drawUp := true

        lastState := "up"

        if orderblockBool

            orderblock newOrderblock = orderblock.new()

            float min = 999999999

            int bar = na

            for i = (time - array.get(highValIndex,array.size(highValIndex)-1)-(time-time ))/(time-time ) to 0

                if low  < min

                    min := low 

                    bar := time 

                

            newOrderblock.barStart := bar

            newOrderblock.barEnd := time

            newOrderblock.broken :=false

            newOrderblock.value := min

            newOrderblock.block := box.new(left = newOrderblock.barStart ,top = newOrderblock.value+atr ,right= newOrderblock.barEnd,bottom=newOrderblock.value,xloc=xloc.bar_time,bgcolor = bullishOrderblockColor,border_width = 1,border_color = bullishOrderblockColor)

            array.push(bullishOrderblock,newOrderblock)

            if array.size(bullishOrderblock) > 33

                array.shift(bullishOrderblock)



// Order block



//update orderblock

if array.size(bullishOrderblock) > 0

    orderblock testOrderblock = na

    int counter = 0

    for i = array.size(bullishOrderblock) - 1 to 0

        testOrderblock := array.get(bullishOrderblock,i)

        if counter < numberObShow

            testOrderblock.block.set_right(time)

            if close < testOrderblock.value

                testOrderblock.block.delete()

                array.remove(bullishOrderblock,i)

            counter := counter + 1

        else

            testOrderblock.block.set_right(testOrderblock.barStart)

    

if array.size(bearishOrderblock) > 0

    orderblock testOrderblock = na

    int counter = 0

    for i = array.size(bearishOrderblock) - 1 to 0

        testOrderblock := array.get(bearishOrderblock,i)

        if counter < numberObShow

            testOrderblock.block.set_right(time)

            if close > testOrderblock.value

                testOrderblock.block.delete()

                array.remove(bearishOrderblock,i)

            counter := counter + 1

        else

            testOrderblock.block.set_right(testOrderblock.barStart)

        

// Liquidity



phLiquidity = ta.pivothigh(high,liquidity_len,liquidity_len)

plLiquidity = ta.pivotlow(low,liquidity_len,liquidity_len)



if not na(phLiquidity) and liquidityBool

    liquidity newLiquidity = liquidity.new()

    newLiquidity.value := high 

    newLiquidity.barStart := time 

    newLiquidity.barEnd := time

    newLiquidity.broken := false

    newLiquidity.liquidityLine := line.new(x1=newLiquidity.barStart,y1=newLiquidity.value,x2=newLiquidity.barEnd ,y2=newLiquidity.value,xloc = xloc.bar_time,color = downColor,width = 1)

    array.push(bearishLiquidity,newLiquidity)

    if array.size(bearishLiquidity) > 7

        deletedLiquidity = array.shift(bearishLiquidity)

        deletedLiquidity.liquidityLine.delete()



if not na(plLiquidity) and liquidityBool

    liquidity newLiquidity = liquidity.new()

    newLiquidity.value := low 

    newLiquidity.barStart := time 

    newLiquidity.barEnd := time

    newLiquidity.broken := false

    newLiquidity.liquidityLine := line.new(x1=newLiquidity.barStart,y1=newLiquidity.value,x2=newLiquidity.barEnd ,y2=newLiquidity.value,xloc = xloc.bar_time,color = upColor,width =1)

    array.push(bullishLiquidity,newLiquidity)

    if array.size(bullishLiquidity) > 7

        deletedLiquidity = array.shift(bullishLiquidity)

        deletedLiquidity.liquidityLine.delete()



// Update liquidity

if array.size(bearishLiquidity) > 0

    liquidity testLiquidity = na

    for i = array.size(bearishLiquidity) - 1 to 0

        testLiquidity := array.get(bearishLiquidity,i)

        if high > testLiquidity.value

            testLiquidity.liquidityLine.set_x2(time)

            testLiquidity.liquidityLine.set_style(line.style_dashed)

            array.remove(bearishLiquidity,i)

            if close < testLiquidity.value

                testLiquidity.sweep := label.new(x = time,y=high,xloc = xloc.bar_time,style = label.style_diamond,size = size.tiny,color= color.rgb(247, 89, 26))



        else

            testLiquidity.liquidityLine.set_x2(time)



if array.size(bullishLiquidity) > 0

    liquidity testLiquidity = na

    for i = array.size(bullishLiquidity) - 1 to 0

        testLiquidity := array.get(bullishLiquidity,i)

        if low < testLiquidity.value

            testLiquidity.liquidityLine.set_x2(time)

            testLiquidity.liquidityLine.set_style(line.style_dashed)

            array.remove(bullishLiquidity,i)

            if close > testLiquidity.value

                testLiquidity.sweep := label.new(x = time,y=low,xloc = xloc.bar_time,style =label.style_diamond,size = size.tiny,color= #34addd)



        else

            testLiquidity.liquidityLine.set_x2(time)





//tradelines

length = input.int(27, 'Swing Detection Lookback' ,group = 'tradeline')

mult = input.float(1., 'Slope', minval = 0, step = .1 ,group = 'tradeline')

calcMethod = input.string('Atr', 'Slope Calculation Method', options =  , group = 'tradeline')

backpaint = input(false, tooltip = 'Backpainting offset displayed elements in the past. Disable backpainting to see real time information returned by the indicator.', group = 'tradeline')





upCss = input.color(color.teal, 'Up Trendline Color', group = 'tradeline')

dnCss = input.color(color.red, 'Down Trendline Color', group = 'tradeline')

showExt = input(true, 'Show Extended Lines')



//-----------------------------------------------------------------------------}

//Calculations

//-----------------------------------------------------------------------------{

var upper = 0.

var lower = 0.

var slope_ph = 0.

var slope_pl = 0.



var offset = backpaint ? length : 0



n = bar_index

src = close



ph = ta.pivothigh(length, length)

pl = ta.pivotlow(length, length)



//Slope Calculation Method

slope = switch calcMethod

    'Atr'    => ta.atr(length) / length * mult

    'Stdev'  => ta.stdev(src,length) / length * mult

    'Linreg' => math.abs(ta.sma(src * n, length) - ta.sma(src, length) * ta.sma(n, length)) / ta.variance(n, length) / 2 * mult



//Get slopes and calculate trendlines

slope_ph := ph ? slope : slope_ph

slope_pl := pl ? slope : slope_pl



upper := ph ? ph : upper - slope_ph

lower := pl ? pl : lower + slope_pl



var upos = 0

var dnos = 0

upos := ph ? 0 : close > upper - slope_ph * length ? 1 : upos

dnos := pl ? 0 : close < lower + slope_pl * length ? 1 : dnos



var uptl  = line.new(na,na,na,na, color = upCss, style = line.style_dashed, extend = extend.right)

var dntl  = line.new(na,na,na,na, color = dnCss, style = line.style_dashed, extend = extend.right)



if ph and showExt

    uptl.set_xy1(n-offset, backpaint ? ph : upper - slope_ph * length)

    uptl.set_xy2(n-offset+1, backpaint ? ph - slope : upper - slope_ph * (length+1))



if pl and showExt

    dntl.set_xy1(n-offset, backpaint ? pl : lower + slope_pl * length)

    dntl.set_xy2(n-offset+1, backpaint ? pl + slope : lower + slope_pl * (length+1))







//HULLTREND

lengthx = input(33, group = 'HULLTREND')

srcx = input(hl2, group = 'HULLTREND')



wma(src, length) =>

    norm = 0.0

    sum = 0.0

    for i = 0 to length - 1

        weight = (length - i) * src 

        norm := norm + (length - i)

        sum := sum + weight

    sum / norm



sqrt(x) =>

    x >= 0 ? math.sqrt(x) : na



floor(x) =>

    x >= 0 ? int(x) : int(x) - 1



ceil(x) =>

    x == int(x) ? x : (x > 0 ? int(x) + 1 : int(x))



round(x) =>

    x > 0 ? floor(x + 0.5) : ceil(x - 0.5)



fract(x) =>

    x - floor(x)



hmax(_srcx, _lengthx) =>

    wma((2 * wma(_srcx, _lengthx / 2)) - wma(_srcx, _lengthx), round(sqrt(_lengthx)))



hma3(_srcx, _lengthx) =>

    p = lengthx / 2

    wma(wma(close, p / 3) * 3 - wma(close, p / 2) - wma(close, p), p)



a = hmax(srcx, lengthx)

b = hma3(srcx, lengthx)

c = b > a ? color.lime : color.red



plot_hmax = plot(a, color=c, linewidth=1, transp=75)

plot_hma3 = plot(b, color=c, linewidth=1, transp=75)

fill(plot_hmax, plot_hma3, color=c, transp=55)



crossdn = a > b and a  < b 

crossup = b > a and b  < a 







//MacdSignal



signalLen = input.int(9, "MACD Length", group = "General Configuration", display = display.none)

smoothing = input.int(5, "Smoothing", group = "General Configuration", display = display.none)

bearishColor = input.color(color.rgb(243, 133, 30), "Bearish", group = "Colors", inline = "col", display = display.none)

bullishColor = input.color(color.rgb(9, 118, 168), "Bullish", group = "Colors", inline = "col", display = display.none)



var isBull = true

const float atrMult = 1.75

const int lineWidth = 2





  = ta.macd(ohlc4, int(signalLen * (12.0 / 9.0)), int(signalLen * (26.0 / 9.0)), int(signalLen))

basePoint = ohlc4

MACDTrailRAWBull = (basePoint + macdLine - (atr * atrMult))

MACDTrailRAWBear = (basePoint + macdLine + (atr * atrMult))

MACDTrailBull = ta.ema(MACDTrailRAWBull, smoothing)

MACDTrailBear = ta.ema(MACDTrailRAWBear, smoothing)



if isBull and close < MACDTrailBull

    isBull := false

else if not isBull and close > MACDTrailBear

    isBull := true



plot(MACDTrailBull, color = isBull ? bullishColor : na, linewidth = lineWidth, display = display.none)

plot(MACDTrailBear, color = isBull ? na : bearishColor, linewidth = lineWidth, display = display.none)











This paste expires in <1 day. Public IP access. Share whatever you see with others in seconds with Context. Terms of ServiceReport this