Nothing Special   »   [go: up one dir, main page]

DynReg EMA Levels SMART DIV - STR Alpha

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 36

//Base source is cloned from built-in technicals - "Linear Regression Channel", v26

//@version=5
indicator("DynReg-EMA-levels-SMART-DIV_STR-Alpha", overlay=true,
max_lines_count=500, max_boxes_count=500, max_bars_back = 500, max_labels_count =
500)

upperMultInput = input.float(2.0, title="Upper Deviation", inline = "Upper


Deviation")
colorUpper = input.color(color.new(color.blue, 85), "", inline = "Upper Deviation")
lowerMultInput = input.float(2.0, title="Lower Deviation", inline = "Lower
Deviation")
colorLower = input.color(color.new(color.red, 85), "", inline = "Lower Deviation")

calcSlope(source, length) =>


max_bars_back(source, 5000)
if barstate.isfirst or length <= 1
[float(na), float(na), float(na)]
else
sumX = 0.0
sumY = 0.0
sumXSqr = 0.0
sumXY = 0.0
for i = 0 to length - 1 by 1
val = source[i]
per = i + 1.0
sumX += per
sumY += val
sumXSqr += per * per
sumXY += val * per
slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
average = sumY / length
intercept = average - slope * sumX / length + slope
[slope, average, intercept]

var start_index = 1
lengthInput = bar_index - start_index + 1
[s, a, i] = calcSlope(close, lengthInput)
startPrice = i + s * (lengthInput - 1)
endPrice = i

calcDev(source, length, slope, average, intercept) =>


if barstate.isfirst or length <= 1
[float(na), float(na), float(na), float(na)]
else
upDev = 0.0
dnDev = 0.0
stdDevAcc = 0.0
dsxx = 0.0
dsyy = 0.0
dsxy = 0.0
periods = length - 1
daY = intercept + slope * periods / 2
val = intercept
for j = 0 to periods by 1
price = high[j] - val
if price > upDev
upDev := price
price := val - low[j]
if price > dnDev
dnDev := price
price := source[j]
dxt = price - average
dyt = val - daY
price -= val
stdDevAcc += price * price
dsxx += dxt * dxt
dsyy += dyt * dyt
dsxy += dxt * dyt
val += slope
stdDev = math.sqrt(stdDevAcc / (periods == 0 ? 1 : periods))
pearsonR = dsxx == 0 or dsyy == 0 ? 0 : dsxy / math.sqrt(dsxx * dsyy)
[stdDev, pearsonR, upDev, dnDev]

[stdDev, pearsonR, upDev, dnDev] = calcDev(close, lengthInput, s, a, i)


upperStartPrice = startPrice + upperMultInput * stdDev
upperEndPrice = endPrice + upperMultInput * stdDev
lowerStartPrice = startPrice - lowerMultInput * stdDev
lowerEndPrice = endPrice - lowerMultInput * stdDev

var baseLine = line.new(na, na, na, na, width=1, color=color.new(colorLower, 0))


var upper = line.new(na, na, na, na, width=1, color=color.new(colorUpper, 0))
var lower = line.new(na, na, na, na, width=1, color=color.new(colorUpper, 0))
linefill.new(upper, baseLine, color = colorUpper)
linefill.new(baseLine, lower, color = colorLower)

if (close > upperEndPrice or close < lowerEndPrice) and (not barstate.islast or


barstate.isconfirmed)
_baseLine = line.new(bar_index - lengthInput + 1, startPrice[1], bar_index - 1,
endPrice[1], width=1, color=color.new(colorLower, 0))
_upper = line.new(bar_index - lengthInput + 1, upperStartPrice[1], bar_index -
1, upperEndPrice[1], width=1, color=color.new(colorUpper, 0))
_lower = line.new(bar_index - lengthInput + 1, lowerStartPrice[1], bar_index -
1, lowerEndPrice[1], width=1, color=color.new(colorUpper, 0))
linefill.new(_upper, _baseLine, color = colorUpper)
linefill.new(_baseLine, _lower, color = colorLower)
start_index := bar_index
else if barstate.islast
j = close > upperEndPrice or close < lowerEndPrice ? 1: 0
line.set_xy1(baseLine, bar_index - lengthInput + 1, startPrice[j])
line.set_xy2(baseLine, bar_index - j, endPrice[j])
line.set_xy1(upper, bar_index - lengthInput + 1, upperStartPrice[j])
line.set_xy2(upper, bar_index - j, upperEndPrice[j])
line.set_xy1(lower, bar_index - lengthInput + 1, lowerStartPrice[j])
line.set_xy2(lower, bar_index - j, lowerEndPrice[j])

//Multiple EMA
//indicator("Multiple EMA", overlay = true)

Lengthema1 = input.int(title = "EMA1", defval = 10, minval = 1, maxval = 500)


Lengthema2 = input.int(title = "EMA2", defval = 20, minval = 1, maxval = 500)
Lengthema3 = input.int(title = "EMA3", defval = 61, minval = 1, maxval = 500)
Lengthema4 = input.int(title = "EMA4", defval = 89, minval = 1, maxval = 500)
Lengthema5 = input.int(title = "EMA5", defval = 200, minval = 1, maxval = 500)
/// EMA INDICATOR
EMA1 = ta.ema(close,Lengthema1)
EMA2 = ta.ema(close,Lengthema2)
EMA3 = ta.ema(close,Lengthema3)
EMA4 = ta.ema(close,Lengthema4)
EMA5 = ta.ema(close,Lengthema5)

/// PLOT

plot(EMA1, color = color.new(color.green,0))


plot(EMA2, color = color.new(color.red,0))
plot(EMA3, color = color.new(color.blue,0))
plot(EMA4, color = color.new(color.yellow,0))
plot(EMA5, color = color.new(color.purple,0))

//plot(close)

// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
//@version=5
//indicator("Litt Institutional Levels", overlay = true)

instructions = input.bool(title='Instructions', defval=true, inline='1', tooltip =


"The Litt Institutional Levels Indicator plots previous timeperiods Highs, Lows,
and Closes. Institutions track these levels and will use them as support and
resistance to enter and exit
their positions. Not every algorithm is a machine-learning wizard.
Institutions still use these relatively simple levels to conduct their trades. The
best way to use The Litt Institutional Levels Indicator is to find overlapping
levels. These areas or lines are
called confluence levels and will act as a stronger level than a single
line. \n\nFor the labeling, Y stands for Yesterday and L stands for Last. For
example, LMC would equal Last Months Close. LQH, would equal Last Quarters High.
YL, would equal Yeserdays Low.")

daily_levels = input.bool(true, title = "Daily Levels", group = "Daily Levels")


daily_line_color = input.color(color.new(color.silver, 20), title = "Line Color",
group = "Daily Levels", inline = '2')
daily_text_color = input.color(color.new(color.white, 20), title = "Label Text
Color", group = "Daily Levels", inline = '2')

weekly_levels = input.bool(true, title = "Weekly Levels", group = "Weekly Levels")


weekly_line_color = input.color(color.new(color.yellow, 20), title = "Line Color",
group = "Weekly Levels", inline = '2')
weekly_text_color = input.color(color.new(color.yellow, 20), title = "Label Text
Color", group = "Weekly Levels", inline = '2')

monthly_levels = input.bool(true, title = "Monthly Levels", group = "Monthly


Levels")
monthly_line_color = input.color(color.new(color.blue, 20), title = "Line Color",
group = "Monthly Levels", inline = '2')
monthly_text_color = input.color(color.new(color.blue, 20), title = "Label Text
Color", group = "Monthly Levels", inline = '2')

qtr_levels = input.bool(true, title = "Quarterly Levels", group = "Quarterly


Levels")
qtr_line_color = input.color(color.new(color.red, 20), title = "Line Color", group
= "Quarterly Levels", inline = '2')
qtr_text_color = input.color(color.new(color.red, 20), title = "Label Text Color",
group = "Quarterly Levels", inline = '2')

yearly_levels = input.bool(true, title = "Yearly Levels", group = "Yearly Levels")


yearly_line_color = input.color(color.new(color.orange, 20), title = "Line Color",
group = "Yearly Levels", inline = '2')
yearly_text_color = input.color(color.new(color.orange, 20), title = "Label Text
Color", group = "Yearly Levels", inline = '2')

timeChange(period) =>
ta.change(time(period))

institution_function(time_period, line_color, text_color, text_text) =>

is_new_period = timeChange(time_period)

var first_bar_in_period = 0
first_bar_in_period := is_new_period ? time : first_bar_in_period[1]

highs = request.security(syminfo.tickerid,time_period, high[1],


lookahead=barmerge.lookahead_on)
lows = request.security(syminfo.tickerid,time_period, low[1],
lookahead=barmerge.lookahead_on)
closes = request.security(syminfo.tickerid,time_period, close[1],
lookahead=barmerge.lookahead_on)

high_line = line.new(first_bar_in_period, highs, time, y2 = highs, xloc =


xloc.bar_time, extend = extend.right, color = line_color, style =
line.style_dotted, width = 2)
line.delete(high_line[1])

low_line = line.new(first_bar_in_period, lows, time, y2 = lows, xloc =


xloc.bar_time, extend = extend.right, color = line_color, style =
line.style_dotted, width = 2)
line.delete(low_line[1])

close_line = line.new(first_bar_in_period, closes, time, y2 = closes, xloc =


xloc.bar_time, extend = extend.right, color = line_color, style =
line.style_dotted, width = 2)
line.delete(close_line[1])

high_label = label.new(x = bar_index + 10, y = highs, text = text_text + "H",


style = label.style_none, textcolor = text_color)
label.delete(high_label[1])

low_label = label.new(x = bar_index + 10, y = lows, text = text_text + "L",


style = label.style_none, textcolor = text_color)
label.delete(low_label[1])

close_label = label.new(x = bar_index + 10, y = closes, text = text_text + "C",


style = label.style_none, textcolor = text_color)
label.delete(close_label[1])

if daily_levels
institution_function("D",daily_line_color, daily_text_color, "Y")

if weekly_levels
institution_function("W",weekly_line_color, weekly_text_color, "LW")

if monthly_levels
institution_function("M",monthly_line_color, monthly_text_color, "LM")

if qtr_levels
institution_function("3M",qtr_line_color, qtr_text_color, "LQ")

if yearly_levels
institution_function("12M",yearly_line_color, yearly_text_color, "LY")

//TABLE
show_dashboard = input.bool(title='Color Legend', defval=true, inline='1',
group='Dashboard Settings')
LabelSize = input.string(defval='Medium', options=['Small', 'Medium', 'Large'],
title='Dashboard Size', inline='2', group='Dashboard Settings')
label_size = LabelSize == 'Small' ? size.small : LabelSize == 'Medium' ?
size.normal : LabelSize == 'Large' ? size.large : size.small
positioning = position.top_right
var table t = table.new(positioning, 5, 1,frame_color=color.new(#000000, 100),
frame_width=0, border_color=color.new(#000000,100), border_width=0)
if barstate.islast and show_dashboard

//Column 1
table.cell(t, 0, 0, text='D', width=0, bgcolor=daily_line_color,
text_color=color.white, text_size=label_size, text_halign=text.align_center)
table.cell(t, 1, 0, text='W', width=0, bgcolor=weekly_line_color,
text_color=color.white, text_size=label_size, text_halign=text.align_center)
table.cell(t, 2, 0, text='M', width=0, bgcolor=monthly_line_color,
text_color=color.white, text_size=label_size, text_halign=text.align_center)
table.cell(t, 3, 0, text='Q', width=0, bgcolor=qtr_line_color,
text_color=color.white, text_size=label_size, text_halign=text.align_center)
table.cell(t, 4, 0, text='Y', width=0, bgcolor=yearly_line_color,
text_color=color.white, text_size=label_size, text_halign=text.align_center)

// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// author © KivancOzbilgic
// developer © KivancOzbilgic
//@version=5
//indicator('AlphaTrend', shorttitle='AT', overlay=true, format=format.price,
precision=2, timeframe='')
coeff = input.float(1, 'Multiplier', step=0.1)
AP = input(14, 'Common Period')
ATR = ta.sma(ta.tr, AP)
src = input(close)
showsignalsk = input(title='Show Signals?', defval=true)
novolumedata = input(title='Change calculation (no volume data)?', defval=false)
upT = low - ATR * coeff
downT = high + ATR * coeff
AlphaTrend = 0.0
AlphaTrend := (novolumedata ? ta.rsi(src, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? upT
< nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ?
nz(AlphaTrend[1]) : downT

//color1 = AlphaTrend > AlphaTrend[2] ? #00E60F : AlphaTrend < AlphaTrend[2] ?


#80000B : AlphaTrend[1] > AlphaTrend[3] ? #00E60F : #80000B
//k1 = plot(AlphaTrend, color=color.new(#0022FC, 0), linewidth=3)
//k2 = plot(AlphaTrend[2], color=color.new(#FC0400, 0), linewidth=3)

//fill(k1, k2, color=color1)

buySignalk = ta.crossover(AlphaTrend, AlphaTrend[2])


sellSignalk = ta.crossunder(AlphaTrend, AlphaTrend[2])

K1 = ta.barssince(buySignalk)
K2 = ta.barssince(sellSignalk)
O1 = ta.barssince(buySignalk[1])
O2 = ta.barssince(sellSignalk[1])

plotshape(buySignalk and showsignalsk and O1 > K2 ? AlphaTrend[2] * 0.9999 : na,


title='A-BUY', text='A-BUY', location=location.absolute, style=shape.labelup,
size=size.tiny, color=color.new(#0022FC, 0), textcolor=color.new(color.white, 0))

plotshape(sellSignalk and showsignalsk and O2 > K1 ? AlphaTrend[2] * 1.0001 : na,


title='A-SELL', text='A-SELL', location=location.absolute, style=shape.labeldown,
size=size.tiny, color=color.new(color.maroon, 0), textcolor=color.new(color.white,
0))

// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © loxx

//@version=5
//indicator("STD-Filtered, N-Pole Gaussian Filter [Loxx]",
//shorttitle="STDFNPGF [Loxx]",
//overlay = true)

import loxx/loxxexpandedsourcetypes/4

greencolor = #2DD204
redcolor = #D2042D

//factorial calc
fact(int n)=>
float a = 1
for i = 1 to n
a *= i
a

//alpha calc
_alpha(int period, int poles)=>
w = 2.0 * math.pi / period
float b = (1.0 - math.cos(w)) / (math.pow(1.414, 2.0 / poles) - 1.0)
float a = - b + math.sqrt(b * b + 2.0 * b)
a

//n-pole calc
_makeCoeffs(simple int period, simple int order)=>
coeffs = matrix.new<float>(order + 1, 3, 0.)
float a = _alpha(period, order)
for r = 0 to order
out = nz(fact(order) / (fact(order - r) * fact(r)), 1)
matrix.set(coeffs, r, 0, out)
matrix.set(coeffs, r, 1, math.pow(a, r))
matrix.set(coeffs, r, 2, math.pow(1.0 - a, r))
coeffs

//n-pole calc
_npolegf(float ssrc, simple int period, simple int order)=>
var coeffs = _makeCoeffs(period, order)
float filt = ssrc * matrix.get(coeffs, order, 1)
int sign = 1
for r = 1 to order
filt += sign * matrix.get(coeffs, r, 0) * matrix.get(coeffs, r, 2) *
nz(filt[r])
sign *= -1
filt

//std filter
_filt(float ssrc, int len, float filter)=>
float price = ssrc
float filtdev = filter * ta.stdev(ssrc, len)
price := math.abs(price - nz(price[1])) < filtdev ? nz(price[1]) : price
price

smthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options =


["AMA", "T3", "Kaufman"], group= "Source Settings")
ssrcoption = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average",
"Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA
Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend
Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical",
"HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB
Trend Biased (Extreme)"])

period = input.int(25,'Period', group = "Basic Settings")


order = input.int(5,'Order', group = "Basic Settings", minval = 1)

filterop = input.string("Gaussian Filter", "Filter Options", options = ["Price",


"Gaussian Filter", "Both", "None"], group= "Filter Settings")
filter = input.float(1, "Filter Devaitions", minval = 0, group= "Filter Settings")
filterperiod = input.int(10, "Filter Period", minval = 0, group= "Filter Settings")

colorbars = input.bool(true, "Color bars?", group = "UI Options")


showSigs = input.bool(true, "Show signals?", group= "UI Options")

kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End",


group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End",
group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group =
"Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group =
"Moving Average Inputs")

[haclose, haopen, hahigh, halow, hamedian, hatypical, haweighted, haaverage] =


request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, [close,
open, high, low, hl2, hlc3, hlcc4, ohlc4])

float ssrc = switch ssrcoption


"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose,
haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen,
hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose,
haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl,
ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl,
ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl,
ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl,
kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl,
kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl,
kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl,
kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype,
amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl,
amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" =>
loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose

ssrc := filterop == "Both" or filterop == "Price" and filter > 0 ? _filt(ssrc,


filterperiod, filter) : ssrc

out = _npolegf(ssrc, period, order)

out := filterop == "Both" or filterop == "Gaussian Filter" and filter > 0 ?


_filt(out, filterperiod, filter) : out

sig = nz(out[1])

state = 0
if (out > sig)
state := 1
if (out < sig)
state := -1

pregoLong = out > sig and (nz(out[1]) < nz(sig[1]) or nz(out[1]) == nz(sig[1]))
pregoShort = out < sig and (nz(out[1]) > nz(sig[1]) or nz(out[1]) == nz(sig[1]))

contsw = 0
contsw := nz(contsw[1])
contsw := pregoLong ? 1 : pregoShort ? -1 : nz(contsw[1])

goLong = pregoLong and nz(contsw[1]) == -1


goShort = pregoShort and nz(contsw[1]) == 1

var color colorout = na


colorout := state == -1 ? redcolor : state == 1 ? greencolor : nz(colorout[1])

plot(out, "N-Pole GF", color = colorout, linewidth = 3)


barcolor(colorbars ? colorout : na)

plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor =


color.yellow, text = "LO", style = shape.triangleup, location = location.belowbar,
size = size.tiny)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor =
color.fuchsia, text = "SH", style = shape.triangledown, location =
location.abovebar, size = size.tiny)

alertcondition(goLong, title = "Long", message = "STD-Filtered, N-Pole Gaussian


Filter [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title = "Short", message = "STD-Filtered, N-Pole Gaussian
Filter [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0


International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo

//@version=5
//indicator("Smart Money Concepts [LUX]", "Smart Money Concepts [LuxAlgo]"
//, overlay = true
//, max_labels_count = 500
//, max_lines_count = 500
//, max_boxes_count = 500
//, max_bars_back = 500)
//-----------------------------------------------------------------------------{
//Constants
//-----------------------------------------------------------------------------{
color TRANSP_CSS = #ffffff00

//Tooltips
string MODE_TOOLTIP = 'Allows to display historical Structure or only the
recent ones'
string STYLE_TOOLTIP = 'Indicator color theme'
string COLOR_CANDLES_TOOLTIP = 'Display additional candles with a color reflecting
the current trend detected by structure'
string SHOW_INTERNAL = 'Display internal market structure'
string CONFLUENCE_FILTER = 'Filter non significant internal structure
breakouts'
string SHOW_SWING = 'Display swing market Structure'
string SHOW_SWING_POINTS = 'Display swing point as labels on the chart'
string SHOW_SWHL_POINTS = 'Highlight most recent strong and weak high/low
points on the chart'
string INTERNAL_OB = 'Display internal order blocks on the chart\n\
nNumber of internal order blocks to display on the chart'
string SWING_OB = 'Display swing order blocks on the chart\n\nNumber
of internal swing blocks to display on the chart'
string FILTER_OB = 'Method used to filter out volatile order blocks \n\
nIt is recommended to use the cumulative mean range method when a low amount of
data is available'
string SHOW_EQHL = 'Display equal highs and equal lows on the chart'
string EQHL_BARS = 'Number of bars used to confirm equal highs and
equal lows'
string EQHL_THRESHOLD = 'Sensitivity threshold in a range (0, 1) used for
the detection of equal highs & lows\n\nLower values will return fewer but more
pertinent results'
string SHOW_FVG = 'Display fair values gaps on the chart'
string AUTO_FVG = 'Filter out non significant fair value gaps'
string FVG_TF = 'Fair value gaps timeframe'
string EXTEND_FVG = 'Determine how many bars to extend the Fair Value
Gap boxes on chart'
string PED_ZONES = 'Display premium, discount, and equilibrium zones on
chart'

//-----------------------------------------------------------------------------{
//Settings
//-----------------------------------------------------------------------------{
//General
//----------------------------------------{
mode = input.string('Historical'
, options = ['Historical', 'Present']
, group = 'Smart Money Concepts'
, tooltip = MODE_TOOLTIP)
style = input.string('Colored'
, options = ['Colored', 'Monochrome']
, group = 'Smart Money Concepts'
, tooltip = STYLE_TOOLTIP)

show_trend = input(false, 'Color Candles'


, group = 'Smart Money Concepts'
, tooltip = COLOR_CANDLES_TOOLTIP)

//----------------------------------------}
//Internal Structure
//----------------------------------------{
show_internals = input(true, 'Show Internal Structure'
, group = 'Real Time Internal Structure'
, tooltip = SHOW_INTERNAL)

show_ibull = input.string('All', 'Bullish Structure'


, options = ['All', 'BOS', 'CHoCH']
, inline = 'ibull'
, group = 'Real Time Internal Structure')

swing_ibull_css = input(#089981, ''


, inline = 'ibull'
, group = 'Real Time Internal Structure')

//Bear Structure
show_ibear = input.string('All', 'Bearish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'ibear'
, group = 'Real Time Internal Structure')

swing_ibear_css = input(#f23645, ''


, inline = 'ibear'
, group = 'Real Time Internal Structure')

ifilter_confluence = input(false, 'Confluence Filter'


, group = 'Real Time Internal Structure'
, tooltip = CONFLUENCE_FILTER)

//----------------------------------------}
//Swing Structure
//----------------------------------------{
show_Structure = input(true, 'Show Swing Structure'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWING)

//Bull Structure
show_bull = input.string('All', 'Bullish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'bull'
, group = 'Real Time Swing Structure')

swing_bull_css = input(#089981, ''


, inline = 'bull'
, group = 'Real Time Swing Structure')

//Bear Structure
show_bear = input.string('All', 'Bearish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'bear'
, group = 'Real Time Swing Structure')

swing_bear_css = input(#f23645, ''


, inline = 'bear'
, group = 'Real Time Swing Structure')

//Swings
show_swings = input(false, 'Show Swings Points'
, inline = 'swings'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWING_POINTS)

length = input.int(50, ''


, minval = 10
, inline = 'swings'
, group = 'Real Time Swing Structure')

show_hl_swings = input(true, 'Show Strong/Weak High/Low'


, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWHL_POINTS)

//----------------------------------------}
//Order Blocks
//----------------------------------------{
show_iob = input(true, 'Internal Order Blocks'
, inline = 'iob'
, group = 'Order Blocks'
, tooltip = INTERNAL_OB)

iob_showlast = input.int(5, ''


, minval = 1
, inline = 'iob'
, group = 'Order Blocks')

show_ob = input(false, 'Swing Order Blocks'


, inline = 'ob'
, group = 'Order Blocks'
, tooltip = SWING_OB)

ob_showlast = input.int(5, ''


, minval = 1
, inline = 'ob'
, group = 'Order Blocks')

ob_filter = input.string('Atr', 'Order Block Filter'


, options = ['Atr', 'Cumulative Mean Range']
, group = 'Order Blocks'
, tooltip = FILTER_OB)

ibull_ob_css = input.color(color.new(#3179f5, 80), 'Internal Bullish OB'


, group = 'Order Blocks')

ibear_ob_css = input.color(color.new(#f77c80, 80), 'Internal Bearish OB'


, group = 'Order Blocks')

bull_ob_css = input.color(color.new(#1848cc, 80), 'Bullish OB'


, group = 'Order Blocks')
bear_ob_css = input.color(color.new(#b22833, 80), 'Bearish OB'
, group = 'Order Blocks')

//----------------------------------------}
//EQH/EQL
//----------------------------------------{
show_eq = input(true, 'Equal High/Low'
, group = 'EQH/EQL'
, tooltip = SHOW_EQHL)

eq_len = input.int(3, 'Bars Confirmation'


, minval = 1
, group = 'EQH/EQL'
, tooltip = EQHL_BARS)

eq_threshold = input.float(0.1, 'Threshold'


, minval = 0
, maxval = 0.5
, step = 0.1
, group = 'EQH/EQL'
, tooltip = EQHL_THRESHOLD)

//----------------------------------------}
//Fair Value Gaps
//----------------------------------------{
show_fvg = input(false, 'Fair Value Gaps'
, group = 'Fair Value Gaps'
, tooltip = SHOW_FVG)

fvg_auto = input(true, "Auto Threshold"


, group = 'Fair Value Gaps'
, tooltip = AUTO_FVG)

fvg_tf = input.timeframe('', "Timeframe"


, group = 'Fair Value Gaps'
, tooltip = FVG_TF)

bull_fvg_css = input.color(color.new(#00ff68, 70), 'Bullish FVG'


, group = 'Fair Value Gaps')

bear_fvg_css = input.color(color.new(#ff0008, 70), 'Bearish FVG'


, group = 'Fair Value Gaps')

fvg_extend = input.int(1, "Extend FVG"


, minval = 0
, group = 'Fair Value Gaps'
, tooltip = EXTEND_FVG)

//----------------------------------------}
//Previous day/week high/low
//----------------------------------------{
//Daily
show_pdhl = input(false, 'Daily'
, inline = 'daily'
, group = 'Highs & Lows MTF')

pdhl_style = input.string('⎯⎯⎯', ''


, options = ['⎯⎯⎯', '----', '····']
, inline = 'daily'
, group = 'Highs & Lows MTF')

pdhl_css = input(#2157f3, ''


, inline = 'daily'
, group = 'Highs & Lows MTF')

//Weekly
show_pwhl = input(false, 'Weekly'
, inline = 'weekly'
, group = 'Highs & Lows MTF')

pwhl_style = input.string('⎯⎯⎯', ''


, options = ['⎯⎯⎯', '----', '····']
, inline = 'weekly'
, group = 'Highs & Lows MTF')

pwhl_css = input(#2157f3, ''


, inline = 'weekly'
, group = 'Highs & Lows MTF')

//Monthly
show_pmhl = input(false, 'Monthly'
, inline = 'monthly'
, group = 'Highs & Lows MTF')

pmhl_style = input.string('⎯⎯⎯', ''


, options = ['⎯⎯⎯', '----', '····']
, inline = 'monthly'
, group = 'Highs & Lows MTF')

pmhl_css = input(#2157f3, ''


, inline = 'monthly'
, group = 'Highs & Lows MTF')

//----------------------------------------}
//Premium/Discount zones
//----------------------------------------{
show_sd = input(false, 'Premium/Discount Zones'
, group = 'Premium & Discount Zones'
, tooltip = PED_ZONES)

premium_css = input.color(#f23645, 'Premium Zone'


, group = 'Premium & Discount Zones')

eq_css = input.color(#b2b5be, 'Equilibrium Zone'


, group = 'Premium & Discount Zones')

discount_css = input.color(#089981, 'Discount Zone'


, group = 'Premium & Discount Zones')

//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index

atr = ta.atr(200)
cmean_range = ta.cum(high - low) / n

//HL Output function


hl() => [high, low]

//Get ohlc values function


get_ohlc()=> [close[1], open[1], high, low, high[2], low[2]]

//Display Structure function


display_Structure(x, y, txt, css, dashed, down, lbl_size)=>
structure_line = line.new(x, y, n, y
, color = css
, style = dashed ? line.style_dashed : line.style_solid)

structure_lbl = label.new(int(math.avg(x, n)), y, txt


, color = TRANSP_CSS
, textcolor = css
, style = down ? label.style_label_down : label.style_label_up
, size = lbl_size)

if mode == 'Present'
line.delete(structure_line[1])
label.delete(structure_lbl[1])

//Swings detection/measurements
swings(len)=>
var os = 0

upper = ta.highest(len)
lower = ta.lowest(len)

os := high[len] > upper ? 0 : low[len] < lower ? 1 : os[1]

top = os == 0 and os[1] != 0 ? high[len] : 0


btm = os == 1 and os[1] != 1 ? low[len] : 0

[top, btm]

//Order block coordinates function


ob_coord(use_max, loc, target_top, target_btm, target_left, target_type)=>
min = 99999999.
max = 0.
idx = 1

ob_threshold = ob_filter == 'Atr' ? atr : cmean_range

//Search for highest/lowest high within the structure interval and get range
if use_max
for i = 1 to (n - loc)-1
if (high[i] - low[i]) < ob_threshold[i] * 2
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
else
for i = 1 to (n - loc)-1
if (high[i] - low[i]) < ob_threshold[i] * 2
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx

array.unshift(target_top, max)
array.unshift(target_btm, min)
array.unshift(target_left, time[idx])
array.unshift(target_type, use_max ? -1 : 1)

//Set order blocks


display_ob(boxes, target_top, target_btm, target_left, target_type, show_last,
swing, size)=>
for i = 0 to math.min(show_last-1, size-1)
get_box = array.get(boxes, i)

box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top,


i))
box.set_rightbottom(get_box, array.get(target_left, i),
array.get(target_btm, i))
box.set_extend(get_box, extend.right)

color css = na

if swing
if style == 'Monochrome'
css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) :
color.new(#5d606b, 80)
border_css = array.get(target_type, i) == 1 ? #b2b5be : #5d606b
box.set_border_color(get_box, border_css)
else
css := array.get(target_type, i) == 1 ? bull_ob_css : bear_ob_css
box.set_border_color(get_box, css)

box.set_bgcolor(get_box, css)
else
if style == 'Monochrome'
css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) :
color.new(#5d606b, 80)
else
css := array.get(target_type, i) == 1 ? ibull_ob_css : ibear_ob_css

box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)

//Line Style function


get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted

//Set line/labels function for previous high/lows


phl(h, l, tf, css)=>
var line high_line = line.new(na,na,na,na
, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))

var label high_lbl = label.new(na,na


, xloc = xloc.bar_time
, text = str.format('P{0}H', tf)
, color = TRANSP_CSS
, textcolor = css
, size = size.small
, style = label.style_label_left)
var line low_line = line.new(na,na,na,na
, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))

var label low_lbl = label.new(na,na


, xloc = xloc.bar_time
, text = str.format('P{0}L', tf)
, color = TRANSP_CSS
, textcolor = css
, size = size.small
, style = label.style_label_left)

hy = ta.valuewhen(h != h[1], h, 1)
hx = ta.valuewhen(h == high, time, 1)

ly = ta.valuewhen(l != l[1], l, 1)
lx = ta.valuewhen(l == low, time, 1)

if barstate.islast
ext = time + (time - time[1])*20

//High
line.set_xy1(high_line, hx, hy)
line.set_xy2(high_line, ext, hy)

label.set_xy(high_lbl, ext, hy)

//Low
line.set_xy1(low_line, lx, ly)
line.set_xy2(low_line, ext, ly)

label.set_xy(low_lbl, ext, ly)

//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
var trend = 0, var itrend = 0

var top_y = 0., var top_x = 0


var btm_y = 0., var btm_x = 0

var itop_y = 0., var itop_x = 0


var ibtm_y = 0., var ibtm_x = 0

var trail_up = high, var trail_dn = low


var trail_up_x = 0, var trail_dn_x = 0

var top_cross = true, var btm_cross = true


var itop_cross = true, var ibtm_cross = true

var txt_top = '', var txt_btm = ''

//Alerts
bull_choch_alert = false
bull_bos_alert = false

bear_choch_alert = false
bear_bos_alert = false

bull_ichoch_alert = false
bull_ibos_alert = false

bear_ichoch_alert = false
bear_ibos_alert = false

bull_iob_break = false
bear_iob_break = false

bull_ob_break = false
bear_ob_break = false

eqh_alert = false
eql_alert = false

//Structure colors
var bull_css = style == 'Monochrome' ? #b2b5be
: swing_bull_css

var bear_css = style == 'Monochrome' ? #b2b5be


: swing_bear_css

var ibull_css = style == 'Monochrome' ? #b2b5be


: swing_ibull_css

var ibear_css = style == 'Monochrome' ? #b2b5be


: swing_ibear_css

//Swings
[top, btm] = swings(length)

[itop, ibtm] = swings(5)

//-----------------------------------------------------------------------------}
//Pivot High
//-----------------------------------------------------------------------------{
var line extend_top = na

var label extend_top_lbl = label.new(na, na


, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = size.tiny)

if top
top_cross := true
txt_top := top > top_y ? 'HH' : 'LH'

if show_swings
top_lbl = label.new(n-length, top, txt_top
, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = size.small)

if mode == 'Present'
label.delete(top_lbl[1])
//Extend recent top to last bar
line.delete(extend_top[1])
extend_top := line.new(n-length, top, n, top
, color = bear_css)

top_y := top
top_x := n - length

trail_up := top
trail_up_x := n - length

if itop
itop_cross := true

itop_y := itop
itop_x := n - 5

//Trailing maximum
trail_up := math.max(high, trail_up)
trail_up_x := trail_up == high ? n : trail_up_x

//Set top extension label/line


if barstate.islast and show_hl_swings
line.set_xy1(extend_top, trail_up_x, trail_up)
line.set_xy2(extend_top, n + 20, trail_up)

label.set_x(extend_top_lbl, n + 20)
label.set_y(extend_top_lbl, trail_up)
label.set_text(extend_top_lbl, trend < 0 ? 'Strong High' : 'Weak High')

//-----------------------------------------------------------------------------}
//Pivot Low
//-----------------------------------------------------------------------------{
var line extend_btm = na

var label extend_btm_lbl = label.new(na, na


, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = size.tiny)

if btm
btm_cross := true
txt_btm := btm < btm_y ? 'LL' : 'HL'

if show_swings
btm_lbl = label.new(n - length, btm, txt_btm
, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = size.small)

if mode == 'Present'
label.delete(btm_lbl[1])

//Extend recent btm to last bar


line.delete(extend_btm[1])
extend_btm := line.new(n - length, btm, n, btm
, color = bull_css)

btm_y := btm
btm_x := n-length

trail_dn := btm
trail_dn_x := n-length

if ibtm
ibtm_cross := true

ibtm_y := ibtm
ibtm_x := n - 5

//Trailing minimum
trail_dn := math.min(low, trail_dn)
trail_dn_x := trail_dn == low ? n : trail_dn_x

//Set btm extension label/line


if barstate.islast and show_hl_swings
line.set_xy1(extend_btm, trail_dn_x, trail_dn)
line.set_xy2(extend_btm, n + 20, trail_dn)

label.set_x(extend_btm_lbl, n + 20)
label.set_y(extend_btm_lbl, trail_dn)
label.set_text(extend_btm_lbl, trend > 0 ? 'Strong Low' : 'Weak Low')

//-----------------------------------------------------------------------------}
//Order Blocks Arrays
//-----------------------------------------------------------------------------{
var iob_top = array.new_float(0)
var iob_btm = array.new_float(0)
var iob_left = array.new_int(0)
var iob_type = array.new_int(0)

var ob_top = array.new_float(0)


var ob_btm = array.new_float(0)
var ob_left = array.new_int(0)
var ob_type = array.new_int(0)

//-----------------------------------------------------------------------------}
//Pivot High BOS/CHoCH
//-----------------------------------------------------------------------------{
//Filtering
var bull_concordant = true

if ifilter_confluence
bull_concordant := high - math.max(close, open) > math.min(close, open - low)

//Detect internal bullish Structure


if ta.crossover(close, itop_y) and itop_cross and top_y != itop_y and
bull_concordant
bool choch = na

if itrend < 0
choch := true
bull_ichoch_alert := true
else
bull_ibos_alert := true
txt = choch ? 'CHoCH' : 'BOS'

if show_internals
if show_ibull == 'All' or (show_ibull == 'BOS' and not choch) or
(show_ibull == 'CHoCH' and choch)
display_Structure(itop_x, itop_y, txt, ibull_css, true, true,
size.tiny)

itop_cross := false
itrend := 1

//Internal Order Block


if show_iob
ob_coord(false, itop_x, iob_top, iob_btm, iob_left, iob_type)

//Detect bullish Structure


if ta.crossover(close, top_y) and top_cross
bool choch = na

if trend < 0
choch := true
bull_choch_alert := true
else
bull_bos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_Structure
if show_bull == 'All' or (show_bull == 'BOS' and not choch) or (show_bull
== 'CHoCH' and choch)
display_Structure(top_x, top_y, txt, bull_css, false, true, size.small)

//Order Block
if show_ob
ob_coord(false, top_x, ob_top, ob_btm, ob_left, ob_type)

top_cross := false
trend := 1

//-----------------------------------------------------------------------------}
//Pivot Low BOS/CHoCH
//-----------------------------------------------------------------------------{
var bear_concordant = true

if ifilter_confluence
bear_concordant := high - math.max(close, open) < math.min(close, open - low)

//Detect internal bearish Structure


if ta.crossunder(close, ibtm_y) and ibtm_cross and btm_y != ibtm_y and
bear_concordant
bool choch = false

if itrend > 0
choch := true
bear_ichoch_alert := true
else
bear_ibos_alert := true
txt = choch ? 'CHoCH' : 'BOS'

if show_internals
if show_ibear == 'All' or (show_ibear == 'BOS' and not choch) or
(show_ibear == 'CHoCH' and choch)
display_Structure(ibtm_x, ibtm_y, txt, ibear_css, true, false,
size.tiny)

ibtm_cross := false
itrend := -1

//Internal Order Block


if show_iob
ob_coord(true, ibtm_x, iob_top, iob_btm, iob_left, iob_type)

//Detect bearish Structure


if ta.crossunder(close, btm_y) and btm_cross
bool choch = na

if trend > 0
choch := true
bear_choch_alert := true
else
bear_bos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_Structure
if show_bear == 'All' or (show_bear == 'BOS' and not choch) or (show_bear
== 'CHoCH' and choch)
display_Structure(btm_x, btm_y, txt, bear_css, false, false,
size.small)

//Order Block
if show_ob
ob_coord(true, btm_x, ob_top, ob_btm, ob_left, ob_type)

btm_cross := false
trend := -1

//-----------------------------------------------------------------------------}
//Order Blocks
//-----------------------------------------------------------------------------{
//Set order blocks
var iob_boxes = array.new_box(0)
var ob_boxes = array.new_box(0)

//Delete internal order blocks box coordinates if top/bottom is broken


for element in iob_type
index = array.indexof(iob_type, element)

if close < array.get(iob_btm, index) and element == 1


array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bull_iob_break := true

else if close > array.get(iob_top, index) and element == -1


array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bear_iob_break := true

//Delete internal order blocks box coordinates if top/bottom is broken


for element in ob_type
index = array.indexof(ob_type, element)

if close < array.get(ob_btm, index) and element == 1


array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bull_ob_break := true

else if close > array.get(ob_top, index) and element == -1


array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bear_ob_break := true

iob_size = array.size(iob_type)
ob_size = array.size(ob_type)

if barstate.isfirst
if show_iob
for i = 0 to iob_showlast-1
array.push(iob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))
if show_ob
for i = 0 to ob_showlast-1
array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))

if iob_size > 0
if barstate.islast
display_ob(iob_boxes, iob_top, iob_btm, iob_left, iob_type, iob_showlast,
false, iob_size)

if ob_size > 0
if barstate.islast
display_ob(ob_boxes, ob_top, ob_btm, ob_left, ob_type, ob_showlast, true,
ob_size)

//-----------------------------------------------------------------------------}
//EQH/EQL
//-----------------------------------------------------------------------------{
var eq_prev_top = 0.
var eq_top_x = 0

var eq_prev_btm = 0.
var eq_btm_x = 0

if show_eq
eq_top = ta.pivothigh(eq_len, eq_len)
eq_btm = ta.pivotlow(eq_len, eq_len)

if eq_top
max = math.max(eq_top, eq_prev_top)
min = math.min(eq_top, eq_prev_top)

if max < min + atr * eq_threshold


eqh_line = line.new(eq_top_x, eq_prev_top, n-eq_len, eq_top
, color = bear_css
, style = line.style_dotted)

eqh_lbl = label.new(int(math.avg(n-eq_len, eq_top_x)), eq_top, 'EQH'


, color = #00000000
, textcolor = bear_css
, style = label.style_label_down
, size = size.tiny)

if mode == 'Present'
line.delete(eqh_line[1])
label.delete(eqh_lbl[1])

eqh_alert := true

eq_prev_top := eq_top
eq_top_x := n-eq_len

if eq_btm
max = math.max(eq_btm, eq_prev_btm)
min = math.min(eq_btm, eq_prev_btm)

if min > max - atr * eq_threshold


eql_line = line.new(eq_btm_x, eq_prev_btm, n-eq_len, eq_btm
, color = bull_css
, style = line.style_dotted)

eql_lbl = label.new(int(math.avg(n-eq_len, eq_btm_x)), eq_btm, 'EQL'


, color = #00000000
, textcolor = bull_css
, style = label.style_label_up
, size = size.tiny)

eql_alert := true

if mode == 'Present'
line.delete(eql_line[1])
label.delete(eql_lbl[1])

eq_prev_btm := eq_btm
eq_btm_x := n-eq_len

//-----------------------------------------------------------------------------}
//Fair Value Gaps
//-----------------------------------------------------------------------------{
var bullish_fvg_max = array.new_box(0)
var bullish_fvg_min = array.new_box(0)

var bearish_fvg_max = array.new_box(0)


var bearish_fvg_min = array.new_box(0)

float bullish_fvg_avg = na
float bearish_fvg_avg = na
bullish_fvg_cnd = false
bearish_fvg_cnd = false

[src_c1, src_o1, src_h, src_l, src_h2, src_l2] =


request.security(syminfo.tickerid, fvg_tf, get_ohlc())

if show_fvg
delta_per = (src_c1 - src_o1) / src_o1 * 100

change_tf = timeframe.change(fvg_tf)

threshold = fvg_auto ? ta.cum(math.abs(change_tf ? delta_per : 0)) / n * 2


: 0

//FVG conditions
bullish_fvg_cnd := src_l > src_h2
and src_c1 > src_h2
and delta_per > threshold
and change_tf

bearish_fvg_cnd := src_h < src_l2


and src_c1 < src_l2
and -delta_per > threshold
and change_tf

//FVG Areas
if bullish_fvg_cnd
array.unshift(bullish_fvg_max, box.new(n-1, src_l, n + fvg_extend,
math.avg(src_l, src_h2)
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))

array.unshift(bullish_fvg_min, box.new(n-1, math.avg(src_l, src_h2), n +


fvg_extend, src_h2
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))

if bearish_fvg_cnd
array.unshift(bearish_fvg_max, box.new(n-1, src_h, n + fvg_extend,
math.avg(src_h, src_l2)
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))

array.unshift(bearish_fvg_min, box.new(n-1, math.avg(src_h, src_l2), n +


fvg_extend, src_l2
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))

for bx in bullish_fvg_min
if low < box.get_bottom(bx)
box.delete(bx)
box.delete(array.get(bullish_fvg_max, array.indexof(bullish_fvg_min,
bx)))

for bx in bearish_fvg_max
if high > box.get_top(bx)
box.delete(bx)
box.delete(array.get(bearish_fvg_min, array.indexof(bearish_fvg_max,
bx)))
//-----------------------------------------------------------------------------}
//Previous day/week high/lows
//-----------------------------------------------------------------------------{
//Daily high/low
[pdh, pdl] = request.security(syminfo.tickerid, 'D', hl()
, lookahead = barmerge.lookahead_on)

//Weekly high/low
[pwh, pwl] = request.security(syminfo.tickerid, 'W', hl()
, lookahead = barmerge.lookahead_on)

//Monthly high/low
[pmh, pml] = request.security(syminfo.tickerid, 'M', hl()
, lookahead = barmerge.lookahead_on)

//Display Daily
if show_pdhl
phl(pdh, pdl, 'D', pdhl_css)

//Display Weekly
if show_pwhl
phl(pwh, pwl, 'W', pwhl_css)

//Display Monthly
if show_pmhl
phl(pmh, pml, 'M', pmhl_css)

//-----------------------------------------------------------------------------}
//Premium/Discount/Equilibrium zones
//-----------------------------------------------------------------------------{
var premium = box.new(na, na, na, na
, bgcolor = color.new(premium_css, 80)
, border_color = na)

var premium_lbl = label.new(na, na


, text = 'Premium'
, color = TRANSP_CSS
, textcolor = premium_css
, style = label.style_label_down
, size = size.small)

var eq = box.new(na, na, na, na


, bgcolor = color.rgb(120, 123, 134, 80)
, border_color = na)

var eq_lbl = label.new(na, na


, text = 'Equilibrium'
, color = TRANSP_CSS
, textcolor = eq_css
, style = label.style_label_left
, size = size.small)

var discount = box.new(na, na, na, na


, bgcolor = color.new(discount_css, 80)
, border_color = na)

var discount_lbl = label.new(na, na


, text = 'Discount'
, color = TRANSP_CSS
, textcolor = discount_css
, style = label.style_label_up
, size = size.small)

//Show Premium/Discount Areas


if barstate.islast and show_sd
avg = math.avg(trail_up, trail_dn)

box.set_lefttop(premium, math.max(top_x, btm_x), trail_up)


box.set_rightbottom(premium, n, .95 * trail_up + .05 * trail_dn)

label.set_xy(premium_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_up)

box.set_lefttop(eq, math.max(top_x, btm_x), .525 * trail_up + .475*trail_dn)


box.set_rightbottom(eq, n, .525 * trail_dn + .475 * trail_up)

label.set_xy(eq_lbl, n, avg)

box.set_lefttop(discount, math.max(top_x, btm_x), .95 * trail_dn + .05 *


trail_up)
box.set_rightbottom(discount, n, trail_dn)
label.set_xy(discount_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_dn)

//-----------------------------------------------------------------------------}
//Trend
//-----------------------------------------------------------------------------{
var color trend_css = na

if show_trend
if style == 'Colored'
trend_css := itrend == 1 ? bull_css : bear_css
else if style == 'Monochrome'
trend_css := itrend == 1 ? #b2b5be : #5d606b

plotcandle(open, high, low, close


, color = trend_css
, wickcolor = trend_css
, bordercolor = trend_css
, editable = false)

//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
//Internal Structure
alertcondition(bull_ibos_alert, 'Internal Bullish BOS', 'Internal Bullish BOS
formed')
alertcondition(bull_ichoch_alert, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH
formed')

alertcondition(bear_ibos_alert, 'Internal Bearish BOS', 'Internal Bearish BOS


formed')
alertcondition(bear_ichoch_alert, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH
formed')

//Swing Structure
alertcondition(bull_bos_alert, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(bull_choch_alert, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(bear_bos_alert, 'Bearish BOS', 'Bearish BOS formed')
alertcondition(bear_choch_alert, 'Bearish CHoCH', 'Bearish CHoCH formed')

//order Blocks
alertcondition(bull_iob_break, 'Bullish Internal OB Breakout', 'Price broke bullish
iternal OB')
alertcondition(bear_iob_break, 'Bearish Internal OB Breakout', 'Price broke bearish
iternal OB')

alertcondition(bull_ob_break, 'Bullish OB Breakout', 'Price broke bullish iternal


OB')
alertcondition(bear_ob_break, 'bearish OB Breakout', 'Price broke bearish iternal
OB')

//EQH/EQL
alertcondition(eqh_alert, 'Equal Highs', 'Equal highs detected')
alertcondition(eql_alert, 'Equal Lows', 'Equal lows detected')

//FVG
alertcondition(bullish_fvg_cnd, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(bearish_fvg_cnd, 'Bearish FVG', 'Bearish FVG formed')

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

// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © reees
//@version=5

//inds
// Ultimate indicator and Constance brown composite index
//
// color and shape of labels, lines

//indicator("Strength of Divergence Across Multiple


Indicators","DivStr",overlay=true,max_lines_count=500,max_labels_count=500,max_bars
_back=500)

import reees/TA/11 as t
import reees/Algebra/3 as alg
//import reees/Trig/2 as trig
//import reees/Utilities/2 as u

//-----------------------------------------
// inputs
//-----------------------------------------

var bullSwitch = input.bool(true, "Bullish", inline="dswitch", group="Divergence


Params")
var bearSwitch = input.bool(true, "Bearish", inline="dswitch", group="Divergence
Params")
var showHidden = input.bool(true, "Hidden", inline="dswitch", group="Divergence
Params")
var noBroken = input.bool(true,"Exclude if broken trendline",group="Divergence
Params",tooltip="If set, divergence is not considered valid if an intermediate
pivot high/low breaks the divergence trendline (on a linear scale). If using a
logarithmic scale, you may want to turn this switch off as some trendlines that are
broken on a linear scale may not be broken on a log scale. Only relevant if
Lookback Pivots > 1.")
var ppLength = input.int(4,"Previous pivot bars
before/after",minval=1,group="Divergence Params",tooltip="Min # bars before and
after a previous pivot high/low to consider it valid for divergence check")
var cpLengthBefore = input.int(4,"Next (divergent) pivot bars
before",minval=1,group="Divergence Params",tooltip="Min # leading bars before the
next (divergent) pivot high/low to consider it valid for divergence check")
var cpLengthAfter = input.int(2,"Next (divergent) pivot bars
after",minval=1,group="Divergence Params",tooltip="# trailing bars after the next
(divergent) pivot high/low to consider it valid for divergence check. Decreasing
this value may detect divergence sooner, but with less confidence.")
var lbBars = input.int(50,"Lookback bars",minval=1,maxval=100,group="Divergence
Params",inline="lb")
var lbPivs = input.int(2,"Lookback pivots",minval=1,group="Divergence
Params",inline="lb",tooltip="# of bars or # of pivot highs/lows to look back
across, whichever comes first")
var w_reg = input.float(1.0,"Regular divergence
weight",step=.1,minval=0.0,group="Divergence Params",inline="degreg")
var w_hid = input.float(1.0,"Hidden divergence
weight",step=.1,minval=0.0,group="Divergence
Params",inline="degreg",tooltip="Value/weight of regular divergence versus hidden
divergence (applies to all indicators)")
var w_p = input.float(0.5,"Δ price weight",step=.1,minval=0.0,group="Divergence
Params",inline="degprice")
var w_i = input.float(1.5,"Δ indicator weight",step=.1,minval=0.0,group="Divergence
Params",inline="degprice",tooltip="Value/weight of change in price versus change in
indicator value (applies to all indicators)")
bullPsource = input.source(low,"Bullish divergence price source",group="Divergence
Params",tooltip="Used for indicators only when appropriate. If the selected source
is not technically feasible or otherwise offends the spirit of an indicator, the
indicator's natural source will be used instead.")
bearPsource = input.source(high,"Bearish divergence price source",group="Divergence
Params",tooltip="Used for indicators only when appropriate. If the selected source
is not technically feasible or otherwise offends the spirit of an indicator, the
indicator's natural source will be used instead.")
//
var iRsi = input.bool(true,"RSI", group="Indicator", inline="ind_rsi")
var w_rsi =
input.float(1.1,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_rsi")
var e_rsi = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_rsi",tooltip="Relative
Strength Index (RSI)\n\nWeight: Weight of RSI divergence in total divergence
strength calculation.\n\nExtreme divergence value: value above which RSI divergence
is considered extreme.")
var iObv = input.bool(true,"OBV", group="Indicator", inline="ind_obv")
var w_obv =
input.float(0.8,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_obv")
var e_obv = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_obv",tooltip="On Balance
Volume (OBV)\n\nWeight: Weight of OBV divergence in total divergence strength
calculation.\n\nExtreme divergence value: value above which OBV divergence is
considered extreme.")
var iMacd = input.bool(true,"MACD", group="Indicator", inline="ind_macd")
var w_macd =
input.float(.9,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_macd")
var e_macd = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_macd",tooltip="Moving
Average Convergence/Divergence (MACD)\n\nWeight: Weight of MACD divergence in total
divergence strength calculation.\n\nExtreme divergence value: value above which
MACD divergence is considered extreme.")
var iStoch = input.bool(true,"STOCH", group="Indicator", inline="ind_stoch")
var w_stoch =
input.float(0.9,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_stoch")
var e_stoch = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_stoch",tooltip="Stochastic
(STOCH)\n\nWeight: Weight of STOCH divergence in total divergence strength
calculation.\n\nExtreme divergence value: value above which STOCH divergence is
considered extreme.")
var iCci = input.bool(true,"CCI", group="Indicator", inline="ind_cci")
var w_cci =
input.float(1.0,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_cci")
var e_cci = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_cci",tooltip="Commodity
Channel Index (CCI)\n\nWeight: Weight of CCI divergence in total divergence
strength calculation.\n\nExtreme divergence value: value above which CCI divergence
is considered extreme.")
var iMfi = input.bool(true,"MFI", group="Indicator", inline="ind_mfi")
var w_mfi =
input.float(1.0,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_mfi")
var e_mfi = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_mfi",tooltip="Money Flow
Index (MFI)\n\nWeight: Weight of MFI divergence in total divergence strength
calculation.\n\nExtreme divergence value: value above which MFI divergence is
considered extreme.")
var iAo = input.bool(true,"AO", group="Indicator", inline="ind_ao")
var w_ao =
input.float(1.0,"Weight",step=.1,minval=0.0,group="Indicator",inline="ind_ao")
var e_ao = input.float(1.0,"Extreme
value",step=.1,minval=0.0,group="Indicator",inline="ind_ao",tooltip="Awesome
Oscillator (AO)\n\nWeight: Weight of AO divergence in total divergence strength
calculation.\n\nExtreme divergence value: value above which AO divergence is
considered extreme.")
//
var a_on = input.bool(true, "Alert", inline="alert", group="Alerts")
var a_above = input.float(5.0, "for values above", step=.1, inline="alert",
group="Alerts")
//
var noLine = input.bool(true,"Show lines",group="Display Settings")==false
var noLab = input.bool(true,"Show labels",group="Display Settings")==false
var extrDiv = input.float(5.0,"Show largest labels for values above:
",minval=0.0,group="Display Settings",tooltip="Total divergence strength greater
than this value will show the largest label (extreme divergence). A good rule of
thumb is to keep this value slightly less than the number of selected indicators.")
var noLabB = input.float(0.5,"Don't show labels for values below:
",minval=0.0,group="Display Settings",tooltip="Total divergence strength less than
this value will not show any label.")
var lTransp = input.int(80,"Line transparency",minval=0,maxval=100)

//-----------------------------------------
// functions
//-----------------------------------------

strengthMap(d,e) =>
if d >= e
5
else if d > e*.8
4
else if d > e*.6
3
else if d > e*.4
2
else if d > e*.2
1
else
0

strengthMapI(d,i="") =>
e = if i=="RSI"
e_rsi
else if i=="OBV"
e_obv
else if i=="MACD"
e_macd
else if i=="STOCH"
e_stoch
else if i=="CCI"
e_cci
else if i=="MFI"
e_mfi
else if i=="AO"
e_ao
else
0
strengthMap(d,e)

strengthDesc(d,i="") =>
s = i!= "" ? strengthMapI(d,i) : strengthMap(d,extrDiv)
if s == 5
"Extreme"
else if s == 4
"Very strong"
else if s == 3
"Strong"
else if s == 2
"Moderate"
else if s == 1
"Weak"
else
"Very weak"

drawLine(x1,y1,x2,y2,dt,h) =>
c = dt==true?color.new(color.red,lTransp):color.new(color.green,lTransp)
if noLine==false and (h==false or showHidden==true)
line.new(x1,y1,x2,y2,color=c,width=1,style=h==true?
line.style_dashed:line.style_solid)

drawLabel(bear,c,d,l) =>
if c > 0 and d >= noLabB and noLab==false
labX = bar_index-cpLengthAfter
labY = bear == true ? bearPsource[cpLengthAfter] :
bullPsource[cpLengthAfter]
s = strengthMap(d,extrDiv)
dtxt = strengthDesc(d) + " divergence (" + str.tostring(math.round(d,3)) +
")\n"
ttxt = dtxt + " Indicator breakdown (" + str.tostring(c) + "):\n" + l
txt = if s < 3
""
else
str.tostring(math.round(d,2)) + " (" + str.tostring(c) + ")"
transp = s < 4 ? 50 : 10
size = if s == 5
size.normal
else if s == 4
size.small
else
size.tiny
clr = bear == true ? color.new(color.red,transp) :
color.new(color.green,transp)
style = bear == true ? label.style_label_down : label.style_label_up

label.new(labX,labY,text=txt,tooltip=ttxt,textalign=text.align_center,style=style,s
ize=size,color=clr,textcolor=color.white)

detail(t,d) =>
" " + t +": " + strengthDesc(d,t) + " (" + str.tostring(math.round(d,3)) +
")\n"

//-----------------------------------------
// test for divergence
//-----------------------------------------

// RSI
bearRsi = false
bullRsi = false
bearRsiDeg = 0.0
bullRsiDeg = 0.0
if iRsi==true
if bearSwitch==true
i_bear = ta.rsi(bearPsource, 14)
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_rsi
if f==true
bearRsi := t==1 or showHidden==true ? true : false
bearRsiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.rsi(bullPsource, 14)
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_rsi
if f==true
bullRsi := t==1 or showHidden==true ? true : false
bullRsiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// OBV
bearObv = false
bullObv = false
bearObvDeg = 0.0
bullObvDeg = 0.0
if iObv==true
if bearSwitch==true
i_bear = ta.obv
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_obv
if f==true
bearObv := t==1 or showHidden==true ? true : false
bearObvDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.obv
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_obv
if f==true
bullObv := t==1 or showHidden==true ? true : false
bullObvDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// MACD
bearMacd = false
bullMacd = false
bearMacdDeg = 0.0
bullMacdDeg = 0.0
if iMacd==true
if bearSwitch==true
[_,_,i_bear] = ta.macd(bearPsource,12,26,9)
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_macd
if f==true
bearMacd := t==1 or showHidden==true ? true : false
bearMacdDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
[_,_,i_bull] = ta.macd(bullPsource,12,26,9)
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_macd
if f==true
bullMacd := t==1 or showHidden==true ? true : false
bullMacdDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// STOCH
bearStoch = false
bullStoch = false
bearStochDeg = 0.0
bullStochDeg = 0.0
if iStoch==true
if bearSwitch==true
i_bear = ta.stoch(close, high, low, 14)
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_stoch
if f==true
bearStoch := t==1 or showHidden==true ? true : false
bearStochDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.stoch(close, high, low, 14)
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_stoch
if f==true
bullStoch := t==1 or showHidden==true ? true : false
bullStochDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// CCI
bearCci = false
bullCci = false
bearCciDeg = 0.0
bullCciDeg = 0.0
if iCci==true
if bearSwitch==true
i_bear = ta.cci(bearPsource,20)
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_cci
if f==true
bearCci := t==1 or showHidden==true ? true : false
bearCciDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.cci(bullPsource,20)
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_cci
if f==true
bullCci := t==1 or showHidden==true ? true : false
bullCciDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// MFI
bearMfi = false
bullMfi = false
bearMfiDeg = 0.0
bullMfiDeg = 0.0
if iMfi==true
if bearSwitch==true
i_bear = ta.mfi(bearPsource,14)
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_mfi
if f==true
bearMfi := t==1 or showHidden==true ? true : false
bearMfiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.mfi(bullPsource,14)
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_mfi
if f==true
bullMfi := t==1 or showHidden==true ? true : false
bullMfiDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)
// AO
bearAo = false
bullAo = false
bearAoDeg = 0.0
bullAoDeg = 0.0
if iAo==true
if bearSwitch==true
i_bear = ta.sma(hl2,5) - ta.sma(hl2,34)
[f,d,t,x1,y1,x2,y2] =
t.div_bear(bearPsource,i_bear,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_ao
if f==true
bearAo := t==1 or showHidden==true ? true : false
bearAoDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,true,t==2)
if bullSwitch==true
i_bull = ta.sma(hl2,5) - ta.sma(hl2,34)
[f,d,t,x1,y1,x2,y2] =
t.div_bull(bullPsource,i_bull,cpLengthAfter,cpLengthBefore,ppLength,lbBars,lbPivs,n
oBroken,w_p,w_i,w_hid,w_reg)
d := d*w_ao
if f==true
bullAo := t==1 or showHidden==true ? true : false
bullAoDeg := t==1 or showHidden==true ? d : 0.0
drawLine(x1,y1,x2,y2,false,t==2)

// Calculate degree of divergence and add labels.


bearCount = 0 // total number of divergent indicators
bearTotalDeg = 0.0 // total degree of divergence across all indicators
bearIndList = "" // list of indicators for tooltip display
bullCount = 0
bullTotalDeg = 0.0
bullIndList = ""

// RSI
if bearRsi==true
bearIndList := bearIndList + detail("RSI",bearRsiDeg)
bearCount+=1
bearTotalDeg += bearRsiDeg
if bullRsi==true
bullIndList := bullIndList + detail("RSI",bullRsiDeg)
bullCount+=1
bullTotalDeg += bullRsiDeg
// OBV
if bearObv==true
bearIndList := bearIndList + detail("OBV",bearObvDeg)
bearCount+=1
bearTotalDeg += bearObvDeg
if bullObv==true
bullIndList := bullIndList + detail("OBV",bullObvDeg)
bullCount+=1
bullTotalDeg += bullObvDeg
// MACD
if bearMacd==true
bearIndList := bearIndList + detail("MACD",bearMacdDeg)
bearCount+=1
bearTotalDeg += bearMacdDeg
if bullMacd==true
bullIndList := bullIndList + detail("MACD",bullMacdDeg)
bullCount+=1
bullTotalDeg += bullMacdDeg
// STOCH
if bearStoch==true
bearIndList := bearIndList + detail("STOCH",bearStochDeg)
bearCount+=1
bearTotalDeg += bearStochDeg
if bullStoch==true
bullIndList := bullIndList + detail("STOCH",bullStochDeg)
bullCount+=1
bullTotalDeg += bullStochDeg
// CCI
if bearCci==true
bearIndList := bearIndList + detail("CCI",bearCciDeg)
bearCount+=1
bearTotalDeg += bearCciDeg
if bullCci==true
bullIndList := bullIndList + detail("CCI",bullCciDeg)
bullCount+=1
bullTotalDeg += bullCciDeg
// MFI
if bearMfi==true
bearIndList := bearIndList + detail("MFI",bearMfiDeg)
bearCount+=1
bearTotalDeg += bearMfiDeg
if bullMfi==true
bullIndList := bullIndList + detail("MFI",bullMfiDeg)
bullCount+=1
bullTotalDeg += bullMfiDeg
// AO
if bearAo==true
bearIndList := bearIndList + detail("AO",bearAoDeg)
bearCount+=1
bearTotalDeg += bearAoDeg
if bullAo==true
bullIndList := bullIndList + detail("AO",bullAoDeg)
bullCount+=1
bullTotalDeg += bullAoDeg

// Draw label(s)
drawLabel(true,bearCount,bearTotalDeg,bearIndList)
drawLabel(false,bullCount,bullTotalDeg,bullIndList)
// Alerts
if a_on and (bullTotalDeg > a_above or bearTotalDeg > a_above)
alert("Divergence strength of "
+str.tostring(math.max(bullTotalDeg,bearTotalDeg),"#.##") + " has formed.")

You might also like