Anlik Trade Merkezi Supertrend
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © hakanar

//@version=5
indicator("Anlik Trade Merkezi Supertrend", overlay=true, timeframe="", timeframe_gaps=true)

atrPeriod = input(10, "ATR Length")
factor = input.float(1.05, "Factor", step = 0.01)

vwmaLength = input.int(10, "vwma Length")
showsignals = input.bool(true, "Show Signals")

pine_vwma(x, y, volume) =>
    ta.sma(x * volume, y) / ta.sma(volume, y)
    
//the same on pine
pine_atr(length) =>
    trueRange = na(high[1])? high-low : math.max(math.max(high - low, math.abs(high - close[1])), math.abs(low - close[1]))
    //true range can be also calculated with ta.tr(true)
    ta.rma(trueRange, length)
    

// The same on Pine
pine_supertrend(factor, atrPeriod) =>
	src = hl2
	atr = pine_atr(atrPeriod)
	
	vwma = pine_vwma(hl2, vwmaLength, volume)
	newfactor = factor + (vwma[1] / vwma[18])
	upperBand = src + newfactor * atr
	lowerBand = src - newfactor * atr
	prevLowerBand = nz(lowerBand[1])
	prevUpperBand = nz(upperBand[1])

    vwmaclose_1 = close[1]
    vwmaclose = close

	lowerBand := lowerBand > prevLowerBand or vwmaclose_1 < prevLowerBand ? lowerBand : prevLowerBand
	upperBand := upperBand < prevUpperBand or vwmaclose_1 > prevUpperBand ? upperBand : prevUpperBand
	int direction = na
	float superTrend = na
	prevSuperTrend = superTrend[1]
	if na(atr[1])
		direction := 1
	else if prevSuperTrend == prevUpperBand
		direction := vwmaclose > upperBand ? -1 : 1
	else
		direction := vwmaclose < lowerBand ? 1 : -1
	superTrend := direction == -1 ? lowerBand : upperBand
	[superTrend, direction]
	
	
[supertrend, direction] = pine_supertrend(factor, atrPeriod)

bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(direction < 0? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)

plotshape(ta.change(direction) < 0 and showsignals ? supertrend : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.green, textcolor=color.white)
plotshape(ta.change(direction) > 0 and showsignals ? supertrend : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.red, textcolor=color.white)