Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //@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 Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
- // © fluxchart
- //@version=5
- const bool DEBUG = false
- const int maxBoxesCount = 500
- const float overlapThresholdPercentage = 0
- const int maxDistanceToLastBar = 1250 // Affects Running Time
- const int maxOrderBlocks = 5
- //indicator(title = 'Order Blocks | Flux Charts',shorttitle = 'Orderblocks | Flux Charts', overlay = true, max_boxes_count = maxBoxesCount, max_labels_count = maxBoxesCount, max_lines_count = maxBoxesCount, max_bars_back = 5000)
- showInvalidated = input.bool(true, "Show Historic Zones", group = "General Configuration", display = display.none)
- OBsEnabled = true
- orderBlockVolumetricInfo = input.bool(true, "Volumetric Info", group = "General Configuration", inline="EV", display = display.none)
- obEndMethod = input.string("Wick", "Zone Invalidation", options = ["Wick", "Close"], group = "General Configuration", display = display.none)
- combineOBs = DEBUG ? input.bool(true, "Combine Zones", group = "General Configuration", display = display.none) : true
- swingLength = input.int(10, 'Swing Length', minval = 3, tooltip="Swing length is used when finding order block formations. Smaller values will result in finding smaller order blocks.",group = "General Configuration", display = display.none)
- bullishOrderBlocks = DEBUG ? input.int(3, 'Bullish Order Blocks', minval = 0, maxval = 3, group = "General Configuration", display = display.none) : 3
- bearishOrderBlocks = DEBUG ? input.int(3, 'Bearish Order Blocks', minval = 0, maxval = 3, group = "General Configuration", display = display.none) : 3
- bullOrderBlockColor = input(#08998180, 'Bullish', inline = 'obColor', group = 'General Configuration', display = display.none)
- bearOrderBlockColor = input(#f2364680, 'Bearish', inline = 'obColor', group = 'General Configuration', display = display.none)
- timeframe1Enabled = true
- timeframe1 = ""
- textColor = DEBUG ? input.color(#ffffff80, "Text Color", group = "Style", inline = "BBcolors") : #ffffff80
- extendZonesBy = DEBUG ? input.int(15, "Extend Zones", group = "Style", minval = 1, maxval = 30, inline = "ExtendZones") : 15
- extendZonesDynamic = DEBUG ? input.bool(true, "Dynamic", group = "Style", inline = "ExtendZones") : true
- combinedText = DEBUG ? input.bool(false, "Combined Text", group = "Style", inline = "CombinedColor") : false
- volumeBarsPlace = DEBUG ? input.string("Left", "Show Volume Bars At", options = ["Left", "Right"], group = "Style", inline = "volumebars") : "Left"
- mirrorVolumeBars = DEBUG ? input.bool(true, "Mirror Volume Bars", group = "Style", inline = "volumebars") : true
- volumeBarsLeftSide = (volumeBarsPlace == "Left")
- extendZonesByTime = extendZonesBy * timeframe.in_seconds(timeframe.period) * 1000
- type orderBlockInfo
- float top
- float bottom
- float obVolume
- string obType
- int startTime
- float bbVolume
- float obLowVolume
- float obHighVolume
- bool breaker
- int breakTime
- string timeframeStr
- bool disabled = false
- string combinedTimeframesStr = na
- bool combined = false
- type orderBlock
- orderBlockInfo info
- bool isRendered = false
- box orderBox = na
- box breakerBox = na
- line orderBoxLineTop = na
- line orderBoxLineBottom = na
- line breakerBoxLineTop = na
- line breakerBoxLineBottom = na
- //
- box orderBoxText = na
- box orderBoxPositive = na
- box orderBoxNegative = na
- line orderSeperator = na
- line orderTextSeperator = na
- createOrderBlock (orderBlockInfo orderBlockInfoF) =>
- orderBlock newOrderBlock = orderBlock.new(orderBlockInfoF)
- newOrderBlock
- safeDeleteOrderBlock (orderBlock orderBlockF) =>
- orderBlockF.isRendered := false
- box.delete(orderBlockF.orderBox)
- box.delete(orderBlockF.breakerBox)
- box.delete(orderBlockF.orderBoxText)
- box.delete(orderBlockF.orderBoxPositive)
- box.delete(orderBlockF.orderBoxNegative)
- line.delete(orderBlockF.orderBoxLineTop)
- line.delete(orderBlockF.orderBoxLineBottom)
- line.delete(orderBlockF.breakerBoxLineTop)
- line.delete(orderBlockF.breakerBoxLineBottom)
- line.delete(orderBlockF.orderSeperator)
- line.delete(orderBlockF.orderTextSeperator)
- type timeframeInfo
- int index = na
- string timeframeStr = na
- bool isEnabled = false
- orderBlockInfo[] bullishOrderBlocksList = na
- orderBlockInfo[] bearishOrderBlocksList = na
- newTimeframeInfo (index, timeframeStr, isEnabled) =>
- newTFInfo = timeframeInfo.new()
- newTFInfo.index := index
- newTFInfo.isEnabled := isEnabled
- newTFInfo.timeframeStr := timeframeStr
- newTFInfo
- type obSwing
- int x = na
- float y = na
- float swingVolume = na
- bool crossed = false
- // ____ TYPES END ____
- var timeframeInfo[] timeframeInfos = array.from(newTimeframeInfo(1, timeframe1, timeframe1Enabled))
- var bullishOrderBlocksList = array.new<orderBlockInfo>(0)
- var bearishOrderBlocksList = array.new<orderBlockInfo>(0)
- var allOrderBlocksList = array.new<orderBlock>(0)
- moveLine(_line, _x, _y, _x2) =>
- line.set_xy1(_line, _x, _y)
- line.set_xy2(_line, _x2, _y)
- moveBox (_box, _topLeftX, _topLeftY, _bottomRightX, _bottomRightY) =>
- box.set_lefttop(_box, _topLeftX, _topLeftY)
- box.set_rightbottom(_box, _bottomRightX, _bottomRightY)
- isTimeframeLower (timeframe1F, timeframe2F) =>
- timeframe.in_seconds(timeframe1F) < timeframe.in_seconds(timeframe2F)
- getMinTimeframe (timeframe1F, timeframe2F) =>
- if isTimeframeLower(timeframe1F, timeframe2F)
- timeframe1F
- else
- timeframe2F
- getMaxTimeframe (timeframe1F, timeframe2F) =>
- if isTimeframeLower(timeframe1F, timeframe2F)
- timeframe2F
- else
- timeframe1F
- formatTimeframeString (formatTimeframe) =>
- timeframeF = formatTimeframe == "" ? timeframe.period : formatTimeframe
- if str.contains(timeframeF, "D") or str.contains(timeframeF, "W") or str.contains(timeframeF, "S") or str.contains(timeframeF, "M")
- timeframeF
- else
- seconds = timeframe.in_seconds(timeframeF)
- if seconds >= 3600
- hourCount = int(seconds / 3600)
- str.tostring(hourCount) + " Hour" + (hourCount > 1 ? "s" : "")
- else
- timeframeF + " Min"
- betterCross(s1, s2) =>
- string ret = na
- if s1 >= s2 and s1[1] < s2
- ret := "Bull"
- if s1 < s2 and s1[1] >= s2
- ret := "Bear"
- ret
- colorWithTransparency (colorF, transparencyX) =>
- color.new(colorF, color.t(colorF) * transparencyX)
- createOBBox (boxColor, transparencyX = 1.0, xlocType = xloc.bar_time) =>
- box.new(na, na, na, na, text_size = size.normal, xloc = xlocType, extend = extend.none, bgcolor = colorWithTransparency(boxColor, transparencyX), text_color = textColor, text_halign = text.align_center, border_color = #00000000)
- renderOrderBlock (orderBlock ob) =>
- orderBlockInfo info = ob.info
- ob.isRendered := true
- orderColor = ob.info.obType == "Bull" ? bullOrderBlockColor : bearOrderBlockColor
- if OBsEnabled and (not false or not (false and info.breaker)) and not (not showInvalidated and info.breaker)
- ob.orderBox := createOBBox(orderColor, 1.5)
- if ob.info.combined
- ob.orderBox.set_bgcolor(colorWithTransparency(orderColor, 1.1))
- ob.orderBoxText := createOBBox(color.new(color.white, 100))
- if orderBlockVolumetricInfo
- ob.orderBoxPositive := createOBBox(bullOrderBlockColor)
- ob.orderBoxNegative := createOBBox(bearOrderBlockColor)
- ob.orderSeperator := line.new(na,na,na,na,xloc.bar_time,extend.none,textColor,line.style_dashed,1)
- ob.orderTextSeperator := line.new(na,na,na,na,xloc.bar_time,extend.none,textColor,line.style_solid,1)
- zoneSize = extendZonesDynamic ? na(info.breakTime) ? extendZonesByTime : (info.breakTime - info.startTime) : extendZonesByTime
- if na(info.breakTime)
- zoneSize := time - info.startTime
- startX = volumeBarsLeftSide ? info.startTime : info.startTime + zoneSize - zoneSize / 3
- maxEndX = volumeBarsLeftSide ? info.startTime + zoneSize / 3 : info.startTime + zoneSize
- moveBox(ob.orderBox, info.startTime, info.top, info.startTime + zoneSize, info.bottom)
- moveBox(ob.orderBoxText, volumeBarsLeftSide ? maxEndX : info.startTime, info.top, volumeBarsLeftSide ? info.startTime + zoneSize : startX, info.bottom)
- percentage = int((math.min(info.obHighVolume, info.obLowVolume) / math.max(info.obHighVolume, info.obLowVolume)) * 100.0)
- OBText = (na(ob.info.combinedTimeframesStr) ? formatTimeframeString(ob.info.timeframeStr) : ob.info.combinedTimeframesStr) + " OB"
- box.set_text(ob.orderBoxText, (orderBlockVolumetricInfo ? str.tostring(ob.info.obVolume, format.volume) + " (" + str.tostring(percentage) + "%)\n" : "") + (combinedText and ob.info.combined ? "[Combined]\n" : "") + OBText)
- if orderBlockVolumetricInfo
- showHighLowBoxText = false
- curEndXHigh = int(math.ceil((info.obHighVolume / info.obVolume) * (maxEndX - startX) + startX))
- curEndXLow = int(math.ceil((info.obLowVolume / info.obVolume) * (maxEndX - startX) + startX))
- moveBox(ob.orderBoxPositive, mirrorVolumeBars ? startX : curEndXLow, info.top, mirrorVolumeBars ? curEndXHigh : maxEndX, (info.bottom + info.top) / 2)
- box.set_text(ob.orderBoxPositive, showHighLowBoxText ? str.tostring(info.obHighVolume, format.volume) : "")
- moveBox(ob.orderBoxNegative, mirrorVolumeBars ? startX : curEndXHigh, info.bottom, mirrorVolumeBars ? curEndXLow : maxEndX, (info.bottom + info.top) / 2)
- box.set_text(ob.orderBoxNegative, showHighLowBoxText ? str.tostring(info.obLowVolume, format.volume) : "")
- moveLine(ob.orderSeperator, volumeBarsLeftSide ? startX : maxEndX, (info.bottom + info.top) / 2, volumeBarsLeftSide ? maxEndX : startX)
- line.set_xy1(ob.orderTextSeperator, volumeBarsLeftSide ? maxEndX : startX, info.top)
- line.set_xy2(ob.orderTextSeperator, volumeBarsLeftSide ? maxEndX : startX, info.bottom)
- findOBSwings(len) =>
- var swingType = 0
- var obSwing top = obSwing.new(na, na)
- var obSwing bottom = obSwing.new(na, na)
- upper = ta.highest(len)
- lower = ta.lowest(len)
- swingType := high[len] > upper ? 0 : low[len] < lower ? 1 : swingType
- if swingType == 0 and swingType[1] != 0
- top := obSwing.new(bar_index[len], high[len], volume[len])
- if swingType == 1 and swingType[1] != 1
- bottom := obSwing.new(bar_index[len], low[len], volume[len])
- [top, bottom]
- findOrderBlocks () =>
- if bar_index > last_bar_index - maxDistanceToLastBar
- [top, btm] = findOBSwings(swingLength)
- useBody = false
- max = useBody ? math.max(close, open) : high
- min = useBody ? math.min(close, open) : low
- // Bullish Order Block
- bullishBreaked = 0
- if bullishOrderBlocksList.size() > 0
- for i = bullishOrderBlocksList.size() - 1 to 0
- currentOB = bullishOrderBlocksList.get(i)
- if not currentOB.breaker
- if (obEndMethod == "Wick" ? low : math.min(open, close)) < currentOB.bottom
- currentOB.breaker := true
- currentOB.breakTime := time
- currentOB.bbVolume := volume
- else
- if high > currentOB.top
- bullishOrderBlocksList.remove(i)
- else if i < bullishOrderBlocks and top.y < currentOB.top and top.y > currentOB.bottom
- bullishBreaked := 1
- if close > top.y and not top.crossed
- top.crossed := true
- boxBtm = max[1]
- boxTop = min[1]
- boxLoc = time[1]
- for i = 1 to (bar_index - top.x) - 1
- boxBtm := math.min(min[i], boxBtm)
- boxTop := boxBtm == min[i] ? max[i] : boxTop
- boxLoc := boxBtm == min[i] ? time[i] : boxLoc
- newOrderBlockInfo = orderBlockInfo.new(boxTop, boxBtm, volume + volume[1] + volume[2], "Bull", boxLoc)
- newOrderBlockInfo.obLowVolume := volume[2]
- newOrderBlockInfo.obHighVolume := volume + volume[1]
- bullishOrderBlocksList.unshift(newOrderBlockInfo)
- if bullishOrderBlocksList.size() > maxOrderBlocks
- bullishOrderBlocksList.pop()
- // Bearish Order Block
- bearishBreaked = 0
- if bearishOrderBlocksList.size() > 0
- for i = bearishOrderBlocksList.size() - 1 to 0
- currentOB = bearishOrderBlocksList.get(i)
- if not currentOB.breaker
- if (obEndMethod == "Wick" ? high : math.max(open, close)) > currentOB.top
- currentOB.breaker := true
- currentOB.breakTime := time
- currentOB.bbVolume := volume
- else
- if low < currentOB.bottom
- bearishOrderBlocksList.remove(i)
- else if i < bearishOrderBlocks and btm.y > currentOB.bottom and btm.y < currentOB.top
- bearishBreaked := 1
- if close < btm.y and not btm.crossed
- btm.crossed := true
- boxBtm = min[1]
- boxTop = max[1]
- boxLoc = time[1]
- for i = 1 to (bar_index - btm.x) - 1
- boxTop := math.max(max[i], boxTop)
- boxBtm := boxTop == max[i] ? min[i] : boxBtm
- boxLoc := boxTop == max[i] ? time[i] : boxLoc
- newOrderBlockInfo = orderBlockInfo.new(boxTop, boxBtm, volume + volume[1] + volume[2], "Bear", boxLoc)
- newOrderBlockInfo.obLowVolume := volume + volume[1]
- newOrderBlockInfo.obHighVolume := volume[2]
- bearishOrderBlocksList.unshift(newOrderBlockInfo)
- if bearishOrderBlocksList.size() > maxOrderBlocks
- bearishOrderBlocksList.pop()
- true
- areaOfOB (orderBlockInfo OBInfoF) =>
- float XA1 = OBInfoF.startTime
- float XA2 = na(OBInfoF.breakTime) ? time + 1 : OBInfoF.breakTime
- float YA1 = OBInfoF.top
- float YA2 = OBInfoF.bottom
- float edge1 = math.sqrt((XA2 - XA1) * (XA2 - XA1) + (YA2 - YA2) * (YA2 - YA2))
- float edge2 = math.sqrt((XA2 - XA2) * (XA2 - XA2) + (YA2 - YA1) * (YA2 - YA1))
- float totalArea = edge1 * edge2
- totalArea
- doOBsTouch (orderBlockInfo OBInfo1, orderBlockInfo OBInfo2) =>
- float XA1 = OBInfo1.startTime
- float XA2 = na(OBInfo1.breakTime) ? time + 1 : OBInfo1.breakTime
- float YA1 = OBInfo1.top
- float YA2 = OBInfo1.bottom
- float XB1 = OBInfo2.startTime
- float XB2 = na(OBInfo2.breakTime) ? time + 1 : OBInfo2.breakTime
- float YB1 = OBInfo2.top
- float YB2 = OBInfo2.bottom
- float intersectionArea = math.max(0, math.min(XA2, XB2) - math.max(XA1, XB1)) * math.max(0, math.min(YA1, YB1) - math.max(YA2, YB2))
- float unionArea = areaOfOB(OBInfo1) + areaOfOB(OBInfo2) - intersectionArea
- float overlapPercentage = (intersectionArea / unionArea) * 100.0
- if overlapPercentage > overlapThresholdPercentage
- true
- else
- false
- isOBValid (orderBlockInfo OBInfo) =>
- valid = true
- if OBInfo.disabled
- valid := false
- valid
- combineOBsFunc () =>
- if allOrderBlocksList.size() > 0
- lastCombinations = 999
- while lastCombinations > 0
- lastCombinations := 0
- for i = 0 to allOrderBlocksList.size() - 1
- curOB1 = allOrderBlocksList.get(i)
- for j = 0 to allOrderBlocksList.size() - 1
- curOB2 = allOrderBlocksList.get(j)
- if i == j
- continue
- if not isOBValid(curOB1.info) or not isOBValid(curOB2.info)
- continue
- if curOB1.info.obType != curOB2.info.obType
- continue
- if doOBsTouch(curOB1.info, curOB2.info)
- curOB1.info.disabled := true
- curOB2.info.disabled := true
- orderBlock newOB = createOrderBlock(orderBlockInfo.new(math.max(curOB1.info.top, curOB2.info.top), math.min(curOB1.info.bottom, curOB2.info.bottom), curOB1.info.obVolume + curOB2.info.obVolume, curOB1.info.obType))
- newOB.info.startTime := math.min(curOB1.info.startTime, curOB2.info.startTime)
- newOB.info.breakTime := math.max(nz(curOB1.info.breakTime), nz(curOB2.info.breakTime))
- newOB.info.breakTime := newOB.info.breakTime == 0 ? na : newOB.info.breakTime
- newOB.info.timeframeStr := curOB1.info.timeframeStr
- newOB.info.obVolume := curOB1.info.obVolume + curOB2.info.obVolume
- newOB.info.obLowVolume := curOB1.info.obLowVolume + curOB2.info.obLowVolume
- newOB.info.obHighVolume := curOB1.info.obHighVolume + curOB2.info.obHighVolume
- newOB.info.bbVolume := nz(curOB1.info.bbVolume, 0) + nz(curOB2.info.bbVolume, 0)
- newOB.info.breaker := curOB1.info.breaker or curOB2.info.breaker
- newOB.info.combined := true
- if timeframe.in_seconds(curOB1.info.timeframeStr) != timeframe.in_seconds(curOB2.info.timeframeStr)
- newOB.info.combinedTimeframesStr := (na(curOB1.info.combinedTimeframesStr) ? formatTimeframeString(curOB1.info.timeframeStr) : curOB1.info.combinedTimeframesStr) + " & " + (na(curOB2.info.combinedTimeframesStr) ? formatTimeframeString(curOB2.info.timeframeStr) : curOB2.info.combinedTimeframesStr)
- allOrderBlocksList.unshift(newOB)
- lastCombinations += 1
- reqSeq (timeframeStr) =>
- [bullishOrderBlocksListF, bearishOrderBlocksListF] = request.security(syminfo.tickerid, timeframeStr, [bullishOrderBlocksList, bearishOrderBlocksList])
- [bullishOrderBlocksListF, bearishOrderBlocksListF]
- getTFData (timeframeInfo timeframeInfoF, timeframeStr) =>
- if not isTimeframeLower(timeframeInfoF.timeframeStr, timeframe.period) and timeframeInfoF.isEnabled
- [bullishOrderBlocksListF, bearishOrderBlocksListF] = reqSeq(timeframeStr)
- [bullishOrderBlocksListF, bearishOrderBlocksListF]
- else
- [na, na]
- handleTimeframeInfo (timeframeInfo timeframeInfoF, bullishOrderBlocksListF, bearishOrderBlocksListF) =>
- if not isTimeframeLower(timeframeInfoF.timeframeStr, timeframe.period) and timeframeInfoF.isEnabled
- timeframeInfoF.bullishOrderBlocksList := bullishOrderBlocksListF
- timeframeInfoF.bearishOrderBlocksList := bearishOrderBlocksListF
- handleOrderBlocksFinal () =>
- if DEBUG
- log.info("Bullish OB Count " + str.tostring(bullishOrderBlocksList.size()))
- log.info("Bearish OB Count " + str.tostring(bearishOrderBlocksList.size()))
- if allOrderBlocksList.size () > 0
- for i = 0 to allOrderBlocksList.size() - 1
- safeDeleteOrderBlock(allOrderBlocksList.get(i))
- allOrderBlocksList.clear()
- for i = 0 to timeframeInfos.size() - 1
- curTimeframe = timeframeInfos.get(i)
- if not curTimeframe.isEnabled
- continue
- if curTimeframe.bullishOrderBlocksList.size() > 0
- for j = 0 to math.min(curTimeframe.bullishOrderBlocksList.size() - 1, bullishOrderBlocks - 1)
- orderBlockInfoF = curTimeframe.bullishOrderBlocksList.get(j)
- orderBlockInfoF.timeframeStr := curTimeframe.timeframeStr
- allOrderBlocksList.unshift(createOrderBlock(orderBlockInfoF))
- if curTimeframe.bearishOrderBlocksList.size() > 0
- for j = 0 to math.min(curTimeframe.bearishOrderBlocksList.size() - 1, bearishOrderBlocks - 1)
- orderBlockInfoF = curTimeframe.bearishOrderBlocksList.get(j)
- orderBlockInfoF.timeframeStr := curTimeframe.timeframeStr
- allOrderBlocksList.unshift(createOrderBlock(orderBlockInfoF))
- if combineOBs
- combineOBsFunc()
- if allOrderBlocksList.size() > 0
- for i = 0 to allOrderBlocksList.size() - 1
- curOB = allOrderBlocksList.get(i)
- if isOBValid(curOB.info)
- renderOrderBlock(curOB)
- findOrderBlocks()
- [bullishOrderBlocksListTimeframe1, bearishOrderBlocksListTimeframe1] = getTFData(timeframeInfos.get(0), timeframe1)
- if barstate.islast
- handleTimeframeInfo(timeframeInfos.get(0), bullishOrderBlocksListTimeframe1, bearishOrderBlocksListTimeframe1)
- handleOrderBlocksFinal()
- //end of this part
- //@version=5
- //indicator(title='robotrading autotriangle 2', shorttitle='autotriangle 2', overlay=true, max_bars_back=5000)
- //Settings
- showh = input(true, title='show upper line')
- showl = input(true, title='show lower line')
- showe = input(true, title='show extend')
- bars = input.int(300, minval=100)
- lw = input.int(2, minval=1, maxval=10, title='line width')
- extend = showe ? extend.right : extend.none
- //Upper line
- hfast = ta.highest(high, 50)
- hslow = ta.highest(high, 100)
- hdot = 0.0
- hdot := hfast != hslow and hfast[1] == hslow[1] ? hslow[1] : hdot[1]
- hdot1 = ta.highest(hdot, bars)
- hdot2 = 0.0
- triangle_h_x1 = 0
- for i = bars * 3 to 0 by 1
- triangle_h_x1 := i + 50
- if hdot[i] == hdot1
- break
- hangle = 1000.0
- for i = 0 to triangle_h_x1 by 1
- hangle := 100 * (hdot1 - high) / i
- hangle
- hminangle = ta.lowest(hangle, math.max(1, triangle_h_x1 - 51))
- triangle_h_x2 = 0
- triangle_h_y2 = 0.0
- for i = 0 to triangle_h_x1 by 1
- triangle_h_x2 := i
- triangle_h_y2 := high[i]
- if hangle[i] == hminangle
- break
- if showh
- var line line1 = na
- line.delete(line1)
- line1 := line.new(bar_index - triangle_h_x1, hdot1, bar_index - triangle_h_x2, triangle_h_y2, color=color.orange, width=lw, extend=extend)
- line1
- //Lower line
- lfast = ta.lowest(low, 50)
- lslow = ta.lowest(low, 100)
- ldot = 0.0
- ldot := lfast != lslow and lfast[1] == lslow[1] ? lslow[1] : ldot[1]
- ldot1 = ta.lowest(ldot, bars)
- ldot2 = 0.0
- triangle_l_x1 = 0
- for i = bars * 3 to 0 by 1
- triangle_l_x1 := i + 50
- if ldot[i] == ldot1
- break
- langle = 1000.0
- for i = 0 to triangle_l_x1 by 1
- langle := 100 * (low - ldot1) / i
- langle
- lminangle = ta.lowest(langle, math.max(1, triangle_l_x1 - 51))
- triangle_l_x2 = 0
- triangle_l_y2 = 0.0
- for i = 0 to triangle_l_x1 by 1
- triangle_l_x2 := i
- triangle_l_y2 := low[i]
- if langle[i] == lminangle
- break
- if showl
- var line line2 = na
- line.delete(line2)
- line2 := line.new(bar_index - triangle_l_x1, ldot1, bar_index - triangle_l_x2, triangle_l_y2, color=color.orange, width=lw, extend=extend)
- line2
- //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/
- // © Zeiierman
- //@version=5
- //indicator("Smart Money Concepts Probability (Expo)",overlay=true,max_bars_back=5000,max_labels_count=500,max_lines_count=500)
- // ~~ Tooltips {
- string t1 = "Set the pivot period"
- string t2 = "Set the response period. A low value returns a short-term structure and a high value returns a long-term structure. If you disable this option the pivot length above will be used."
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Inputs {
- prd = input.int(20,minval=1,title="Structure Period",tooltip=t1)
- s1 = input.bool(true,title="Structure Response ", inline="resp")
- resp = input.int(7,minval=1,title="",inline="resp",tooltip=t2)
- bull = input.bool(true,"Bullish Structure ",inline="Bullish"), bull2 = input.color(color.rgb(8, 236, 126),"",inline="Bullish"), bull3 = input.color(color.rgb(8, 236, 126),"",inline="Bullish")
- bear = input.bool(true,"Bearish Structure ",inline="Bearish"), bear2 = input.color(color.rgb(255, 34, 34),"",inline="Bearish"), bear3 = input.color(color.rgb(255, 34, 34),"",inline="Bearish")
- showPD = input.bool(true,"Premium & Discount",inline="pd"), prem = input.color(color.new(color.rgb(255, 34, 34),80),"",inline="pd"), disc = input.color(color.new(color.rgb(8, 236, 126),80),"",inline="pd")
- hlloc = input.string("Right","", options=["Left","Right"],inline="pd")
- var bool [] alert_bool = array.from(
- input.bool(true,title="Ticker ID",group="Any alert() function call"),
- input.bool(true,title="Timeframe",group="Any alert() function call"),
- input.bool(true,title="Probability Percentage",group="Any alert() function call"))
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Variables {
- b = bar_index
- var Up = float(na)
- var Dn = float(na)
- var iUp = int(na)
- var iDn = int(na)
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Matrix & Array {
- var vals = matrix.new<float>(9,4,0.0)
- var string [] txt = array.new<string>(2,"")
- var tbl = matrix.new<table>(1,1,table.new(position.top_right,2,3,
- frame_color =color.new(color.gray,50),frame_width=3,
- border_color =chart.bg_color,border_width=-2))
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Functions {
- //Labels
- CreateLabel(x,y,txt,col,z)=>
- label.new(x,y,txt,textcolor=col,style=z?label.style_label_down:label.style_label_up,color=color(na))
- //Lines
- CreateLine(x1,x2,y,col)=>
- line.new(x1,x2,b,y,color=col)
- //Current
- Current(v)=>
- str = ""
- val1 = float(na)
- val2 = float(na)
- if v>=0
- if v==1
- str := "SMS: "
- val1 := matrix.get(vals,0,1)
- val2 := matrix.get(vals,0,3)
- else if v==2
- str := "BMS: "
- val1 := matrix.get(vals,1,1)
- val2 := matrix.get(vals,1,3)
- else if v>2
- str := "BMS: "
- val1 := matrix.get(vals,2,1)
- val2 := matrix.get(vals,2,3)
- else if v<=0
- if v==-1
- str := "SMS: "
- val1 := matrix.get(vals,3,1)
- val2 := matrix.get(vals,3,3)
- else if v==-2
- str := "BMS: "
- val1 := matrix.get(vals,4,1)
- val2 := matrix.get(vals,4,3)
- else if v<-2
- str := "BMS: "
- val1 := matrix.get(vals,5,1)
- val2 := matrix.get(vals,5,3)
- [str,val1,val2]
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Pivots {
- Up := math.max(Up[1],high)
- Dn := math.min(Dn[1],low)
- pvtHi = ta.pivothigh(high,prd,prd)
- pvtLo = ta.pivotlow(low,prd,prd)
- if pvtHi
- Up := pvtHi
- if pvtLo
- Dn := pvtLo
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Structure {
- var pos = 0
- if Up>Up[1]
- iUp := b
- centerBull = math.round(math.avg(iUp[1],b))
- if pos<=0
- if bull
- CreateLabel(centerBull,Up[1],"CHoCH",bull3,true)
- CreateLine(iUp[1],Up[1],Up[1],bull2)
- pos := 1
- matrix.set(vals,6,0,matrix.get(vals,6,0)+1)
- else if pos==1 and Up>Up[1] and Up[1]==Up[s1?resp:prd]
- if bull
- CreateLabel(centerBull,Up[1],"SMS",bull3,true)
- CreateLine(iUp[1],Up[1],Up[1],bull2)
- pos := 2
- matrix.set(vals,6,1,matrix.get(vals,6,1)+1)
- else if pos>1 and Up>Up[1] and Up[1]==Up[s1?resp:prd]
- if bull
- CreateLabel(centerBull,Up[1],"BMS",bull3,true)
- CreateLine(iUp[1],Up[1],Up[1],bull2)
- pos := pos + 1
- matrix.set(vals,6,2,matrix.get(vals,6,2)+1)
- else if Up<Up[1]
- iUp := b-prd
- if Dn<Dn[1]
- iDn := b
- centerBear = math.round(math.avg(iDn[1],b))
- if pos>=0
- if bear
- CreateLabel(centerBear,Dn[1],"CHoCH",bear3,false)
- CreateLine(iDn[1],Dn[1],Dn[1],bear2)
- pos := -1
- matrix.set(vals,7,0,matrix.get(vals,7,0)+1)
- else if pos==-1 and Dn<Dn[1] and Dn[1]==Dn[s1?resp:prd]
- if bear
- CreateLabel(centerBear,Dn[1],"SMS",bear3,false)
- CreateLine(iDn[1],Dn[1],Dn[1],bear2)
- pos := -2
- matrix.set(vals,7,1,matrix.get(vals,7,1)+1)
- else if pos<-1 and Dn<Dn[1] and Dn[1]==Dn[s1?resp:prd]
- if bear
- CreateLabel(centerBear,Dn[1],"BMS",bear3,false)
- CreateLine(iDn[1],Dn[1],Dn[1],bear2)
- pos := pos - 1
- matrix.set(vals,7,2,matrix.get(vals,7,2)+1)
- else if Dn>Dn[1]
- iDn := b-prd
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Probability Calculation {
- if ta.change(pos)
- //Results
- if pos>0 and pos[1]>0 or pos<0 and pos[1]<0
- if matrix.get(vals,8,0)<matrix.get(vals,8,1)
- matrix.set(vals,8,2,matrix.get(vals,8,2)+1)
- else
- matrix.set(vals,8,3,matrix.get(vals,8,3)+1)
- else
- if matrix.get(vals,8,0)>matrix.get(vals,8,1)
- matrix.set(vals,8,2,matrix.get(vals,8,2)+1)
- else
- matrix.set(vals,8,3,matrix.get(vals,8,3)+1)
- //Score Calulation
- //Variables
- buC0 = matrix.get(vals,0,0)
- buC1 = matrix.get(vals,0,2)
- buS0 = matrix.get(vals,1,0)
- buS1 = matrix.get(vals,1,2)
- buB0 = matrix.get(vals,2,0)
- buB1 = matrix.get(vals,2,2)
- beC0 = matrix.get(vals,3,0)
- beC1 = matrix.get(vals,3,2)
- beS0 = matrix.get(vals,4,0)
- beS1 = matrix.get(vals,4,2)
- beB0 = matrix.get(vals,5,0)
- beB1 = matrix.get(vals,5,2)
- tbuC = matrix.get(vals,6,0)
- tbuS = matrix.get(vals,6,1)
- tbuB = matrix.get(vals,6,2)
- tbeC = matrix.get(vals,7,0)
- tbeS = matrix.get(vals,7,1)
- tbeB = matrix.get(vals,7,2)
- //Bull
- if (pos[1]==1 or pos[1]==0) and pos<0
- matrix.set(vals,0,0,buC0+1)
- matrix.set(vals,0,1,math.round(((buC0+1)/tbuC)*100,2))
- if (pos[1]==1 or pos[1]==0) and pos==2
- matrix.set(vals,0,2,buC1+1)
- matrix.set(vals,0,3,math.round(((buC1+1)/tbuC)*100,2))
- if pos[1]==2 and pos<0
- matrix.set(vals,1,0,buS0+1)
- matrix.set(vals,1,1,math.round(((buS0+1)/tbuS)*100,2))
- if pos[1]==2 and pos>2
- matrix.set(vals,1,2,buS1+1)
- matrix.set(vals,1,3,math.round(((buS1+1)/tbuS)*100,2))
- if pos[1]>2 and pos<0
- matrix.set(vals,2,0,buB0+1)
- matrix.set(vals,2,1,math.round(((buB0+1)/tbuB)*100,2))
- if pos[1]>2 and pos>pos[1]
- matrix.set(vals,2,2,buB1+1)
- matrix.set(vals,2,3,math.round(((buB1+1)/tbuB)*100,2))
- //Bear
- if (pos[1]==-1 or pos[1]==0) and pos>0
- matrix.set(vals,3,0,beC0+1)
- matrix.set(vals,3,1,math.round(((beC0+1)/tbeC)*100,2))
- if (pos[1]==-1 or pos[1]==0) and pos==-2
- matrix.set(vals,3,2,beC1+1)
- matrix.set(vals,3,3,math.round(((beC1+1)/tbeC)*100,2))
- if pos[1]==-2 and pos>0
- matrix.set(vals,4,0,beS0+1)
- matrix.set(vals,4,1,math.round(((beS0+1)/tbeS)*100,2))
- if pos[1]==-2 and pos<-2
- matrix.set(vals,4,2,beS1+1)
- matrix.set(vals,4,3,math.round(((beS1+1)/tbeS)*100,2))
- if pos[1]<-2 and pos>0
- matrix.set(vals,5,0,beB0+1)
- matrix.set(vals,5,1,math.round(((beB0+1)/tbeB)*100,2))
- if pos[1]<-2 and pos<pos[1]
- matrix.set(vals,5,2,beB1+1)
- matrix.set(vals,5,3,math.round(((beB1+1)/tbeB)*100,2))
- [str,val1,val2] = Current(pos)
- array.set(txt,0,"CHoCH: "+str.tostring(val1,format.percent))
- array.set(txt,1,str+str.tostring(val2,format.percent))
- matrix.set(vals,8,0,val1)
- matrix.set(vals,8,1,val2)
- //Alerts
- if array.includes(alert_bool,true)
- st1 = syminfo.ticker
- st2 = timeframe.period
- st3 = str.tostring(array.join(txt,'\n'))
- string [] str_vals = array.from(st1,st2,st3)
- output = array.new_string()
- for x=0 to array.size(alert_bool)-1
- if array.get(alert_bool,x)
- array.push(output,array.get(str_vals,x))
- alert(array.join(output,'\n'),alert.freq_once_per_bar_close)
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Premium & Discount {
- var hi = line.new(na,na,na,na,color=bear2)
- var lo = line.new(na,na,na,na,color=bull2)
- var fill = linefill.new(hi,lo,na)
- var premium = box.new(na,na,na,na,na,bgcolor=prem)
- var discount = box.new(na,na,na,na,na,bgcolor=disc)
- var mid = box.new(na,na,na,na,na,bgcolor=color.new(color.gray,80))
- PremiumTop = Up-(Up-Dn)*.1
- PremiumBot = Up-(Up-Dn)*.25
- DiscountTop = Dn+(Up-Dn)*.25
- DiscountBot = Dn+(Up-Dn)*.1
- MidTop = Up-(Up-Dn)*.45
- MidBot = Dn+(Up-Dn)*.45
- if barstate.islast and showPD
- loc = hlloc=="Left"?math.min(iUp,iDn):math.max(iUp,iDn)
- //High & Low
- line.set_xy1(hi,loc,Up)
- line.set_xy2(hi,b,Up)
- line.set_xy1(lo,loc,Dn)
- line.set_xy2(lo,b,Dn)
- linefill.set_color(fill,color.new(color.gray,90))
- //Premium & Mid & Discount
- box.set_lefttop(premium,loc,PremiumTop)
- box.set_rightbottom(premium,b,PremiumBot)
- box.set_lefttop(discount,loc,DiscountTop)
- box.set_rightbottom(discount,b,DiscountBot)
- box.set_lefttop(mid,loc,MidTop)
- box.set_rightbottom(mid,b,MidBot)
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Probability {
- var prob1 = label.new(na,na,na,color=color(na),textcolor=chart.fg_color,style=label.style_label_left)
- var prob2 = label.new(na,na,na,color=color(na),textcolor=chart.fg_color,style=label.style_label_left)
- if barstate.islast
- str1 = pos<0?array.get(txt,0):array.get(txt,1)
- str2 = pos>0?array.get(txt,0):array.get(txt,1)
- label.set_xy(prob1,b,Up)
- label.set_text(prob1,str1)
- label.set_xy(prob2,b,Dn)
- label.set_text(prob2,str2)
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
- // ~~ Table {
- if barstate.islast
- //Calulate WinRatio
- W = matrix.get(vals,8,2)
- L = matrix.get(vals,8,3)
- WR = math.round(W/(W+L)*100,2)
- string [] tbl_vals = array.from("WIN: "+str.tostring(W),
- "LOSS: "+str.tostring(L),
- "Profitability: "+str.tostring(WR,format.percent))
- color [] tbl_col = array.from(color.green,color.red,chart.fg_color)
- for i=0 to 2
- table.cell(matrix.get(tbl,0,0),0,i,array.get(tbl_vals,i),
- text_halign=text.align_center,bgcolor=chart.bg_color,
- text_color=array.get(tbl_col,i),text_size=size.auto)
- //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
Advertisement
Comments
-
- download all types of premium tradingview indicators codes available on telegram - https://t.me/tradingview_premium_indicator
Add Comment
Please, Sign In to add comment
Advertisement