67% found this document useful (3 votes)
323 views36 pages

Secure Ai 2.5

Uploaded by

Minh Hoàng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
67% found this document useful (3 votes)
323 views36 pages

Secure Ai 2.5

Uploaded by

Minh Hoàng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 36

/// © Securealgo

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

// @version=5

indicator("SECURE AI 2.5", shorttitle="SECURE AI 2.5", overlay = true, precision=0,


explicit_plot_zorder=true, max_labels_count=500)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ User Inputs
-----------------------------------------------------------------------------------
------ }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

signalGroup = "Signal Settings"


overlayGroup = "Chart Overlays"
dashboardGroup = "Trend Dashboard"
advancedGroup = "Advanced Settings"
alertGroup = "Any Alert() Function Call"

// ----------------------------------- }}
// ------------- signal settings ----- }}
// ----------------------------------- }}

signalMode = input.string('Ai Mode', 'Signal Mode⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', ['Trend


Mode', "Ai Mode", 'None'],
group = signalGroup, tooltip='Change Your Signal Appearance And Strategies')

sensitivity = input.float(15, "Sensitivity⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀", 1, 100,


step=1,
group = signalGroup, inline = 'sig1')
//autoMaximizer = input.bool(false, "Auto Tuner", tooltip='Change Your Tuning
For Trend Signals...\n\nAutomatically Set To Best Backtested Sensitivity', inline =
'sig1', group="signal settings")

agility = input.string('Auto Pilot', 'Agility %', ['Auto Pilot', 'High',


'Medium', 'Low', 'Strict'],
group = signalGroup, tooltip='Change how often you signals are displayed
based on this % system')

enableCandle = input.bool(true, "", group = signalGroup, inline = "candles1")


CandleColor = input.string('Gradient Trend', 'Candle Coloring⠀⠀⠀⠀⠀⠀',
['Gradient Trend', 'TrendEdge'], group = signalGroup, inline = "candles1")

enableStructures = input.bool(false, "", group = signalGroup, inline =


"structure1")
marketStructures = input.string("Reversals", "Market Structures⠀⠀⠀ ⠀",
["Reversals", "Engulfing", "Reversals + Eg"], group = signalGroup, inline =
"structure1")
// ----------------------------------- }}
// ------------- chart overlays ------ }}
// ----------------------------------- }}

EckoCloud = input.bool(false, "Ecko Cloud", "Toggle On/Off Cloud on your


chart as a slow moving cloud that identifies the longerterm trend", group =
overlayGroup)

radientAssistance = input.bool(false, "Radient Assistance", "Toggle On/Off Radient


Assistance; Dynamically Moving Average Great For Finding Market Bounces or Tops &
Bottoms, Break Outs, Etc", group = overlayGroup)

dynamicTrend = input.bool(false, "Dynamic Trend", "Toggle On/Off The Dynamic


Trailing Price Action Overlay, Great For Finding Bounce & S&R", group =
overlayGroup)

trendSniper = input.bool(false, "Trend Sniper", "Toggle On/Off Trend Sniping


Ma great for finding trend establishments, etc.", group = overlayGroup)

reversalCloud = input.bool(false, "ReversoWave Zones", group = overlayGroup,


tooltip = "Toggle On/Off the dynamic support and resistance zones(areas) that
highlight key reversal areas\n\nUse to take pre-caution!")

// ----------------------------------- }}
// ------------- trend dashboard ----- }}
// ----------------------------------- }}

showDashboard = input(true, "Show Dashboard⠀⠀⠀⠀⠀⠀", group = dashboardGroup,


inline = "dash1")
statisticsDas = input(false, "Statistics", group = dashboardGroup, inline =
"dash1")
locationDashboard = input.string("Bottom Right", "Location / Size", ["Top Right",
"Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center",
"Top Left", "Middle Left", "Bottom Left"],
group = dashboardGroup, inline = "dash2")
sizeDashboard = input.string("Auto", "", ["Auto", "Large", "Normal", "Small",
"Tiny"], group = dashboardGroup, inline = "dash2")

// ----------------------------------- }}
// ------------ color palletes ------- }}
// ----------------------------------- }}

colorScheme = input.string("Delta Mode", "Color Scheme", ["Standard Mode", "Bright


Light", "Delta Mode", "Freezer Mode"], inline = "Color Theme", group =
advancedGroup)
aiMinimum = input.int(0, "Ai Strength | Minimum :", 0, 5, 1, group =
advancedGroup)

// ----------------------------------- }}
// ------------ risk management ------ }}
// ----------------------------------- }}

TPrisk = 2
TPpoints = true

// ----------------------------------- }}
// ------------- call functions ------ }}
// ----------------------------------- }}
normalbuy = input(false, 'Buy⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', group = alertGroup,
inline='normal signals')
normalsell = input(false, 'Sell', 'Sends An Alert Everytime A Normal Sell
Signal Is Placed \n\nSends An Alert Evertime A Normal Buy Signal Is Placed'
, group = alertGroup, inline='normal signals')
strongbuy = input(false, 'Strong Buy⠀⠀⠀⠀⠀', group = alertGroup,
inline='strong signals')
strongsell = input(false, 'Strong Sell', 'Sends An Alert Everytime A Strong
Sell Signal Is Placed \n\nSends An Alert Evertime A Strong Buy Signal Is Placed'
, group = alertGroup, inline='strong signals')

tp1s = input(false, 'TakeProfit(s) 1⠀ ⠀', group = alertGroup,


inline='tp signals')
tp2s = input(false, 'TakeProfit(s) 2', 'Sends An Alert Everytime A TP1
Signal Is Placed \n\nSends An Alert Evertime A TP 2 Signal Is Placed'
, group = alertGroup, inline='tp signals')
tp3s = input(false, 'TakeProfit(s) 3⠀ ⠀', group = alertGroup,
inline='tp signals2')
tp4s = input(false, 'TakeProfit(s) 4', 'Sends An Alert Everytime A TP3
Signal Is Placed \n\nSends An Alert Evertime A TP 4 Signal Is Placed'
, group = alertGroup, inline='tp signals2')

revu = input(false, 'Reversal Up⠀⠀⠀⠀', group = alertGroup,


inline='rev signals')
revd = input(false, 'Reversal Down', 'Sends An Alert Everytime A
Reversal Up Signal Placed \n\nSends An Alert Evertime A Reversal Down Signal Is
Placed'
, group = alertGroup, inline='rev signals')

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------- Color Schemes
-----------------------------------------------------------------------------------
--- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

Light_Pallet = array.new_color(7, na)

array.set(Light_Pallet, 0, color.new(#5BFF29, 0))


array.set(Light_Pallet, 1, color.new(#affc41, 0))
array.set(Light_Pallet, 2, color.new(#FF2937, 0))
array.set(Light_Pallet, 3, color.new(#FF8629, 0))
array.set(Light_Pallet, 4, color.new(#B029FF, 0))
array.set(Light_Pallet, 5, color.new(#FF29B8, 0))
array.set(Light_Pallet, 6, color.new(#29F8FF, 0))

Default_Pallet = array.new_color(7, na)

array.set(Default_Pallet, 0, color.new(#4caf50, 0))


array.set(Default_Pallet, 1, color.new(#4caf50, 0))
array.set(Default_Pallet, 2, color.new(#ff5252, 0))
array.set(Default_Pallet, 3, color.new(#ff5252, 0))
array.set(Default_Pallet, 4, color.new(color.purple, 0))
array.set(Default_Pallet, 5, color.new(color.maroon, 0))
array.set(Default_Pallet, 6, color.new(color.blue, 0))
Delta_Pallet = array.new_color(7, na)

array.set(Delta_Pallet, 0, color.new(#00cf4b, 0))


array.set(Delta_Pallet, 1, color.new(#00cb0a, 0))
array.set(Delta_Pallet, 2, color.new(#ff1100, 0))
array.set(Delta_Pallet, 3, color.new(#c90905, 0))
array.set(Delta_Pallet, 4, color.new(#524678, 0))
array.set(Delta_Pallet, 5, color.new(#14b0e7, 0))
array.set(Delta_Pallet, 6, color.new(#C4AD83, 0))

Ice_Pallet = array.new_color(7, na)

array.set(Ice_Pallet, 0, color.new(#007BBA, 0))


array.set(Ice_Pallet, 1, color.new(#0194fe, 0))
array.set(Ice_Pallet, 2, color.new(#F1F2F6, 0))
array.set(Ice_Pallet, 3, color.new(#B2B0B0, 0))
array.set(Ice_Pallet, 4, color.new(#00A9E2, 0))
array.set(Ice_Pallet, 5, color.new(#EBEBEB, 0))
array.set(Ice_Pallet, 6, color.new(#FF8600, 0))

NA_Palett = array.new_color(7, na)

array.set(NA_Palett, 0, color.new(color.green, 0))


array.set(NA_Palett, 1, color.new(color.green, 0))
array.set(NA_Palett, 2, color.new(color.red, 0))
array.set(NA_Palett, 3, color.new(color.red, 0))
array.set(NA_Palett, 4, color.new(color.purple, 0))
array.set(NA_Palett, 5, color.new(color.maroon, 0))
array.set(NA_Palett, 6, color.new(color.blue, 0))

// Pallet Input

// Pallet Switch
Color_Pallet = switch colorScheme
"Bright Light" => Light_Pallet
"Standard Mode" => Default_Pallet
"Delta Mode" => Delta_Pallet
"Freezer Mode" => Ice_Pallet
"None" => NA_Palett

// Color Assign
color_1 = array.get(Color_Pallet, 0) // Buy - Primary
color_2 = array.get(Color_Pallet, 1) // Buy - Secondary
color_3 = array.get(Color_Pallet, 2) // Sell - Primary
color_4 = array.get(Color_Pallet, 3) // Sell - Secondary
color_5 = array.get(Color_Pallet, 4) // Supporting 1
color_6 = array.get(Color_Pallet, 5) // Supporting 2
color_7 = array.get(Color_Pallet, 6) // Neutral

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Signal Concepts
-----------------------------------------------------------------------------------
-- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

// ----------------------------------- }}
// ----------- gloabl variables ------ }}
// ----------------------------------- }}

src = close

fa(src, len, factor) => ta.ema(src, len) * (1 + factor) - ta.ema(ta.ema(src, len),


len) * .7
smoothedMA(sr , len, factor) => fa(fa(fa(src, len, factor), len, factor), len,
factor)

// ----------------------------------- }}
// ------------- signal concept ------ }}
// ----------------------------------- }}

agil = agility == 'Auto Pilot' ? 45 : agility == 'High' ? 5 : agility == 'Medium' ?


25 : agility == 'Low' ? 100 : agility == 'Strict' ? 200 : 315

smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x[1]), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng

// signal sensitivity
smrng = smoothrng(close, agil, (sensitivity + 12) / 10)

rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r
: x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r
rngfilt
filt = rngfilt(src, smrng)

Periods = 24
Multiplier = 2
atr = ta.sma(ta.tr, Periods)

upx = hl2 - Multiplier * atr


up1x = nz(upx[1], upx)
upx := close[1] > up1x ? math.max(upx, up1x) : upx
dnx = hl2 + Multiplier * atr
dn1x = nz(dnx[1], dnx)
dnx := close[1] < dn1x ? math.min(dnx, dn1x) : dnx

trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1x ? 1 : trend == 1 and close < up1x ? -1 :
trend

Trend = 0.0
TrendUp = 0.0
TrendDown = 0.0
TrendUp := close[1] > TrendUp[1] ? math.max(upx, TrendUp[1]) : upx
TrendDown := close[1] < TrendDown[1] ? math.min(dnx, TrendDown[1]) : dnx

upward = 0.0
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])
downward = 0.0
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 :
nz(downward[1])

longCond = bool(na)
shortCond = bool(na)
longCond := src > filt and src > src[1] and upward > 0 or src > filt and src <
src[1] and upward > 0
shortCond := src < filt and src < src[1] and downward > 0 or src < filt and src
> src[1] and downward > 0
CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]
// ----------------------------------- }}
// ------------ signal conditions ---- }}
// ----------------------------------- }}

buyCond = longCond and CondIni[1] == -1 and smoothedMA(close,


math.round(sensitivity * 2.25), 0.7) > close
strongBuyCond = longCond and CondIni[1] == -1 and smoothedMA(close,
math.round(sensitivity * 2.25), 0.7) < close
sellCond = shortCond and CondIni[1] == 1 and smoothedMA(close,
math.round(sensitivity * 2.25), 0.7) < close
strongSellCond = shortCond and CondIni[1] == 1 and smoothedMA(close,
math.round(sensitivity * 2.25), 0.7) > close

bull= buyCond or strongBuyCond


bear= sellCond or strongSellCond
// ----------------------------------- }}
// ----------------- ai mode --------- }}
// ----------------------------------- }}

var alrRevUp = false, var alrRevDn = false


var dynamicBull = false, var dynamicBear = false
var lowVol = false, var highVol = false

// ----------------- conditions ------ }}

Long_Signal_Strength = 0
Short_Signal_Strength = 0

if buyCond or strongBuyCond
if ta.ema(close, 85) < close
Long_Signal_Strength += 1
if alrRevUp
Long_Signal_Strength += 1
if dynamicBull
Long_Signal_Strength += 1
if lowVol
Long_Signal_Strength += 1
if strongBuyCond
Long_Signal_Strength += 1

if sellCond or strongSellCond
if ta.ema(close, 85) > close
Short_Signal_Strength += 1
if alrRevDn
Short_Signal_Strength += 1
if dynamicBear
Short_Signal_Strength += 1
if highVol
Short_Signal_Strength += 1
if strongSellCond
Short_Signal_Strength += 1

// ----------------------------------- }}
// ------------- other variable ------ }}
// ----------------------------------- }}

y1 = low - (ta.atr(30) * 1.05), y2 = high + (ta.atr(30) * 1.05)

// ----------------------------------- }}
// ----------- Plotting Signals ------ }}
// ----------------------------------- }}

// plotshape(signalMode == 'Trend Mode' ? buyCond : na, "Buy", shape.labelup,


location.belowbar, color.new(color_1, 40), text = "Buy", textcolor = #ffffff, size
= size.normal)

// plotshape(signalMode == 'Trend Mode' ? strongBuyCond : na, "Strong Buy",


shape.labelup, location.belowbar, color.new(color_1, 50), text = "Strong",
textcolor = #ffffff, size = size.normal)

// plotshape(signalMode == 'Trend Mode' ? sellCond : na, "Sell", shape.labeldown,


location.abovebar, color.new(color_3, 50), text = "Sell", textcolor = #ffffff, size
= size.normal)

// plotshape(signalMode == 'Trend Mode' ? strongSellCond : na, "Strong Sell",


shape.labeldown, location.abovebar, color.new(color_3, 50), text = "Strong",
textcolor = #ffffff, size = size.normal)

// -------------- Label Version ---- }}

//if signalMode == 'Trend Mode' and buyCond


// label.new(bar_index, y1, "Buy", color = color.new(#00cf4b, 35), textcolor =
#ffffff, size = size.normal, style = label.style_label_up) //#363a45

//if signalMode == 'Trend Mode' and strongBuyCond


// label.new(bar_index, y1, "Strong", color = color.new(#00cf4b, 35), textcolor
= #ffffff, size = size.normal, style = label.style_label_up)

//if signalMode == 'Trend Mode' and sellCond


// label.new(bar_index, y2, "Sell", color = color.new(#c90505, 35), textcolor =
#ffffff, size = size.normal, style = label.style_label_down)

//if signalMode == 'Trend Mode' and strongSellCond


// label.new(bar_index, y2, "Strong", color = color.new(#c90505, 35), textcolor
= #ffffff, size = size.normal, style = label.style_label_down)

if signalMode == 'Ai Mode' and buyCond and Long_Signal_Strength >= aiMinimum or


signalMode == 'Ai Mode' and strongBuyCond and Long_Signal_Strength >= aiMinimum or
signalMode == "Ai + Reversal" and buyCond and Long_Signal_Strength >= aiMinimum or
signalMode == "Ai + Reversal" and strongBuyCond and Long_Signal_Strength >=
aiMinimum
label.new(bar_index, y1, "Buy\n" + str.tostring(Long_Signal_Strength) + "★",
color = color.new(color_1, 35), textcolor = #ffffff, size = size.normal, style =
label.style_label_up)

if signalMode == 'Ai Mode' and sellCond and Short_Signal_Strength >= aiMinimum or


signalMode == 'Ai Mode' and strongSellCond and Short_Signal_Strength >= aiMinimum
or signalMode == "Ai + Reversal" and sellCond and Short_Signal_Strength >=
aiMinimum or signalMode == "Ai + Reversal" and strongSellCond and
Short_Signal_Strength >= aiMinimum
label.new(bar_index, y2, str.tostring(Short_Signal_Strength) + "★" + "\nSell",
color = color.new(color_4, 35), textcolor = #ffffff, size = size.normal, style =
label.style_label_down)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Candle Concepts
-----------------------------------------------------------------------------------
-- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

[macd, signal, hist] = ta.macd(src, math.round(sensitivity * 1.25),


math.round(sensitivity * 2.5), math.round(sensitivity))

color barcolor = na

// terms

rsi2 = ta.rsi(close, math.round(sensitivity))


[macd2, signal2, hist2] = ta.macd(rsi2, math.round(sensitivity * 1.36),
math.round(sensitivity * 2.55), math.round(sensitivity))

macdHigh = ta.sma(ta.highest(hist, 100), 25)


macdLow = ta.sma(ta.lowest(hist, 35), 25)

color gradientBull = color.from_gradient(ta.rsi(close, math.round(sensitivity)),


32, 75, #67249f, colorScheme == "Delta Mode" ? #30DC1E : color_2)
color gradientBear = color.from_gradient(ta.rsi(close, math.round(sensitivity)),
25, 72, color_3, #67249f)

// conditions change
//if CandleColor == 'ConfirmationPlus'
// barcolor := macd2 > 0 and upward > downward ? #00db0a : macd2 < 0 and upward
< downward ? #ff0000 : #56328f
//barcolor := upward > downward and hist > 0 ? #00db0a : upward < downward and
hist < 0 ? #ff0000 : #7e7e7e

if CandleColor == 'Gradient Trend'


barcolor := upward > downward ? gradientBull : gradientBear

if CandleColor == 'TrendEdge'
barcolor := upward > downward ? color.new(color_1, 5) : upward < downward ?
color.new(color_3, 5) : color.new(color_5, 0)

barcolor(enableCandle ? barcolor : na)


dimGreen = #258E40, dimRed = #C10E40

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// -------------------------------------- Ecko Cloud
-----------------------------------------------------------------------------------
---- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

fastEk = ta.ema(close, 95) + (ta.atr(2) * 0.05), slowEk = ta.ema(close, 125) -


(ta.atr(11) * 0.08)
EkF = plot(EckoCloud ? fastEk : na, editable = false, color = fastEk > slowEk ?
color.new(color_1, 80) : color.new(color_3, 80))
EkS = plot(EckoCloud ? slowEk : na, editable = false, color = fastEk > slowEk ?
color.new(color_1, 80) : color.new(color_3, 80))

fill(EkF, EkS, color = fastEk > slowEk ? color.new(color_1, 85) :


color.new(color_3, 85), title = "Ecko Cloud")

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------- Trend Sniper
-----------------------------------------------------------------------------------
---- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

sniper = smoothrng(close, 50, 2.36)


trndSniper = rngfilt(close, sniper)

sniperUp = 0.0
sniperUp := trndSniper > trndSniper[1] ? nz(sniperUp[1]) + 1 : trndSniper <
trndSniper[1] ? 0 : nz(sniperUp[1])
sniperDn = 0.0
sniperDn := trndSniper < trndSniper[1] ? nz(sniperDn[1]) + 1 : trndSniper >
trndSniper[1] ? 0 : nz(sniperDn[1])

plot(trendSniper ? trndSniper : na, "Trend Sniper", sniperUp > sniperDn ?


color.new(color_1, 5) : sniperUp <= sniperDn ? color.new(color_3, 5) : na, 2,
plot.style_line)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------- Dyanmics Trend
-----------------------------------------------------------------------------------
-- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

stopTrail(mode, src, len) =>


float result = 0.0
result := ta.sma(src, len)
result

ATR = stopTrail(ta.sma(ta.tr, 7), ta.tr, 7)


upperTrail = ta.sma(ta.lowest(close, 17) + 4 * ATR, 8)
lowerTrail = ta.sma(ta.highest(close, 17) - 4 * ATR, 8)

float trailingStop = 0.0


trailingStop := close < trailingStop[1] ? upperTrail[1] : close > trailingStop[1] ?
lowerTrail[1] : trailingStop

//plot
plot(dynamicTrend ? trailingStop : na, title='Dynamic Trail', color=close <
trailingStop ? color.new(color_3, 0) : color.new(color_1, 0))

// ai stuff

if trailingStop < close


dynamicBull := true
dynamicBear := false
if trailingStop > close
dynamicBear := true
dynamicBull := false

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Radient Assistance
----------------------------------------------------------------------------------
}}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

radientMa = ta.ema(close, 55)

plot(radientAssistance ? radientMa : na, "radientAssistance", radientMa < close ?


color.new(color_1, 35) : color.new(color_3, 35), 6, editable = false)
plot(radientAssistance ? radientMa : na, "radientAssistance", radientMa < close ?
color.new(color_1, 80) : color.new(color_3, 80), 7, editable = false)
plot(radientAssistance ? radientMa : na, "radientAssistance", radientMa < close ?
color.new(color_1, 85) : color.new(color_3, 85), 8, editable = false)
plot(radientAssistance ? radientMa : na, "radientAssistance", radientMa < close ?
color.new(color_1, 90) : color.new(color_3, 89), 9, editable = false)
plot(radientAssistance ? radientMa : na, "radientAssistance", radientMa < close ?
color.new(color_1, 90) : color.new(color_3, 92), 11, editable = false)
plot(radientAssistance ? radientMa : na, "radientAssistance", radientMa < close ?
color.new(color_1, 90) : color.new(color_3, 96), 12, editable = false)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Reversal Cloud
-----------------------------------------------------------------------------------
--- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
s = ta.lowest(10)
r = ta.highest(10)

[mid, up, dn] = ta.kc(r, 18, 2)


[mid2, up2, dn2] = ta.kc(r, 10, 2.4)
[mid3, up3, dn3] = ta.kc(r, 17, 3.7)

[m, u, d] = ta.kc(s, 18, 2)


[m2, u2, d2] = ta.kc(s, 10, 2.4)
[m3, u3, d3] = ta.kc(s, 17, 3.7)

rsiR = ta.rsi(close, 16)

color topBandR = color.from_gradient(rsiR, 50, 85, color.new(#df6a26, 100),


color.new(#df6a26, 35)) //#df2635
color botBandR = color.from_gradient(rsiR, 15, 50, color.new(#07b354, 35),
color.new(#07b354, 100))

r1 = plot(reversalCloud ? ta.sma(up, 25) : na, color = color.new(#f74444, 80),


editable = false)
r2 = plot(reversalCloud ? ta.sma(up2, 25) + ta.atr(12) : na, color =
color.new(#f74444, 100), editable = false)
r3 = plot(reversalCloud ? ta.sma(up3, 25) + ta.atr(6) : na, color = topBandR,
editable = false, linewidth = 4)

s1 = plot(reversalCloud ? ta.sma(d, 25) : na, color = color.new(#4caf50, 80),


editable = false)
s2 = plot(reversalCloud ? ta.sma(d2, 25) - ta.atr(11) : na, color =
color.new(#4caf50, 100), editable = false)
s3 = plot(reversalCloud ? ta.sma(d3, 25) - ta.atr(5) : na, color = botBandR,
editable = false, linewidth = 4)

fill(r1, r2, title = "Reversal Cloud (R1, R2)", color = color.new(#e92d3d, 80))
//#f74444
fill(r2, r3, title = "Reversal Cloud (R2, R3)", color = color.new(#e92d3d, 65))

fill(s1, s2, title = "Reversal Cloud (S1, S2)", color = color.new(#089969, 80))
//#089969
fill(s2, s3, title = "Reversal Cloud (S2, S3)", color = color.new(#089969, 65))

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Dashboard Concepts
----------------------------------------------------------------------------------
}}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

length = 20
smoothing = "RMA"
length_2 = 200

ma_function(source, length) =>


switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
ATR_Fast = ma_function(ta.tr(true), length)

ATR_Slow = ma_function(ta.tr(true), length_2)

Volitility = ATR_Fast > ATR_Slow ? "High" : "Low"

if Volitility == "High"
highVol := true
lowVol := false
if Volitility == "Low"
lowVol := true
lowVol := false

// ------------------------------------------------------------------ }}
// ----------- Trade Backtesting ------------------------------------ }}
// ------------------------------------------------------------------ }}

//tradeBacktest() =>
var trades = 0, var wins = 0, var losses = 0

if (buyCond or strongBuyCond)
trades += 1
if (sellCond or strongSellCond)
lastBuyValue = ta.valuewhen(buyCond or strongBuyCond, close, 0)
currentValue = close
if lastBuyValue < currentValue
wins += 1
else
losses += 1

signalWinrate = (wins / trades) * 100

//trend strength
strength = ta.sma(nz(math.abs((open - close) / (high - low) * 100)), 10)

//plotting dashboard
var dashboard_loc = locationDashboard == "Top Right" ? position.top_right :
locationDashboard == "Middle Right" ? position.middle_right : locationDashboard ==
"Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ?
position.top_center : locationDashboard == "Middle Center" ? position.middle_center
: locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard
== "Top Left" ? position.top_left : locationDashboard == "Middle Left" ?
position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard ==
"Normal" ? size.normal : sizeDashboard == "Small" ? size.small : sizeDashboard ==
"Tiny" ? size.tiny : size.auto
var dashboard = showDashboard ? table.new(dashboard_loc, 4, 6, #1d1c24,
#11121f, 2, color.new(#11121f, 0), 2) : na
dashboard_cell(column, row, txt, signal=false) => table.cell(dashboard, column,
row, txt, 0, 0, signal ? color.new(#ffffff, 5) : color.new(#ffffff, 5),
text_size=dashboard_size)
dashboard_cell_bg(column, row, col) => table.cell_set_bgcolor(dashboard, column,
row, col)
dashboard_txt(column, row, col) => table.cell_set_text_color(dashboard, column,
row, col)
dashboard_txt_pos(column, row, align) => table.cell_set_text_halign(dashboard,
column, row, align)
if barstate.islast and showDashboard
dashboard_cell(0, 0 , "Market Strength"), dashboard_txt_pos(0, 0,
text.align_left)//, dashboard_cell_bg(0, 0, color.new(#000000, 25))
dashboard_cell(1, 0 , "Market Volatility"), dashboard_txt_pos(1, 0,
text.align_left)//, dashboard_cell_bg(1, 0, color.new(#000000, 25))
dashboard_cell(0, 1 , str.tostring(strength, format.percent), true)//,
dashboard_txt(1, 0, strength > 80 ? color.new(#7af080, 20) : strength < 20 ?
color.new(#f0675d, 20) : color.new(#ffffff, 5))
dashboard_cell(1, 1 , Volitility), dashboard_cell_bg(1, 1, Volitility ==
"Low" ? #d68812 : #1c51c5)// dashboard_txt_pos(1, 1, text.align_left)
if statisticsDas
dashboard_cell(2, 0, "Profitability")
dashboard_cell(2, 1, str.tostring(trades, "#"))

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ----------------------------------- Reversal Concepts
-----------------------------------------------------------------------------------
- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

rsi = ta.rsi(close, math.round(sensitivity))

revU = ta.crossover(rsi, 30)


revD = ta.crossunder(rsi, 70)

reversalUpCond = revU and not revU[1] and not revU[2] and not revU[3] and not
revU[4]and not revU[5]and not revU[6]and not revU[7]and not revU[8]and not
revU[9]and not revU[10]and not revU[11]and not revU[12]and not revU[13]
reversalDownCond = revD and not revD[1] and not revD[2] and not revD[3] and not
revD[4] and not revD[5] and not revD[6] and not revD[7] and not revD[8] and not
revD[9] and not revD[10] and not revD[11] and not revD[12] and not revD[13]

if reversalUpCond
alrRevUp := true
alrRevDn := false

if reversalDownCond
alrRevUp := false
alrRevDn := true

revEbull = rsi < 40 //and open[1] < close and close[1] > open
revEbear = rsi > 58 //and open[1] > close and close[1] < open

eBull = revEbull and open[1] > close[1] and close > open[1]
eBear = revEbear and open[1] < close[1] and close < open[1]

eBull := revEbull and open[1] > close[1] and close > open[1] and not eBull[1] and
not eBull[2] and not eBull[3] and not eBull[4]
eBear := revEbear and open[1] < close[1] and close < open[1] and not eBear[1] and
not eBear[2] and not eBear[3] and not eBear[4]

plotshape(marketStructures == "Reversals" and enableStructures and reversalUpCond


and barstate.isconfirmed or marketStructures == "Reversals + Eg" and
enableStructures and reversalUpCond and barstate.isconfirmed, "Reversal Up
Signals", shape.labelup, location.belowbar, color.new(#56328f, 38), 0, "Reversal
Up", #ffffff, size=size.small)
plotshape(marketStructures == "Reversals" and enableStructures and reversalDownCond
and barstate.isconfirmed or marketStructures == "Reversals + Eg" and
enableStructures and reversalDownCond and barstate.isconfirmed, "Reversal Down
Signals", shape.labeldown, location.abovebar, color.new(#b22833, 38), 0, "Reversal
Down", #ffffff, size=size.small)

plotshape(marketStructures == "Engulfing" and enableStructures and eBull and


barstate.isconfirmed or marketStructures == "Reversals + Eg" and enableStructures
and eBull and barstate.isconfirmed, "Bullish Engulfing", shape.xcross,
location.belowbar, color.new(#2157f3, 100), 0, "Eg ©", color.new(#089981, 65),
size=size.tiny)
plotshape(marketStructures == "Engulfing" and enableStructures and eBear and
barstate.isconfirmed or marketStructures == "Reversals + Eg" and enableStructures
and eBear and barstate.isconfirmed, "Bearish Engulfing", shape.xcross,
location.abovebar, color.new(color.orange, 100), 0, "Eg ©", color.new(#ff5252, 65),
size=size.tiny)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ TP/SL Concepts
-----------------------------------------------------------------------------------
--- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

lvlDistance = (2), atrLen = (14)


trigger = buyCond or strongBuyCond ? 1 : 0, trigger2 = sellCond or strongSellCond ?
0 : 1

atrBand = ta.atr(atrLen) * TPrisk


atrStop = trigger == 1 ? low - atrBand : high + atrBand

lastTrade(src) => ta.valuewhen((buyCond or strongBuyCond) or (sellCond or


strongSellCond), src, 0)

tp1lvl = (lastTrade(close)-lastTrade(atrStop))*0.75 + lastTrade(close)

tp2lvl = (lastTrade(close)-lastTrade(atrStop))*1.75 + lastTrade(close)

tp3lvl = (lastTrade(close)-lastTrade(atrStop))*2.75 + lastTrade(close)

tp4lvl = (lastTrade(close)-lastTrade(atrStop))*3.75 + lastTrade(close)

// -------------------------------------------------------------- }}
// ---------------- Signal Concepts ----------------------------- }}
// -------------------------------------------------------------- }}

var alrTP1 = false, var alrTPS1 = false, var alrTP2 = false, var alrTPS2 = false,
var alrTP3 = false, var alrTPS3 = false, var alrTP4 = false, var alrTPS4 = false

TP1up = not alrTP1 and ta.crossover(close, tp1lvl) and not sellCond and not
strongSellCond and upward > downward
TP2up = not alrTP2 and ta.crossover(close, tp2lvl) and not sellCond and not
strongSellCond and upward > downward
TP3up = not alrTP3 and ta.crossover(close, tp3lvl) and not sellCond and not
strongSellCond and upward > downward
TP4up = not alrTP4 and ta.crossover(close, tp4lvl) and not sellCond and not
strongSellCond and upward > downward
TP1dn = not alrTPS1 and ta.crossunder(close, tp1lvl) and not buyCond and not
strongBuyCond and upward < downward
TP2dn = not alrTPS2 and ta.crossunder(close, tp2lvl) and not buyCond and not
strongBuyCond and upward < downward
TP3dn = not alrTPS3 and ta.crossunder(close, tp3lvl) and not buyCond and not
strongBuyCond and upward < downward
TP4dn = not alrTPS4 and ta.crossunder(close, tp4lvl) and not buyCond and not
strongBuyCond and upward < downward

if buyCond or strongBuyCond
alrTP1 := false
alrTPS1 := true
alrTP2 := false
alrTPS2 := true
alrTP3 := false
alrTPS3 := true
alrTP4 := false
alrTPS4 := true
if sellCond or strongSellCond
alrTP1 := true
alrTPS1 := false
alrTP2 := true
alrTPS2 := false
alrTP3 := true
alrTPS3 := false
alrTP4 := true
alrTPS4 := false
if TP1up
alrTP1 := true
if TP2up
alrTP2 := true
if TP3up
alrTP3 := true
if TP4up
alrTP4 := true
if TP1dn
alrTPS1 := true
if TP2dn
alrTPS2 := true
if TP3dn
alrTPS3 := true
if TP4dn
alrTPS4 := true

plotshape(TPpoints ? TP1up : na, 'TakeProfit 1', shape.labeldown,


location.abovebar, color.new(#2157f9, 100), 0, '✗', #2157f9, true, size.tiny)
plotshape(TPpoints ? TP2up : na, 'TakeProfit 2', shape.labeldown,
location.abovebar, color.new(#2157f9, 100), 0, '✗', #2157f9, true, size.tiny)
plotshape(TPpoints ? TP3up : na, 'TakeProfit 3', shape.labeldown,
location.abovebar, color.new(#2157f9, 100), 0, '✗', #2157f9, true, size.tiny)
plotshape(TPpoints ? TP4up : na, 'TakeProfit 4', shape.labeldown,
location.abovebar, color.new(#2157f9, 100), 0, '✗', #2157f9, true, size.tiny)

plotshape(TPpoints ? TP1dn : na, 'StopLoss 1', shape.labelup, location.belowbar,


color.new(#ff1100, 100), 0, '✗', #ff1100, true, size.tiny)
plotshape(TPpoints ? TP2dn : na, 'StopLoss 2', shape.labelup, location.belowbar,
color.new(#ff1100, 100), 0, '✗', #ff1100, true, size.tiny)
plotshape(TPpoints ? TP3dn : na, 'StopLoss 3', shape.labelup, location.belowbar,
color.new(#ff1100, 100), 0, '✗', #ff1100, true, size.tiny)
plotshape(TPpoints ? TP4dn : na, 'StopLoss 4', shape.labelup, location.belowbar,
color.new(#ff1100, 100), 0, '✗', #ff1100, true, size.tiny)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Alert Concepts
-----------------------------------------------------------------------------------
--- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

normBuy = normalbuy ? buyCond : na


normSell = normalsell ? buyCond : na
stroBuy = strongbuy ? strongBuyCond : na
stroSell = strongsell ? strongSellCond : na
tp1Alert = tp1s ? TP1up or TP1dn : na
tp2Alert = tp2s ? TP2up or TP2dn : na
tp3Alert = tp3s ? TP3up or TP3dn : na
tp4Alert = tp4s ? TP4up or TP4dn : na
revUpAlert = revu ? reversalUpCond : na
revDnAlert = revd ? reversalDownCond : na

alertFunction = normBuy or normSell or stroBuy or stroSell or tp1Alert or tp2Alert


or tp3Alert or tp4Alert or revUpAlert or revDnAlert

alertcondition(alertFunction, alertGroup, 'Alert Triggered On {{ticker}} @


{{close}}')

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Ending Barrier
-----------------------------------------------------------------------------------
--- }}

enableTpSlAreas = input(true, "Enable take profit/stop-loss areas", group="RISK


MANAGEMENT SETTINGS")
useTP1 = input(true, "", inline="4", group="RISK MANAGEMENT SETTINGS")
multTP1 = input.float(1, "TP 1", 0, inline="4", group="RISK MANAGEMENT
SETTINGS")
useTP2 = input(true, "", inline="5", group="RISK MANAGEMENT SETTINGS")
multTP2 = input.float(2, "TP 2", 0, inline="5", group="RISK MANAGEMENT
SETTINGS")
useTP3 = input(true, "", inline="6", group="RISK MANAGEMENT SETTINGS")
multTP3 = input.float(3, "TP 3", 0, inline="6", group="RISK MANAGEMENT
SETTINGS")
usePercSL = input(false, "% Trailing sl", inline="2", group="RISK
MANAGEMENT SETTINGS")
percTrailingSL = input.float(1, "", 0, step=0.1, inline="2", group="RISK
MANAGEMENT SETTINGS")

countBull = ta.barssince(bull)
countBear = ta.barssince(bear)
trigger3 = nz(countBull, bar_index) < nz(countBear, bar_index) ? 1 : 0
none = close > 0

atrBand2 = usePercSL ? (trigger3 ? low : high) * (percTrailingSL / 100) :


ta.atr(14) * 2.2
atrStop3 = trigger3 ? low - atrBand2 : high + atrBand2
lastTrade4(src) => ta.valuewhen(bull or bear, src, 0)
entry_y = lastTrade4(close)
stop_y = lastTrade4(atrStop3)
tp1_y = (entry_y-lastTrade4(atrStop3))*multTP1 + entry_y
tp2_y = (entry_y-lastTrade4(atrStop3))*multTP2 + entry_y
tp3_y = (entry_y-lastTrade4(atrStop3))*multTP3 + entry_y
labelTpSl(cond, y, txt, color) =>
label labelTpSl = enableTpSlAreas and cond ? label.new(bar_index + 1, y, txt,
xloc.bar_index, yloc.price, color, label.style_label_left, color.white,
size.normal) : na
label.delete(labelTpSl[1])
labelTpSl(none, entry_y, "Entry : " + str.tostring(math.round_to_mintick(entry_y)),
color.orange)
labelTpSl(none, stop_y , "Stop loss : " +
str.tostring(math.round_to_mintick(stop_y)), color.red)
labelTpSl(useTP1 and multTP1 != 0, tp1_y, "TP 1 : " +
str.tostring(math.round_to_mintick(tp1_y)), color.green)
labelTpSl(useTP2 and multTP2 != 0, tp2_y, "TP 2 : " +
str.tostring(math.round_to_mintick(tp2_y)), color.green)
labelTpSl(useTP3 and multTP3 != 0, tp3_y, "TP 3 : " +
str.tostring(math.round_to_mintick(tp3_y)), color.green)
lineTpSl(cond, y, color, style) =>
line lineTpSl = enableTpSlAreas and cond ? line.new(bar_index - (trigger3 ?
countBull : countBear), y, bar_index + 1, y, xloc.bar_index, extend.none, color,
style) : na
line.delete(lineTpSl[1])
lineTpSl(none, entry_y, color.orange, line.style_dashed)
lineTpSl(none, stop_y , color.red , line.style_solid )
lineTpSl(useTP1 and multTP1 != 0, tp1_y, color.green, line.style_dotted)
lineTpSl(useTP2 and multTP2 != 0, tp2_y, color.green, line.style_dotted)
lineTpSl(useTP3 and multTP3 != 0, tp3_y, color.green, line.style_dotted)

enableTrailingSL = input(false, "Enable trailing stop-loss", group="RISK


MANAGEMENT SETTINGS")

atr(len) =>
tr = ta.tr
atr = 0.0
atr := nz(atr[1] + (tr - atr[1]) / len, tr)

trailingSL(buy, sell, factor, len, usePerc, perc) =>


atr = atr(len)
upperBand = high + (usePerc ? high * (perc / 100) : factor * atr)
lowerBand = low - (usePerc ? low * (perc / 100) : factor * atr)
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or buy ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or sell ? upperBand : prevUpperBand
int direction = na
float stop = na
prevSuperTrend = stop[1]
if prevSuperTrend == prevUpperBand
direction := bull ? 1 : -1
else
direction := bear ? -1 : 1
stop := direction == 1 ? lowerBand : direction == -1 ? upperBand : na

trailingStop2 = trailingSL(bull, bear, 2.2, 14, usePercSL, percTrailingSL)

//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}
// ------------------------------------ Ending Barrier
-----------------------------------------------------------------------------------
--- }}
//
-----------------------------------------------------------------------------------
------------------------------------------------------- }}

//PIVOTES
////////////////////////////////////////////////////////////////////////////////
//
// ====== ABOUT THIS INDICATOR
//
// - All your common Pivot types in one nifty bundle.
//
// • Have up to three pivot sets.
// • Each pivot set has it's own resolution option.
// • Whatever flavour suits your tastes - each pivot set can be of a
// different type if you truly wish.
//
// ====== SOURCES and CREDITS
//
// - All included pivot calcs were sourced from:
//
// • https://www.tradingview.com/support/solutions/43000521824-pivot-points-
standard/
// • Using the new 'time_close()' function, so thankyou Pine dev's <3
//
// ====== REASON FOR STUDY
//
// - To practice making scalable code for working with similar datasets.
//
// • all the reasons
//
// ====== DISCLAIMER
//
// Any trade decisions you make are entirely your own responsibility.
// I've made an effort to squash all the bugs, but you never know!
//
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
// //
// ====== OPTION LIST VARS ====== //
// //
// * Setting up option list variables outside of the actual input can //
// make them much easier to work with if any comparison checks are //
// required, and can help keep subsequent code clean and readable. //
// //
////////////////////////////////////////////////////////////////////////////////

// -- verbose resolution options.


i_res0 = '1 Hour'
i_res1 = '2 Hour'
i_res2 = '3 Hour'
i_res3 = '4 Hour'
i_res4 = '6 Hour'
i_res5 = '12 Hour'
i_res6 = '1 Day'
i_res7 = '5 Day'
i_res8 = '1 Week'
i_res9 = '1 Month'
i_res10 = '3 Month'
i_res11 = '6 Month'
i_res12 = '1 Year'

// -- pivot options
i_piv0 = 'Traditional'
i_piv1 = 'Fibonacci'
i_piv2 = 'Woodie'
i_piv3 = 'Classic'
i_piv4 = 'Demark'
i_piv5 = 'Camarilla'
i_piv6 = 'Fibonacci Extended'

// -- line style options.


i_line0 = 'Solid'
i_line1 = 'Dotted'
i_line2 = 'Dashed'

////////////////////////////////////////////////////////////////////////////////
// //
// ====== VAR and ARRAY PRESET ====== //
// //
////////////////////////////////////////////////////////////////////////////////

// -- Preset INT for maximum amount of S|R levels for any single pivot type.
// NOTE - this variable should only be changed if:
// • you extend a pivot to have more than 5 levels of S|R
// • you add a new pivot type wiith more than 5 levels of S|R
var int i_maxLevels = 5

// -- Preset INT for max length of pivot arrays [PP + S max + R max]
// * NOTE: should not be changed.
var int i_maxLength = 1 + i_maxLevels * 2

// -- Initiate arrays to contain INT variables used in drawing function


// settings, we fill these at the end of the INPUTS section.
var int[] i_settingsA = array.new_int(3, 0)
//var int[] i_settingsB = array.new_int(3, 0)
//var int[] i_settingsC = array.new_int(3, 0)

////////////////////////////////////////////////////////////////////////////////
// //
// ====== INPUTS ====== //
// //
// * Using the new 'inline' feature * //
// //
////////////////////////////////////////////////////////////////////////////////

// -- Pivots A Main Settings


INP_showPivotsA = input.bool(false, ' -----------------------Show
Pivots------------', group='Pivot Set A Settings')
INP_resolutionA = input.string(i_res6, ' ', inline='line1', group='Pivot Set A
Settings', options=[i_res0, i_res1, i_res2, i_res3, i_res4, i_res5, i_res6, i_res7,
i_res8, i_res9, i_res10, i_res11, i_res12])

INP_supportsA = input.int(2, ' ', inline='line2', group='Pivot Set A Settings',


minval=0, maxval=i_maxLevels)
INP_flavourA = input.string(i_piv1, 'S# ', inline='line2', group='Pivot Set A
Settings', options=[i_piv0, i_piv1, i_piv2, i_piv3, i_piv4, i_piv5, i_piv6])
INP_resistsA = input.int(2, ' R#', inline='line2', group='Pivot Set A Settings',
minval=0, maxval=i_maxLevels)

// -- Pivots B Main Settings

//INP_resolutionB = input( i_res8, " ", inline = "line3",


group = "Pivot Set B Settings",
// options = [ i_res0, i_res1, i_res2, i_res3, i_res4, i_res5,
// i_res6, i_res7, i_res8, i_res9, i_res10, i_res11, i_res12
// ])
//INP_showPivotsB = input( false, " Show Pivots Set B", inline = "line3",
group = "Pivot Set B Settings",
// type = input.bool
// )
//INP_supportsB = input( 2, " ", inline = "line4",
group = "Pivot Set B Settings",
// type = input.integer, minval = 0, maxval = i_maxLevels
// )
//INP_flavourB = input( i_piv1, "S# ", inline = "line4",
group = "Pivot Set B Settings",
// options = [ i_piv0, i_piv1, i_piv2, i_piv3, i_piv4, i_piv5, i_piv6
// ])
//INP_resistsB = input( 2, " R#", inline = "line4",
group = "Pivot Set B Settings",
// type = input.integer, minval = 0, maxval = i_maxLevels
// )

// -- Pivots C Main Settings

//INP_resolutionC = input( i_res9, " ", inline = "line5",


group = "Pivot Set C Settings",
// options = [ i_res0, i_res1, i_res2, i_res3, i_res4, i_res5,
// i_res6, i_res7, i_res8, i_res9, i_res10, i_res11, i_res12
// ])
//INP_showPivotsC = input( false, " Show Pivots Set C", inline = "line5",
group = "Pivot Set C Settings",
// type = input.bool
// )
//INP_supportsC = input( 2, " ", inline = "line6",
group = "Pivot Set C Settings",
// type = input.integer, minval = 0, maxval = i_maxLevels
// )
//INP_flavourC = input( i_piv1, "S# ", inline = "line6",
group = "Pivot Set C Settings",
//// options = [ i_piv0, i_piv1, i_piv2, i_piv3, i_piv4, i_piv5, i_piv6
// ])
//INP_resistsC = input( 2, " R#", inline = "line6",
group = "Pivot Set C Settings",
// type = input.integer, minval = 0, maxval = i_maxLevels
// )

// -- price labels

INP_showPrice = input.bool(false, ' ', inline='line7', group='Price Labels')


INP_priceColour = input.color(color.gray, ' Text Colour', inline='line7',
group='Price Labels')

// -- styling options

INP_supportStyle = input.string(i_line0, ' ', inline='line8', group='Styling


Options', options=[i_line0, i_line1, i_line2])
INP_supportColour = input.color(color.green, ' S Levels', inline='line8',
group='Styling Options')

INP_pivotStyle = input.string(i_line0, ' ', inline='line9', group='Styling


Options', options=[i_line0, i_line1, i_line2])
INP_pivotColour = input.color(color.silver, ' P Levels', inline='line9',
group='Styling Options')

INP_resistStyle = input.string(i_line0, ' ', inline='line10', group='Styling


Options', options=[i_line0, i_line1, i_line2])
INP_resistColour = input.color(color.red, ' R Levels', inline='line10',
group='Styling Options')

// -- drawing settings for selection A


array.set(i_settingsA, 0, INP_showPivotsA ? 1 : 0)
array.set(i_settingsA, 1, INP_supportsA)
array.set(i_settingsA, 2, INP_resistsA)
// -- drawing settings for selection B
//array.set(i_settingsB, 0, INP_showPivotsB ? 1 : 0)
//array.set(i_settingsB, 1, INP_supportsB)
//array.set(i_settingsB, 2, INP_resistsB)
// -- drawing settings for selection C
//array.set(i_settingsC, 0, INP_showPivotsC ? 1 : 0)
//array.set(i_settingsC, 1, INP_supportsC)
//array.set(i_settingsC, 2, INP_resistsC)

////////////////////////////////////////////////////////////////////////////////
// //
// ====== FUNCTIONS ====== //
// //
////////////////////////////////////////////////////////////////////////////////

f_getResolution(_inputResolution) =>
// string _inputResolution : user selected resolution input
// () Description:
// - Resolver for custom resolution input selection, converts input to
// compatible return string for security, output is also used for less
// verbose label text options.
// Dependencies:
// - i_res1, i_res2, i_res3, i_res4, i_res5, i_res6
// - i_res7, i_res8, i_res9, i_res10, i_res11, i_res12
// Notes:
// - i_res0 excluded as it's a token placeholder for default "60".

string _r = _inputResolution // a more ternary challenge friendly var


string _default = '60' // if i_res0 was input, or failure.

// compare input to determine proper string return for security calls.


_return = _r == i_res1 ? '120' : _r == i_res2 ? '180' : _r == i_res3 ? '240' :
_r == i_res4 ? '360' : _r == i_res5 ? '720' : _r == i_res6 ? '1D' : _r == i_res7 ?
'5D' : _r == i_res8 ? '1W' : _r == i_res9 ? '1M' : _r == i_res10 ? '3M' : _r ==
i_res11 ? '6M' : _r == i_res12 ? '12M' : _default
_return

f_getLineStyle(_inputStyle) =>
// string _inputStyle : user selected style input
// () resolver for custom line style input selection, returns a usable
// line style type.
// Dependencies:
// - i_line1, i_line2
// Notes:
// * i_line0 omitted as we default to 'line.style_solid' anyway

// compare input to determine proper line style to return.


_return = _inputStyle == i_line1 ? line.style_dotted : _inputStyle == i_line2 ?
line.style_dashed : line.style_solid
_return

// -- helper function for checking if a value is inside a min-max range


f_isInsideRange(_val, _min, _max) =>
_val >= _min and _val <= _max

f_getPivotTraditional(_prevHigh, _prevLow, _prevClose) =>


// float _prevHigh | _prevLow | _prevClose : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// init empty array with predefined length of i_maxLength


var float[] _array = array.new_float(i_maxLength, na)

// pivot level, array index [0]


_pivot = (_prevHigh + _prevLow + _prevClose) / 3
array.set(_array, 0, _pivot)

// support levels, array indexes [1] through [i_maxLevels]


array.set(_array, 1, _pivot * 2 - _prevHigh)
array.set(_array, 2, _pivot - (_prevHigh - _prevLow))
array.set(_array, 3, _pivot * 2 - (2 * _prevHigh - _prevLow))
array.set(_array, 4, _pivot * 3 - (3 * _prevHigh - _prevLow))
array.set(_array, 5, _pivot * 4 - (4 * _prevHigh - _prevLow))

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, _pivot * 2 - _prevLow)
array.set(_array, 2 + i_maxLevels, _pivot + _prevHigh - _prevLow)
array.set(_array, 3 + i_maxLevels, _pivot * 2 + _prevHigh - 2 * _prevLow)
array.set(_array, 4 + i_maxLevels, _pivot * 3 + _prevHigh - 3 * _prevLow)
array.set(_array, 5 + i_maxLevels, _pivot * 4 + _prevHigh - 4 * _prevLow)

_return = _array
_return

f_getPivotFibonacci(_prevHigh, _prevLow, _prevClose) =>


// float _prevHigh | _prevLow | _prevClose : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// init empty array with predefined length of i_maxLength


var float[] _array = array.new_float(i_maxLength, na)

// pivot level, array index [0]


_pivot = (_prevHigh + _prevLow + _prevClose) / 3
array.set(_array, 0, _pivot)

// support levels, array indexes [1] through [i_maxLevels]


array.set(_array, 1, _pivot - 0.382 * (_prevHigh - _prevLow))
array.set(_array, 2, _pivot - 0.618 * (_prevHigh - _prevLow))
array.set(_array, 3, _pivot - (_prevHigh - _prevLow))

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, _pivot + 0.382 * (_prevHigh - _prevLow))
array.set(_array, 2 + i_maxLevels, _pivot + 0.618 * (_prevHigh - _prevLow))
array.set(_array, 3 + i_maxLevels, _pivot + _prevHigh - _prevLow)

_return = _array
_return

f_getPivotWoodie(_prevHigh, _prevLow, _currentOpen) =>


// float _prevHigh | _prevLow | _currentOpen : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// init empty array with predefined length of i_maxLength


var float[] _array = array.new_float(i_maxLength, na)

// pivot level, array index [0]


_pivot = (_prevHigh + _prevLow + 2 * _currentOpen) / 4
array.set(_array, 0, _pivot)
// support levels, array indexes [1] through [i_maxLevels]
array.set(_array, 1, 2 * _pivot - _prevHigh)
array.set(_array, 2, _pivot - (_prevHigh - _prevLow))
array.set(_array, 3, _prevLow - 2 * (_prevHigh - _pivot))
array.set(_array, 4, array.get(_array, 3) - (_prevHigh - _prevLow))

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, 2 * _pivot - _prevLow)
array.set(_array, 2 + i_maxLevels, _pivot + _prevHigh - _prevLow)
array.set(_array, 3 + i_maxLevels, _prevHigh + 2 * (_pivot - _prevLow))
array.set(_array, 4 + i_maxLevels, array.get(_array, 3 + i_maxLevels) +
_prevHigh - _prevLow)

_return = _array
_return

f_getPivotClassic(_prevHigh, _prevLow, _prevClose) =>


// float _prevHigh | _prevLow | _prevClose : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// init empty array with predefined length of i_maxLength


var float[] _array = array.new_float(i_maxLength, na)

// pivot level, array index [0]


_pivot = (_prevHigh + _prevLow + _prevClose) / 3
array.set(_array, 0, _pivot)

// support levels, array indexes [1] through [i_maxLevels]


array.set(_array, 1, 2 * _pivot - _prevHigh)
array.set(_array, 2, _pivot - (_prevHigh - _prevLow))
array.set(_array, 3, _pivot - 2 * (_prevHigh - _prevLow))
array.set(_array, 4, _pivot - 3 * (_prevHigh - _prevLow))

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, 2 * _pivot - _prevLow)
array.set(_array, 2 + i_maxLevels, _pivot + _prevHigh - _prevLow)
array.set(_array, 3 + i_maxLevels, _pivot + 2 * (_prevHigh - _prevLow))
array.set(_array, 4 + i_maxLevels, _pivot + 3 * (_prevHigh - _prevLow))

_return = _array
_return

f_getPivotDemark(_prevOpen, _prevHigh, _prevLow, _prevClose) =>


// float _prevOpen | _prevHigh
// _prevLow | _prevClose : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]
// init empty array with predefined length of i_maxLength
var float[] _array = array.new_float(i_maxLength, na)

// demark basis calc


var float _basis = na
if _prevOpen == _prevClose
_basis := _prevHigh + _prevLow + 2 * _prevClose
_basis
else if _prevClose > _prevOpen
_basis := 2 * _prevHigh + _prevLow + _prevClose
_basis
else
_basis := _prevHigh + 2 * _prevLow + _prevClose
_basis

// pivot level, array index [0]


_pivot = _basis / 4
array.set(_array, 0, _pivot)

// support levels, array indexes [1] through [i_maxLevels]


array.set(_array, 1, _basis / 2 - _prevHigh)

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, _basis / 2 - _prevLow)

_return = _array
_return

f_getPivotCamarilla(_prevHigh, _prevLow, _prevClose) =>


// float _open | _high | _low | _close : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// init empty array with predefined length of i_maxLength


var float[] _array = array.new_float(i_maxLength, na)

// pivot level, array index [0]


_pivot = (_prevHigh + _prevLow + _prevClose) / 3
array.set(_array, 0, _pivot)

// support levels, array indexes [1] through [i_maxLevels]


array.set(_array, 1, _prevClose - 1.1 * (_prevHigh - _prevLow) / 12)
array.set(_array, 2, _prevClose - 1.1 * (_prevHigh - _prevLow) / 6)
array.set(_array, 3, _prevClose - 1.1 * (_prevHigh - _prevLow) / 4)
array.set(_array, 4, _prevClose - 1.1 * (_prevHigh - _prevLow) / 2)

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, _prevClose + 1.1 * (_prevHigh - _prevLow) /
12)
array.set(_array, 2 + i_maxLevels, _prevClose + 1.1 * (_prevHigh - _prevLow) /
6)
array.set(_array, 3 + i_maxLevels, _prevClose + 1.1 * (_prevHigh - _prevLow) /
4)
array.set(_array, 4 + i_maxLevels, _prevClose + 1.1 * (_prevHigh - _prevLow) /
2)

_return = _array
_return

f_getPivotFibonacciExt(_prevHigh, _prevLow, _prevClose) =>


// float _open | _high | _low | _close : HTF security OHLC values
// () calculates a pivot set and assigns to proper array indexes for return.
// Notes:
// - f_renderPivotArray() expects float data in the following sequence..
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// init empty array with predefined length of i_maxLength


var float[] _array = array.new_float(i_maxLength, na)

// pivot level, array index [0]


_pivot = (_prevHigh + _prevLow + _prevClose) / 3
array.set(_array, 0, _pivot)

// support levels, array indexes [1] through [i_maxLevels]


array.set(_array, 1, _pivot - 0.236 * (_prevHigh - _prevLow))
array.set(_array, 2, _pivot - 0.382 * (_prevHigh - _prevLow))
array.set(_array, 3, _pivot - 0.618 * (_prevHigh - _prevLow))
array.set(_array, 4, _pivot - 0.786 * (_prevHigh - _prevLow))
array.set(_array, 5, _pivot - (_prevHigh - _prevLow))

// resistance levels, array indexes [i_maxLevels + 1] through [i_maxLength]


array.set(_array, 1 + i_maxLevels, _pivot + 0.236 * (_prevHigh - _prevLow))
array.set(_array, 2 + i_maxLevels, _pivot + 0.382 * (_prevHigh - _prevLow))
array.set(_array, 3 + i_maxLevels, _pivot + 0.618 * (_prevHigh - _prevLow))
array.set(_array, 4 + i_maxLevels, _pivot + 0.786 * (_prevHigh - _prevLow))
array.set(_array, 5 + i_maxLevels, _pivot + _prevHigh - _prevLow)

_return = _array
_return

f_getPivotSet(_flavour, _resolution) =>


// string _flavour : user input pivot type selection
// string _resolution : user input resolution selection
// () gets OHLC values from selected resolution, and returns requested
// pivot calculation array.

// previous OHLC series for selected resolution


[_prevOpen, _prevHigh, _prevLow, _prevClose] =
request.security(syminfo.tickerid, _resolution, [open[1], high[1], low[1],
close[1]], lookahead=barmerge.lookahead_on)

var float _currOpen = na


if ta.change(time(_resolution)) != 0
_currOpen := open
_currOpen

// float array to contain S|R levels for return.


var float[] _pivotSet = array.new_float(i_maxLength, na)
_pivotSet := _flavour == i_piv0 ? f_getPivotTraditional(_prevHigh, _prevLow,
_prevClose) : _flavour == i_piv1 ? f_getPivotFibonacci(_prevHigh, _prevLow,
_prevClose) : _flavour == i_piv2 ? f_getPivotWoodie(_prevHigh, _prevLow, _currOpen)
: _flavour == i_piv3 ? f_getPivotClassic(_prevHigh, _prevLow, _prevClose) :
_flavour == i_piv4 ? f_getPivotDemark(_prevOpen, _prevHigh, _prevLow, _prevClose) :
_flavour == i_piv5 ? f_getPivotCamarilla(_prevHigh, _prevLow, _prevClose) :
f_getPivotFibonacciExt(_prevHigh, _prevLow, _prevClose)

_pivotSet // return the float array

f_renderPivotArray(_resolution, _settings, _floats, _lines, _labels) =>


// string _resolution : user selected resolution input
// int[] _settings : pivot specific input settings
// float[] _floats : pivot float array
// line[] _lines : line array to hold rendered lines
// label[] _labels : label array to hold rendered labels
//
// () Description:
// - Designed for scalability and plug-n-play functionality if any new
// pivot type is added, or extended.
// - If a f_pivotType() function properly assigns it's float values in the
// following format/order, it should be able to to render them with no
// hassle at all.
//
// Pivot : [ 0 ]
// Supports : [ 1 to i_maxLevels ]
// Resists : [ ( i_maxLevels + 1 ) to i_maxLength ]

// set up a few common vars for drawing using 'time' placement


_xloc = xloc.bar_time
_x1 = ta.valuewhen(ta.change(time(_resolution)), time, 0) // time
_x2 = time_close(_resolution) // new! Thanks pine team <3

// set up some temp vars for creating our lines and labels
var line _line = na
var label _labelLeft = na
var label _labelRight = na
var label _labelPrice = na

// init some readable settings variables to hold _settings data


var bool _showPivot = false
var int _maxSupports = i_maxLevels
var int _maxResists = i_maxLevels

// hand off the settings array to the vars


_showPivot := array.get(_settings, 0) > 0 ? true : false
_maxSupports := array.get(_settings, 1)
_maxResists := array.get(_settings, 2)

// if we want to show the particular pivot set


// * the change() check was causing issues on extended hours intraday charts
// so i have removed it for now. I will look into other options for the
// next proper update.
if _showPivot // change( time( _resolution ) ) != 0 and _showPivot

// clean up old lines and labels before drawing our new set
for i = 1 to array.size(_lines) by 1 // loop and delete 1 by 1
line.delete(array.get(_lines, i - 1))
// the label array is dynamic length, so we..
if array.size(_labels) > 0 // ..check to see if it has content..
for i = 1 to array.size(_labels) by 1 // ..then loop it into the trash
label.delete(array.shift(_labels))

// check for properly populated float array


if array.size(_floats) > 0 and not na(array.get(_floats, 0))

// now loop through the floats


for i = 1 to array.size(_floats) by 1

// don't want to bother with [i - 1] throughout the entire loop


_index = i - 1 // so set up a var

// if we have a valid float at the current loop index


if not na(array.get(_floats, _index))

// common variables used in all conditions


_activePrice = array.get(_floats, _index)
_priceString = '• ' + str.tostring(_activePrice, '#.#####')

// IDENTIFYING SUPPORT LEVELS IN ARRAY


//
// support index range : [ from 1 to i_maxLevels ]
if f_isInsideRange(_index, 1, i_maxLevels)

// only draw levels : [ from 1 to _maxSupports ]


if f_isInsideRange(_index, 1, _maxSupports)

// dynamic line width based on index value


int _width = _index > 3 ? _index - 2 : _index
// use index to set level numbers on labels
string _level = str.tostring(_index)

_line := line.new(_x1, _activePrice, _x2, _activePrice,


_xloc, extend.none, style=f_getLineStyle(INP_supportStyle),
color=INP_supportColour, width=_width)

_labelLeft := label.new(_x1, _activePrice, 'S' + _level


+ '\n', _xloc, style=label.style_label_left, color=#00000000,
textcolor=INP_supportColour)

_labelRight := label.new(_x2, _activePrice, 'S' +


_level + '\n', _xloc, style=label.style_label_right, color=#00000000,
textcolor=INP_supportColour)

_labelPrice := INP_showPrice ? label.new(_x2,


_activePrice, _priceString, _xloc, style=label.style_label_left, color=#00000000,
textcolor=INP_priceColour) : na
_labelPrice

// IDENTIFYING RESISTANCE LEVELS IN ARRAY


//
// resistance index range : [ from (1 + i_maxLevels) to (2 *
i_maxLevels) ]

// only draw levels : [ from (1 + i_maxLevels) to


(_maxResists + i_maxLevels) ]
else if f_isInsideRange(_index, 1 + i_maxLevels, 2 *
i_maxLevels)
if f_isInsideRange(_index, 1 + i_maxLevels, _maxResists +
i_maxLevels)

// adjusted _index value to attain 1/2/3 sequence for


string operation
int _adjust = _index - i_maxLevels
// dynamic line width based on adjusted _index value
int _width = _adjust > 3 ? _adjust - 2 : _adjust
// use adjusted index value to set proper level numbers
on labels
string _level = str.tostring(_adjust)

_line := line.new(_x1, _activePrice, _x2, _activePrice,


_xloc, extend.none, style=f_getLineStyle(INP_resistStyle), color=INP_resistColour,
width=_width)

_labelLeft := label.new(_x1, _activePrice, 'R' + _level


+ '\n', _xloc, style=label.style_label_left, color=#00000000,
textcolor=INP_resistColour)

_labelRight := label.new(_x2, _activePrice, 'R' +


_level + '\n', _xloc, style=label.style_label_right, color=#00000000,
textcolor=INP_resistColour)

_labelPrice := INP_showPrice ? label.new(_x2,


_activePrice, _priceString, _xloc, style=label.style_label_left, color=#00000000,
textcolor=INP_priceColour) : na
_labelPrice
else

// PIVOT - No identification needed, always using index 0

_line := line.new(_x1, _activePrice, _x2, _activePrice,


_xloc, extend.none, style=f_getLineStyle(INP_pivotStyle), color=INP_pivotColour,
width=3)

_labelLeft := label.new(_x1, _activePrice, 'PP\n', _xloc,


style=label.style_label_left, color=#00000000, textcolor=INP_pivotColour)

_labelRight := label.new(_x2, _activePrice, 'PP\n', _xloc,


style=label.style_label_right, color=#00000000, textcolor=INP_pivotColour)

_labelPrice := INP_showPrice ? label.new(_x2, _activePrice,


_priceString, _xloc, style=label.style_label_left, color=#00000000,
textcolor=INP_priceColour) : na
_labelPrice

// set our line to it's respective array index


array.set(_lines, _index, _line)

// push labels into array, order doesn't matter.


if not na(_labelLeft)
array.push(_labels, _labelLeft)
if not na(_labelRight)
array.push(_labels, _labelRight)
if not na(_labelPrice)
array.push(_labels, _labelPrice)
////////////////////////////////////////////////////////////////////////////////
// //
// ====== SERIES, LINES and LABELS ====== //
// //
////////////////////////////////////////////////////////////////////////////////

// -- selected resolutions
string _resolutionA = f_getResolution(INP_resolutionA)
//string _resolutionB = f_getResolution( INP_resolutionB )
//string _resolutionC = f_getResolution( INP_resolutionC )

// -- pivot series price data sets


float[] _pivotFloatsA = f_getPivotSet(INP_flavourA, _resolutionA)
//float[] _pivotFloatsB = f_getPivotSet( INP_flavourB, _resolutionB )
//float[] _pivotFloatsC = f_getPivotSet( INP_flavourC, _resolutionC )

// -- pivot lines array A, and companion labels array


var line[] _pivotLinesA = array.new_line(i_maxLength, na)
var label[] _pivotLabelsA = array.new_label()

// -- pivot lines array B, and companion labels array


//var line[] _pivotLinesB = array.new_line( i_maxLength, na )
//var label[] _pivotLabelsB = array.new_label()

// -- pivot lines array C, and companion labels array


//var line[] _pivotLinesC = array.new_line( i_maxLength, na )
//var label[] _pivotLabelsC = array.new_label()

////////////////////////////////////////////////////////////////////////////////
// //
// ====== DRAWING and PLOTTING ====== //
// //
////////////////////////////////////////////////////////////////////////////////

// -- feed in our settings and data to the render function for set A
f_renderPivotArray(_resolutionA, i_settingsA, _pivotFloatsA, _pivotLinesA,
_pivotLabelsA)
//------------------- Money Move TrendLine ----------------------//
// Get user input
var string GROUP_ATL = "Money Moves [TrendLine V2]"
var bool show_tl = input.bool(false, title="Show TrendLine", tooltip="Shows
lower/upper trendlines", group=GROUP_ATL)
var int n = input.int(15, title="Trendline Sensitivity", minval=2, group=GROUP_ATL)
// A Fractal is always a Pivot H/L (but a Pivot H/L is not always a Fractal):
float pivtHigh = ta.pivothigh(n, n)[1]
float PivtLow = ta.pivotlow(n, n)[1]
bool upfract = not na(pivtHigh)
bool downfract = not na(PivtLow)
var string LINE_WIDTH1_STR = "Width 1"
var string LINE_WIDTH2_STR = "Width 2"
// @function : _get_width(), a map {string:int}
_get_width(string str_input) =>
return_int = switch str_input
LINE_WIDTH1_STR => 1
LINE_WIDTH2_STR => 2
return_int
var string subgroup1 = "recent line"

colors = input.string(title='Color Scheme', defval='DARK', options=['DARK',


'LIGHT'] , group="Money Moves [Tool Kit Premium]")
bullcolor = colors == 'DARK' ? #00DBFF : color.rgb(0, 255, 8)
bearcolor = colors == 'DARK' ? #E91E63 : color.rgb(255, 0, 0)

var color ln_col_up = color.new(bearcolor , 0)


var color ln_col_down = color.new(bullcolor , 0)
var int lnwidth_recent = _get_width(input.string(LINE_WIDTH1_STR,
options=[LINE_WIDTH1_STR, LINE_WIDTH2_STR], title="", inline=subgroup1,
group=GROUP_ATL))
var string subgroup2 = "historical line"
var color ln_col_prev = input.color(color.new(color.gray, 50), title="Historical
Line", group=GROUP_ATL, inline=subgroup2)
var int lnwidth_prev = _get_width(input.string(LINE_WIDTH1_STR,
options=[LINE_WIDTH1_STR, LINE_WIDTH2_STR], title="", inline=subgroup2,
group=GROUP_ATL))

var int max_tl = input.int(1, title="Max pair of lines", maxval=250,


minval=1, group=GROUP_ATL)*2
var string _str_extend = input.string("Right", options=["Right", "Both ways"],
title="Which way to extend lines", group=GROUP_ATL)
var string str_extend = _str_extend == "Both ways" ? extend.both : extend.right

/// Money Moves [TrendLine V2]

// Inputs:
// {

// Recent fractals.
var float recent_dn1 = low, var int i_recent_dn1 = bar_index
var float recent_up1 = high, var int i_recent_up1 = bar_index
var float recent_dn2 = low, var int i_recent_dn2 = bar_index
var float recent_up2 = high, var int i_recent_up2 = bar_index

// Array of lines, newest elements inserted to front.


var line[] arr_ln_up = array.new_line()
var line[] arr_ln_dn = array.new_line()

// @function cleanup()
// @returns void : To delete excess lines and assign new color to historical lines.
cleanup(line[] arr) =>
if array.size(arr) > 1
line.set_color(array.get(arr, 1), ln_col_prev)
line.set_width(array.get(arr, 1), lnwidth_prev)
while array.size(arr) > math.floor(max_tl/2)
line.delete(array.pop(arr))

// @function : draw upper trendline


_draw_upper_TL() =>
ln_up = line.new(i_recent_up2, recent_up2, i_recent_up1, recent_up1,
xloc.bar_index,
str_extend, color=ln_col_up, style=line.style_solid, width=lnwidth_recent)
array.unshift(arr_ln_up, ln_up)
cleanup(arr_ln_up)

// @function : draw lower trendline


_draw_lower_TL() =>
ln_dn = line.new(i_recent_dn2, recent_dn2, i_recent_dn1, recent_dn1,
xloc.bar_index,
str_extend, color=ln_col_down, style=line.style_solid, width=lnwidth_recent)
array.unshift(arr_ln_dn, ln_dn)
cleanup(arr_ln_dn)

// Checking for fractals & Drawing trendlines


if downfract and show_tl// and PassCorrect
recent_dn2:=recent_dn1, i_recent_dn2:=i_recent_dn1
recent_dn1:=low[n+1], i_recent_dn1 := bar_index-n-1
_draw_lower_TL()

if upfract and show_tl// and PassCorrect


recent_up2:=recent_up1, i_recent_up2:=i_recent_up1
recent_up1:=high[n+1], i_recent_up1 := bar_index-n-1
_draw_upper_TL()

// PivtLowotting fractals
bool hh = not na(pivtHigh) and recent_up1 > recent_up2 ? high[n+1] : na
bool lh = not na(pivtHigh) and recent_up1 < recent_up2 ? high[n+1] : na
bool hl = not na(PivtLow) and recent_dn1 > recent_dn2 ? low[n+1] : na
bool ll = not na(PivtLow) and recent_dn1 < recent_dn2 ? low[n+1] : na

//------------------- Money Moves [Order Blocks] ----------------------//


// Get user input

var bool show_OBls = input.bool(false, title="Show Order Blocks", tooltip="Show


lower/upper trendlines" , group = "Money Moves [OrderBlocks]")
lengthh = input.int(5, 'Sensitivity' , minval = 1, group = "Money Moves
[OrderBlocks]")
line_style = input.string('Dotted', 'Order Block Line Style' , options = ['Solid',
'Dashed', 'Dotted'] , group = "Money Moves [OrderBlocks]")
line_width = input.int(1, 'Order Block Line Width' , minval = 1 , group = "Money
Moves [OrderBlocks]")
mitigation = input.string('Wick', 'Confirmation Type' , options = ['Wick', 'Close']
, group = "Money Moves [OrderBlocks]")

bull_ext_last = input.int(1, 'Bullish OB ' , minval = 1 , inline = 'bull' , group =


"Money Moves [OrderBlocks]")
bear_ext_last = input.int(1, 'Bearish OB' , minval = 1 , inline = 'bear' , group =
"Money Moves [OrderBlocks]")
bg_bull_css = color.new(bullcolor, 80)
bull_css = bullcolor
bull_avg_css = color.new(bullcolor, 37)
bg_bear_css = color.new(bearcolor, 80)
bear_css = bearcolor
bear_avg_css = color.new(bearcolor, 37)
//-----------------------------------------------------------------------------}
//Function to get order block coordinates
get_coordinates(condition, top, btm, ob_val)=>
var ob_top = array.new_float(0)
var ob_btm = array.new_float(0)
var ob_avg = array.new_float(0)
var ob_left = array.new_int(0)

float ob = na

//Append coordinates to arrays


if condition
avg = math.avg(top, btm)

array.unshift(ob_top, top)
array.unshift(ob_btm, btm)
array.unshift(ob_avg, avg)
array.unshift(ob_left, time[length])

ob := ob_val

[ob_top, ob_btm, ob_avg, ob_left, ob]

//Function to remove mitigated order blocks from coordinate arrays


remove_mitigated(ob_top, ob_btm, ob_left, ob_avg, target, bull)=>
mitigated = false
target_array = bull ? ob_btm : ob_top

for element in target_array


idx = array.indexof(target_array, element)

if (bull ? target < element : target > element)


mitigated := true

array.remove(ob_top, idx)
array.remove(ob_btm, idx)
array.remove(ob_avg, idx)
array.remove(ob_left, idx)

mitigated
//Functions
//-----------------------------------------------------------------------------{
//Line Style function
get_line_style(style) =>
out = switch style
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted

//Function to set order blocks


set_order_blocks(ob_top, ob_btm, ob_left, ob_avg, ext_last, bg_css, border_css,
lvl_css)=>
var ob_box = array.new_box(0)
var ob_lvl = array.new_line(0)

//Fill arrays with boxes/lines


if barstate.isfirst and show_OBls
for i = 0 to ext_last-1
array.unshift(ob_box, box.new(na,na,na,na
, xloc = xloc.bar_time
, extend= extend.right
, bgcolor = bg_css
, border_color = color.new(border_css, 70)))

array.unshift(ob_lvl, line.new(na,na,na,na
, xloc = xloc.bar_time
, extend = extend.right
, color = lvl_css
, style = get_line_style(line_style)
, width = line_width))

//Set order blocks


if barstate.islast and show_OBls
if array.size(ob_top) > 0
for i = 0 to math.min(ext_last-1, array.size(ob_top)-1)
get_box = array.get(ob_box, i)
get_lvl = array.get(ob_lvl, i)

box.set_lefttop(get_box, array.get(ob_left, i), array.get(ob_top,


i))
box.set_rightbottom(get_box, array.get(ob_left, i),
array.get(ob_btm, i))

line.set_xy1(get_lvl, array.get(ob_left, i), array.get(ob_avg, i))


line.set_xy2(get_lvl, array.get(ob_left, i)+1, array.get(ob_avg,
i))

//-----------------------------------------------------------------------------}
//Global elements
//-----------------------------------------------------------------------------{
var os = 0
var target_bull = 0.
var target_bear = 0.

nn = bar_index
upper = ta.highest(length)
lower = ta.lowest(length)
if mitigation == 'Close'
target_bull := ta.lowest(close, length)
target_bear := ta.highest(close, length)
else
target_bull := lower
target_bear := upper

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

phv = ta.pivothigh(volume, length, length)

//-----------------------------------------------------------------------------}
//Get bullish/bearish order blocks coordinates
//-----------------------------------------------------------------------------{
[bull_top , bull_btm , bull_avg , bull_left , bull_ob] = get_coordinates(phv and os
== 1, hl2[length], low[length], low[length])

[bear_top , bear_btm , bear_avg , bear_left , bear_ob] = get_coordinates(phv and os


== 0, high[length], hl2[length], high[length])

//-----------------------------------------------------------------------------}
//Remove mitigated order blocks
//-----------------------------------------------------------------------------{
mitigated_bull = remove_mitigated(bull_top , bull_btm , bull_left , bull_avg ,
target_bull , true)

mitigated_bear = remove_mitigated(bear_top , bear_btm , bear_left , bear_avg ,


target_bear , false)

//-----------------------------------------------------------------------------}
//Display order blocks
//-----------------------------------------------------------------------------{
//Set bullish order blocks
set_order_blocks(bull_top , bull_btm , bull_left , bull_avg , bull_ext_last ,
bg_bull_css , bull_css , bull_avg_css)

//Set bearish order blocks


set_order_blocks(bear_top , bear_btm , bear_left , bear_avg , bear_ext_last ,
bg_bear_css , bear_css , bear_avg_css)

//Show detected order blocks


plot(bull_ob, 'Bull OB', bull_css, 2, plot.style_linebr , offset = -length ,
display = display.none)

plot(bear_ob, 'Bear OB', bear_css, 2, plot.style_linebr , offset = -length ,


display = display.none)
//
===================================================================================
=====================================
// PROFIT AND LOSS COMPUTATION
//
===================================================================================
=====================================
// atr = ta.atr(14)
//
-----------------------------------------------------------------------------------
-----------------------------------------------------
// BUY
//
-----------------------------------------------------------------------------------
-----------------------------------------------------
var float longBP_Var = na
var float shortBP_Var = na
if (buyCond or strongBuyCond)
longBP_Var := close
label.new(bar_index, low-atr*3, str.tostring(shortBP_Var - close ), style =
label.style_label_up, color = color.red, textcolor = color.white)

// if (signalMode == 'Trend Mode')


if sellCond or strongSellCond
shortBP_Var := close
label.new(bar_index, high+atr*3, str.tostring(close - longBP_Var ), style =
label.style_label_down, color = color.red, textcolor = color.white)
// label.new(bar_index, high, "", style = label.style_label_down, color =
color.red, textcolor = color.white)

// lotshape(signalMode == 'Trend Mode' ? buyCond : na, "Buy", shape.labelup,


location.belowbar, color.new(color_1, 40), text = "Buy", textcolor = #ffffff, size
= size.normal)

// plotshape(signalMode == 'Trend Mode' ? strongBuyCond : na, "Strong Buy",


shape.labelup, location.belowbar, color.new(color_1, 50), text = "Strong",
textcolor = #ffffff, size = size.normal)

// plotshape(signalMode == 'Trend Mode' ? sellCond : na, "Sell", shape.labeldown,


location.abovebar, color.new(color_3, 50), text = "Sell", textcolor = #ffffff, size
= size.normal)

// plotshape(signalMode == 'Trend Mode' ? strongSellCond : na, "Strong Sell",


shape.labeldown, location.abovebar, color.new(color_3, 50), text = "Strong",
textcolor = #ffffff, size = size.normal)

You might also like