//@version=5
indicator("Gann medians MA targets", overlay=true, max_bars_back=1500,
max_lines_count=500, max_labels_count=500, max_boxes_count = 500)
// Inputs
method1 = input.string('Median', options=['EMA', 'Median', 'SMA'])
length1 = input(56)
mult1 = input.int(1, minval=0, maxval=1)
method2 = input.string('Median', options=['EMA', 'Median', 'SMA'])
length2 = input(100)
mult2 = input.int(1, minval=0, maxval=1)
method3 = input.string('Median', options=['EMA', 'Median', 'SMA'])
length3 = input(200)
mult3 = input.int(1, minval=0, maxval=1)
// Calculation of medians
Avg(x, length, method) =>
sma_1 = ta.sma(x, length)
ema_1 = ta.ema(x, length)
percentile_linear_interpolation_1 = ta.percentile_linear_interpolation(x,
length, 50)
method == 'SMA' ? sma_1 : method == 'EMA' ? ema_1 :
percentile_linear_interpolation_1
a1 = ta.highest(length1) - math.max(close, open)
b1 = math.min(close, open) - ta.lowest(length1)
c1 = math.max(close, open) + a1 * mult1
d1 = math.min(close, open) - b1 * mult1
a2 = ta.highest(length2) - math.max(close, open)
b2 = math.min(close, open) - ta.lowest(length2)
c2 = math.max(close, open) + a2 * mult2
d2 = math.min(close, open) - b2 * mult2
a3 = ta.highest(length3) - math.max(close, open)
b3 = math.min(close, open) - ta.lowest(length3)
c3 = math.max(close, open) + a3 * mult3
d3 = math.min(close, open) - b3 * mult3
// Calculation of volume
volLength = input.int(20, minval=1, title='Volume Length')
volMultiplier = input.float(1.0, title='Volume Multiplier')
volAvg = ta.sma(volume, volLength) * volMultiplier
// Calculation of signals and liquidity levels
e1 = Avg(c1, length1, method1)
f1 = Avg(d1, length1, method1)
gx1 = 0
cross_1 = ta.cross(close, f1)
gx1 := ta.cross(close, e1) ? 1 : cross_1 ? 0 : nz(gx1[1])
e2 = Avg(c2, length2, method2)
f2 = Avg(d2, length2, method2)
gx2 = 0
cross_2 = ta.cross(close, f2)
gx2 := ta.cross(close, e2) ? 1 : cross_2 ? 0 : nz(gx2[1])
e3 = Avg(c3, length3, method3)
f3 = Avg(d3, length3, method3)
gx3 = 0
cross_3 = ta.cross(close, f3)
gx3 := ta.cross(close, e3) ? 1 : cross_3 ? 0 : nz(gx3[1])
// Calculation of liquidity levels with volume
hilo1 = gx1 * f1 + (1 - gx1) * e1
css1 = gx1 == 1 ? color.green : color.red
plot(hilo1, color=css1, style=plot.style_line, show_last=1, linewidth=1,
trackprice=true, transp=0)
hilo2 = gx2 * f2 + (1 - gx2) * e2
css2 = gx2 == 1 ? color.green : color.red
plot(hilo2, color=css2, style=plot.style_line, show_last=1, linewidth=1,
trackprice=true, transp=0)
hilo3 = gx3 * f3 + (1 - gx3) * e3
css3 = gx3 == 1 ? color.green : color.red
plot(hilo3, color=css3, style=plot.style_line, show_last=1, linewidth=1,
trackprice=true, transp=0)
//end of the code
//@version=5
//indicator(title='HiLo Activator', overlay=true)
length = input.int(3, minval=1)
displace = input.int(0, minval=0)
highsma = ta.sma(high, length)
lowsma = ta.sma(low, length)
iff_1 = close < lowsma[displace] ? -1 : 0
swing = close > highsma[displace] ? 1 : iff_1
mah = ta.highest(high, length)
mal = ta.lowest(low, length)
var stop = 0.0
iff_2 = swing == -1 ? mah : stop[1]
stop := swing == 1 ? mal : iff_2
linecolor = stop < low ? color.green : color.red
plot(stop, show_last=1, linewidth=1, trackprice=true, transp=0)
//end of this part
//study(title="TrapTrading (Study)", overlay=true)
// input
counterTrend = input(defval=false, title='Trade Mode (ON: Counter Trend OFF: Trend
Following)')
len1 = input.int(defval=20, title='Period (1-200)', minval=1, maxval=200)
multiple = input(defval=0.7, title='Multiple')
m1 = close - close[len1]
lowest_1 = ta.lowest(math.abs(m1), len1)
highest_1 = ta.highest(math.abs(m1), len1)
controlPoint = counterTrend ? lowest_1 == math.abs(m1) : highest_1 == math.abs(m1)
baseLine = ta.valuewhen(controlPoint, math.avg(close, close[len1]), 0)
// trap line
atr = ta.valuewhen(controlPoint, ta.highest(math.max(math.max(ta.atr(len1),
ta.atr(len1 * 2)), ta.atr(len1 * 3)), len1), 0)
line1Up = baseLine + atr * multiple
line2Up = baseLine + atr * 2 * multiple
line3Up = baseLine + atr * 3 * multiple
line4Up = baseLine + atr * 4 * multiple
line5Up = baseLine + atr * 5 * multiple
line6Up = baseLine + atr * 6 * multiple
line7Up = baseLine + atr * 7 * multiple
line8Up = baseLine + atr * 8 * multiple
line9Up = baseLine + atr * 9 * multiple
line10Up = baseLine + atr * 10 * multiple
line1Down = baseLine - atr * multiple
line2Down = baseLine - atr * 2 * multiple
line3Down = baseLine - atr * 3 * multiple
line4Down = baseLine - atr * 4 * multiple
line5Down = baseLine - atr * 5 * multiple
line6Down = baseLine - atr * 6 * multiple
line7Down = baseLine - atr * 7 * multiple
line8Down = baseLine - atr * 8 * multiple
line9Down = baseLine - atr * 9 * multiple
line10Down = baseLine - atr * 10 * multiple
// draw
//barcolor(controlPoint ? color.yellow : close >= baseLine ? color.teal :
color.red, title="Candle Color")
// find which bar is 5 days away from the current time
milliseconds_in_5days = 1000 * 60 * 60 * 24 * 1 // millisecs * secs * min * hours
* days
leftborder = timenow - time < milliseconds_in_5days // true or na when false
rightborder = barstate.islast
plot(baseLine, title='Base Line', color=color.new(color.purple, 0), linewidth=1,
style=plot.style_stepline, show_last=1, linewidth=1, trackprice=true, transp=0)
//plot(leftborder?line1Up:na, title="1Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line2Up:na, title="2Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line3Up:na, title="3Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line4Up:na, title="4Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line5Up:na, title="5Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line6Up:na, title="6Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line7Up:na, title="7Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line8Up:na, title="8Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line9Up:na, title="9Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line10Up:na, title="10Up Line", color=color.red, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line1Down:na, title="1Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line2Down:na, title="2Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line3Down:na, title="3Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line4Down:na, title="4Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line5Down:na, title="5Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line6Down:na, title="6Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line7Down:na, title="7Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line8Down:na, title="8Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line9Down:na, title="9Down Line", color=color.green, linewidth=1,
style=plot.style_stepline, transp=0)
//plot(leftborder?line10Down:na, title="10Down Line", color=color.green,
linewidth=1, style=plot.style_stepline, transp=0)
//end of this part
// © asenski at gmail dot com
//@version=5
//indicator("Opening Range with Fibs", "OR", overlay=true)
orSpec = input.session("0930-1000", "Opening Range with Fib Extensions")
refsym = input.symbol("SPX500USD", "Reference for time range (So that it is in
EST)")
rgColor = input.color(color.rgb(255, 255, 0), "Range color")
// L1Color = input.color(color.rgb(0, 0, 255), "L1 color")
// L2Color = input.color(color.rgb(255, 115, 40), "L2 color")
// L3Color = input.color(color.rgb(255, 0, 255), "L3 color")
L1 = input.float(1.272, "L1")
L2 = input.float(1.618, "L2")
// L3 = input.float(2.618, "L3")
t = request.security(refsym, timeframe.period, time(timeframe.period, orSpec),
gaps=barmerge.gaps_on)
var float orh = na
var float orl = na
var int orbars = 0
var float extL1up = na
var float extL2up = na
var float extL3up = na
var float extL1dn = na
var float extL2dn = na
var float extL3dn = na
newSession = na(t[1]) and not na(t)
inSession = not na(t[1]) and not na(t)
endSession = not na(t[1]) and na(t)
if newSession
orh := high
orl := low
orbars := 0
extL1up := na
extL2up := na
extL3up := na
extL1dn := na
extL2dn := na
extL3dn := na
if inSession
orh := math.max(high, orh)
orl := math.min(low, orl)
orbars += 1
var float vwapsum = na
var float volumesum = na
if endSession
extL1up := orl + (orh - orl) * L1
extL2up := orl + (orh - orl) * L2
// extL3up := orl + (orh - orl) * L3
extL1dn := orh - (orh - orl) * L1
extL2dn := orh - (orh - orl) * L2
// extL3dn := orh - (orh - orl) * L3
b1 = box.new(bar_index - orbars - 1, orh, bar_index - 1, orl, border_color =
rgColor, bgcolor = na)
b2 = box.new(bar_index - orbars - 1, extL1up, bar_index - 1, extL2up,
border_color = rgColor, bgcolor = na)
b3 = box.new(bar_index - orbars - 1, extL1dn, bar_index - 1, extL2dn,
border_color = rgColor, bgcolor = na)
if barstate.islast
box.delete(b1[1])
box.delete(b2[1])
box.delete(b3[1])
//plot(newSession ? na : orh, "OR high", color=rgColor,style=plot.style_linebr)
//plot(newSession ? na : orl, "OR low", color=rgColor,style=plot.style_linebr)
//plot(newSession ? na : extL1up, "L1 above", color=L1Color,
style=plot.style_linebr)
//plot(newSession ? na : extL2up, "L2 above", color=L2Color,
style=plot.style_linebr)
//plot(newSession ? na : extL3up, "L3 above", color=L3Color,
style=plot.style_linebr)
//plot(newSession ? na : extL1dn, "L1 below", color=L1Color,
style=plot.style_linebr)
//plot(newSession ? na : extL2dn, "L2 below", color=L2Color,
style=plot.style_linebr)
//plot(newSession ? na : extL3dn, "L3 below", color=L3Color,
style=plot.style_linebr)
//end of this part
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © Lenny_Kiruthu
//@version=5
//indicator(title = "Multi Timeframe Supply & Demand zones"
//, shorttitle = "MTF SnD"
//, overlay = true
//, max_bars_back = 500
//, max_lines_count = 500
//, max_boxes_count = 500)
// Constants
Transparent_Color = color.new(color.white, 100)
// Groups
General_Settings_group = "-------General Settings-------"
Timeframe_1_Group = "-------Timeframe 1 Settings--------"
Timeframe_2_Group = "-------Timeframe 2 Settings--------"
Timeframe_3_Group = "-------Timeframe 3 Settings--------"
// Tooltips
Timeframe_Tooltip = "If set to chart is true no need to alter these two inputs."
Set_To_Chart_Tooltip = "If set to chart is set to true, there is no need to alter
the Timeframe inputs, it will automatically configure itself to the charts
timeframe."
Lower_Timeframe_Tooltip = "If set to true and chart timeframe is higher than the
choosen timeframe, supply and demand will not display. Note plotting ltf structure
on a htf will provide inaccurate plots."
Mitigation_Tooltip = "If set to true supply zones with a high above them or a
demand zone with a low below them will be removed since they are considered
mitigated if false the close value will be used for both supply and demand."
Alert_Tooltip = "After setting the alert to true or false head over to the alert
dialog box and activate the any alert function under the indicator."
Hide_Demand = "Hide or show the demand zones of the specific timeframe."
Hide_Supply = "Hide or show the supply zones of the specific timeframe."
Hide_Timeframe = "Hide or show the entire timeframe."
// General Settings
Hide_All_Demand = input.bool(defval = false, title = "Hide all demand zones", group
= General_Settings_group)
Hide_All_Supply = input.bool(defval = false, title = "Hide all supply zones", group
= General_Settings_group)
Show_Only_On_Lower_Timeframes = input.bool(defval = true, title = "Show Supply and
Demand only on Lower Timeframes", group = General_Settings_group, tooltip =
Lower_Timeframe_Tooltip)
// User Inputs
// Timeframe 1 Settings
TF_1_Chart_Feature = input.bool(defval = false, title = "Set Timeframe to Chart",
group = Timeframe_1_Group, tooltip = Set_To_Chart_Tooltip)
TF_1_Use_High_Low = input.bool(defval = false, title = "Use High/Low to mitigates
zones", group = Timeframe_1_Group, tooltip = Mitigation_Tooltip)
TF_1_Show_Demand = input.bool(defval = true, title = "Show Demand", group =
Timeframe_1_Group, tooltip = Hide_Demand)
TF_1_Show_Supply = input.bool(defval = true, title = "Show Supply", group =
Timeframe_1_Group, tooltip = Hide_Supply)
TF_1_Demand_Alert = input.bool(defval = true, title = "Use TF 1 Demand Alert",
group = Timeframe_1_Group, tooltip = Alert_Tooltip)
TF_1_Supply_Alert = input.bool(defval = true, title = "Use TF 1 Supply Alert",
group = Timeframe_1_Group, tooltip = Alert_Tooltip)
TF_1_Multip = input.int(defval=2, minval=1, maxval=1440, title="Timeframe 1",
group=Timeframe_1_Group, inline="T1")
TF_1_Period = input.string(defval="Hour", title="", options=["Minute", "Hour",
"Day", "Week", "Month"], group=Timeframe_1_Group, inline="T1",
tooltip=Timeframe_Tooltip)
TF_1_Swing_Length = input.int(defval = 7, title = "Swing Length", minval = 1, group
= Timeframe_1_Group)
TF_1_Line_Type = input.string(defval = "Solid", title = "Border Type", options =
["Solid", "Dashed", "Dotted"], group = Timeframe_1_Group)
TF_1_Text_Size = input.string(defval = "Small", title = "Text Size", options =
["Normal", "Tiny", "Small", "Large", "Huge", "Auto"], group = Timeframe_1_Group)
TF_1_Line_Width = input.int(defval = 1, title = "Border Width", group =
Timeframe_1_Group)
TF_1_Demand_Show_Last = input.int(defval = 2, title = "Show last (Demand)", group =
Timeframe_1_Group)
TF_1_Supply_Show_Last = input.int(defval = 2, title = "Show last (Supply)", group =
Timeframe_1_Group)
TF_1_Demand_Color = input.color(defval = #c6f89560, title = "Demand Color", group =
Timeframe_1_Group, inline = "TF 1 Color")
TF_1_Supply_Color = input.color(defval = #fb726a60, title = "Supply Color", group =
Timeframe_1_Group, inline = "TF 1 Color")
TF_1_Text_Color = input.color(defval = color.white, title = "Text Color", group =
Timeframe_1_Group)
// Timeframe 2 Settings
TF_2_Chart_Feature = input.bool(defval = false, title = "Set Timeframe to Chart",
group = Timeframe_2_Group, tooltip = Set_To_Chart_Tooltip)
TF_2_Use_High_Low = input.bool(defval = false, title = "Use High/Low to mitigates
zones", group = Timeframe_2_Group, tooltip = Mitigation_Tooltip)
TF_2_Show_Demand = input.bool(defval = true, title = "Show Demand", group =
Timeframe_2_Group, tooltip = Hide_Demand)
TF_2_Show_Supply = input.bool(defval = true, title = "Show Supply", group =
Timeframe_2_Group, tooltip = Hide_Supply)
TF_2_Demand_Alert = input.bool(defval = true, title = "Use TF 2 Demand Alert",
group = Timeframe_2_Group, tooltip = Alert_Tooltip)
TF_2_Supply_Alert = input.bool(defval = true, title = "Use TF 2 Supply Alert",
group = Timeframe_2_Group, tooltip = Alert_Tooltip)
TF_2_Multip = input.int(defval=30, minval=1, maxval=1440, title="Timeframe 2",
group=Timeframe_2_Group, inline="T2")
TF_2_Period = input.string(defval="Minute", title="", options=["Minute", "Hour",
"Day", "Week", "Month"], group=Timeframe_2_Group, inline="T2",
tooltip=Timeframe_Tooltip)
TF_2_Swing_Length = input.int(defval = 7, title = "Swing Length", minval = 1, group
= Timeframe_2_Group)
TF_2_Line_Type = input.string(defval = "Solid", title = "Border Type", options =
["Solid", "Dashed", "Dotted"], group = Timeframe_2_Group)
TF_2_Text_Size = input.string(defval = "Small", title = "Text Size", options =
["Normal", "Tiny", "Small", "Large", "Huge", "Auto"], group = Timeframe_2_Group)
TF_2_Line_Width = input.int(defval = 1, title = "Border Width", group =
Timeframe_2_Group)
TF_2_Demand_Show_Last = input.int(defval = 2, title = "Show last (Demand)", group =
Timeframe_2_Group)
TF_2_Supply_Show_Last = input.int(defval = 2, title = "Show last (Supply)", group =
Timeframe_2_Group)
TF_2_Demand_Color = input.color(defval = #5794f860, title = "Demand Color", group =
Timeframe_2_Group, inline = "TF 2 Color")
TF_2_Supply_Color = input.color(defval = #f9c9fe60, title = "Supply Color", group =
Timeframe_2_Group, inline = "TF 2 Color")
TF_2_Text_Color = input.color(defval = color.white, title = "Text Color", group =
Timeframe_2_Group)
// General functions
// Getting the line type from the user.
Line_Type_Control(Type) =>
Line_Functionality = switch Type
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
Line_Functionality
// Text size from the user
Text_Size_Switch(Text_Size) =>
Text_Type = switch Text_Size
"Normal" => size.normal
"Tiny" => size.tiny
"Small" => size.small
"Large" => size.large
"Huge" => size.huge
"Auto" => size.auto
Text_Type
// Timeframe functionality
// Timeframe for security functions
TF(TF_Period, TF_Multip) =>
switch TF_Period
"Minute" => str.tostring(TF_Multip)
"Hour" => str.tostring(TF_Multip*60)
"Day" => str.tostring(TF_Multip) + "D"
"Week" => str.tostring(TF_Multip) + "W"
"Month" => str.tostring(TF_Multip) + "M"
=> timeframe.period
// Timeframe shortcut form
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) =>
if Chart_as_Timeframe == false
switch TF_Period
"Minute" => str.tostring(TF_Multip) + "Min"
"Hour" => str.tostring(TF_Multip) + "H"
"Day" => str.tostring(TF_Multip) + "D"
"Week" => str.tostring(TF_Multip) + "W"
"Month" => str.tostring(TF_Multip) + "M"
else if Chart_as_Timeframe == true
switch
timeframe.isminutes and timeframe.multiplier % 60 != 0
=> str.tostring(timeframe.multiplier) + "Min"
timeframe.isminutes and timeframe.multiplier % 60 == 0
=> str.tostring(timeframe.multiplier/60) + "H"
timeframe.isdaily => str.tostring(timeframe.multiplier) + "D"
timeframe.isweekly => str.tostring(timeframe.multiplier) + "W"
timeframe.ismonthly => str.tostring(timeframe.multiplier) + "M"
MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length) =>
if Chart_as_Timeframe == true
Swing_Length
else
switch
TF_Period == "Month" and timeframe.isminutes and timeframe.multiplier %
60 == 0 and
(24*5*5/((TF_Multip * 1440*5*5)/timeframe.multiplier)) * 60 ==
timeframe.multiplier => ((TF_Multip * 1440)*5*5/ timeframe.multiplier)*Swing_Length
TF_Period == "Month" and timeframe.isweekly and
(5/((TF_Multip * 1440 * 5)/timeframe.multiplier)) * 1440 ==
timeframe.multiplier => ((TF_Multip * 1440)*5/ 1440)*Swing_Length
TF_Period == "Month" and timeframe.isdaily and
(5*5/((TF_Multip * 1440 * 5*5)/timeframe.multiplier)) * 1440 ==
timeframe.multiplier => ((TF_Multip * 1440)*5*5/ 1440)*Swing_Length
timeframe.ismonthly and timeframe.multiplier == TF_Multip and
TF_Period == "Month" => Swing_Length
TF_Period == "Week" and timeframe.isminutes and timeframe.multiplier %
60 == 0 and
(24*5/((TF_Multip * 1440*5)/timeframe.multiplier)) * 60 ==
timeframe.multiplier => ((TF_Multip * 1440)*5/ timeframe.multiplier)*Swing_Length
TF_Period == "Week" and timeframe.isdaily and
(5/((TF_Multip * 1440 * 5)/timeframe.multiplier)) * 1440 ==
timeframe.multiplier => ((TF_Multip * 1440)*5/ 1440)*Swing_Length
timeframe.isweekly and timeframe.multiplier == TF_Multip and
TF_Period == "Week" => Swing_Length
TF_Period == "Day" and timeframe.isminutes and timeframe.multiplier %
60 == 0 and
(24/((TF_Multip * 1440)/timeframe.multiplier)) * 60 ==
timeframe.multiplier => (TF_Multip * 1440/ timeframe.multiplier)*Swing_Length
timeframe.isdaily and timeframe.multiplier == TF_Multip and
TF_Period == "Day" => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and
TF_Period == "Minute" and TF_Multip == timeframe.multiplier =>
Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and
TF_Period == "Minute" and TF_Multip != timeframe.multiplier =>
((TF_Multip/60) * 60/timeframe.multiplier)*Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and
TF_Period == "Hour" and TF_Multip != timeframe.multiplier =>
((TF_Multip * 60 /60) * 60/timeframe.multiplier)*Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and
TF_Period == "Hour" and TF_Multip == timeframe.multiplier and
timeframe.multiplier * 60 == 60 => ((TF_Multip * 60 /60) *
60/timeframe.multiplier)*Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and
TF_Period == "Day" and TF_Multip != timeframe.multiplier =>
((TF_Multip * 1440 /60) * 60/timeframe.multiplier)*Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 == 0 and
TF_Period == "Hour" and TF_Multip * 60 == timeframe.multiplier =>
Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 == 0 and
TF_Period == "Hour" and TF_Multip * 60 != timeframe.multiplier =>
(TF_Multip * 60/timeframe.multiplier)*Swing_Length
HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) =>
if Chart_as_Timeframe == true
true
else if Show_Only_On_Lower_Timeframes == false
true
else
switch
TF_Period == "Minute" and TF_Multip < timeframe.multiplier and
timeframe.isminutes
=> false
TF_Period == "Minute" and TF_Multip >= timeframe.multiplier and
timeframe.isminutes
=> true
TF_Period == "Minute" and timeframe.isdaily
=> false
TF_Period == "Minute" and timeframe.isweekly
=> false
TF_Period == "Minute" and timeframe.ismonthly
=> false
TF_Period == "Hour" and TF_Multip * 60 < timeframe.multiplier and
timeframe.isminutes
=> false
TF_Period == "Hour" and TF_Multip * 60 >= timeframe.multiplier and
timeframe.isminutes
=> true
TF_Period == "Hour" and timeframe.isdaily
=> false
TF_Period == "Hour" and timeframe.isweekly
=> false
TF_Period == "Hour" and timeframe.ismonthly
=> false
TF_Period == "Day" and timeframe.isdaily or timeframe.isminutes
=> true
TF_Period == "Week" and timeframe.isweekly or timeframe.isdaily or
timeframe.isminutes
=> true
TF_Period == "Month" and timeframe.ismonthly or timeframe.isweekly or
timeframe.isdaily or timeframe.isminutes
=> true
// Arrays
var Bullish_SnD_Top_TF_1 = array.new_float(0)
var Bullish_SnD_Btm_TF_1 = array.new_float(0)
var Bullish_SnD_Left_TF_1 = array.new_int(0)
var Bullish_SnD_Type_TF_1 = array.new_int(0)
var Bearish_SnD_Top_TF_1 = array.new_float(0)
var Bearish_SnD_Btm_TF_1 = array.new_float(0)
var Bearish_SnD_Left_TF_1 = array.new_int(0)
var Bearish_SnD_Type_TF_1 = array.new_int(0)
var Bullish_SnD_Top_TF_2 = array.new_float(0)
var Bullish_SnD_Btm_TF_2 = array.new_float(0)
var Bullish_SnD_Left_TF_2 = array.new_int(0)
var Bullish_SnD_Type_TF_2 = array.new_int(0)
var Bearish_SnD_Top_TF_2 = array.new_float(0)
var Bearish_SnD_Btm_TF_2 = array.new_float(0)
var Bearish_SnD_Left_TF_2 = array.new_int(0)
var Bearish_SnD_Type_TF_2 = array.new_int(0)
// TF Pivot values
// TF_1_Calc_High = ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length)
// Getting the high and low values
[TF_1_SH, TF_1_SL, TF_1_SH_Low, TF_1_SL_High, TF_1_Atr] = request.security(symbol =
syminfo.tickerid, timeframe = (TF_1_Chart_Feature ? timeframe.period :
TF(TF_1_Period, TF_1_Multip))
, expression = [ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length)
, ta.pivotlow(low, TF_1_Swing_Length, TF_1_Swing_Length)
, not na(ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length)) ?
low[TF_1_Swing_Length] : 0
, not na(ta.pivotlow(low, TF_1_Swing_Length, TF_1_Swing_Length)) ?
high[TF_1_Swing_Length] : 0
, ta.atr(200)]
, gaps = barmerge.gaps_on)
[TF_2_SH, TF_2_SL, TF_2_SH_Low, TF_2_SL_High, TF_2_Atr] = request.security(symbol =
syminfo.tickerid, timeframe = (TF_2_Chart_Feature ? timeframe.period :
TF(TF_2_Period, TF_2_Multip))
, expression = [ta.pivothigh(high, TF_2_Swing_Length, TF_2_Swing_Length)
, ta.pivotlow(low, TF_2_Swing_Length, TF_2_Swing_Length)
, not na(ta.pivothigh(high, TF_2_Swing_Length, TF_2_Swing_Length)) ?
low[TF_2_Swing_Length] : 0
, not na(ta.pivotlow(low, TF_2_Swing_Length, TF_2_Swing_Length)) ?
high[TF_2_Swing_Length] : 0
, ta.atr(200)]
, gaps = barmerge.gaps_on)
// [TF_3_SH, TF_3_SL] = request.security(symbol = syminfo.ticker, timeframe =
(TF_3_Chart_Feature ? timeframe.period : TF(TF_3_Period, TF_3_Multip))
// , expression = [ta.pivothigh(high, TF_3_Swing_Length, TF_3_Swing_Length),
ta.pivotlow(low, TF_3_Swing_Length, TF_3_Swing_Length)], gaps = barmerge.gaps_on)
// Functions //
// The function below is designed to loop through the arrays holding the box plot
values for supply and demand box plots
// and remove the mitigated (unnecessary plots) on the chart.
Supply_and_Demand_Mitigation(SnD_Top, SnD_Btm, SnD_Left, SnD_Type, SnD_Dir,
TF_Use_High_Low) =>
if SnD_Dir == "Bearish"
for i in SnD_Type
index = array.indexof(SnD_Type, i)
if (TF_Use_High_Low ? high : close) > array.get(SnD_Top, index)
array.remove(SnD_Top, index)
array.remove(SnD_Btm, index)
array.remove(SnD_Left, index)
array.remove(SnD_Type, index)
// array.set()
else if SnD_Dir == "Bullish"
for i in SnD_Type
index = array.indexof(SnD_Type, i)
if (TF_Use_High_Low ? low : close) < array.get(SnD_Btm, index)
array.remove(SnD_Top, index)
array.remove(SnD_Btm, index)
array.remove(SnD_Left, index)
array.remove(SnD_Type, index)
// The function below is designed to find the necessary swing points in our chart
that fit the description
// of demand and supply zones
Supply_and_Demand_Functionality(TF_SH, TF_SL, TF_SH_Low, TF_SL_High, TF_Atr
, Swing_Length, Chart_as_Timeframe, TF_Period, TF_Multip
, Bullish_SnD_Top, Bullish_SnD_Btm, Bullish_SnD_Left, Bullish_SnD_Type
, Bearish_SnD_Top, Bearish_SnD_Btm, Bearish_SnD_Left, Bearish_SnD_Type
, Use_Demand_Alert, Use_Supply_Alert) =>
// Variables to identify HH, HL, LH, LL
var float TF_Prev_High = na
var float TF_Prev_Low = na
TF_Prev_High_Time = 0
TF_Prev_Low_Time = 0
//Tracking whether previous levels have been broken
var bool TF_High_Present = false
var bool TF_Low_Present = false
// Variables for creating supply and demand boxes
bool HH = false
bool LH = false
bool HL = false
bool LL = false
// Identify new pivot highs and lows
if not na(TF_SH)
if TF_SH >= TF_Prev_High
HH := true
else
LH := true
TF_Prev_High := TF_SH
TF_Prev_High_Time := TF_Prev_High != TF_Prev_High[1] ?
time[MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)] :
TF_Prev_High_Time[1]
TF_High_Present := true
if not na(TF_SL)
if TF_SL >= TF_Prev_Low
HL := true
else
LL := true
TF_Prev_Low := TF_SL
TF_Prev_Low_Time := TF_Prev_Low != TF_Prev_Low[1] ?
time[MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)] :
TF_Prev_Low_Time[1]
TF_Low_Present := true
// Displaying Swing Level
// Demand zones
if LL and (math.abs(TF_SL_High - TF_Prev_Low) < TF_Atr * 2)
array.unshift(Bullish_SnD_Top, TF_SL_High)
array.unshift(Bullish_SnD_Btm, TF_Prev_Low)
array.unshift(Bullish_SnD_Left, TF_Prev_Low_Time)
array.unshift(Bullish_SnD_Type, 1)
if Use_Demand_Alert
alert(message = "New demand zone formed on " + +
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq =
alert.freq_once_per_bar_close)
if HL and (math.abs(TF_SL_High - TF_Prev_Low) < TF_Atr * 2)
array.unshift(Bullish_SnD_Top, TF_SL_High)
array.unshift(Bullish_SnD_Btm, TF_Prev_Low)
array.unshift(Bullish_SnD_Left, TF_Prev_Low_Time)
array.unshift(Bullish_SnD_Type, 1)
if Use_Demand_Alert
alert(message = "New demand zone formed on " + +
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq =
alert.freq_once_per_bar_close)
// Supply zones
if HH and (math.abs(TF_Prev_High - TF_SH_Low) < TF_Atr * 2)
array.unshift(Bearish_SnD_Top, TF_Prev_High)
array.unshift(Bearish_SnD_Btm, TF_SH_Low)
array.unshift(Bearish_SnD_Left, TF_Prev_High_Time)
array.unshift(Bearish_SnD_Type, -1)
if Use_Supply_Alert
alert(message = "New supply zone formed on " + +
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq =
alert.freq_once_per_bar_close)
if LH and (math.abs(TF_Prev_High - TF_SH_Low) < TF_Atr * 2)
array.unshift(Bearish_SnD_Top, TF_Prev_High)
array.unshift(Bearish_SnD_Btm, TF_SH_Low)
array.unshift(Bearish_SnD_Left, TF_Prev_High_Time)
array.unshift(Bearish_SnD_Type, -1)
if Use_Supply_Alert
alert(message = "New supply zone formed on " + +
TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq =
alert.freq_once_per_bar_close)
// The function below is designed to sift through our boxes, plot them on the chart
and apply the necessary formatting.
Display_SnD_Zones(Box_PLot_Type, Box_Top, Box_Btm, Box_Left, Box_Type, Show_Last,
Box_Arr_size
, TF_Demand_Color, TF_Supply_Color, TF_Text_Color, TF_Text_Size, TF_Border_style,
TF_Border_width
, Chart_as_Timeframe, TF_Period, TF_Multip)=>
for i = 0 to math.min(Show_Last-1, Box_Arr_size-1)
get_box = array.get(Box_PLot_Type, i)
if HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip)
box.set_top(get_box, array.get(Box_Top, i))
box.set_bottom(get_box, array.get(Box_Btm, i))
box.set_left(get_box, array.get(Box_Left,i))
box.set_right(get_box, time_close("W"))
if Box_Type == "Bullish"
box.set_bgcolor(get_box, TF_Demand_Color)
box.set_border_color(get_box, TF_Demand_Color)
box.set_text(get_box, TF_Display(Chart_as_Timeframe, TF_Period,
TF_Multip))
box.set_text_color(get_box, TF_Text_Color)
box.set_text_font_family(get_box, font.family_default)
box.set_text_halign(get_box, text.align_right)
box.set_text_valign(get_box, text.align_top)
box.set_text_size(get_box, TF_Text_Size)
box.set_border_style(get_box, TF_Border_style)
box.set_border_width(get_box, TF_Border_width)
else if Box_Type == "Bearish"
box.set_bgcolor(get_box, TF_Supply_Color)
box.set_border_color(get_box, TF_Supply_Color)
box.set_text(get_box, TF_Display(Chart_as_Timeframe, TF_Period,
TF_Multip))
box.set_text_color(get_box, TF_Text_Color)
box.set_text_font_family(get_box, font.family_default)
box.set_text_halign(get_box, text.align_right)
box.set_text_valign(get_box, text.align_bottom)
box.set_text_size(get_box, TF_Text_Size)
box.set_border_style(get_box, TF_Border_style)
box.set_border_width(get_box, TF_Border_width)
// Calling functions
Supply_and_Demand_Functionality(TF_1_SH, TF_1_SL, TF_1_SH_Low, TF_1_SL_High,
TF_1_Atr
, TF_1_Swing_Length, TF_1_Chart_Feature, TF_1_Period, TF_1_Multip
, Bullish_SnD_Top_TF_1, Bullish_SnD_Btm_TF_1,
Bullish_SnD_Left_TF_1 ,Bullish_SnD_Type_TF_1
, Bearish_SnD_Top_TF_1, Bearish_SnD_Btm_TF_1, Bearish_SnD_Left_TF_1,
Bearish_SnD_Type_TF_1
, TF_1_Demand_Alert, TF_1_Supply_Alert)
Supply_and_Demand_Functionality(TF_2_SH, TF_2_SL, TF_2_SH_Low, TF_2_SL_High,
TF_2_Atr
, TF_2_Swing_Length, TF_2_Chart_Feature, TF_2_Period, TF_2_Multip
, Bullish_SnD_Top_TF_2, Bullish_SnD_Btm_TF_2,
Bullish_SnD_Left_TF_2 ,Bullish_SnD_Type_TF_2
, Bearish_SnD_Top_TF_2, Bearish_SnD_Btm_TF_2, Bearish_SnD_Left_TF_2,
Bearish_SnD_Type_TF_2
, TF_2_Demand_Alert, TF_2_Supply_Alert)
var TF_1_Bullish_Box_PLots = array.new_box(0)
var TF_1_Bearish_Box_PLots = array.new_box(0)
var TF_2_Bullish_Box_PLots = array.new_box(0)
var TF_2_Bearish_Box_PLots = array.new_box(0)
TF_1_Bullish_Size = array.size(Bullish_SnD_Top_TF_1)
TF_1_Bearish_Size = array.size(Bearish_SnD_Top_TF_1)
TF_2_Bullish_Size = array.size(Bullish_SnD_Top_TF_2)
TF_2_Bearish_Size = array.size(Bearish_SnD_Top_TF_2)
Supply_and_Demand_Mitigation(Bullish_SnD_Top_TF_1, Bullish_SnD_Btm_TF_1,
Bullish_SnD_Left_TF_1, Bullish_SnD_Type_TF_1, "Bullish", TF_1_Use_High_Low)
Supply_and_Demand_Mitigation(Bearish_SnD_Top_TF_1, Bearish_SnD_Btm_TF_1,
Bearish_SnD_Left_TF_1, Bearish_SnD_Type_TF_1, "Bearish", TF_1_Use_High_Low)
Supply_and_Demand_Mitigation(Bullish_SnD_Top_TF_2, Bullish_SnD_Btm_TF_2,
Bullish_SnD_Left_TF_2, Bullish_SnD_Type_TF_2, "Bullish", TF_2_Use_High_Low)
Supply_and_Demand_Mitigation(Bearish_SnD_Top_TF_2, Bearish_SnD_Btm_TF_2,
Bearish_SnD_Left_TF_2, Bearish_SnD_Type_TF_2, "Bearish", TF_2_Use_High_Low)
if barstate.isfirst
for i = 0 to 125
array.push(TF_1_Bullish_Box_PLots, box.new(na,na,na,na, xloc =
xloc.bar_time))
array.push(TF_1_Bearish_Box_PLots, box.new(na,na,na,na, xloc =
xloc.bar_time))
array.push(TF_2_Bullish_Box_PLots, box.new(na,na,na,na, xloc =
xloc.bar_time))
array.push(TF_2_Bearish_Box_PLots, box.new(na,na,na,na, xloc =
xloc.bar_time))
if TF_1_Bullish_Size > 0 and TF_1_Show_Demand and not Hide_All_Demand
if barstate.islast
Display_SnD_Zones(TF_1_Bullish_Box_PLots, Bullish_SnD_Top_TF_1,
Bullish_SnD_Btm_TF_1, Bullish_SnD_Left_TF_1, "Bullish", TF_1_Demand_Show_Last,
TF_1_Bullish_Size
, TF_1_Demand_Color, TF_1_Supply_Color, TF_1_Text_Color,
Text_Size_Switch(TF_1_Text_Size), Line_Type_Control(TF_1_Line_Type),
TF_1_Line_Width
, TF_1_Chart_Feature, TF_1_Period, TF_1_Multip)
if TF_1_Bearish_Size > 0 and TF_1_Show_Supply and not Hide_All_Supply
if barstate.islast
Display_SnD_Zones(TF_1_Bearish_Box_PLots, Bearish_SnD_Top_TF_1,
Bearish_SnD_Btm_TF_1, Bearish_SnD_Left_TF_1, "Bearish", TF_1_Supply_Show_Last,
TF_1_Bearish_Size
, TF_1_Demand_Color, TF_1_Supply_Color, TF_1_Text_Color,
Text_Size_Switch(TF_1_Text_Size), Line_Type_Control(TF_1_Line_Type),
TF_1_Line_Width
, TF_1_Chart_Feature, TF_1_Period, TF_1_Multip)
if TF_2_Bullish_Size > 0 and TF_2_Show_Demand and not Hide_All_Demand
if barstate.islast
Display_SnD_Zones(TF_2_Bullish_Box_PLots, Bullish_SnD_Top_TF_2,
Bullish_SnD_Btm_TF_2, Bullish_SnD_Left_TF_2, "Bullish", TF_2_Demand_Show_Last,
TF_2_Bullish_Size
, TF_2_Demand_Color, TF_2_Supply_Color, TF_2_Text_Color,
Text_Size_Switch(TF_2_Text_Size), Line_Type_Control(TF_2_Line_Type),
TF_2_Line_Width
, TF_2_Chart_Feature, TF_2_Period, TF_2_Multip)
if TF_2_Bearish_Size > 0 and TF_2_Show_Supply and not Hide_All_Supply
if barstate.islast
Display_SnD_Zones(TF_2_Bearish_Box_PLots, Bearish_SnD_Top_TF_2,
Bearish_SnD_Btm_TF_2, Bearish_SnD_Left_TF_2, "Bearish", TF_2_Supply_Show_Last,
TF_2_Bearish_Size
, TF_2_Demand_Color, TF_2_Supply_Color, TF_2_Text_Color,
Text_Size_Switch(TF_2_Text_Size), Line_Type_Control(TF_2_Line_Type),
TF_2_Line_Width
, TF_2_Chart_Feature, TF_2_Period, TF_2_Multip)
//end of this part
// 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("Predictive Ranges [LuxAlgo]", "LuxAlgo - Predictive Ranges", overlay =
true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
lengthd = input.int(200, 'Length', minval = 2)
mult = input.float(6., 'Factor', minval = 0, step = .5)
tf = input.timeframe('', 'Timeframe')
src = input(close, 'Source')
//-----------------------------------------------------------------------------}
//Function
//-----------------------------------------------------------------------------{
pred_ranges(lengthd, mult)=>
var avg = src
var hold_atr = 0.
atr = nz(ta.atr(lengthd)) * mult
avg := src - avg > atr ? avg + atr :
avg - src > atr ? avg - atr :
avg
hold_atr := avg != avg[1] ? atr / 2 : hold_atr
[avg + hold_atr * 2, avg + hold_atr, avg, avg - hold_atr, avg - hold_atr * 2]
//-----------------------------------------------------------------------------}
//Calculation
//-----------------------------------------------------------------------------{
[prR2
, prR1
, avg
, prS1
, prS2] = request.security(syminfo.tickerid, tf, pred_ranges(lengthd, mult))
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot_pru2 = plot(prR2, 'PR Upper 2', avg != avg[1] ? na : #f23645)
plot_pru1 = plot(prR1, 'PR Upper 1', avg != avg[1] ? na : #f23645)
plot_pravg = plot(avg , 'PR Average', avg != avg[1] ? na : #5b9cf6)
plot_prl1 = plot(prS1, 'PR Lower 1', avg != avg[1] ? na : #089981)
plot_prl2 = plot(prS2, 'PR Lower 2', avg != avg[1] ? na : #089981)
//Fills
fill(plot_pru2, plot_pru1, avg != avg[1] ? na : color.new(#f23645, 95))
fill(plot_prl1, plot_prl2, avg != avg[1] ? na : color.new(#089981, 95))
//-----------------------------------------------------------------------------}
//end of this part
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
at https://mozilla.org/MPL/2.0/
// © RozaniGhani-RG
//@version=5
//indicator('Linear Regression Channel 200', 'LRC200', true)
// 0. Inputs
// 1. Custom function
// 2. Variables
// 3. Contructs
// 4. Alerts
//#region ———————————————————— 0. Inputs
devLen = input.float(2.0, 'Deviation')
regLen = input.int( 200, 'Length', minval = 1, maxval = 5000)
//#endregion
//#region ———————————————————— 1. Custom function
calculateRegression(int len = 200) =>
max_bars_back(close, 1500)
mid = math.sum( close, len) / len
slope = ta.linreg(close, len, 0) - ta.linreg(close, len, 1)
price1 = mid - slope * math.floor(len / 2) + (1 - len % 2) / 2 * slope
price2 = price1 + slope * (len - 1)
dev = 0.0
for x = 0 to len - 1
dev += math.pow(close[x] - (slope * (len - x) + price1), 2)
dev
dev := math.sqrt(dev / len)
[price1, price2, dev, slope]
//#endregion
//#region ———————————————————— 2. Variables
[price1, price2, stdDev, slope] = calculateRegression(regLen)
mid1 = chart.point.new(na, bar_index - regLen + 1, price1)
up1 = chart.point.new(na, bar_index - regLen + 1, price1 + (devLen * stdDev))
dn1 = chart.point.new(na, bar_index - regLen + 1, price1 - (devLen * stdDev))
mid2 = chart.point.new(na, bar_index, price2)
up2 = chart.point.new(na, bar_index, price2 + (devLen * stdDev))
dn2 = chart.point.new(na, bar_index, price2 - (devLen * stdDev))
col = price1 > price2 ? color.red : color.teal
//#endregion
//#region ———————————————————— 3. Contructs
if barstate.islast
var line midLine = na, midLine.delete(), midLine := line.new(mid1, mid2,
xloc.bar_index, extend.right, chart.fg_color, line.style_dashed, 1)
var line upLine = na, upLine.delete(), upLine := line.new( up1, up2,
xloc.bar_index, extend.right, chart.fg_color, line.style_solid, 2)
var line dnLine = na, dnLine.delete(), dnLine := line.new( dn1, dn2,
xloc.bar_index, extend.right, chart.fg_color, line.style_solid, 2)
//#endregion
//#region ———————————————————— 4. Alerts
float trend = math.sign(price1 - price2)
alertcondition(trend[1] >= 0 and trend < 0, 'Uptrend', 'Regression Channel change
to Uptrend')
alertcondition(trend[1] <= 0 and trend > 0, 'Downtrend', 'Regression Channel change
to Downtrend')
//#endregion
//end of this part
//@version=5
//@author Eugene
//
// HOLP (High of the low period) and LOHP (Low of the high period)
// Catching Trend Reversals by shorting tops and buying bottoms
// using this Swing High/Low Indicator
//
// Trading Strategy comes from Mastering the Trade, by John Carter pg 300.
// Trading Rules for Sells, Buys are reversed
//
// 1. Identifying a trending market, where today's price is making a 20-day high
(17-18 day highs are also fine)
// Note this is configurable by setting the trending period variable (defaults
to 20)
// For example if price is making a 20 period high or 20 period low, it will
show a triangle up/down above the candle.
// 2. Identify the high bar in the uptrend
// 3. Go short once the price action closes below the low of this high bar
// 4. The intial stop is the high of the high bar.
// 5. If you are in the trade on the third day or period, use a 2 bar trailing
stop.
// You can check 2-bar trailing stop to draw the line, defaults to off.
// Stop is indicated by the white dot.
//
// Code Converted from TradeStation EasyLanguage
// I can't find the original source anymore for the swing high/low plots, but if
someone knows,
// let me know and I'll credit here.
//
//indicator(shorttitle='HOLP/LOHP', title='Catching Trend Reversals by shorting
tops and buying bottoms', overlay=true)
bartype() =>
if timeframe.period == "D"
2
else if timeframe.period == "W"
3
else if timeframe.period == "M"
4
else
1
barinterval() =>
timeframe.multiplier
fPushPeriods(iInterval) =>
if iInterval < 5
60
else if iInterval < 10
45
else if iInterval == 10
6
else if iInterval == 15
12
else if iInterval == 30
4
else if iInterval == 60
6
else if iInterval > 60
10
var iMode = "Yes"
var iPeriods = input.int(5, 'Periods')
var highColor = input.color(color.red, 'high color')
var lowColor = input.color( color.blue, 'low color')
var trendingPeriod = input.int(20, 'Trending Period (shows triangleup or
triangledown if price is making this period high/low)')
var showShortStop = input.bool(false, '2 bar trailing stop when shorting')
var showLongStop = input.bool(false, '2 bar trailing stop when buying (going
long)')
var xPeriods = 60
var xInterval = 0
var sFirstPass = true
var havePrevLines = false
var tLHigh = 0.0
var tLLow = 0.0
var pushHigh = 0.0
var pushHighBar = 0
var pushLow = 0.0
var pushLowBar = 0
var oldPushHigh = 0.0
var oldPushLow = 0.0
var prevPushHigh = 0.0
var prevPushLow = 0.0
var K = 0.0
var R = 0.0
var H0C1 = 0.0
var L0C1 = 0.0
var H0L0 = 0.0
var C1O1 = 0.0
var DL = 1.0
var SI =0.0
var ASI = 0.0
var SLOW_K =0.0
var SLOW_D = 0.0
var SWING_HIGH = 0.0
var SWING_LOW = 0.0
H0C1 := math.abs(high - close[1] )
L0C1 := math.abs( low - close[1] )
H0L0 := high - low
C1O1 := math.abs(close[1] - open[1] )
if H0C1 >= L0C1
K := H0C1
if H0C1 >= H0L0
R := H0C1 - 0.5 * L0C1 + 0.25 * C1O1
else
R := H0L0 + 0.25 * C1O1
else
K := L0C1
if L0C1 >= H0L0
R := L0C1 - 0.5 * H0C1 + 0.25 * C1O1
else
R := H0L0 + 0.25 * C1O1
if R != 0
SI := 50 * ( ( ( close - close[1] ) + 0.50 * ( close - open ) + 0.25 *
( close[1] - open[1] ) ) / R ) * K / DL
else
SI := 0
ASI := ASI + SI
if sFirstPass
sFirstPass := false
if bartype() == 4 // monthly
xInterval := 94
else if bartype() == 3 // weekly
xInterval := 93
else if bartype() == 2 // daily
xInterval := 92
else if bartype() == 1 // minute
xInterval := barinterval()
if iMode != "Auto" and iMode != "auto" and iMode != "AUTO"
xPeriods := iPeriods
else
xPeriods := fPushPeriods(xInterval)
if pushHigh != prevPushHigh
oldPushHigh := prevPushHigh
if pushLow != prevPushLow
oldPushLow := prevPushLow
oldPushHigh := prevPushHigh
oldPushLow := prevPushLow
prevPushHigh := pushHigh
prevPushLow := pushLow
pushHigh := ta.highest(high, xPeriods)
pushLow := ta.lowest(low, xPeriods)
var lowBreakout = 0.0
var highBreakout = 0.0
var pushBar = 0
if pushHigh != high and pushHigh < prevPushHigh
pushHigh := prevPushHigh
if pushLow != low and pushLow > prevPushLow
pushLow := prevPushLow
if pushHigh != pushHigh[1]
lowBreakout := low
if pushLow != pushLow[1]
highBreakout := high
var stopz = 0.0
var prevHighBreakout = 0.0
var entry = 0.0
plot(pushHigh, "PushHigh", color.yellow, style=plot.style_circles)
plot(pushLow, "PushLow", color.blue, style=plot.style_circles)
plotshape(close >= ta.highest(trendingPeriod)[1] ? close : na,
style=shape.triangledown, location=location.abovebar, color=color.red)
plotshape(close <= ta.lowest(trendingPeriod)[1] ? close : na,
style=shape.triangleup, location=location.abovebar, color=color.green)
plot(showShortStop ? ta.highest(2)[1] : na, color=color.white,
style=plot.style_cross)
plot(showLongStop ? ta.lowest(2)[1] : na, color=color.white,
style=plot.style_cross)
//end of this part
// This work is licensed under Creative Commons Attribution-NonCommercial-
ShareAlike 4.0 International License (CC BY-NC-SA 4.0)
https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope Pty Ltd
// ░▒
// ▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒
// ▒▒▒▒▒▒▒░ ▒ ▒▒
// ▒▒▒▒▒▒ ▒ ▒▒
// ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
// ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒
// ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒
// ▒▒▒▒▒ ▒▒▒▒▒▒▒
// ▒▒▒▒▒▒▒▒▒
// ▒▒▒▒▒ ▒▒▒▒▒
// ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗
██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
// ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗
██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║
██║███████╗██║ ██║ ██║██████╔╝█████╗
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║
██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝
// ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║
╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗
// ▒▒ ▒
//@version=5
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/ZigzagTypes/5 as zg
import HeWhoMustNotBeNamed/ZigzagMethods/6
import HeWhoMustNotBeNamed/utils/1 as ut
import HeWhoMustNotBeNamed/FibRatios/1 as fibs
//indicator("ABC on Recursive Zigzag [Trendoscope]", "ABC-RZ[Trendoscope]", overlay
= true, max_lines_count=500, max_labels_count=500, max_bars_back = 1000)
theme = input.string('Dark', title='Theme', options=['Light', 'Dark'],
group='Generic Settings',
tooltip='Chart theme settings. Line and label colors are generted based on
the theme settings. If dark theme is selected, '+
'lighter colors are used and if light theme is selected, darker colors are
used.', display=display.none)
zigzagLength = input.int(13, step=5, minval=3, title='Length', group='Zigzag',
tooltip='Zigzag length for level 0 zigzag', display = display.none)
depth = input.int(200, "Depth", step=25, maxval=500, group='Zigzag',
tooltip='Zigzag depth refers to max number of pivots to show on chart', display =
display.none)
minimumZigZagLevel = input.int(0, "Minimum Zigzag Level", group='Zigzag', minval =
0, tooltip = 'Minimum zigzag level to consider for pattern scanning',
display=display.none)
indicators = matrix.new<float>()
indicatorNames = array.new<string>()
base = input.string('ABC Extension', 'Base', ['ABC Extension', 'BC Retracement'],
'Base on which entry, stop and target are calculated', group='ABC', display =
display.none)
entryRatio = input.float(0.3, 'Entry Ratio', group='ABC', minval=0.1, step=0.1,
display = display.none, tooltip = 'Entry ratio for the calculation of entry level')
targetRatio = input.float(1.0, 'Target Ratio', group='ABC', display = display.none,
tooltip = 'Target Ratio for the calculation of target level')
stopRatio = input.float(0.0, 'Stop Ratio', group='ABC', maxval=0.0, step=0.1,
display = display.none, tooltip = 'Stop Ratio for the calculation of stop level')
logScale = input.bool(false, 'Log Scale', group='ABC', display = display.none,
tooltip = 'Use log scale for scanning and targets')
useClosePricesForEntry = input.bool(true, 'Entry', group='Use Close Prices',
display = display.none, tooltip = 'Use close prices for tracking', inline = 'ucp')
useClosePricesForTarget = input.bool(true, 'Target', group='Use Close Prices',
display = display.none, tooltip = 'Use close prices for tracking', inline = 'ucp')
useClosePricesForStop = input.bool(true, 'Stop', group='Use Close Prices', display
= display.none, tooltip = 'Use close prices for tracking', inline = 'ucp')
useClosePricesForRetest = input.bool(true, 'Retest', group='Use Close Prices',
display = display.none, tooltip = 'Use close prices for tracking', inline = 'ucp')
tradeConditionTooltip = 'any - no filter\ntrend - Both A and B pivots in the
direction of trend. Example, HH, and HL for long signal and LH and LL for short
signal\n'+
'reverse - Both A and B pivots in the opposite
direction of trend. Example, LH, and LL for long signal and HH and HL for short
signal\n'+
'contracting - Consider only if both A and B pivots
are either LH or HL\nexpanding - Consider only if both A and B pivots are either HH
or LL'
tradeCondition = input.string('any', 'Trade Condition', ['any', 'trend', 'reverse',
'contracting', 'expanding'], group='ABC', display = display.none, tooltip =
tradeConditionTooltip)
condition = tradeCondition == 'any'? 0:
tradeCondition == 'trend'? 1:
tradeCondition == 'reverse'? 2:
tradeCondition == 'contracting'? 3: 4
baseVal = base == 'ABC Extension'? 1 : 2
var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth)
zigzag.calculate(array.from(high, low), indicators, indicatorNames)
type ABCProperties
int base = 1
float entryRatio = 0.23
float targetRatio = 1.0
float stopRatio = -0.1
bool logScale = false
bool useClosePricesForEntry = true
bool useClosePricesForTarget = false
bool useClosePricesForStop = true
bool useClosePricesForRetest = false
int condition = 0
type ABCDrawing
dr.Line ab
dr.Line bc
dr.Line ac
dr.Label a
dr.Label b
dr.Label c
dr.Label abcRatio
dr.Box entryBox
dr.Box targetBox
type ABC
int id
int direction
zg.Pivot a
zg.Pivot b
zg.Pivot c
color patternColor
ABCProperties properties
float entryPrice
float stopPrice
float targetPrice
int status = 0
ABCDrawing drawing
initialiseCounts(int numberOfStatus)=>
countMap = map.new<int, int>()
for i=0 to numberOfStatus-1
countMap.put(i, 0)
countMap
var array<ABC> abcdPatterns = array.new<ABC>()
var array<ABC> oldPatterns = array.new<ABC>()
var map<int, int> bullishCounts = initialiseCounts(3)
var map<int, int> bearishCounts = initialiseCounts(3)
var int bullishRetests = 0
var int bearishRetests = 0
method calculateTargets(ABC this)=>
this.entryPrice := this.properties.base == 1 ?
fibs.extension(this.a.point.price, this.b.point.price, this.c.point.price,
this.properties.entryRatio, this.properties.logScale) :
fibs.retracement(this.b.point.price, this.c.point.price,
this.properties.entryRatio, this.properties.logScale)
this.targetPrice := this.properties.base == 1 ?
fibs.extension(this.a.point.price, this.b.point.price, this.c.point.price,
this.properties.targetRatio, this.properties.logScale) :
fibs.retracement(this.b.point.price, this.c.point.price,
this.properties.targetRatio, this.properties.logScale)
this.stopPrice := this.properties.base == 1 ?
fibs.extension(this.a.point.price, this.b.point.price, this.c.point.price,
this.properties.stopRatio, this.properties.logScale) :
fibs.retracement(this.b.point.price, this.c.point.price,
this.properties.stopRatio, this.properties.logScale)
this
method withinEntry(ABC this)=>
dir = this.c.point.price > this.b.point.price? -1 : 1
close*dir < this.entryPrice*dir
method delete(ABCDrawing this)=>
if(not na(this))
this.ab.delete()
this.bc.delete()
this.ac.delete()
this.abcRatio.delete()
this.a.delete()
this.b.delete()
this.c.delete()
this.entryBox.delete()
this.targetBox.delete()
else
log.info('this should not be na')
this
method draw(ABCDrawing this)=>
if(not na(this))
this.ab.draw()
this.bc.draw()
this.ac.draw()
this.abcRatio.draw()
this.a.draw()
this.b.draw()
this.c.draw()
this.entryBox.draw()
this.targetBox.draw()
else
log.info('this should not be na')
this
method draw(ABC this)=>
this.drawing.draw()
this
method deleteDrawing(ABC this)=>
if(not na(this.drawing))
this.drawing.delete()
this.drawing := na
this
method createDrawing(ABC this)=>
if(not na(this.drawing))
this.drawing.delete()
dr.LineProperties patternLineProps =
dr.LineProperties.new(color=this.patternColor, width = 1, style = line.style_solid)
ab = this.a.point.createLine(this.b.point, patternLineProps)
bc = this.b.point.createLine(this.c.point, patternLineProps)
dr.LineProperties angleLineProps =
dr.LineProperties.new(color=this.patternColor, width = 0, style =
line.style_dotted)
ac = dr.Line.new(this.a.point, this.c.point, angleLineProps)
acMidPoint = dr.Point.new((this.a.point.price+this.c.point.price)/2,
(this.a.point.bar + this.c.point.bar)/2, (this.a.point.bartime +
this.c.point.bartime)/2)
abcRatioValue = fibs.retracementRatio(this.a.point.price, this.b.point.price,
this.c.point.price)
ratioLabelProperties = dr.LabelProperties.new(yloc = yloc.price, textcolor =
this.patternColor, style = label.style_none)
abcRatio = dr.Label.new(acMidPoint, str.tostring(abcRatioValue), properties =
ratioLabelProperties)
pivotLabelPropertiesAC = dr.LabelProperties.new(yloc = this.a.point.price <
this.b.point.price? yloc.belowbar : yloc.abovebar, textcolor = this.patternColor)
pivotLabelPropertiesBD = dr.LabelProperties.new(yloc = this.a.point.price >
this.b.point.price? yloc.belowbar : yloc.abovebar, textcolor = this.patternColor)
a = dr.Label.new(this.a.point, 'A', properties = pivotLabelPropertiesAC)
b = dr.Label.new(this.b.point, 'B', properties = pivotLabelPropertiesBD)
c = dr.Label.new(this.c.point, 'C', properties = pivotLabelPropertiesAC)
entryPoint = dr.Point.new(this.entryPrice, this.c.point.bar,
this.c.point.bartime)
barDiff = math.min((this.c.point.bar- this.a.point.bar)/2, 490)
entryBoxEndPoint = dr.Point.new(this.stopPrice, this.c.point.bar+barDiff)
targetBoxEndPoint = dr.Point.new(this.targetPrice, this.c.point.bar+barDiff)
boxPropertiesEntry = dr.BoxProperties.new(this.patternColor,
color.new(color.red, 90))
boxPropertiesTarget = dr.BoxProperties.new(this.patternColor,
color.new(color.green, 90))
entryBox = dr.Box.new(entryPoint, entryBoxEndPoint, boxPropertiesEntry)
targetBox = dr.Box.new(entryPoint, targetBoxEndPoint, boxPropertiesTarget)
this.drawing := ABCDrawing.new(ab, bc, ac, a, b, c, abcRatio, entryBox,
targetBox)
this
method update(ABC this, zg.Pivot c)=>
this.c := c
alert('ABC Pattern Coordinates Updated')
this.calculateTargets()
if(this.withinEntry())
this.deleteDrawing().
createDrawing().
draw()
this
method createAbc(zg.Zigzag this, ABCProperties props, color patternColor)=>
var id = 1
c = this.zigzagPivots.get(0)
b = this.zigzagPivots.get(1)
a = this.zigzagPivots.get(2)
direction = b.point.price > c.point.price? 1 : -1
abc = ABC.new(id, direction, a, b, c, patternColor, props)
id+=1
abc
method scanAbc(zg.Zigzag this, ABCProperties props)=>
isAbc = false
if(this.zigzagPivots.size() >= 4)
c = this.zigzagPivots.get(0)
b = this.zigzagPivots.get(1)
a = this.zigzagPivots.get(2)
aDir = math.abs(a.dir)
bDir = math.abs(b.dir)
conditionInLine = props.condition == 0 or
(props.condition == 1 and aDir == 1 and bDir == 2) or
(props.condition == 2 and aDir == 2 and bDir == 1) or
(props.condition == 3 and aDir == 1 and bDir == 1) or
(props.condition == 4 and aDir == 2 and bDir == 2)
ratioInLine = c.ratio >= 0.618 and c.ratio <= 0.786
if(ratioInLine and conditionInLine)
existingPattern = false
isAbc := true
for p in abcdPatterns
existingPattern := p.a.point.price == a.point.price and
p.b.point.price == b.point.price
if(existingPattern)
if(p.c.point.bar > c.point.bar and p.status == 0)
p.update(c)
isAbc:=false
break
isAbc
method record(ABC pattern)=>
countMapToSet = pattern.direction >0? bullishCounts : bearishCounts
countMapToSet.put(pattern.status, countMapToSet.get(pattern.status)+1)
method removePattern(array<ABC> patterns, int index)=>
pattern = patterns.remove(index)
pattern.deleteDrawing()
pattern.record()
method traverse(array<ABC> patterns)=>
for i = patterns.size() >0? patterns.size()-1: na to 0
pattern = patterns.get(i)
baseTarget = pattern.properties.useClosePricesForTarget? close :
(pattern.direction > 0? high : low)
baseStop = pattern.properties.useClosePricesForStop? close :
(pattern.direction >0? low : high)
baseEntry = pattern.properties.useClosePricesForEntry? close :
(pattern.direction > 0? high : low)
baseValueRetest = pattern.properties.useClosePricesForRetest? close :
(pattern.direction > 0? low : high)
baseInvalidation = close
newStatus = baseTarget*pattern.direction >=
pattern.targetPrice*pattern.direction? 2 :
baseEntry*pattern.direction >=
pattern.entryPrice*pattern.direction? 1: pattern.status
retested = pattern.status == 1 and baseValueRetest <= pattern.entryPrice
newStatus := math.max(pattern.status, newStatus)
closed = (newStatus > 0 and baseStop*pattern.direction <=
pattern.stopPrice*pattern.direction) or
(newStatus == 0 and baseInvalidation*pattern.direction <=
pattern.stopPrice*pattern.direction) or
pattern.status == 2
increment = newStatus >= pattern.status
pattern.status := newStatus
if(closed)
patterns.removePattern(i)
var properties = ABCProperties.new(baseVal, entryRatio, targetRatio, stopRatio,
logScale, useClosePricesForEntry, useClosePricesForTarget, useClosePricesForStop,
useClosePricesForRetest, condition)
var themeColors = ut.getColors(theme)
abcdPatterns.traverse()
oldPatterns.traverse()
if zigzag.flags.newPivot
mlzigzag = zigzag
while(mlzigzag.zigzagPivots.size() >= 3)
if(mlzigzag.level >= minimumZigZagLevel)
isAbcd = mlzigzag.scanAbc(properties)
if(isAbcd)
patternColor = themeColors.shift()
alert('New ABC Pattern Detected')
pattern = mlzigzag.createAbc(properties,
patternColor).calculateTargets()
if(pattern.withinEntry())
pattern.createDrawing().draw()
abcdPatterns.push(pattern)
while(abcdPatterns.size() > 10)
last = abcdPatterns.shift()
oldPatterns.push(last)
last.deleteDrawing()
themeColors.push(patternColor)
mlzigzag := mlzigzag.nextlevel()
while(abcdPatterns.size() < 10 and oldPatterns.size() > 0)
restoreOld = oldPatterns.pop()
abcdPatterns.unshift(restoreOld)
restoreOld.draw()
if barstate.islast
var closedStatsTable = table.new(position.top_right, 6, 3, border_color =
chart.bg_color)
closedStatsTable.clear(0, 0, 5, 2)
closedStatsTable.cell(0, 0, 'Direction\\Status', text_color=color.white,
bgcolor = color.maroon)
closedStatsTable.cell(1, 0, 'Invalid', text_color=color.white, bgcolor =
color.maroon)
closedStatsTable.cell(2, 0, 'Stopped', text_color=color.white, bgcolor =
color.maroon)
closedStatsTable.cell(3, 0, 'Complete', text_color=color.white, bgcolor =
color.maroon)
closedStatsTable.cell(4, 0, 'Win Ratio', text_color=color.white, bgcolor =
color.maroon)
closedStatsTable.cell(5, 0, 'Risk Reward', text_color=color.white, bgcolor =
color.maroon)
closedStatsTable.cell(0, 1, 'Bullish', text_color=color.white, bgcolor =
color.new(color.green, 50))
closedStatsTable.cell(0, 2, 'Bearish', text_color=color.white, bgcolor =
color.new(color.red, 50))
bullishInvalid = bullishCounts.get(0)
bullishStopped = bullishCounts.get(1)
bullishCompleted = bullishCounts.get(2)
riskReward =(targetRatio - entryRatio)/(entryRatio - stopRatio)
bullishBgColor = color.new(color.green, 70)
closedStatsTable.cell(1, 1, str.tostring(bullishInvalid),
text_color=color.white, bgcolor = bullishBgColor)
closedStatsTable.cell(2, 1, str.tostring(bullishStopped),
text_color=color.white, bgcolor = bullishBgColor)
closedStatsTable.cell(3, 1, str.tostring(bullishCompleted),
text_color=color.white, bgcolor = bullishBgColor)
closedStatsTable.cell(4, 1,
str.tostring(bullishCompleted*100/(bullishCompleted+bullishStopped),
format.percent), text_color=color.white, bgcolor = bullishBgColor)
closedStatsTable.cell(5, 1, str.tostring(riskReward, '#.##'),
text_color=color.white, bgcolor = bullishBgColor)
bearishInvalid = bearishCounts.get(0)
bearishStopped = bearishCounts.get(1)
bearishCompleted = bearishCounts.get(2)
bearishBgColor = color.new(color.red, 70)
closedStatsTable.cell(1, 2, str.tostring(bearishInvalid),
text_color=color.white, bgcolor = bearishBgColor)
closedStatsTable.cell(2, 2, str.tostring(bearishStopped),
text_color=color.white, bgcolor = bearishBgColor)
closedStatsTable.cell(3, 2, str.tostring(bearishCompleted),
text_color=color.white, bgcolor = bearishBgColor)
closedStatsTable.cell(4, 2,
str.tostring(bearishCompleted*100/(bearishCompleted+bearishStopped),
format.percent), text_color=color.white, bgcolor = bearishBgColor)
closedStatsTable.cell(5, 2, str.tostring(riskReward, '#.##'),
text_color=color.white, bgcolor = bearishBgColor)
//end of this part
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
at https://mozilla.org/MPL/2.0/
// © ismailcarlik
//@version=5
//indicator("Trend Lines, Supports and Resistances", shorttitle = "TSR", overlay =
true, max_bars_back = 5000)
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * I N P U T S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
grpPivotPoints = "Pivot Points ・ Common"
pvtLength = input.int(20, title = "Pivot Length", minval = 1, group =
grpPivotPoints)
pvtMarkPivots = input.bool(false, title = "Mark Pivots", group = grpPivotPoints)
grpTrendLines = "Trend Lines"
tlEnabled = input.bool(true, title = "Enabled", group = grpTrendLines)
tlPointsToCheck = input.int(3, title = "Points to Check", minval = 2, group =
grpTrendLines)
tlMaxViolation = input.int(0, title = "Maximum Violation", minval = 0, group =
grpTrendLines)
tlExceptBars = input.int(3, title = "Excepted Last Bars", minval = 0, group =
grpTrendLines)
tlShowViolated = input.bool(false, title = "Show Violated Trend Lines", group =
grpTrendLines)
tlExtension = input.string("Right", title = "Line Extension", options = ["None",
"Left", "Right", "Both"], group = grpTrendLines)
tlShowLabels = input.bool(true, title = "Show Labels", group = grpTrendLines)
tlAlertsEnabled = input.bool(true, title = "Alerts Enabled", inline = "tlAlerts",
group = grpTrendLines)
tlAlertrequency = input.string("Once Per Bar", title = " ・ Frequency", options =
["Once Per Bar", "Once Per Bar Close", "All"], inline = "tlAlerts", group =
grpTrendLines, display = display.none)
grpSupportResistance = "Supports & Resistances"
srEnabled = input.bool(true, title = "Enabled", group = grpSupportResistance)
srPointsToCheck = input.int(3, title = "Points to Check", minval = 2, group =
grpSupportResistance)
srMaxViolation = input.int(0, title = "Maximum Violation Allowed", minval = 0,
group = grpSupportResistance)
srExceptBars = input.int(3, title = "Excepted Last Bars", minval = 0, group =
grpSupportResistance)
srShowLabels = input.bool(true, title = "Show Labels", group =
grpSupportResistance)
srAlertsEnabled = input.bool(true, title = "Alerts Enabled", inline = "srAlerts",
group = grpSupportResistance)
srAlertrequency = input.string("Once Per Bar", title = " ・ Frequency", options =
["Once Per Bar", "Once Per Bar Close", "All"], inline = "srAlerts", group =
grpSupportResistance, display = display.none)
grpVisual = "Style"
stlHighColor = input.color(color.blue, title = "High Color", inline = "colors",
group = grpVisual)
stlLowColor = input.color(color.red, title = "Low Color", inline = "colors", group
= grpVisual)
lineWidth = input.int(1, title = "Line Width", minval = 1, group = grpVisual)
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * T Y P E S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
// @type Used to represent a point pair.
// @field firstPoint First point of pair.
// @field secondPoint Second point of pair.
type pointPair
chart.point firstPoint
chart.point secondPoint
// @type Used to represent a trend line.
// @field mainLine Main visible line of the trend.
// @field extensionLine Extension line of the trend.
// @field priceLabel Price label of the trend.
// @field isViolated Violation status of the trend.
type trendLine
line mainLine
line extensionLine = na
label priceLabel = na
bool isViolated = false
// @type Used to represent a support or resistance level.
// @field levelBox Level box for support or resistance.
// @field price Price level of the support or resistance.
// @field priceLabel Price label of the support or resistance.
type srLevel
box levelBox
float price
label priceLabel = na
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * V A R I A B L E S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
tlExtendMode = str.lower(array.get(str.split(tlExtension, ""), 0))
tlAlertrequencyMode = switch tlAlertrequency
"Once Per Bar" => alert.freq_once_per_bar
"Once Per Bar Close" => alert.freq_once_per_bar_close
"All" => alert.freq_all
=> alert.freq_once_per_bar
srAlertrequencyMode = switch srAlertrequency
"Once Per Bar" => alert.freq_once_per_bar
"Once Per Bar Close" => alert.freq_once_per_bar_close
"All" => alert.freq_all
=> alert.freq_once_per_bar
var array<chart.point> highPivots = array.new<chart.point>()
var array<chart.point> lowPivots = array.new<chart.point>()
var array<trendLine> uptrends = array.new<trendLine>()
var array<trendLine> downtrends = array.new<trendLine>()
var array<srLevel> supports = array.new<srLevel>()
var array<srLevel> resistances = array.new<srLevel>()
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * M E T H O D S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
// @function Returns reversed version of array.
// @param id (chart.point[]) Array object.
// @returns (chart.point[]) Reversed version of given array.
method reversed(array<chart.point> id) =>
array<chart.point> reversedArray = array.new<chart.point>()
for [i, v] in id
reversedArray.unshift(v)
reversedArray
// @function Checks for the bars if highs above trend line price.
// @param id (trendLine) Trend line object.
// @param exceptBars (int) Count of last bars for exception.
// @returns (int) Count of the bars above trend line price.
method getHighsAbovePrice(trendLine id, int exceptBars) =>
historyReference = bar_index - id.mainLine.get_x1()
count = 0
if exceptBars < historyReference
for i = historyReference to exceptBars
if high[i] > line.get_price(id.mainLine, bar_index - i)
count += 1
count
// @function Checks for the bars if lows below trend line price.
// @param id (trendLine) Trend line object.
// @param exceptBars (int) Count of last bars for exception.
// @returns (int) Count of the bars below trend line price.
method getLowsBelowPrice(trendLine id, int exceptBars) =>
historyReference = bar_index - id.mainLine.get_x1()
count = 0
if exceptBars < historyReference
for i = historyReference to exceptBars
if low[i] < line.get_price(id.mainLine, bar_index - i)
count += 1
count
// @function Sets the trend lines status to violated.
// @param id (trendLine) Trend line object.
// @param trendColor (color) Color of the trend line.
// @returns (void)
method setViolated(trendLine id, color trendColor) =>
id.isViolated := true
line.delete(id.extensionLine)
label.delete(id.priceLabel)
line.set_style(id.mainLine, line.style_dotted)
line.set_extend(id.mainLine, extend = tlExtendMode)
line.set_color(id.mainLine, tlShowViolated ? color.new(trendColor, 50) : na)
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * F U N C T I O N S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
// @function Compares two points and returns true if first one is higher.
// @param firstPoint (chart.point) First point to compare.
// @param secondPoint (chart.point) Second point to compare.
// @returns (bool) Whether the first point is higher than the second.
f_isHigher (chart.point firstPoint, chart.point secondPoint) =>
firstPoint.price > secondPoint.price
// @function Compares two points and returns true if first one is lower.
// @param firstPoint (chart.point) First point to compare.
// @param secondPoint (chart.point) Second point to compare.
// @returns (bool) Whether the first point is lower than the second.
f_isLower (chart.point firstPoint, chart.point secondPoint) =>
firstPoint.price < secondPoint.price
// @function Checks for violation of support level.
// @param point (chart.point) Point of support level.
// @param exceptBars (int) Count of last bars for exception.
// @returns (int) Count of violations.
f_checkSupportViolation (chart.point point, int exceptBars) =>
historyReference = bar_index - point.index
violationCount = 0
if exceptBars < historyReference
for i = historyReference to exceptBars
if low[i] < point.price
violationCount += 1
violationCount
// @function Checks for violation of reistance level.
// @param point (chart.point) Point of resistance level.
// @param exceptBars (int) Count of last bars for exception.
// @returns (int) Count of violations.
f_checkResistanceViolation(chart.point point, int exceptBars) =>
historyReference = bar_index - point.index
violationCount = 0
if exceptBars < historyReference
for i = historyReference to exceptBars
if high[i] > point.price
violationCount += 1
violationCount
// @function Draws support level to chart.
// @param index (int) Bar index of support level.
// @returns (void)
f_drawSupport(int index) =>
historyReference = bar_index - index
lowValue = low[historyReference]
boxColor = color.new(stlHighColor, 70)
textColor = color.new(stlHighColor, 50)
supportBox = box.new(left = index, top = math.min(open[historyReference],
close[historyReference]), right = bar_index, bottom = lowValue, bgcolor = boxColor,
border_color = boxColor)
supportLabel = srShowLabels ? label.new(x = bar_index - int(historyReference /
2), y = lowValue, text = "Support : " + str.tostring(lowValue, format.mintick),
style = label.style_label_up, color = color.new(boxColor, 100), textcolor =
textColor) : na
supports.push(srLevel.new(levelBox = supportBox, price = lowValue, priceLabel =
supportLabel))
// @function Draws resistance level to chart.
// @param index (int) Bar index of reistance level.
// @returns (void)
f_drawResistance(int index) =>
historyReference = bar_index - index
highValue = high[historyReference]
boxColor = color.new(stlLowColor, 70)
textColor = color.new(stlLowColor, 50)
resistanceBox = box.new(left = index, top = highValue, right = bar_index,
bottom = math.max(open[historyReference], close[historyReference]), bgcolor =
boxColor, border_color = boxColor)
resistanceLabel = srShowLabels ? label.new(x = bar_index - int(historyReference
/ 2), y = highValue, text = "Resistance : " + str.tostring(highValue,
format.mintick), style = label.style_label_down, color = color.new(boxColor, 100),
textcolor = textColor) : na
resistances.push(srLevel.new(levelBox = resistanceBox, price = highValue,
priceLabel = resistanceLabel))
// @function Gets all pair combinations of given point array.
// @param srcArray (chart.point[]) Source array.
// @returns (pointPair[]) Array of point pairs.
f_getAllPairCombinations(array<chart.point> srcArray) =>
int inputLength = array.size(srcArray)
array<pointPair> pairs = array.new<pointPair>()
for i = 0 to inputLength - 2 by 1
for j = i + 1 to inputLength - 1 by 1
pairs.push(pointPair.new(firstPoint = srcArray.get(i), secondPoint =
srcArray.get(j)))
pairs
// @function Draws an uptrend to chart.
// @param start (chart.point) Starting point of trend line.
// @param end (chart.point) Ending point of trend line.
// @returns (void)
f_drawUptrend(chart.point start, chart.point end) =>
uExtension = tlExtendMode == "n" ? na : line.new(start, end, color =
color.new(stlHighColor, 50), extend = tlExtendMode, style = line.style_dashed,
width = lineWidth)
uMain = line.new(start, end, color = stlHighColor, style =
line.style_arrow_both, width = lineWidth)
uPrice = line.get_price(uMain, bar_index)
uLabel = tlShowLabels ? label.new(x = bar_index, y = uPrice, text = "Uptrend :
" + str.tostring(uPrice, format.mintick), style = label.style_label_left, color =
color.new(stlHighColor, 80), textcolor = stlHighColor) : na
uptrends.push(trendLine.new(mainLine = uMain, extensionLine = uExtension,
priceLabel = uLabel))
// @function Draws a downtrend to chart.
// @param start (chart.point) Starting point of trend line.
// @param end (chart.point) Ending point of trend line.
// @returns (void)
f_drawDowntrend(chart.point start, chart.point end) =>
uExtension = tlExtendMode == "n" ? na : line.new(start, end, color =
color.new(stlLowColor, 50), extend = tlExtendMode, style = line.style_dashed, width
= lineWidth)
uMain = line.new(start, end, color = stlLowColor, style =
line.style_arrow_both, width = lineWidth)
uPrice = line.get_price(uMain, bar_index)
uLabel = tlShowLabels ? label.new(x = bar_index, y = uPrice, text =
"Downtrend : " + str.tostring(uPrice, format.mintick), style =
label.style_label_left, color = color.new(stlLowColor, 80), textcolor =
stlLowColor) : na
downtrends.push(trendLine.new(mainLine = uMain, extensionLine = uExtension,
priceLabel = uLabel))
// @function Clears all lines, boxes, labels off the chart and empties all trend
line, support and resistance arrays.
// @returns (void)
f_clearAll() =>
for [i, v] in line.all
line.delete(v)
for [i, v] in box.all
box.delete(v)
for [i, v] in label.all
label.delete(v)
supports.clear()
resistances.clear()
uptrends.clear()
downtrends.clear()
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * C A L C U L A T I O N S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
ph = ta.pivothigh(pvtLength, pvtLength)
pl = ta.pivotlow(pvtLength, pvtLength)
if not na(ph)
highPivots.unshift(chart.point.from_index(bar_index[pvtLength], ph))
if not na(pl)
lowPivots.unshift(chart.point.from_index(bar_index[pvtLength], pl))
//
╔══════════════════════════════════════════════════════════════════════════════════
═══════════╗
// ║ * * * P L O T S * * *
║
//
╚══════════════════════════════════════════════════════════════════════════════════
═══════════╝
if barstate.islast
f_clearAll()
if tlEnabled
for [i, v] in f_getAllPairCombinations(lowPivots.slice(0,
tlPointsToCheck).reversed())
if f_isLower(v.firstPoint, v.secondPoint)
f_drawUptrend(v.firstPoint, v.secondPoint)
for [i, v] in uptrends
if v.getLowsBelowPrice(exceptBars = tlExceptBars) > tlMaxViolation
v.setViolated(trendColor = stlHighColor)
for [i, v] in uptrends
trendPrice = line.get_price(v.mainLine, bar_index)
if not v.isViolated and low <= trendPrice and tlAlertsEnabled
alert(str.format("Uptrend at {0} broken with a new low price at {1}
now.", str.tostring(trendPrice, format.mintick), str.tostring(low,
format.mintick)), tlAlertrequencyMode)
for [i, v] in f_getAllPairCombinations(highPivots.slice(0,
tlPointsToCheck).reversed())
if f_isHigher(v.firstPoint, v.secondPoint)
f_drawDowntrend(v.firstPoint, v.secondPoint)
for [i, v] in downtrends
if v.getHighsAbovePrice(exceptBars = tlExceptBars) > tlMaxViolation
v.setViolated(trendColor = stlLowColor)
for [i, v] in downtrends
trendPrice = line.get_price(v.mainLine, bar_index)
if not v.isViolated and high >= trendPrice and tlAlertsEnabled
alert(str.format("Downtrend at {0} broken with a new high price at
{1} now.", str.tostring(trendPrice, format.mintick), str.tostring(high,
format.mintick)), tlAlertrequencyMode)
if srEnabled
sCount = 0, lIndex = 0
rCount = 0, hIndex = 0
while sCount < srPointsToCheck
if f_isLower(lowPivots.get(lIndex), lowPivots.get(lIndex + 1))
if f_checkSupportViolation(lowPivots.get(lIndex), exceptBars =
srExceptBars) <= srMaxViolation
f_drawSupport(lowPivots.get(lIndex).index)
sCount += 1
lIndex += 1
while rCount < srPointsToCheck
if f_isHigher(highPivots.get(hIndex), highPivots.get(hIndex + 1))
if f_checkResistanceViolation(highPivots.get(hIndex), exceptBars =
srExceptBars) <= srMaxViolation
f_drawResistance(highPivots.get(hIndex).index)
rCount += 1
hIndex += 1
for [i, v] in supports
if low <= v.price and srAlertsEnabled
alert(str.format("Support at {0} broken by new low price at {1}
now.", str.tostring(v.price, format.mintick), str.tostring(low, format.mintick)),
srAlertrequencyMode)
for [i, v] in resistances
if high >= v.price and srAlertsEnabled
alert(str.format("Resistance at {0} broken by new high price at {1}
now.", str.tostring(v.price, format.mintick), str.tostring(high, format.mintick)),
srAlertrequencyMode)
plotshape(not na(ph) and pvtMarkPivots ? ph : na, title = "High Pivots", style =
shape.triangleup, color = stlHighColor, location = location.abovebar, size =
size.tiny, offset = -pvtLength)
plotshape(not na(pl) and pvtMarkPivots ? pl : na, title = "Low Pivots", style =
shape.triangledown, color = stlLowColor, location = location.belowbar, size =
size.tiny, offset = -pvtLength)
//end of this part
// ____ __ ___ ________ ___________ ___________ __ ____ ___
// / __ )/ / / | / ____/ //_/ ____/ |/_ __< / // / / __ |__ \
// / __ / / / /| |/ / / ,< / / / /| | / / / / // /_/ / / __/ /
// / /_/ / /___/ ___ / /___/ /| / /___/ ___ |/ / / /__ __/ /_/ / __/
// /_____/_____/_/ |_\____/_/ |_\____/_/ |_/_/ /_/ /_/ \____/____/
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © blackcat1402
//@version=5
//indicator(title="[blackcat] L1 Fibonacci MA Band", shorttitle="FMAB",
overlay=true)
// Implementing the slope function
xsl(src, len) =>
out = 0.0
lrc = ta.linreg(src, len, 0)
lrprev = ta.linreg(src[1], len, 0)
out := (lrc - lrprev) / timeframe.multiplier
out
whales = ta.ema(close, 13)
resoline = ta.ema(close, 144)
trendline = ta.ema((xsl(close, 21) * 23 + close), 50)
// plot candles
plotcandle(whales, resoline, whales, resoline, color=(whales > resoline) ?
color.new(color.blue, 0) : na)
plotcandle(whales, resoline, whales, resoline, color=(whales < resoline) ?
color.new(color.green, 0) : na)
// plot lines
plot(whales, color=color.new(#FF7F00, 0), linewidth=2, style=plot.style_linebr)
plot(resoline, color=color.yellow, linewidth=1, style=plot.style_linebr)
plot(trendline, color=color.red, linewidth=3, style=plot.style_linebr)
// Conditional plotting for trendline based on the closing price
plot(close < trendline ? trendline : na, color=color.green, linewidth=3,
style=plot.style_linebr)
//end of this part
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © traderharikrishna
// Idea and Code by @traderharikrishna
//@version=5
//indicator("RSI TREND FILTER",overlay=true)
showrsi=input.bool(false,title='Show RSI Cloud',group='RSI ')
showmidband=input.bool(false,title='Show RSI Mid Band',group='RSI ')
showgrid=input.bool(false,title='Show RSI Levels',group='RSI Levels')
grid=input.color(color.rgb(26, 22, 22, 34),'RSI LEVELS',group='RSI Levels')
rsilen=input.int(14,'RSI LENGTH',group='RSI')
rsima=input.int(100,'RSI 50 level',group='RSI')
emalen=input.int(20,'RSI EMA Length',group='RSI')
orsi=ta.rsi(close,rsilen)
adjrsi=close+ta.atr(100)*orsi/100
rma=ta.ema(adjrsi,rsima)
r1=plot(showrsi?adjrsi:na,display=display.all,title='RSI')
r2=plot(rma,color=open>rma?#00ff08:open<rma?#ff0404:color.white,title='RSI
MA',linewidth=2)
fill(r1,r2,color=adjrsi>rma?color.rgb(76, 175, 79, 70):color.rgb(255, 82, 82,
75),title='RSI Cloud',display=showrsi?display.all:display.none)
level2=input.float(10,'RSI LEVEL2',minval=10,maxval=100,group='RSI Levels')
rmau=rma+ta.atr(100)*level2/10
rmal=rma-ta.atr(100)*level2/10
u=plot(rmau,display=showgrid?display.all:display.none,title='70',color=grid)
l=plot(rmal,display=showgrid?display.all:display.none,title='30',color=grid)
fill(u,l,color=color.rgb(232, 237, 242, 82),title='RSI
ZeroBand',display=showmidband?display.all:display.none)
level3=input.float(40,'RSI LEVEL3',minval=10,maxval=100,group='RSI Levels')
rmau3=rma+ta.atr(100)*level3/10
rmal3=rma-ta.atr(100)*level3/10
o8=plot(rmau3,display=showgrid?display.all:display.none,title='80',color=grid)
o2=plot(rmal3,display=showgrid?display.all:display.none,title='20',color=grid)
level5=input.float(50,'RSI LEVEL5',minval=10,maxval=100,group='RSI Levels')
rmau5=rma+ta.atr(100)*level5/10
rmal5=rma-ta.atr(100)*level5/10
ul=plot(rmau5,color=grid,display=showgrid?display.all:display.none,title='100')
ll=plot(rmal5,color=grid,display=showgrid?display.all:display.none,title='0')
fill(o8,ul,color=color.rgb(232, 4, 205, 45),title='OverBought')
fill(o2,ll,color=color.rgb(9, 198, 15, 53),title='OverSold')
fill(r2,ul,color=color.rgb(76, 175, 79, 85),title='UP TREND')
fill(r2,ll,color=color.rgb(175, 76, 167, 85),title='DOWN TREND')
rsiMA=ta.ema(adjrsi,emalen)
plot(rsiMA,color=color.yellow)
//end of this part
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
at https://mozilla.org/MPL/2.0/
// © TFlab
//@version=5
//indicator("ZigZag Multi [TradingFinder] Trend & Wave Lines - Structures", overlay
= true , max_bars_back = 1000 , max_lines_count = 500 , max_labels_count = 500)
// // Input and Setting
// //Short Term Zig Zag Line
ShShTZ = input.bool(true , 'Show Short term Zig Zag Line', group = 'Short Term Zig
Zag') //Show Short Term Zig Zag
PPShTZ = input.int(3 ,'Pivot Period Short Term Zig Zag Line' , group = 'Short Term
Zig Zag') //Pivot Period Short Term Zig Zag
ShTZLS = input.string(line.style_dashed , 'Short Term Zig Zag Line Style' , options
= [line.style_solid ,line.style_dotted , line.style_dashed], group = 'Short Term
Zig Zag' ) //Short Term Zig Zag Line Style
ShTZLC = input.color(color.rgb(0, 0, 0) , 'Short Term Zig Zag Line Color' , group =
'Short Term Zig Zag') //Short Term Zig Zag Line Color
ShTZLW = input.int(1 ,'Short Term Zig Zag Line Width' , group = 'Short Term Zig
Zag')//Short Term Zig Zag Line Width
//Short Term Label
ShShTL = input.bool(true , 'Show Short Term Label', group = 'Short Term Label')
//Show Short Term Label
ShTLC = input.color(color.rgb(0, 0, 0) , 'Short Term Label Color' , group = 'Short
Term Label')//Short Term Label Color
ShTLS = input.string(size.tiny , 'Short Term Label size' , options = [size.auto,
size.tiny, size.small, size.normal, size.large, size.huge], group = 'Short Term
Label' )//Short Term Label size
//Long Term Zig Zag Line
ShLTZ = input.bool(true , 'Show Long term Zig Zag Line', group = 'Long Term Zig
Zag') //Show Long Term Zig Zag
PPLTZ = input.int(9 ,'Pivot Period Long Term Zig Zag Line' , group = 'Long Term Zig
Zag') //Pivot Period Long Term Zig Zag
LTZLS = input.string(line.style_solid , 'Long Term Zig Zag Line Style' , options =
[line.style_solid ,line.style_dotted , line.style_dashed], group = 'Long Term Zig
Zag' ) //Long Term Zig Zag Line Style
LTZLC = input.color(color.rgb(66, 187, 9) , 'Long Term Zig Zag Line Color' , group
= 'Long Term Zig Zag') //Long Term Zig Zag Line Color
LTZLW = input.int(1 ,'Long Term Zig Zag Line Width' , group = 'Long Term Zig
Zag')//Long Term Zig Zag Line Width
//Long Term Label
LShTL = input.bool(true , 'Show Long Term Label', group = 'Long Term Label') //Show
Long Term Label
LTLC = input.color(color.rgb(42, 116, 8) , 'Long Term Label Color' , group = 'Long
Term Label')//Long Term Label Color
LTLS = input.string(size.small , 'Long Term Label size' , options = [size.auto,
size.tiny, size.small, size.normal, size.large, size.huge], group = 'Long Term
Label' )//Long Term Label size
// Zig Zag Function
ZigZag(OPEN ,HIGH ,LOW ,CLOSE ,BAR_INDEX ,PiPe , SHOW_LINE ,STYLE_LINE ,
COLOR_LINE, WIDTH_LINE ,SHOW_LABEL ,COLOR_LABEL , SIZE_LABEL ) => //{PiPe : Pivot
Period}
Open = OPEN
High = HIGH
Low = LOW
Close = CLOSE
Bar_Index = BAR_INDEX
PP = PiPe
Show_Line = SHOW_LINE
Style_Line = STYLE_LINE
Color_Line = COLOR_LINE
Width_Line = WIDTH_LINE
Show_Label = SHOW_LABEL
Color_Label = COLOR_LABEL
Size_Label = SIZE_LABEL
var ArrayType = array.new_string()
var ArrayValue = array.new_float()
var ArrayIndex = array.new_int()
var line ZZLine = na
var label Label = na
PASS = 0
HighPivot = ta.pivothigh(PP,PP)
LowPivot = ta.pivotlow(PP,PP)
HighValue = ta.valuewhen(HighPivot ,High[PP], 0)
LowValue = ta.valuewhen(LowPivot ,Low[PP], 0)
HighIndex = ta.valuewhen(HighPivot ,Bar_Index[PP], 0)
LowIndex = ta.valuewhen(LowPivot ,Bar_Index[PP], 0)
Correct_HighPivot = 0.0
Correct_LowPivot = 0.0
if HighPivot and LowPivot
if ArrayType.size() == 0
PASS := 1
else if ArrayType.size() >= 1
if ((ArrayType.get(ArrayType.size() - 1)) == "L" or
(ArrayType.get(ArrayType.size() - 1)) == "LL")
if LowPivot < ArrayValue.get(ArrayType.size() - 1)
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H" ) ///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if (ArrayType.get(ArrayType.size() - 1)) == "H" or
(ArrayType.get(ArrayType.size() - 1)) == "HH"
if HighPivot > ArrayValue.get(ArrayType.size() - 1)
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H")///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else if (ArrayType.get(ArrayType.size() - 1)) == "LH"
if HighPivot < ArrayValue.get(ArrayType.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else if HighPivot > ArrayValue.get(ArrayType.size() - 1)
if close < ArrayValue.get(ArrayType.size() - 1)
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H")///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if close > ArrayValue.get(ArrayType.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else if (ArrayType.get(ArrayType.size() - 1)) == "HL"
if LowPivot > ArrayValue.get(ArrayType.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H" ) ///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if LowPivot < ArrayValue.get(ArrayType.size() - 1)
if close > ArrayValue.get(ArrayType.size() - 1)
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else if close < ArrayValue.get(ArrayType.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H")///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if HighPivot
if ArrayType.size() == 0
array.insert(ArrayType, 0, "H")
array.insert(ArrayValue, 0, HighValue)
array.insert(ArrayIndex, 0, HighIndex)
Correct_HighPivot := HighValue
else if ArrayType.size() >= 1
if ((ArrayType.get(ArrayType.size() - 1)) == "L" or
(ArrayType.get(ArrayType.size() - 1)) == "HL" or
(ArrayType.get(ArrayType.size() - 1)) == "LL")
if HighPivot > ArrayValue.get(ArrayType.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H" ) ///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if HighPivot < ArrayValue.get(ArrayType.size() - 1)
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else if (ArrayType.get(ArrayType.size() - 1)) == "H" or
(ArrayType.get(ArrayType.size() - 1)) == "HH" or
(ArrayType.get(ArrayType.size() - 1)) == "LH"
if (ArrayValue.get(ArrayValue.size() - 1)) < HighValue
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H")///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if LowPivot
if ArrayType.size() == 0
array.insert(ArrayType, 0, "L")
array.insert(ArrayValue, 0, LowValue)
array.insert(ArrayIndex, 0, LowIndex)
Correct_LowPivot := LowValue
else if ArrayType.size() >= 1
if (ArrayType.get(ArrayType.size() - 1)) == "H" or
(ArrayType.get(ArrayType.size() - 1)) == "HH" or
(ArrayType.get(ArrayType.size() - 1)) == "LH"
if LowPivot < ArrayValue.get(ArrayType.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
else if LowPivot > ArrayValue.get(ArrayType.size() - 1)
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < HighValue ? "HH" : "LH" :
"H")///////////////////////////////Here
array.push(ArrayValue, HighValue)
array.push(ArrayIndex, HighIndex)
Correct_HighPivot := HighValue
else if (ArrayType.get(ArrayType.size() - 1)) == "L" or
(ArrayType.get(ArrayType.size() - 1)) == "HL" or
(ArrayType.get(ArrayType.size() - 1)) == "LL"
if (ArrayValue.get(ArrayValue.size() - 1)) > LowValue
array.remove(ArrayType,ArrayType.size() - 1)
array.remove(ArrayValue,ArrayValue.size() - 1)
array.remove(ArrayIndex,ArrayIndex.size() - 1)
array.push(ArrayType,ArrayType.size()>2?
ArrayValue.get(ArrayType.size() - 2) < LowValue ? "HL" : "LL" :
"L")///////////////////////////////Here
array.push(ArrayValue, LowValue)
array.push(ArrayIndex, LowIndex)
Correct_LowPivot := LowValue
if ArrayType.size() > 2
X1 = ArrayIndex.get(ArrayIndex.size()-2)
Y1 = ArrayValue.get(ArrayIndex.size()-2)
X2 = ArrayIndex.get(ArrayIndex.size()-1)
Y2 = ArrayValue.get(ArrayIndex.size()-1)
T1 = ArrayType.get(ArrayIndex.size()-1)
if Show_Line
ZZLine := line.new( X1 , Y1 , X2 , Y2 ,color = Color_Line, style =
Style_Line , width = Width_Line )
if Show_Label
Label := label.new(x = X2 , y = Y2 , text = T1, color = color.rgb(255,
255, 255, 100) ,
style = T1 == "LL" or T1 == "HL" ? label.style_label_up :
label.style_label_down ,textcolor = Color_Label , size = Size_Label)
if line.get_x1(ZZLine) == line.get_x1(ZZLine[1])
label.delete(Label[1])
line.delete(ZZLine[1])
//Call Function
ZigZag(open ,high ,low ,close ,bar_index ,PPShTZ , ShShTZ ,ShTZLS , ShTZLC,
ShTZLW ,ShShTL ,ShTLC , ShTLS )
ZigZag(open ,high ,low ,close ,bar_index ,PPLTZ , ShLTZ ,LTZLS , LTZLC,
LTZLW ,LShTL ,LTLC ,LTLS )