OPEN-SOURCE SCRIPT

MarketMagnet Algo

//version=5
indicator(" MarketMagnet Algo ", overlay = true, max_bars_back = 5000, max_labels_count = 500, max_lines_count = 500)

const bool DEBUG = false
const float epsilon = 0.02 / 100.0
const int showLastXPivots = 50

todayEnabled = input.bool(true, "Today                ", group = "General Configuration", inline = "Today")
todayLineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "Today", display = display.none)
todayHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "Today", display = display.none)
todayLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "Today", display = display.none)
todayOpenLineColor = input.color(color.blue, "Open", group = "General Configuration", inline = "Today", display = display.none)

yesterdayEnabled = input.bool(true, "Yesterday          ", group = "General Configuration", inline = "Yesterday")
yesterdayLineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "Yesterday", display = display.none)
yesterdayHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "Yesterday", display = display.none)
yesterdayLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "Yesterday", display = display.none)
yesterdayCloseLineColor = input.color(color.fuchsia, "Close", group = "General Configuration", inline = "Yesterday", display = display.none)

day3 = input.bool(false, "3rd Day             ", group = "General Configuration", inline = "day3")
day3LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day3", display = display.none)
day3HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day3", display = display.none)
day3LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day3", display = display.none)

day4 = input.bool(false, "4th Day             ", group = "General Configuration", inline = "day4")
day4LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day4", display = display.none)
day4HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day4", display = display.none)
day4LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day4", display = display.none)

day5 = input.bool(false, "5th Day             ", group = "General Configuration", inline = "day5")
day5LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day5", display = display.none)
day5HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day5", display = display.none)
day5LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day5", display = display.none)

day6 = input.bool(false, "6th Day             ", group = "General Configuration", inline = "day6")
day6LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day6", display = display.none)
day6HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day6", display = display.none)
day6LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day6", display = display.none)

day7 = input.bool(false, "7th Day             ", group = "General Configuration", inline = "day7")
day7LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day7", display = display.none)
day7HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day7", display = display.none)
day7LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day7", display = display.none)

day8 = input.bool(false, "8th Day             ", group = "General Configuration", inline = "day8")
day8LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day8", display = display.none)
day8HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day8", display = display.none)
day8LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day8", display = display.none)

day9 = input.bool(false, "9th Day             ", group = "General Configuration", inline = "day9")
day9LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day9", display = display.none)
day9HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day9", display = display.none)
day9LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day9", display = display.none)

day10 = input.bool(false, "10th Day           ", group = "General Configuration", inline = "day10")
day10LineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "day10", display = display.none)
day10HighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "day10", display = display.none)
day10LowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "day10", display = display.none)

preMarketEnabled = input.bool(false, "Pre-Market        ", group = "General Configuration", inline = "premarket")
preMarketLineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "premarket", display = display.none)
preMarketHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "premarket", display = display.none)
preMarketLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "premarket", display = display.none)

previousMonthEnabled = input.bool(false, "Previous Month  ", group = "General Configuration", inline = "month")
monthLineStyle = input.string("____", " ", options = ["____", "----", "...."], group = "General Configuration", inline = "month", display = display.none)
monthHighLineColor = input.color(color.green, "High", group = "General Configuration", inline = "month", display = display.none)
monthLowLineColor = input.color(color.red, "Low", group = "General Configuration", inline = "month", display = display.none)

pivotsEnabled = input.bool(false, "Enabled", group = "High & Low Pivots")
pivotRange = input.int(14, "Pivot Range", options = [7, 14, 21], group = "High & Low Pivots")
pivotHighColor = input.color(color.green, "High", group = "High & Low Pivots", inline = "style", display = display.none)
pivotLowColor = input.color(color.red, "Low", group = "High & Low Pivots", inline = "style", display = display.none)
textSizePivotIn = input.string("Normal", "Size", ["Large", "Normal", "Small"], group = "High & Low Pivots", inline = "style", display = display.none)

barOffset = input.int(20, "Text Offset", group = "Style Settings", display = display.none)
lineThickness = input.int(2, "Thickness", group = "Style Settings", options = [1,2,3,4], display = display.none)
extendLines = input.bool(true, "Extend Lines", group = "Style Settings", tooltip = "Enabled -> Extend lines infinitely.\nDisabled -> Clamp lines in their timestamps.", display = display.none)
showLineValues = input.bool(true, "Show Line Values", group = "Style Settings", display = display.none)
labelsAlign = input.string("Right", "Align Labels", options = ["Right", "Center"], group = "Style Settings", display = display.none)
textColor = input.color(color.white, "Text Color", group = "Style Settings", inline = "text", display = display.none)
textSizeIn = input.string("Normal", "Size", ["Large", "Normal", "Small"], group = "Style Settings", inline = "text", display = display.none)

textSize = (textSizeIn == "Normal" ? size.normal : (textSizeIn == "Small" ? size.small : size.large))
textSizePivot = (textSizePivotIn == "Normal" ? size.normal : (textSizePivotIn == "Small" ? size.small : size.large))

type bInfo
float h = high
float l = low
float o = open
float c = close
int t = time

curBInfo = bInfo.new()

doValuesTouch (float value1, float value2) =>
if math.abs(value1 - value2) / ((value1 + value2) / 2.0) <= epsilon
true
else
false

f_newLine(_color, _lineStyle) => line.new(na, na, na, na, xloc.bar_time, width = lineThickness ,extend = extendLines ? extend.both : extend.none, color = _color, style = _lineStyle == "____" ? line.style_solid : _lineStyle == "----" ? line.style_dashed : line.style_dotted)

f_moveLine(_line, _x, _y, _x2) =>
line.set_xy1(_line, _x, _y)
line.set_xy2(_line, _x2, _y)

f_getInfo (timeframe) =>
request.security(syminfo.tickerid, timeframe, [curBInfo, curBInfo[1], curBInfo[2], curBInfo[3], curBInfo[4], curBInfo[5], curBInfo[6], curBInfo[7], curBInfo[8], curBInfo[9]], calc_bars_count = 30)

f_calculatePreMarketHighLow () =>
curIndex = 0
float preMarketHighF = 0
float preMarketLowF = -1
bool foundPreMarket = false
while (session.isfirstbar[curIndex] == false)
if session.ispremarket[curIndex]
foundPreMarket := true
preMarketHighF := math.max(preMarketHighF, high[curIndex])
preMarketLowF := preMarketLowF == -1 ? low[curIndex] : math.min(preMarketLowF, low[curIndex])
if not session.ispremarket[curIndex] and foundPreMarket
break
curIndex += 1
if curIndex > 4000
break
[preMarketHighF, preMarketLowF]

type lineInfo
string[] timeNames
string[] infos
float price
int startTime
int endTime
color col
string lStyle
line zone
label lbl
bool disabled = false

type pivot
bool isHigh = false
int index
float price
float atr

label textLabel

safeDeletePivot (pivot p) =>
label.delete(p.textLabel)

createLineInfo (string timeName, string info, float p, int t, int tend, color col, string sty) =>
newLI = lineInfo.new(array.new<string>(0), array.new<string>(0), p, t, tend, col, sty)
if not na(timeName)
newLI.timeNames.unshift(timeName)
if not na (info)
newLI.infos.unshift(info)
newLI

safeDeleteLineInfo (lineInfoF) =>
line.delete(lineInfoF.zone)
label.delete(lineInfoF.lbl)

var allLineInfos = array.new<lineInfo>(0)
var allPivots = array.new<pivot>(0)

extendedTicker = ticker.modify(syminfo.tickerid, session = session.extended)
[preMarketHigh, preMarketLow] = request.security(extendedTicker, "1", f_calculatePreMarketHighLow())

[bInfo1, bInfo2, bInfo3, bInfo4, bInfo5, bInfo6, bInfo7, bInfo8, bInfo9, bInfo10] = f_getInfo("D")
[mInfo1, mInfo2] = f_getInfo("M")

calculateLineInfos () =>
if allLineInfos.size() > 0
for i = 0 to allLineInfos.size() - 1
safeDeleteLineInfo(allLineInfos.get(i))
allLineInfos.clear()

if todayEnabled and not na(bInfo1)
allLineInfos.unshift(createLineInfo("Today", "High", bInfo1.h, bInfo1.t, time, todayHighLineColor, todayLineStyle))
allLineInfos.unshift(createLineInfo("Today", "Low", bInfo1.l, bInfo1.t, time, todayLowLineColor, todayLineStyle))
allLineInfos.unshift(createLineInfo("Today", "Open", bInfo1.o, bInfo1.t, time, todayOpenLineColor, todayLineStyle))
if yesterdayEnabled and not na(bInfo2)
allLineInfos.unshift(createLineInfo("Yesterday", "High", bInfo2.h, bInfo2.t, bInfo1.t, yesterdayHighLineColor, yesterdayLineStyle))
allLineInfos.unshift(createLineInfo("Yesterday", "Low", bInfo2.l, bInfo2.t, bInfo1.t, yesterdayLowLineColor, yesterdayLineStyle))
allLineInfos.unshift(createLineInfo("Yesterday", "Close", bInfo2.c, bInfo2.t, bInfo1.t, yesterdayCloseLineColor, yesterdayLineStyle))
if day3 and not na(bInfo3)
allLineInfos.unshift(createLineInfo("3rd Day", "High", bInfo3.h, bInfo3.t, bInfo2.t, day3HighLineColor, day3LineStyle))
allLineInfos.unshift(createLineInfo("3rd Day", "Low", bInfo3.l, bInfo3.t, bInfo2.t, day3LowLineColor, day3LineStyle))
if day4 and not na(bInfo4)
allLineInfos.unshift(createLineInfo("4th Day", "High", bInfo4.h, bInfo4.t, bInfo3.t, day4HighLineColor, day4LineStyle))
allLineInfos.unshift(createLineInfo("4th Day", "Low", bInfo4.l, bInfo4.t, bInfo3.t, day4LowLineColor, day4LineStyle))
if day5 and not na(bInfo5)
allLineInfos.unshift(createLineInfo("5th Day", "High", bInfo5.h, bInfo5.t, bInfo4.t, day5HighLineColor, day5LineStyle))
allLineInfos.unshift(createLineInfo("5th Day", "Low", bInfo5.l, bInfo5.t, bInfo4.t, day5LowLineColor, day5LineStyle))
if day6 and not na(bInfo6)
allLineInfos.unshift(createLineInfo("6th Day", "High", bInfo6.h, bInfo6.t, bInfo5.t, day6HighLineColor, day6LineStyle))
allLineInfos.unshift(createLineInfo("6th Day", "Low", bInfo6.l, bInfo6.t, bInfo5.t, day6LowLineColor, day6LineStyle))
if day7 and not na(bInfo7)
allLineInfos.unshift(createLineInfo("7th Day", "High", bInfo7.h, bInfo7.t, bInfo6.t, day7HighLineColor, day7LineStyle))
allLineInfos.unshift(createLineInfo("7th Day", "Low", bInfo7.l, bInfo7.t, bInfo6.t, day7LowLineColor, day7LineStyle))
if day8 and not na(bInfo8)
allLineInfos.unshift(createLineInfo("8th Day", "High", bInfo8.h, bInfo8.t, bInfo7.t, day8HighLineColor, day8LineStyle))
allLineInfos.unshift(createLineInfo("8th Day", "Low", bInfo8.l, bInfo8.t, bInfo7.t, day8LowLineColor, day8LineStyle))
if day9 and not na(bInfo9)
allLineInfos.unshift(createLineInfo("9th Day", "High", bInfo9.h, bInfo9.t, bInfo8.t, day9HighLineColor, day9LineStyle))
allLineInfos.unshift(createLineInfo("9th Day", "Low", bInfo9.l, bInfo9.t, bInfo8.t, day9LowLineColor, day9LineStyle))
if day10 and not na(bInfo10)
allLineInfos.unshift(createLineInfo("10th Day", "High", bInfo10.h, bInfo10.t, bInfo9.t, day10HighLineColor, day10LineStyle))
allLineInfos.unshift(createLineInfo("10th Day", "Low", bInfo10.l, bInfo10.t, bInfo9.t, day10LowLineColor, day10LineStyle))
if preMarketEnabled and not na(preMarketHigh) and not na(bInfo1)
allLineInfos.unshift(createLineInfo("Pre-Market", "High", preMarketHigh, bInfo1.t, time, preMarketHighLineColor, preMarketLineStyle))
allLineInfos.unshift(createLineInfo("Pre-Market", "Low", preMarketLow, bInfo1.t, time, preMarketLowLineColor, preMarketLineStyle))
if previousMonthEnabled and not na(mInfo2)
allLineInfos.unshift(createLineInfo("Previous Month", "High", mInfo2.h, mInfo2.t, mInfo1.t, monthLowLineColor, monthLineStyle))
allLineInfos.unshift(createLineInfo("Previous Month", "Low", mInfo2.l, mInfo2.t, mInfo1.t, monthHighLineColor, monthLineStyle))

calculateLineInfos()

combineLineInfos () =>
if allLineInfos.size() > 0
lastCombinations = 999
while lastCombinations > 0
lastCombinations := 0
for i = 0 to allLineInfos.size() - 1
curLI1 = allLineInfos.get(i)
for j = 0 to allLineInfos.size() - 1
curLI2 = allLineInfos.get(j)
if i == j
continue
if curLI1.disabled or curLI2.disabled
continue
if doValuesTouch(curLI1.price, curLI2.price) and extendLines
curLI1.disabled := true
curLI2.disabled := true
newLI = createLineInfo(na, na, curLI1.price, na, na, na, na)
if curLI1.timeNames.size() > 0
for a = 0 to curLI1.timeNames.size() - 1
newLI.timeNames.unshift(curLI1.timeNames.get(a))
for a = 0 to curLI1.infos.size() - 1
newLI.infos.unshift(curLI1.infos.get(a))

if curLI2.timeNames.size() > 0
for a = 0 to curLI2.timeNames.size() - 1
newLI.timeNames.unshift(curLI2.timeNames.get(a))
for a = 0 to curLI2.infos.size() - 1
newLI.infos.unshift(curLI2.infos.get(a))

newLI.startTime := math.min(curLI1.startTime, curLI2.startTime)
newLI.endTime := math.max(curLI1.endTime, curLI2.endTime)
newLI.col := curLI1.col
newLI.lStyle := curLI1.lStyle
allLineInfos.unshift(newLI)
lastCombinations += 1

renderPivot (pivot pivotF) =>
pivotF.textLabel := label.new(pivotF.index, pivotF.price + (pivotF.atr * 1 * (pivotF.isHigh ? 1 : -1)), str.tostring(pivotF.price, format.mintick), style = label.style_none, size = textSizePivot, textcolor = (pivotF.isHigh ? pivotHighColor : pivotLowColor))

renderLineInfo (lineInfoF) =>
safeDeleteLineInfo(lineInfoF)
if not lineInfoF.disabled
lineInfoF.zone := f_newLine(lineInfoF.col, lineInfoF.lStyle)
if lineInfoF.startTime == lineInfoF.endTime
lineInfoF.endTime += 1

f_moveLine(lineInfoF.zone, lineInfoF.startTime, lineInfoF.price, lineInfoF.endTime)
lblText = ""

if lineInfoF.timeNames.size() > 0
for i = 0 to lineInfoF.timeNames.size() - 1
lblText += lineInfoF.timeNames.get(i) + " "
lblText += lineInfoF.infos.get(i)
if i != lineInfoF.timeNames.size() - 1
lblText += " & "

if showLineValues
lblText += " (" + str.tostring(lineInfoF.price, format.mintick) + ")"

if extendLines
lineInfoF.lbl := label.new(labelsAlign == "Center" ? ((chart.right_visible_bar_time + chart.left_visible_bar_time) / 2) : (last_bar_index + barOffset), lineInfoF.price, textcolor = textColor, text = lblText, style = label.style_none, xloc = labelsAlign == "Center" ? xloc.bar_time : xloc.bar_index, size = textSize)
else
lineInfoF.lbl := label.new(labelsAlign == "Center" ? (lineInfoF.startTime + lineInfoF.endTime) / 2 : lineInfoF.endTime, lineInfoF.price, xloc = xloc.bar_time, textcolor = textColor, text = lblText, style = label.style_none, size = textSize)

renderLineInfos () =>
if allLineInfos.size() > 0
for i = 0 to allLineInfos.size() - 1
curLineInfo = allLineInfos.get(i)
renderLineInfo(curLineInfo)

renderPivots () =>
if allPivots.size() > 0
for i = 0 to allPivots.size() - 1
curPivot = allPivots.get(i)
safeDeletePivot(curPivot)
renderPivot(curPivot)

combineLineInfos()
renderLineInfos()

pivotHigh = ta.pivothigh(pivotRange, pivotRange)
pivotLow = ta.pivotlow(pivotRange, pivotRange)

curAtr = ta.atr(5)
if not na(pivotHigh)
allPivots.unshift(pivot.new(true, bar_index - pivotRange, pivotHigh, curAtr))
if not na(pivotLow)
allPivots.unshift(pivot.new(false, bar_index - pivotRange, pivotLow, curAtr))

if allPivots.size() > showLastXPivots
allPivots.remove(allPivots.size() - 1)

if barstate.islast
if pivotsEnabled
renderPivots()

// Get user input
sensitivity = input.float(2.8, "  Sensitivity (0.5 - 10)", 0.5, 10, step=0.1)
emaEnergy = input.bool(true, "EMA Energy")
keltner_length = input(10, "Keltner Channel Length")
atrPeriod = input(10, "ATR Length")
factor = input.float(3.5, "Factor", step = 0.01)
// Keltner Channel function
keltner_channel(src, length) =>
ma = ta.sma(src, length)
rangec = high - low
upper = ma + rangec
lower = ma - rangec
[upper, lower]

// Modified Supertrend function using Keltner Channel
supertrend(_src, factor, atrLen, kel_length) =>
[upperKeltner, lowerKeltner] = keltner_channel(_src, kel_length)
rangec = upperKeltner - lowerKeltner
upperBand = _src + factor * rangec
lowerBand = _src - factor * rangec
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]

if na(rangec[1])
direction := 1
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
else
direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
// Get Components
ema1 = ta.ema(high, 9)
ema2 = ta.ema(high, 12)
ema3 = ta.ema(high, 15)
ema4 = ta.ema(high, 18)
ema5 = ta.ema(high, 21)
ema6 = ta.ema(high, 24)
ema7 = ta.ema(high, 27)
ema8 = ta.ema(high, 30)
ema9 = ta.ema(high, 33)
ema10 = ta.ema(high, 36)
ema11 = ta.ema(high, 39)
ema12 = ta.ema(high, 42)
ema13 = ta.ema(high, 45)
ema14 = ta.ema(high, 48)
ema15 = ta.ema(high, 51)
// Colors
green = #2BBC4D, red = #C51D0B
emaEnergyColor(ma) => emaEnergy ? (close >= ma ? green : red) : na
// Plots
plot(ema1, "", emaEnergyColor(ema1), editable=false)
plot(ema2, "", emaEnergyColor(ema2), editable=false)
plot(ema3, "", emaEnergyColor(ema3), editable=false)
plot(ema4, "", emaEnergyColor(ema4), editable=false)
plot(ema5, "", emaEnergyColor(ema5), editable=false)
plot(ema6, "", emaEnergyColor(ema6), editable=false)
plot(ema7, "", emaEnergyColor(ema7), editable=false)
plot(ema8, "", emaEnergyColor(ema8), editable=false)
plot(ema9, "", emaEnergyColor(ema9), editable=false)
plot(ema10, "", emaEnergyColor(ema10), editable=false)
plot(ema11, "", emaEnergyColor(ema11), editable=false)
plot(ema12, "", emaEnergyColor(ema12), editable=false)
plot(ema13, "", emaEnergyColor(ema13), editable=false)
plot(ema14, "", emaEnergyColor(ema14), editable=false)
plot(ema15, "", emaEnergyColor(ema15), editable=false)
[supertrend, direction] = supertrend(close, sensitivity, 11, keltner_length)
bull = ta.crossover(close, supertrend)
bear = ta.crossunder(close, supertrend)
y1 = low - (ta.atr(30) * 2)
y2 = high + (ta.atr(30) * 2)
buy = bull ? label.new(bar_index, y1, "BUY CE", xloc.bar_index, yloc.price, green, label.style_label_up, color.white, size.normal) : na
sell = bear ? label.new(bar_index, y2, "BUY PE", xloc.bar_index, yloc.price, red, label.style_label_down, color.white, size.normal) : na
[supertrends, directions] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
// Trend Catcher Indicator (Example)
ema100 = ta.ema(close, 10)
ema200 = ta.ema(close, 20)
trendCatcher = ta.crossover(ema100, ema200) ? 1 : ta.crossunder(ema100, ema200) ? -1 : 0
trendColor = trendCatcher == 1 ? color.rgb(90, 23, 102) : na
barcolor(trendColor)
// Colored candles
barcolor(color = close > supertrends ? color.rgb(102, 255, 0) : color.rgb(255, 0, 0))
// 添加警報條件
alertcondition(bull, title="Buy CE", message="Buy CE!")
alertcondition(bear, title="Buy PE", message="Buy PE!")

// Plot EMAs
plot(ema1, color=color.blue, title="EMA 9")
plot(ema2, color=color.orange, title="EMA 21")
plot(ema3, color=color.purple, title="EMA 61")

// Input settings
ccimomCross = input.string('CCI', 'Entry Signal Source', options=['CCI', 'Momentum'], tooltip='CCI or Momentum will be the final source of the Entry signal if selected.')
ccimomLength = input.int(10, minval=1, title='CCI/Momentum Length')
useDivergence = input.bool(true, title='Find Regular Bullish/Bearish Divergence', tooltip='If checked, it will only consider an overbought or oversold condition that has a regular bullish or bearish divergence formed inside that level.')
rsiOverbought = input.int(65, minval=1, title='RSI Overbought Level', tooltip='Adjusting the level to extremely high may filter out some signals especially when the option to find divergence is checked.')
rsiOversold = input.int(35, minval=1, title='RSI Oversold Level', tooltip='Adjusting this level extremely low may filter out some signals especially when the option to find divergence is checked.')
rsiLength = input.int(14, minval=1, title='RSI Length')
plotMeanReversion = input.bool(false, 'Plot Mean Reversion Bands on the chart', tooltip='This function doesn\'t affect the entry of signal but it suggests buying when the price is at the lower band, and then sell it on the next bounce at the higher bands.')
emaPeriod = input(200, title='Lookback Period (EMA)')
bandMultiplier = input.float(1.8, title='Outer Bands Multiplier', tooltip='Multiplier for both upper and lower bands')


// CCI and Momentum calculation
momLength = ccimomCross == 'Momentum' ? ccimomLength : 10
mom = close - close[momLength]
cci = ta.cci(close, ccimomLength)
ccimomCrossUp = ccimomCross == 'Momentum' ? ta.cross(mom, 0) : ta.cross(cci, 0)
ccimomCrossDown = ccimomCross == 'Momentum' ? ta.cross(0, mom) : ta.cross(0, cci)

// RSI calculation
src = close
up = ta.rma(math.max(ta.change(src), 0), rsiLength)
down = ta.rma(-math.min(ta.change(src), 0), rsiLength)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
oversoldAgo = rsi[0] <= rsiOversold or rsi[1] <= rsiOversold or rsi[2] <= rsiOversold or rsi[3] <= rsiOversold
overboughtAgo = rsi[0] >= rsiOverbought or rsi[1] >= rsiOverbought or rsi[2] >= rsiOverbought or rsi[3] >= rsiOverbought

// Regular Divergence Conditions
bullishDivergenceCondition = rsi[0] > rsi[1] and rsi[1] < rsi[2]
bearishDivergenceCondition = rsi[0] < rsi[1] and rsi[1] > rsi[2]

// Entry Conditions
longEntryCondition = ccimomCrossUp and oversoldAgo and (not useDivergence or bullishDivergenceCondition)
shortEntryCondition = ccimomCrossDown and overboughtAgo and (not useDivergence or bearishDivergenceCondition)


// Mean Reversion Indicator
meanReversion = plotMeanReversion ? ta.ema(close, emaPeriod) : na
stdDev = plotMeanReversion ? ta.stdev(close, emaPeriod) : na
upperBand = plotMeanReversion ? meanReversion + stdDev * bandMultiplier : na
lowerBand = plotMeanReversion ? meanReversion - stdDev * bandMultiplier : na


// Plotting
plotshape(longEntryCondition, title='BUY', style=shape.triangleup, text='B', location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.new(color.white, 0), size=size.tiny)
plotshape(shortEntryCondition, title='SELL', style=shape.triangledown, text='S', location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny)

plot(upperBand, title='Upper Band', color=color.new(color.fuchsia, 0), linewidth=1)
plot(meanReversion, title='Mean', color=color.new(color.gray, 0), linewidth=1)
plot(lowerBand, title='Lower Band', color=color.new(color.blue, 0), linewidth=1)

// Entry signal alerts
alertcondition(longEntryCondition, title='BUY Signal', message='Buy Entry Signal')
alertcondition(shortEntryCondition, title='SELL Signal', message='Sell Entry Signal')
alertcondition(longEntryCondition or shortEntryCondition, title='BUY or SELL Signal', message='Entry Signal')

// User Input To Enable / Disable, Either / Both Side Levels
bullishbreakout = input(true, title="Bullish Target & SL")
bearishbreakout = input(true, title="Bearish Target & SL")

// Identify High & Low for Selected Scripts
prevClose = request.security(syminfo.tickerid, "D", close[1])

is_newbar(res) => ta.change(time(res)) != 0

adopt(r, s) => request.security(syminfo.tickerid, r, s)

open_range_high = ta.valuewhen(is_newbar('D'),high,0)
open_range_low = ta.valuewhen(is_newbar('D'),low,0)

// Function to check if a candle is the 1:15 PM candle
is_115_candle() =>
hour == 13 and minute == 15

// Check if the current candle is the 1:15 PM candle
is_115_candle_current = is_115_candle()

// Plotting the candle highlight
bgcolor(is_115_candle_current ? color.new(color.blue, 80) : na)

// Marking high and low of the 1:15 PM candle
var float high_115_candle = na
var float low_115_candle = na
if is_115_candle_current and not is_115_candle_current[1]
high_115_candle := high
low_115_candle := low

// Plotting high and low of the 1:15 PM candle
plot(high_115_candle, color=color.red, style=plot.style_circles, linewidth=2)
plot(low_115_candle, color=color.green, style=plot.style_circles, linewidth=2)

//rsi
mrsi = ta.rsi(close,14)
colorRsi = mrsi>55?color.green: mrsi<45?color.red:color.gray

//ADX
len = input.int(14, minval=1, title="DI Length")
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
[diplus, diminus, adx] = ta.dmi(len, lensig)
colorADX = adx>25?color.rgb(33, 208, 243):color.gray

//creating the table
var testTable = table.new(position = position.top_right, columns = 4, rows = 2, border_width = 1, border_color = color.black, frame_width = 1, frame_color = color.black)

//column Headings
table.cell(table_id = testTable, column = 0, row = 0, text = " RSI ", bgcolor=color.aqua, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 0, text = " DI+ ", bgcolor=color.green, text_color = color.white)
table.cell(table_id = testTable, column = 2, row = 0, text = " DI- ", bgcolor=color.red, text_color = color.white)
table.cell(table_id = testTable, column = 3, row = 0, text = " ADX ", bgcolor=color.aqua, text_color = color.white)

//column values
table.cell(table_id = testTable, column = 0, row = 1, text = str.tostring(math.round(mrsi,0)) , bgcolor= color.aqua, text_color = color.white)
table.cell(table_id = testTable, column = 1, row = 1, text = str.tostring(math.round(diplus,0)) , bgcolor= color.green, text_color = color.white)// "RSI")//, bgcolor=color.red)
table.cell(table_id = testTable, column = 2, row = 1, text = str.tostring(math.round(diminus,0)) , bgcolor= color.red, text_color = color.white)// "DI+")//, bgcolor=color.red)
table.cell(table_id = testTable, column = 3, row = 1, text = str.tostring(math.round(adx,0)) , bgcolor= color.aqua, text_color = color.white)//"DI-")//, bgcolor=color.red)

// SmartMoneyConcept

string visual = "➞ Visuals Settings🔸"
string core = "➞ Main Core Settings 🔸"
int atrLen = 30
float mult = 0.3
float per = 10.0
float perc = close * (per/100)
float srdatr = ta.atr (atrLen) * mult
float band = math.min (srdatr, perc) [20] /2
int sync = bar_index
var BINDEX = 0
var line [] Lines = array.new_line()
var label [] Labels = array.new_label()
float [] TotalVolume = array.new_float()
float [] Greenvolume = array.new_float()
float [] redvolume = array.new_float()
var ph = float(na)
var phL = int(na)
var pl = float(na)
float lowestValue = low
float HighValue = high
float Midhigh = high
float Midindex = bar_index
int lowestIndex = bar_index
int HighIndex = bar_index
float HH = low
int prd = input.int(30,"period",group = core)
int levs = input.int(24,"Volume Levels",tooltip = "Number of the Volume levels to check", group = core)
bool ShowVolume = input.bool(true,"Show Volume ❓  ",inline = "01",group = visual)
bool randomcolor = input.bool(false,"Random Coloring ❓  ",inline = "01",group = visual)
color Bull = input.color(color.new(#42f07f, 35),"1st",inline = "01",group = visual)
color Bear = input.color(color.new(#f37451, 70),"2nd",inline = "01",group = visual)
bool Showlines = input.bool(true,"Show Zigzag ❓    ",inline = "02",group = visual)
bool randomcolor1 = input.bool(false,"Random Coloring ❓  ",inline = "02",group = visual)
color LineZ = input.color(color.yellow,"",inline = "02",group = visual)


//~~~~~~~~~}

// ~~ Pivots {
pvtHi = ta.pivothigh(high,prd,prd)
pvtLo = ta.pivotlow(low,prd,prd)
if pvtHi
ph := high[prd]
phL:= sync[prd]

if pvtLo
pl:=low[prd]

Points = array.new_float(2,0)
Counter(lev,sup = true)=>

if sup
for i = 0 to 2000
max_bars_back(low,2000)
if low[ i + 1 ] < lev and lev < close
array.set(Points,0,array.get(Points,0)+1)
Points.get(0)

else
for i = 0 to 2000
max_bars_back(high,2000)
if high[ i + 1 ] > lev and lev > close
array.set(Points,1,array.get(Points,1)+1)
Points.get(1)

if barstate.islast

Count = (bar_index - phL)
// levs= math.floor(Count/3)
// levs= math.floor(24)
float [] VPlevels = array.new_float(levs+1)
var box [] VPboxes = array.new_box(levs+3)
var box [] VPboxes2 = array.new_box(levs+3)
int [] ticks = array.new_int(levs,0)
float [] Volumes = array.new_float(levs,0.0)
float [] SCR = array.new_float()

for i = 0 to Count
SCR.push(close)

for i = 1 to Count
if low <= lowestValue
lowestValue := low
lowestIndex := bar_index

if high >= HighValue
HighValue := high
HighIndex := bar_index
//
// M = bar_index + 135
// CC = int( (M - lowestIndex) / 2) s
Value = Counter(pl)
Value2 = Counter(HighValue,false)
max_bars_back(Value,2000)
max_bars_back(Value2,2000)
for i = 1 to 20
if high >= Midhigh
Midhigh := high
Midindex := bar_index

step = ( HighValue-lowestValue ) / levs
for i=0 to levs by 1
array.set(VPlevels,i, lowestValue + step * i)


Col=color.rgb(math.random(10,200),math.random(10,160),math.random(10,180))
Gcolo = color.rgb(math.random(25,32),math.random(40,200),math.random(15,100))

//color.rgb(9, 155, 99, 90)
var box BOX1 = na , box.delete(BOX1)
var box BOX2 = na , box.delete(BOX2)
LA = sync - HighIndex
labelplace = (170 + LA ) / 2
BOX1:=box.new(lowestIndex,lowestValue+ (band* 2),bar_index+170,lowestValue,bgcolor = color.rgb(9, 155, 99, 90),border_color = color.rgb(9, 155, 99, 50))
BOX2:=box.new(HighIndex,HighValue + (band* 2),bar_index+170,HighValue,bgcolor = color.rgb(255, 4, 4, 90) ,border_color = color.rgb(255, 4, 4, 50))
Labels.push(label.new(lowestIndex ,lowestValue - (band * 13),str.tostring(Value),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
Labels.push(label.new(bar_index+135 ,lowestValue - (band * 13),str.tostring(Value + 1),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))
Labels.push(label.new(HighIndex + labelplace ,HighValue + (band * 10),str.tostring(Value2),style = label.style_none,textcolor= color.white,color = color.new(color.black, 100),xloc=xloc.bar_index,size= size.large))

if Showlines

// 2
Lines.push(line.new(HighIndex,HighValue,lowestIndex + 50,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(HighIndex + 2 ,HighValue,lowestIndex + 52,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))

// 3
Lines.push(line.new(lowestIndex + 50,lowestValue+ (band* 2),HighIndex + (labelplace-2) ,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(lowestIndex + 52,lowestValue+ (band* 2),HighIndex + labelplace,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
// 4
Lines.push(line.new(HighIndex + (labelplace-2),HighValue,bar_index+133,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(HighIndex + labelplace,HighValue,bar_index+135,lowestValue+ (band* 2),color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))

Lines.push(line.new(bar_index+135,lowestValue+ (band* 2),bar_index+170,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))
Lines.push(line.new(bar_index+133,lowestValue+ (band* 2),bar_index+168,HighValue,color = randomcolor1 ? Col : LineZ,width = 1,style = line.style_dashed,xloc=xloc.bar_index))


if array.size(Lines) > 8
for i = 0 to 7
line.delete(Lines.shift())



if array.size(Labels) > 3
for i = 0 to 2
label.delete(Labels.shift())

for i=0 to array.size(SCR) -1
for x=0 to array.size(VPlevels) - 2 by 1
if low[ i + 1 ] < array.get(VPlevels,x+1) and array.get(VPlevels,x) < close
array.set(ticks,x,array.get(ticks,x)+1)
array.set(Volumes,x,array.get(Volumes,x)+Counter(close[x]))
break

// label.new(bar_index+20 , low , str.tostring(ticks.size()))
if ShowVolume
for i = 0 to array.size(ticks) -2
box.delete(array.get(VPboxes,i))
array.set(VPboxes,i,
box.new(sync + 170+array.get(ticks,i),
array.get(VPlevels,i+1)+(band* 2),
sync + 170,
array.get(VPlevels,i)+(band* 2),
border_color = color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Col : Bull , 70),
color.new(randomcolor ? Col : Bull , 35)),
bgcolor=color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Col : Bull , 70),
color.new(randomcolor ? Col : Bull , 35)),
text=array.get(Volumes,i) > 0 ? str.tostring(array.get(Volumes,i),format.volume): "",
text_color=color.white))

for i = 0 to array.size(ticks) -2
box.delete(array.get(VPboxes2,i))
array.set(VPboxes2,i,
box.new(sync + 170-array.get(ticks,i),
array.get(VPlevels,i+1)+(band* 2),
sync + 170,
array.get(VPlevels,i)+(band* 2),
border_color = color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Gcolo : Bear , 70),
color.new(randomcolor ? Gcolo : Bear , 35)),
bgcolor=color.from_gradient(array.get(ticks,i),0,
array.max(ticks),
color.new(randomcolor ? Gcolo : Bear , 70),
color.new(randomcolor ? Gcolo : Bear , 35)),
text=str.tostring(array.get(ticks,i)),
text_color=color.white))
// )


// AutoFibExtension

depthTooltip = "The minimum number of bars that will be taken into account when calculating the indicator."
depth = input.int(title="Depth", defval=10, minval=2, inline = "Pivots", tooltip=depthTooltip)
reverse = input(false, "Reverse", display = display.data_window)
var extendLeft = input(false, "Extend Left    |    Extend Right", inline = "Extend Lines", display = display.data_window)
var extendRight = input(true, "", inline = "Extend Lines", display = display.data_window)
var extending = extend.none
if extendLeft and extendRight
extending := extend.both
if extendLeft and not extendRight
extending := extend.left
if not extendLeft and extendRight
extending := extend.right
prices = input(true, "Show Prices", display = display.data_window)
levels = input(true, "Show Levels", inline = "Levels", display = display.data_window)
levelsFormat = input.string("Values", "", options = ["Values", "Percent"], inline = "Levels", display = display.data_window)
labelsPosition = input.string("Left", "Labels Position", options = ["Left", "Right"], display = display.data_window)
backgroundTransparency = input.int(85, "Background Transparency", minval = 0, maxval = 100, display = display.data_window)

upperThreshold = 0.236
lowerThreshold = 1.0

import TradingView/ZigZag/7 as zigzag

pivots(src, length, isHigh) =>
if bar_index >= length
price = nz(src[length])
found = true
for i = 0 to length * 2
if (isHigh and src > price) or (not isHigh and src < price)
found := false
break
if found
chart.point.from_time(time[length], price)

update()=>
var line lineLastHL = na
var line lineLastLH = na
var line lineLast = na

var chart.point[] pivotsH = array.new<chart.point>()
var chart.point lastH = na
var chart.point[] pivotsL = array.new<chart.point>()
var chart.point lastL = na

var isHighLast = false
var float startPrice = na
var float endPrice = na

H = pivots(high, depth / 2, true)
L = pivots(low, depth / 2, false)

countPivotsH = array.size(pivotsH)
countPivotsL = array.size(pivotsL)

if countPivotsH > 0 and countPivotsL > 0
lastH := array.get(pivotsH, countPivotsH-1)
lastL := array.get(pivotsL, countPivotsL-1)
isHighLast := lastH.time > lastL.time
if isHighLast
if not na(H)
if H.price > lastH.price
array.set(pivotsH, countPivotsH-1, H)
H := na
else
if not na(L)
if L.price < lastL.price
array.set(pivotsL, countPivotsL-1, L)
L := na

if not na(H)
array.push(pivotsH, H)

if not na(L)
array.push(pivotsL, L)

if barstate.islast and array.size(pivotsH) > 0 and array.size(pivotsL) > 0
pivotsHCopy = array.copy(pivotsH)
pivotsLCopy = array.copy(pivotsL)
while array.size(pivotsHCopy) > 0 and array.size(pivotsLCopy) > 0
lastH := array.pop(pivotsHCopy)
lastL := array.pop(pivotsLCopy)

isHighLast := lastH.time > lastL.time
pivots = isHighLast ? pivotsHCopy : pivotsLCopy

for i = array.size(pivots)-1 to 0
if i < 0
break
p = array.get(pivots, i)
if p.time < lastL.time
break
betterPrice = isHighLast ? p.price > lastH.price : p.price < lastL.price
if p.price > lastH.price
lastH := array.pop(pivots)
else
array.remove(pivots, i)

if array.size(pivotsHCopy) == 0 or array.size(pivotsLCopy) == 0
break

isHighLast := lastH.time > lastL.time
pivots := isHighLast ? pivotsHCopy : pivotsLCopy

prevPivot = array.get(pivots, array.size(pivots)-1)
startPrice := prevPivot.price

if isHighLast
endPrice := lastL.price
diff = math.abs(startPrice - endPrice)
if lastH.price > endPrice + diff * lowerThreshold or lastH.price < endPrice + diff * upperThreshold
array.push(pivotsLCopy, lastL)
continue
line.delete(lineLastHL)
line.delete(lineLastLH)
lineLastHL := line.new(prevPivot, lastL, color=color.red, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLastLH := line.new(lastL, lastH, color=color.green, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLast := lineLastLH
else
endPrice := lastH.price
diff = math.abs(startPrice - endPrice)
if lastL.price < endPrice - diff * lowerThreshold or lastL.price > endPrice - diff * upperThreshold
array.push(pivotsHCopy, lastH)
continue
line.delete(lineLastHL)
line.delete(lineLastLH)
lineLastLH := line.new(prevPivot, lastH, color=color.red, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLastHL := line.new(lastH, lastL, color=color.green, width=1, style=line.style_dashed, xloc = xloc.bar_time)
lineLast := lineLastHL
break
diff = (isHighLast ? -1 : 1) * math.abs(startPrice - endPrice)
offset = isHighLast ? line.get_y1(lineLastLH) - line.get_y2(lineLastLH) : line.get_y1(lineLastHL) - line.get_y2(lineLastHL)
offset := (isHighLast ? -1 : 1) * math.abs(offset)
[endPrice - offset, diff, lineLast]

[endPrice, diff, lineLast] = update()

_draw_line(price, col) =>
var id = line.new(time, price, time, price, color=col, width=1, extend=extending, xloc = xloc.bar_time)
if not na(lineLast)
line.set_xy1(id, line.get_x1(lineLast), price)
line.set_xy2(id, line.get_x2(lineLast), price)
id

_draw_label(price, txt, txtColor) =>
if not na(price)
x = labelsPosition == "Left" ? line.get_x1(lineLast) : not extendRight ? line.get_x2(lineLast) : time
labelStyle = labelsPosition == "Left" ? label.style_label_right : label.style_label_left
align = labelsPosition == "Left" ? text.align_right : text.align_left
labelsAlignStrLeft = txt + '\n ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ \n'
labelsAlignStrRight = ' ' + txt + '\n ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ ‏ \n'
labelsAlignStr = labelsPosition == "Left" ? labelsAlignStrLeft : labelsAlignStrRight
var id = label.new(x=x, y=price, text=labelsAlignStr, textcolor=txtColor, style=labelStyle, textalign=align, color=#00000000, xloc = xloc.bar_time)
label.set_xy(id, x, price)
label.set_text(id, labelsAlignStr)
label.set_textcolor(id, txtColor)

_wrap(txt) =>
"(" + str.tostring(txt, format.mintick) + ")"

_label_txt(level, price) =>
if not na(price)
l = levelsFormat == "Values" ? str.tostring(level) : str.tostring(level * 100) + "%"
(levels ? l : "") + (prices ? _wrap(price) : "")

_crossing_level(sr, r) =>
(r > sr and r < sr[1]) or (r < sr and r > sr[1])


processLevel(show, value, colorL, lineIdOther) =>
float m = value
r = endPrice + ((reverse ? -1 : 1) * diff * m)
if show
lineId = _draw_line(r, colorL)
_draw_label(r, _label_txt(m, r), colorL)
if _crossing_level(close, r)
alert("Autofib: " + syminfo.ticker + " crossing level " + str.tostring(value))
if not na(lineIdOther)
linefill.new(lineId, lineIdOther, color = color.new(colorL, backgroundTransparency))
lineId
else
lineIdOther

show_0 = input(true, "", inline = "Level0", display = display.data_window)
value_0 = input(0, "", inline = "Level0", display = display.data_window)
color_0 = input(#787b86, "", inline = "Level0", display = display.data_window)

show_0_236 = input(true, "", inline = "Level0", display = display.data_window)
value_0_236 = input(0.236, "", inline = "Level0", display = display.data_window)
color_0_236 = input(#f44336, "", inline = "Level0", display = display.data_window)

show_0_382 = input(true, "", inline = "Level1", display = display.data_window)
value_0_382 = input(0.382, "", inline = "Level1", display = display.data_window)
color_0_382 = input(#81c784, "", inline = "Level1", display = display.data_window)

show_0_5 = input(true, "", inline = "Level1", display = display.data_window)
value_0_5 = input(0.5, "", inline = "Level1", display = display.data_window)
color_0_5 = input(#4caf50, "", inline = "Level1", display = display.data_window)

show_0_618 = input(true, "", inline = "Level2", display = display.data_window)
value_0_618 = input(0.618, "", inline = "Level2", display = display.data_window)
color_0_618 = input(#009688, "", inline = "Level2", display = display.data_window)

show_0_65 = input(false, "", inline = "Level2", display = display.data_window)
value_0_65 = input(0.65, "", inline = "Level2", display = display.data_window)
color_0_65 = input(#009688, "", inline = "Level2", display = display.data_window)

show_0_786 = input(true, "", inline = "Level3", display = display.data_window)
value_0_786 = input(0.786, "", inline = "Level3", display = display.data_window)
color_0_786 = input(#64b5f6, "", inline = "Level3", display = display.data_window)

show_1 = input(true, "", inline = "Level3", display = display.data_window)
value_1 = input(1, "", inline = "Level3", display = display.data_window)
color_1 = input(#787b86, "", inline = "Level3", display = display.data_window)

show_1_272 = input(false, "", inline = "Level4", display = display.data_window)
value_1_272 = input(1.272, "", inline = "Level4", display = display.data_window)
color_1_272 = input(#81c784, "", inline = "Level4", display = display.data_window)

show_1_414 = input(false, "", inline = "Level4", display = display.data_window)
value_1_414 = input(1.414, "", inline = "Level4", display = display.data_window)
color_1_414 = input(#f44336, "", inline = "Level4", display = display.data_window)

show_1_618 = input(true, "", inline = "Level5", display = display.data_window)
value_1_618 = input(1.618, "", inline = "Level5", display = display.data_window)
color_1_618 = input(#2962ff, "", inline = "Level5", display = display.data_window)

show_1_65 = input(false, "", inline = "Level5", display = display.data_window)
value_1_65 = input(1.65, "", inline = "Level5", display = display.data_window)
color_1_65 = input(#2962ff, "", inline = "Level5", display = display.data_window)

show_2_618 = input(true, "", inline = "Level6", display = display.data_window)
value_2_618 = input(2.618, "", inline = "Level6", display = display.data_window)
color_2_618 = input(#f44336, "", inline = "Level6", display = display.data_window)

show_2_65 = input(false, "", inline = "Level6", display = display.data_window)
value_2_65 = input(2.65, "", inline = "Level6", display = display.data_window)
color_2_65 = input(#f44336, "", inline = "Level6", display = display.data_window)

show_3_618 = input(true, "", inline = "Level7", display = display.data_window)
value_3_618 = input(3.618, "", inline = "Level7", display = display.data_window)
color_3_618 = input(#9c27b0, "", inline = "Level7", display = display.data_window)

show_3_65 = input(false, "", inline = "Level7", display = display.data_window)
value_3_65 = input(3.65, "", inline = "Level7", display = display.data_window)
color_3_65 = input(#9c27b0, "", inline = "Level7", display = display.data_window)

show_4_236 = input(true, "", inline = "Level8", display = display.data_window)
value_4_236 = input(4.236, "", inline = "Level8", display = display.data_window)
color_4_236 = input(#e91e63, "", inline = "Level8", display = display.data_window)

show_4_618 = input(false, "", inline = "Level8", display = display.data_window)
value_4_618 = input(4.618, "", inline = "Level8", display = display.data_window)
color_4_618 = input(#81c784, "", inline = "Level8", display = display.data_window)

show_neg_0_236 = input(false, "", inline = "Level9", display = display.data_window)
value_neg_0_236 = input(-0.236, "", inline = "Level9", display = display.data_window)
color_neg_0_236 = input(#f44336, "", inline = "Level9", display = display.data_window)

show_neg_0_382 = input(false, "", inline = "Level9", display = display.data_window)
value_neg_0_382 = input(-0.382, "", inline = "Level9", display = display.data_window)
color_neg_0_382 = input(#81c784, "", inline = "Level9", display = display.data_window)

show_neg_0_618 = input(false, "", inline = "Level10", display = display.data_window)
value_neg_0_618 = input(-0.618, "", inline = "Level10", display = display.data_window)
color_neg_0_618 = input(#009688, "", inline = "Level10", display = display.data_window)

show_neg_0_65 = input(false, "", inline = "Level10", display = display.data_window)
value_neg_0_65 = input(-0.65, "", inline = "Level10", display = display.data_window)
color_neg_0_65 = input(#009688, "", inline = "Level10", display = display.data_window)


lineId0 = processLevel(show_neg_0_65, value_neg_0_65, color_neg_0_65, line(na))
lineId1 = processLevel(show_neg_0_618, value_neg_0_618, color_neg_0_618, lineId0)
lineId2 = processLevel(show_neg_0_382, value_neg_0_382, color_neg_0_382, lineId1)
lineId3 = processLevel(show_neg_0_236, value_neg_0_236, color_neg_0_236, lineId2)
lineId4 = processLevel(show_0, value_0, color_0, lineId3)
lineId5 = processLevel(show_0_236, value_0_236, color_0_236, lineId4)
lineId6 = processLevel(show_0_382, value_0_382, color_0_382, lineId5)
lineId7 = processLevel(show_0_5, value_0_5, color_0_5, lineId6)
lineId8 = processLevel(show_0_618, value_0_618, color_0_618, lineId7)
lineId9 = processLevel(show_0_65, value_0_65, color_0_65, lineId8)
lineId10 = processLevel(show_0_786, value_0_786, color_0_786, lineId9)
lineId11 = processLevel(show_1, value_1, color_1, lineId10)
lineId12 = processLevel(show_1_272, value_1_272, color_1_272, lineId11)
lineId13 = processLevel(show_1_414, value_1_414, color_1_414, lineId12)
lineId14 = processLevel(show_1_618, value_1_618, color_1_618, lineId13)
lineId15 = processLevel(show_1_65, value_1_65, color_1_65, lineId14)
lineId16 = processLevel(show_2_618, value_2_618, color_2_618, lineId15)
lineId17 = processLevel(show_2_65, value_2_65, color_2_65, lineId16)
lineId18 = processLevel(show_3_618, value_3_618, color_3_618, lineId17)
lineId19 = processLevel(show_3_65, value_3_65, color_3_65, lineId18)
lineId20 = processLevel(show_4_236, value_4_236, color_4_236, lineId19)
lineId21 = processLevel(show_4_618, value_4_618, color_4_618, lineId20)

//=====Inputs
//____Source Inputs allowing for non-price inputs such as an oscillator
hi_ = input.source(high,"High variable input",inline="source",group="Source")
lo_ = input.source(low,"Low variable input",inline="source",group="Source")
track_var = input.source(hlc3,title="Value to use to locate levels",group="Source")

//____Presentation related inputs
bool use_vis = input.bool(false,"Use Visible range",tooltip="Limit lines drawn to the pane visible range",group="Pivots",inline="p0")
bool use_fibs = input.bool(false,"Use Fibs vs Divide by 2",tooltip="Fibs Used: 0.236, 0.382, 0.5, 0.618, 0.786",group="Pivots",inline="p0")
int layer_to_show = input.int(2,"Layers",minval=0,maxval=10,group="Pivots",tooltip="Increasing will further subdivid the range")-1
int offset_lastbar = input.int(defval=5,minval=0,maxval=300,title="Offset to last bar",group="Pivots",inline="p1")
int l_len = input.int(50,"Root layer length",group="Pivots",inline="p1",tooltip="Higher level lengths will be a multiple>1 of this length")
bool show_labels = input.bool(false,title="Show Labels",group="Labels",inline="lbl1")
bool label_info = input.bool(false,"Show value vs ratio",group="Labels",inline="lbl1")
int label_layer_lim = input.int(2,title="Layer limit",group="Labels",inline="lbl2")
bool show_only_50 = input.bool(false,"Show mid_points for layers above limit ",group="Labels",inline="lbl2")
string label_location = input.string("Center",title="Location",options=["Left","Center","Right"],group="Labels",inline="lbl3")
string label_string = input.string("Center",title="Orientation",options=["Center","Above","Below"],group="Labels",inline="lbl3")
string label_txt_size = input.string('Normal',"Text Size",options=['Tiny','Small','Normal','Large'],group="Labels",inline="lbl3")

//==== UDTs and Methods

//___ Detailed layer UDT - a wrapper for a map
type level
map <float,float> level_data

//____ Pivot UDT
type cPivot
bool recalc = false
bool show_labels = false
bool label_info = false
bool new_variable_location = false
int line_length = 0
int label_offset = 0
int label_limit = 0
float layer_mult = 0
float current_top
float current_bot
string label_txt_size = size.auto
string label_style
string label_loc
map <int,level> level_groups
map <float,color> level_color
map <float,string> level_label
array <line> lines_
array <label> labels_

// Function Finds levels by drilling down and iterating to desired layer
// param this (cPivot) UDT for the pivots
// param hi (float) high value variable
// param lo (float) low value variable
// param tracking_x (float) value to be used to find levels in proximity
// param layer (int) drill down layer
// Returns (void) all maps stored in UDT
method get_levels(cPivot this,float hi,float lo,float tracking_x_, int layer)=>
var Max_H=0.
var Min_L=10E10
[htf_max, htf_min]=request.security(syminfo.tickerid,"W",[nz(ta.max(hi_),hi_),nz(ta.min(lo_),lo_)],lookahead=barmerge.lookahead_off)
Max_H := math.max(Max_H,nz(htf_max,hi_),hi_)
Min_L := math.min(Min_L,nz(htf_min,lo_),lo_)
change_high = nz(ta.change(Max_H))!=0
change_low = nz(ta.change(Min_L))!=0

this.recalc := change_low or change_high or bar_index==120
top_line =0.
bot_line =0.

//__If the bar_index==120 to avoid potential issues with a range of 0 at bar_index==0
//__or if there is a change in the ATH or ATL
if this.recalc
this.level_groups.clear()
one_before_levels=map.new<float,float>()

for i=0 to layer
new_levels = map.new<float,float>()

if i==0
top_line := Max_H
bot_line := Min_L
else
levels_array = one_before_levels.values()
for [idx,level_] in levels_array

if tracking_x_>= level_
bot_line := level_
if idx>0
top_line := levels_array.get(idx-1)
else
top_line := levels_array.get(idx)
break

range_ = top_line - bot_line
key_array = this.level_color.keys()

for fib_ratio in key_array
level_calc = math.round_to_mintick(bot_line+fib_ratio*(range_))
new_levels.put(fib_ratio,level_calc)

this.level_groups.put(i,level.new(new_levels))
one_before_levels := new_levels.copy()


this.current_top := top_line
this.current_bot := bot_line
this.new_variable_location := true
// end recalc

//Check if the tracking_x location changed to a different map and if it did then redo the lower layer maps
this.new_variable_location := (tracking_x_> this.current_top or tracking_x_< this.current_bot)

// only refresh levels if the variable location change requires it
if not(this.recalc) and this.new_variable_location and bar_index>120
one_before_levels = this.level_groups.get(0).level_data.copy()
this.level_groups.clear()
this.level_groups.put(0,level.new(one_before_levels))

for i=1 to layer
new_levels = map.new<float,float>()
levels_array= one_before_levels.values()
for [idx,level_] in levels_array
if tracking_x_>= level_
bot_line := level_
if idx>0
top_line := levels_array.get(idx-1)
else
top_line := levels_array.get(idx)
break

range_ = top_line - bot_line
key_array = this.level_color.keys()

for fib_ratio in key_array
level_calc = math.round_to_mintick(bot_line+fib_ratio*(range_))
new_levels.put(fib_ratio,level_calc)

this.level_groups.put(i,level.new(new_levels))

if i<layer
one_before_levels := new_levels.copy()

this.current_top := top_line
this.current_bot := bot_line

// Function Method used for presentation, drawing lines and labels
// param this (cPivot) UDT for the pivots
// param layer (int) drill down layer
// Returns (void) all drawing objects stored in UDT arrays
method draw_pivots(cPivot this,int layer,vis_hi,vis_lo,vis_range_off)=>
//Refresh lines and labels if either ATH/ATL changed or teh variable location moved to a new zone
if bar_index>120 and (this.recalc or this.new_variable_location)
label_map=map.new<float,int>()
label_map.clear()

for element in this.lines_
line.delete(element)
for element in this.labels_
label.delete(element)

this.lines_.clear()
this.labels_.clear()
for i=0 to layer
j= layer - i

layer_adj = (1+ i* this.layer_mult)
x1_offset = math.round(this.line_length*layer_adj)
x1_coord = math.max(0,bar_index- x1_offset)

lab_layer = (1+ j* this.layer_mult)
x1_lab_offset= math.round(this.line_length*lab_layer)
x1_lab_coord = math.max(0,bar_index-x1_lab_offset)

x2_coord = bar_index+this.label_offset
ln_width = layer-j

x2_lab_coord = switch this.label_loc
"Right" => x2_coord+ math.round(this.label_offset*lab_layer)
"Left" => x1_lab_coord
"Center" => x1_lab_coord+ int(x1_lab_offset/2)

lvl_str = "L"+str.tostring(i+1)+": "

// Label drawing
if this.show_labels
for key_ in this.level_groups.get(i).level_data.keys()
element = this.level_groups.get(i).level_data.get(key_)
text_ = this.label_info? str.tostring(math.round_to_mintick(element)): this.level_label.get(key_)
conditions_ = (i+1<= this.label_limit or (i+1> this.label_limit and show_only_50 and key_==0.5)) and (element>= 0.98*vis_lo and element<=1.02*vis_hi or vis_range_off)
if na(label_map.get(element)) and conditions_
this.labels_.push(label.new(x2_lab_coord,element,text=lvl_str+text_,color=this.level_color.get(key_), textcolor=color.black,style=this.label_style,size=this.label_txt_size))
label_map.put(element,1)

// Line drawing
for key_ in this.level_groups.get(j).level_data.keys()
element = this.level_groups.get(j).level_data.get(key_)
if (element>= 0.98*vis_lo and element<=1.02*vis_hi) or vis_range_off
this.lines_.push(line.new(x1_coord,element,x2_coord,element,color=this.level_color.get(key_),width=ln_width))

//Only update the x coordinate if the levels have not changed or the variabel did not force a change
if bar_index>120 and not(this.recalc) and not(this.new_variable_location)
if this.show_labels
for label_ in this.labels_
label_.set_x(label_.get_x()+1)

// Line drawing
for line_ in this.lines_
line_.set_x1(line_.get_x1()+1)
line_.set_x2(line_.get_x2()+1)

//==== Execution
var clone_pivot = cPivot.new(label_limit=label_layer_lim,label_loc=label_location,label_info=label_info, show_labels=show_labels, level_color=map.new<float,color>(), level_label=map.new<float,string>(), level_groups =map.new<int,level>(),lines_=array.new<line>(),labels_=array.new<label>(), layer_mult=1.25,label_offset=offset_lastbar, line_length=l_len)

//___One time bar index at 0 execution and setup.
if bar_index==0
clone_pivot.label_txt_size := switch label_txt_size
"Tiny" => size.tiny
"Small" => size.small
"Normal"=> size.normal
"Large" => size.large
=> size.auto

clone_pivot.label_style := switch label_location
"Right"=>
switch label_string
"Center" => label.style_label_left
"Above" => label.style_label_lower_left
"Below" => label.style_label_upper_left
"Center"=>
switch label_string
"Center" => label.style_label_center
"Above" => label.style_label_down
"Below" => label.style_label_up
"Left"=>
switch label_string
"Center" => label.style_label_right
"Above" => label.style_label_lower_right
"Below" => label.style_label_upper_right

//maps are not ordered but we will put (or push in array terms) the ratios in
//descending order since in the method it will be needed in that order
if use_fibs
clone_pivot.level_color.put(1.0,color.white)
clone_pivot.level_color.put(0.7864,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0.618,color.silver)
clone_pivot.level_color.put(0.5,color.yellow)
clone_pivot.level_color.put(0.382,color.silver)
clone_pivot.level_color.put(0.236,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0,color.white)

clone_pivot.level_label.put(1.0,'top')
clone_pivot.level_label.put(0.7864,'0.786')
clone_pivot.level_label.put(0.618,'0.618')
clone_pivot.level_label.put(0.5,'0.5')
clone_pivot.level_label.put(0.382,'0.386')
clone_pivot.level_label.put(0.236,'0.236')
clone_pivot.level_label.put(0,'bot')

else
clone_pivot.level_color.put(1.0,color.white)
clone_pivot.level_color.put(0.75,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0.5,color.yellow)
clone_pivot.level_color.put(0.25,color.rgb(138, 141, 151))
clone_pivot.level_color.put(0,color.white)

clone_pivot.level_label.put(1.0,'top')
clone_pivot.level_label.put(0.75,'0.75')
clone_pivot.level_label.put(0.5,'0.5')
clone_pivot.level_label.put(0.25,'0.25')
clone_pivot.level_label.put(0.,'bot')


//=== Get visible chart information to limit what is drawn
visible_bars = (chart.right_visible_bar_time - chart.left_visible_bar_time)/(1000*timeframe.in_seconds())

if bar_index==0
visible_bars:= 3000

max_hi = nz(ta.highest(visible_bars,3000),hi_)
min_lo = nz(ta.lowest(visible_bars,3000),lo_)
visible_hi = nz(ta.highest(hi_, visible_bars),max_hi)
visible_lo = nz(ta.lowest(lo_, visible_bars),min_lo)


//___ Method calls on each bar
clone_pivot.get_levels(hi_,lo_,track_var,layer_to_show)
clone_pivot.draw_pivots(layer_to_show,visible_hi,visible_lo,not(use_vis))

// While it seemed like a nice idea at the time, having separately-configurable upper and lower bands just doesn't really seem that useful as 90% of the time the settings for both are the same.
// Therefore, We're going to simplify the config to make these settings unified for both bands, as it would otherwise just add even more confusion with the addition of take-profit bands as well...
//
// atrMultiplierUpper = input.float(title='ATR Upper Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Upper Band Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
// "This will usually be between 1 and 3.")
// srcUpper = input.source(title='ATR Upper Offset Source', defval=close, group="ATR Upper Band Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "For this band, 'high' and 'close' (default) are generally the most appropriate values.")
//
atrMultiplier = input.float(title='ATR Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Bands Standard Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
"This will usually be between 1 and 3.\n\nDefault: 2.5")
// On second thought, I'm going to nix this setting and force it to be the "close" source. Having the ability to offset based on the wicks was a nice idea, but doesn't really seem to have any notable practical application.
atrSourceRef = "close"
//atrSourceRef = input.string(title='ATR Upper Offset Source', defval="close", options=["close","wicks"], group="ATR Bands Standard Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "The default value 'close' should be your go-to, but 'wicks' might provide a bit more breathing room in securities that tend to have large wicks.")
//
// See above - these are deprecated and no longer used...
//
// atrMultiplierLower = input.float(title='ATR Lower Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Lower Band Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
// "This will usually be between 1 and 3.")
// srcLower = input.source(title='ATR Lower Offset Source', defval=close, group="ATR Lower Band Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "For this band, 'low' and 'close' (default) are generally the most appropriate values.")
//
//
// Take-Profit band settings
showTPBands = input.bool(title="Show opposite bands for take-profit zones", defval=false, tooltip="If enalbled, the existing ATR bands will be treated as 'stop-loss' bands, and 'take-profit' bands will be plotted " +
"to depict potential take-profit targets that are scaled based on the 'stop-loss' band and an additional reward/risk scaling factor (see below).\n\nDefault: Unchecked", group="Take-Profit Settings")
tpScaleFactor = input.float(title="Take-Profit Scale Factor", defval=1.5, minval=1, step=0.1, tooltip="This is a secondary scaling factor used based on the 'stop-loss' ATR bands to calculate and plot a potential take-profit target.\n\n" +
"The easiest way to think of this is as a desired reward/risk ratio, where the primary ATR Bands
Bands and Channels

Skrip open-source

Dengan semangat TradingView yang sesungguhnya, penulis skrip ini telah menerbitkannya sebagai sumber terbuka, sehingga para trader dapat memahami dan memverifikasinya. Hormat untuk penulisnya! Anda dapat menggunakannya secara gratis, namun penggunaan kembali kode ini dalam publikasi diatur oleh Tata Tertib. Anda dapat memfavoritkannya untuk digunakan pada chart

Inggin menggunakan skrip ini pada chart?

Pernyataan Penyangkalan