name
stringlengths
1
64
url
stringlengths
44
135
author
stringlengths
3
30
author_url
stringlengths
34
61
likes_count
int64
0
33.2k
kind
stringclasses
3 values
pine_version
int64
1
5
license
stringclasses
3 values
source
stringlengths
177
279k
Bitcoin as Heikin Ashi Candles with Pivot Points
https://www.tradingview.com/script/9tLxrbew-Bitcoin-as-Heikin-Ashi-Candles-with-Pivot-Points/
weak_hand
https://www.tradingview.com/u/weak_hand/
18
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© weak_hand //@version=5 indicator("Bitcoin as Heikin Ashi Candles with Pivot Points", "BTC HA+PP", false, max_lines_count = 500) string my_symbol = "INDEX:BTCUSD" string my_timefr = timeframe.isdaily ? "W" : timeframe.isweekly ? "M" : timeframe.ismonthly ? "12M" : "D" int x_start = time(my_timefr) int x_stop = time_close(my_timefr) string is_type = input.string(defval = "Traditional", title = "Pivot Type", options=["Traditional", "Fibonacci", "Woodie", "Classic", "DM", "Camarilla"]) bool is_anchor = timeframe.change(my_timefr) [open_ha, high_ha, low_ha, close_ha, pivots_ha] = request.security(ticker.heikinashi(my_symbol), timeframe.period, [open, high, low, close, ta.pivot_point_levels(is_type, is_anchor)]) color my_color = close_ha >= open_ha ? color.teal : color.red plotcandle(open_ha, high_ha, low_ha, close_ha, "Average Pace", my_color, my_color, bordercolor = my_color, display = display.all) type pivot_lines line p line r1 line r2 line r3 line r4 line r5 line s1 line s2 line s3 line s4 line s5 var pivot_lines = array.new<pivot_lines>() int pp_back = input.int(defval = 15, title = "Number of Pivots Back", minval = 1, maxval = 49) if pivot_lines.size() > pp_back old_pivots = pivot_lines.pop() old_pivots.p.delete() old_pivots.r1.delete() old_pivots.r2.delete() old_pivots.r3.delete() old_pivots.r4.delete() old_pivots.r5.delete() old_pivots.s1.delete() old_pivots.s2.delete() old_pivots.s3.delete() old_pivots.s4.delete() old_pivots.s5.delete() //import weak_hand/colors/17 as colors //colors.theme color_auto = colors.find(syminfo.basecurrency) color color_pp = input.color(#f7931a, "Color for Pivots") //if input.bool(false, "Use Color Theme of the Token") //color_pp := color_auto.bg if input.bool(false, "Show Central Pivots Back only") and pivot_lines.size() > 1 for counter = pivot_lines.size() - 1 to 1 pivot_lines old_pivots = pivot_lines.get(counter) old_pivots.r1.delete() old_pivots.r2.delete() old_pivots.r3.delete() old_pivots.r4.delete() old_pivots.r5.delete() old_pivots.s1.delete() old_pivots.s2.delete() old_pivots.s3.delete() old_pivots.s4.delete() old_pivots.s5.delete() if is_anchor new_pivots = pivot_lines.new() new_pivots.p := line.new(x_start, pivots_ha.get(0), x_stop, pivots_ha.get(0), xloc.bar_time, extend.none, color_pp, line.style_solid, 2) new_pivots.r1 := line.new(x_start, pivots_ha.get(1), x_stop, pivots_ha.get(1), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.s1 := line.new(x_start, pivots_ha.get(2), x_stop, pivots_ha.get(2), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.r2 := line.new(x_start, pivots_ha.get(3), x_stop, pivots_ha.get(3), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.s2 := line.new(x_start, pivots_ha.get(4), x_stop, pivots_ha.get(4), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.r3 := line.new(x_start, pivots_ha.get(5), x_stop, pivots_ha.get(5), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.s3 := line.new(x_start, pivots_ha.get(6), x_stop, pivots_ha.get(6), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.r4 := line.new(x_start, pivots_ha.get(7), x_stop, pivots_ha.get(7), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.s4 := line.new(x_start, pivots_ha.get(8), x_stop, pivots_ha.get(8), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.r5 := line.new(x_start, pivots_ha.get(9), x_stop, pivots_ha.get(9), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) new_pivots.s5 := line.new(x_start, pivots_ha.get(10), x_stop, pivots_ha.get(10), xloc.bar_time, extend.none, color_pp, line.style_dotted, 1) pivot_lines.unshift(new_pivots.copy())
HTF Support & Resistance [QuantVue]
https://www.tradingview.com/script/fQSNAk7Z-HTF-Support-Resistance-QuantVue/
QuantVue
https://www.tradingview.com/u/QuantVue/
315
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© QuantVue //@version=5 indicator("HTF Support & Resistance [QuantVue]", overlay = true, shorttitle = 'HTF Support & Resistance [QuantVue]') // inputs var g1 = 'Daily Levels' showDaily = input.bool(true, 'Show Daily Levels', group = g1) dayOpenCol = input.color(color.orange, 'Daily Open Color', inline = '1', group = g1) dayOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '1', group = g1) dayHighCol = input.color(color.red, 'Daily High Color', inline = '2', group = g1) dayHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '2', group = g1) dayLowCol = input.color(color.lime, 'Daily Low Color', inline = '3', group = g1) dayLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '3', group = g1) showPrevDay = input.bool(true, 'Show Previous Days Levels', group = g1) prevDayOpenCol = input.color(color.orange, 'Previous Days Open Color', inline = '4', group = g1) prevDayOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '4', group = g1) prevDayHighCol = input.color(color.red, 'Previous Days High Color', inline = '5', group = g1) prevDayHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '5', group = g1) prevDayLowCol = input.color(color.lime, 'Previous Days Low Color', inline = '6', group = g1) prevDayLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '6', group = g1) var g2 = 'Weekly Levels' showWeekly = input.bool(true, 'Show Weekly Levels', group = g2) weekOpenCol = input.color(color.orange, 'Weekly Open Color', inline = '7', group = g2) weekOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '7', group = g2) weekHighCol = input.color(color.red, 'Weekly High Color', inline = '8', group = g2) weekHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '8', group = g2) weekLowCol = input.color(color.lime, 'Weekly Low Color', inline = '9', group = g2) weekLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '9', group = g2) showPrevWeek = input.bool(true, 'Show Previous Weeks Levels', group = g2) prevWeekOpenCol = input.color(color.orange, 'Previous Weeks Open Color', inline = '10', group = g2) prevWeekOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '10', group = g2) prevWeekHighCol = input.color(color.red, 'Previous Weeks High Color', inline = '11', group = g2) prevWeekHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '11', group = g2) prevWeekLowCol = input.color(color.lime, 'Previous Weeks Low Color', inline = '12', group = g2) prevWeekLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '12', group = g2) var g3 = 'Monthly Levels' showMonthly = input.bool(true, 'Show Monthly Levels', group = g3) monthOpenCol = input.color(color.orange, 'Monthly Open Color', inline = '13', group = g3) monthOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '13', group = g3) monthHighCol = input.color(color.red, 'Monthly High Color', inline = '14', group = g3) monthHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '14', group = g3) monthLowCol = input.color(color.lime, 'Monthly Low Color', inline = '15', group = g3) monthLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '15', group = g3) showPrevMonth = input.bool(false, 'Show Previous Months Levels', group = g3) prevMonthOpenCol = input.color(color.orange, 'Previous Months Open Color', inline = '16', group = g3) prevMonthOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '16', group = g3) prevMonthHighCol = input.color(color.red, 'Previous Months High Color', inline = '17', group = g3) prevMonthHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '17', group = g3) prevMonthLowCol = input.color(color.lime, 'Previous Months Low Color', inline = '18', group = g3) prevMonthLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '18', group = g3) var g4 = 'Quarterly Levels' showQtr = input.bool(false, 'Show Quarterly Levels', group = g4) qtrOpenCol = input.color(color.orange, 'Quarterly Open Color', inline = '19', group = g4) qtrOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '19', group = g4) qtrHighCol = input.color(color.red, 'Quarterly High Color', inline = '20', group = g4) qtrHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '20', group = g4) qtrLowCol = input.color(color.lime, 'Quarterly Low Color', inline = '21', group = g4) qtrLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '21', group = g4) showPrevQtr = input.bool(false, 'Show Previous Quarters Levels', group = g4) prevQtrOpenCol = input.color(color.orange, 'Previous Quarterss Open Color', inline = '22', group = g4) prevQtrOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '22', group = g4) prevQtrHighCol = input.color(color.red, 'Previous Quarterss High Color', inline = '23', group = g4) prevQtrHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '23', group = g4) prevQtrLowCol = input.color(color.lime, 'Previous Quarterss Low Color', inline = '24', group = g4) prevQtrLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '24', group = g4) var g5 = 'Yearly Levels' showYear = input.bool(false, 'Show Yearly Levels', group = g5) yearOpenCol = input.color(color.orange, 'Yearly Open Color', inline = '25', group = g5) yearOpenStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '25', group = g5) yearHighCol = input.color(color.red, 'Yearly High Color', inline = '26', group = g5) yearHighStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '26', group = g5) yearLowCol = input.color(color.lime, 'Yearly Low Color', inline = '27', group = g5) yearLowStyle = input.string('Solid', '', options = ['Solid', 'Dashed', 'Dotted'], inline = '27', group = g5) var g6 = 'Misc Options' extendLines = input.bool(false, 'Extend Lines', group = g6) //methods switches and functions extended = switch extendLines true => extend.right false => extend.none method styler(string this) => switch this 'Solid' => line.style_solid 'Dashed' => line.style_dashed 'Dotted' => line.style_dotted getHTF(htf,x,idx,oCol,oStyle,hCol,hStyle,lCol,lStyle,oStr,hStr,lStr) => [o,h,l] = request.security(syminfo.tickerid, htf, [open[x], high[x], low[x]]) line.new(idx,o,chart.right_visible_bar_time,o,xloc=xloc.bar_time,extend=extended,color=oCol,style=oStyle.styler()) line.new(idx,h,chart.right_visible_bar_time,h,xloc=xloc.bar_time,extend=extended,color=hCol,style=hStyle.styler()) line.new(idx,l,chart.right_visible_bar_time,l,xloc=xloc.bar_time,extend=extended,color=lCol,style=lStyle.styler()) label.new(bar_index+5,o,oStr,style=label.style_none,textcolor=oCol) label.new(bar_index+5,h,hStr,style=label.style_none,textcolor=hCol) label.new(bar_index+5,l,lStr,style=label.style_none,textcolor=lCol) // index variables var dayIndex = 0 var weekIndex = 0 var monthIndex = 0 var qtrIndex = 0 var prevDayIndex = 0 var prevWeekIndex = 0 var prevMonthIndex = 0 var prevQtrIndex = 0 var yearIndex = 0 var prevYearIndex = 0 // new times newDay = ta.change(time('D')) newWeek = ta.change(time('W')) newMonth = ta.change(time('M')) newQtr = ta.change(time('3M')) newYear = ta.change(time('12M')) // set the starting points for lines if newDay prevDayIndex := dayIndex dayIndex := time if newWeek prevWeekIndex := weekIndex weekIndex := time if newMonth prevMonthIndex := monthIndex monthIndex := time if newQtr prevQtrIndex := qtrIndex qtrIndex := time if newYear prevYearIndex := yearIndex yearIndex := time //delete previous lines lines = line.all for li in lines li.delete() labels = label.all for la in labels la.delete() //run the code if showDaily getHTF('D',0,dayIndex,dayOpenCol,dayOpenStyle,dayHighCol,dayHighStyle,dayLowCol,dayLowStyle,'Open','High','Low') if showPrevDay getHTF('D',1,prevDayIndex,prevDayOpenCol,prevDayOpenStyle,prevDayHighCol,prevDayHighStyle,prevDayLowCol,prevDayLowStyle,'PDO','PDH','PDL') if showWeekly getHTF('W',0,weekIndex,weekOpenCol,weekOpenStyle,weekHighCol,weekHighStyle,weekLowCol,weekLowStyle,'Week Open','Week High','Week Low') if showPrevWeek getHTF('W',1,prevWeekIndex,prevWeekOpenCol,prevWeekOpenStyle,prevWeekHighCol,prevWeekHighStyle,prevWeekLowCol,prevWeekLowStyle,'PWO','PWH','PWL') if showMonthly getHTF('M',0,monthIndex,monthOpenCol,monthOpenStyle,monthHighCol,monthHighStyle,monthLowCol,monthLowStyle,'Month Open','Month High','Month Low') if showPrevMonth getHTF('M',1,prevMonthIndex,prevMonthOpenCol,prevMonthOpenStyle,prevMonthHighCol,prevMonthHighStyle,prevMonthLowCol,prevMonthLowStyle,'PMO','PMH','PML') if showQtr getHTF('3M',0,qtrIndex,qtrOpenCol,qtrOpenStyle,qtrHighCol,qtrHighStyle,qtrLowCol,qtrLowStyle,'Quarter Open','Quarter High','Quarter Low') if showPrevQtr getHTF('3M',1,prevQtrIndex,prevQtrOpenCol,prevQtrOpenStyle,prevQtrHighCol,prevQtrHighStyle,prevQtrLowCol,prevQtrLowStyle,'PQO','PQH','PQL') if showYear getHTF('12M',0,yearIndex,yearOpenCol,yearOpenStyle,yearHighCol,yearHighStyle,yearLowCol,yearLowStyle,'Year Open','Year High','Year Low')
Daily Network Value to Transactions Signal (NVTS)
https://www.tradingview.com/script/JSlkwPCA-Daily-Network-Value-to-Transactions-Signal-NVTS/
weak_hand
https://www.tradingview.com/u/weak_hand/
6
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© weak_hand //@version=5 indicator("Daily Network Value to Transactions Signal (NVTS)", "NVTS", false, format.volume) if timeframe.isintraday runtime.error("The timeframe is to low. It has to be at least one day.") // ----------------------------------------------} // EXCLUDED CURRENCIES // ----------------------------------------------{ var CoinMetrics_MARKETCAPFF = array.new<string>() if bar_index == 0 CoinMetrics_MARKETCAPFF.push("ALPHA") CoinMetrics_MARKETCAPFF.push("BNB") CoinMetrics_MARKETCAPFF.push("KNC") CoinMetrics_MARKETCAPFF.push("TXZ") var CoinMetrics_TXVOLUMEUSD = array.new<string>() if bar_index == 0 CoinMetrics_TXVOLUMEUSD.push("ANT") CoinMetrics_TXVOLUMEUSD.push("BNB") CoinMetrics_TXVOLUMEUSD.push("BTC") CoinMetrics_TXVOLUMEUSD.push("DOGE") CoinMetrics_TXVOLUMEUSD.push("DOT") CoinMetrics_TXVOLUMEUSD.push("LTC") CoinMetrics_TXVOLUMEUSD.push("WTC") CoinMetrics_TXVOLUMEUSD.push("XTZ") var GlassNode_TOTALVOLUMEUSD = array.new<string>() if bar_index == 0 GlassNode_TOTALVOLUMEUSD.push("ELF") GlassNode_TOTALVOLUMEUSD.push("ETH") GlassNode_TOTALVOLUMEUSD.push("MATIC") GlassNode_TOTALVOLUMEUSD.push("MKR") GlassNode_TOTALVOLUMEUSD.push("OMG") GlassNode_TOTALVOLUMEUSD.push("WTC") var IntoTheBlock_TXVOLUMEUSD = array.new<string>() if bar_index == 0 IntoTheBlock_TXVOLUMEUSD.push("ADA") IntoTheBlock_TXVOLUMEUSD.push("ANT") IntoTheBlock_TXVOLUMEUSD.push("FUN") IntoTheBlock_TXVOLUMEUSD.push("FXS") IntoTheBlock_TXVOLUMEUSD.push("HOT") IntoTheBlock_TXVOLUMEUSD.push("STX") IntoTheBlock_TXVOLUMEUSD.push("WTC") IntoTheBlock_TXVOLUMEUSD.push("ZEC") // ----------------------------------------------} // PREDEFINED TICKER IDs // ----------------------------------------------{ string my_token = syminfo.basecurrency string symbol_marketcap_cryptocap = ticker.standard(str.format("CRYPTOCAP:{0}", my_token)) string symbol_volumeusd_intotheblock = ticker.standard(str.format("INTOTHEBLOCK:{0}_TXVOLUMEUSD", my_token)) string symbol_marketcap_coinmetrics = ticker.standard(str.format("COINMETRICS:{0}_MARKETCAPFF", my_token)) string symbol_volumeusd_coinmetrics = ticker.standard(str.format("COINMETRICS:{0}_TXVOLUMEUSD", my_token)) string symbol_marketcap_glassnode = ticker.standard(str.format("GLASSNODE:{0}_MARKETCAP" , my_token)) string symbol_volumeusd_glassnode = ticker.standard(str.format("GLASSNODE:{0}_TOTALVOLUMEUSD", my_token)) // ----------------------------------------------} // FETCHING DATA // ----------------------------------------------{ string my_timeframe = timeframe.period float my_source = close float marketcap_cryptocap = request.security(symbol_marketcap_cryptocap, my_timeframe, my_source[1], ignore_invalid_symbol = true) float marketcap_glassnode = request.security(symbol_marketcap_glassnode, my_timeframe, my_source, ignore_invalid_symbol = true) float marketcap_coinmetrics = request.security(symbol_marketcap_coinmetrics, my_timeframe, my_source, ignore_invalid_symbol = true) float volume_intotheblock = request.security(symbol_volumeusd_intotheblock, my_timeframe, my_source, ignore_invalid_symbol = true) float volume_coinmetrics = request.security(symbol_volumeusd_coinmetrics, my_timeframe, my_source, ignore_invalid_symbol = true) float volume_glassnode = request.security(symbol_volumeusd_glassnode, my_timeframe, my_source, ignore_invalid_symbol = true) // ----------------------------------------------} // FILTER // ----------------------------------------------{ float marketcap = na // CryptoCap > GlassNode > CoinMetrics if not na(marketcap_cryptocap) marketcap := marketcap_cryptocap else if not na(marketcap_glassnode) marketcap := marketcap_glassnode else if not na(marketcap_coinmetrics) and not CoinMetrics_MARKETCAPFF.includes(my_token) marketcap := marketcap_coinmetrics else if barstate.islastconfirmedhistory runtime.error(str.format("Market Cap of {0} is not available.", my_token)) float volume_usd = na // IntoTheBlock > CoinMetrics > GlassNode if not na(volume_intotheblock) and not IntoTheBlock_TXVOLUMEUSD.includes(my_token) volume_usd := volume_intotheblock else if not na(volume_coinmetrics) and not CoinMetrics_TXVOLUMEUSD.includes(my_token) volume_usd := volume_coinmetrics else if not na(volume_glassnode) and not GlassNode_TOTALVOLUMEUSD.includes(my_token) volume_usd := volume_glassnode else if barstate.islastconfirmedhistory runtime.error(str.format("Transactions volume of {0} is not available.", my_token)) // ----------------------------------------------} // MOVING AVERAGE // ----------------------------------------------{ string ma_grp = "Daily Moving Average..." int ma_length = input.int(90, "Length", minval = 2, group = ma_grp) string tooltip = " DEMA = Double Moving Average Exponential\n\n EMA = Moving Average Exponential\n\n SMA = Simple Moving Average\n\n TEMA = Tripple Moving Average Exponential " string ma_type = input.string("SMA", "Type", ["DEMA", "EMA", "SMA", "TEMA"], tooltip, group = ma_grp) dema(source, length) => float ema1 = ta.ema(source, length) float ema2 = ta.ema(ema1, length) 2 * ema1 - ema2 tema(source, length) => float ema3 = ta.ema(source, length) float ema4 = ta.ema(ema3, length) float ema5 = ta.ema(ema4, length) 3 * (ema3 - ema4) + ema5 mean(source, length, ma_type) => switch ma_type "DEMA" => dema(source, length) "EMA" => ta.ema(source, length) "TEMA" => tema(source, length) => ta.sma(source, length) // ----------------------------------------------} // CALCULATIONS // ----------------------------------------------{ float volume_ma = mean(volume_usd, ma_length, ma_type) float nvts = marketcap / volume_ma float nvt = marketcap / volume_usd // ----------------------------------------------} // COLORS // ----------------------------------------------{ //import weak_hand/colors/17 as colors //colors.theme color_auto = colors.find(syminfo.basecurrency) color my_color = input.color(#f7931a, "Color") //if input.bool(false, "Use Color Theme of the Token") //my_color := color_auto.bg // ----------------------------------------------} // OUTPUT // ----------------------------------------------{ plot(nvts, "NVTS", my_color, 2, editable = false, offset = -1) //plot(nvt, "NVT", color.gray, 1, plot.style_columns, editable = false)
Filtered Volume Profile [ChartPrime]
https://www.tradingview.com/script/EPciWdx9-Filtered-Volume-Profile-ChartPrime/
ChartPrime
https://www.tradingview.com/u/ChartPrime/
964
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Chartprime //@version=5 indicator('Filtered Volume Profile [ChartPrime]', overlay=true, max_boxes_count = 500, max_bars_back = 500) look_back = input.int(200, "Length", 1, 500) length = input.int(3, "Smoothing", 1, 6) pivot = input.int(3, "Peak Sensitivity", 1, 10) peak_thresh = input.int(80, "Peak Threshold") score_length = input.int(20, "Mean Score Length") enable_levels = input.string("POC", "Control Lines", ["POC", "All", "None"]) high_color = input.color(color.rgb(235, 170, 252), "Histogram Colors", inline = "hist") low_color = input.color(color.rgb(163, 46, 192), "", inline = "hist") trans = input.int(10, "Transparency", 0, 100) POC_color = input.color(color.red, "POC Color", inline = "POC") level_color = input.color(color.rgb(255, 134, 65), "Peak Level Color", inline = "POC") alpha = color.new(color.black, 100) gamma(float src) => var float math_LnPi = 1.1447298858494001741434273513530587116472948129153 var float math_LogTwoSqrtEOverPi = 0.6207822376352452223455184457816472122518527279025978 var float math_TwoSqrtEOverPi = 1.8603827342052657173362492472666631120594218414085755 var int GammaN = 10 var float GammaR = 10.900511 var float[] series_GammaDk = array.from( 2.48574089138753565546e-5, 1.05142378581721974210, -3.45687097222016235469, 4.51227709466894823700, -2.98285225323576655721, 1.05639711577126713077, -1.95428773191645869583e-1, 1.70970543404441224307e-2, -5.71926117404305781283e-4, 4.63399473359905636708e-6, -2.71994908488607703910e-9) float z = src if z < 0.5 float s = array.get(series_GammaDk, 0) for int i = 1 to GammaN by 1 s += array.get(series_GammaDk, i) / (i - z) s return_Gamma = math.pi / math.sin(math.pi * z) * s * math_TwoSqrtEOverPi * math.pow((0.5 - z + GammaR) / math.e, 0.5 - z) return_Gamma else float s = array.get(series_GammaDk, 0) for int i = 1 to GammaN by 1 s += array.get(series_GammaDk, i) / (z + i - 1.0) s return_Gamma = s * math_TwoSqrtEOverPi * math.pow((z - 0.5 + GammaR) / math.e, z - 0.5) return_Gamma t_dist_pdf(float x, int v) => gamma((v + 1) / 2) / (math.sqrt(v * math.pi) * gamma(v / 2)) * math.pow(1 + x * x / v, -(v + 1) / 2) rising_factorial(float c, int n) => float product = 1.0 if n > 0 for i = 0 to n - 1 product *= (c + i) product hypergeometric(float a, float b, float c, float z) => float sum = 0.0 for i = 0 to 2 sum += rising_factorial(a, i) * rising_factorial(b, i) * math.pow(z, i) / (rising_factorial(c, i) * rising_factorial(i, i)) sum t_dist_cdf(float x, int v) => 1/2.0 + x * gamma((v+1)/2.0) * (hypergeometric(1/2.0, (v+1)/2.0, 3.0/2, x*x/v) / (math.sqrt(v * math.pi)* gamma(v/2))) rounder(number)=> if number >= 1000000000 str.tostring(math.round(number / 1000000000, 2)) + " B" else if number >= 1000000 str.tostring(math.round(number / 1000000, 2)) + " M" else if number >= 1000 str.tostring(math.round(number / 1000, 2)) + " K" else str.tostring(math.round(number, 2)) mean_length = score_length stdev_length = score_length mean = ta.sma(close, score_length) p = (1 - 0.99) / 2 float lower = -100 float upper = 100 float mid = (lower + upper) / 2 while math.abs(t_dist_cdf(mid, stdev_length - 1) - p) > 0.000001 if t_dist_cdf(mid, stdev_length - 1) > p upper := mid else lower := mid mid := (lower + upper) / 2 float t_value = mid if t_value < 0 t_value := -t_value squared_diff = math.pow(open - mean, 2) summed_squares = math.sum(squared_diff, stdev_length) mean_squared_error = summed_squares / (stdev_length - 1) rmse = math.sqrt(mean_squared_error) root_standard_error = math.sqrt(1 + 1 / stdev_length + squared_diff / summed_squares) offset = t_value * rmse * root_standard_error sq(source) => math.pow(source, 2) sinc(source, bandwidth) => if source == 0 1 else math.sin(math.pi * source / bandwidth) / (math.pi * source / bandwidth) window_function(size, n) => 0.54 - 0.46 * math.cos(2 * math.pi * n / (size - 1)) multi_kernel_regression(source, length)=> src_size = array.size(source) estimate_array = array.new<float>(src_size) float current_price = na for i = 0 to src_size - 1 float sum = 0 float sumw = 0 for j = 0 to src_size - 1 diff = i - j weight = sinc(diff, length) sum += array.get(source, j) * weight sumw += weight current_price := sum / sumw array.set(estimate_array, i, current_price >= 0 ? current_price : 0) estimate_array cnum = 100 top = ta.highest(look_back) bot = ta.lowest(look_back) dist = (top - bot) / 500 step = (top - bot) / cnum RANGE = step * pivot levels = array.new_float(cnum + 1) for x = 0 to cnum by 1 array.set(levels, x, bot + step * x) get_vol(a, b, x, y, vol) => // Bar is completely below or above the range if y < a or x > b 0 // Entire bar is inside the range but doesn't span it else if x >= a and y <= b p_range = (y - x) / (b - a) p_range * vol // Bar completely covers the range else if x <= a and y >= b p_bar = (b - a) / (y - x) p_bar * vol // Top of the bar is inside the range else if x < a and y <= b p_bar = (y - a) / (y - x) p_bar * vol // Bottom of the bar is inside the range else if x >= a and y > b p_bar = (b - x) / (y - x) p_bar * vol else vol var lines = array.new<line>() var probs = array.new<box>() var volus = array.new<box>() var float line_float = na if array.size(lines) > 0 for i = array.size(lines) - 1 to 0 line.delete(array.get(lines, i)) array.remove(lines, i) for i = array.size(probs) - 1 to 0 box.delete(array.get(probs, i)) array.remove(probs, i) for i = array.size(volus) - 1 to 0 box.delete(array.get(volus, i)) array.remove(volus, i) if barstate.islast _volumes = array.new_float(cnum, 0.) bullish_volumes = array.new_float(cnum, 0.) for bars = 0 to look_back - 1 by 1 High = high[bars] Low = low[bars] Volume = volume[bars] state = open[bars] < close[bars] for x = 0 to cnum - 1 by 1 array.set(_volumes, x, array.get(_volumes, x) + get_vol(array.get(levels, x), array.get(levels, x + 1), Low, High, Volume)) if state array.set(bullish_volumes, x, array.get(bullish_volumes, x) + get_vol(array.get(levels, x), array.get(levels, x + 1), Low, High, Volume)) smooth_volume = multi_kernel_regression(_volumes, length) int poc = array.indexof(smooth_volume, array.max(smooth_volume)) pocs = array.new<float>() vpoc = array.new<float>() var hl = array.new_float(pivot, na) var hr = array.new_float(pivot, na) for i = 0 to array.size(smooth_volume) - 1 max = array.max(smooth_volume, i) var previous = 0. idx = array.indexof(smooth_volume, max) if max > array.percentile_nearest_rank(smooth_volume, peak_thresh) for j = 0 to array.size(hl) - 1 array.set(hl, j, array.get(smooth_volume, math.max(0, idx - 1 - j))) array.set(hr, j, array.get(smooth_volume, math.min(array.size(smooth_volume) - 1, idx + 1 + j))) is_peak = true for j = 0 to array.size(hl) - 1 if (max < array.get(hr, j) or max < array.get(hl, j)) and (array.get(hr, math.min(array.size(hl) - 1, j + 1)) <= array.get(hl, j) or array.get(hl, math.min(array.size(hl) - 1, j + 1)) <= array.get(hl, j)) is_peak := false break if is_peak poc_i = idx POC = math.avg(array.get(levels, poc_i), array.get(levels, poc_i < array.size(levels) ? poc_i + 1 : poc_i - 1)) if i == 0 array.push(pocs, POC) array.push(vpoc, max) else for j = 0 to array.size(pocs) if j < array.size(pocs) if not (POC > array.get(pocs, j) ? POC - RANGE > RANGE + array.get(pocs, j) : POC + RANGE < array.get(pocs, j) - RANGE) break if j == array.size(pocs) array.push(pocs, POC) array.push(vpoc, max) color_array = array.new_float(cnum, 0.) for i = 0 to cnum - 1 max_level = array.get(_volumes, i) bullish_level = array.get(bullish_volumes, i) array.set(color_array, i, bullish_level/max_level) maxvol = array.max(_volumes) for x = 0 to cnum - 1 by 1 array.set(_volumes, x, array.get(_volumes, x) * look_back / (3 * maxvol)) normal_volumes = multi_kernel_regression(_volumes, length) edge = bar_index - look_back + 1 var vol_bars = array.new_box(cnum, na) for i = 0 to cnum - 1 by 1 box.delete(array.get(vol_bars, i)) array.set( vol_bars, i, box.new(edge, array.get(levels, i + 1) - dist, edge + math.round(array.get(normal_volumes, i)), array.get(levels, i) + dist, border_width = 0, bgcolor = color.new(color.from_gradient(array.get(color_array, i), 0, 1, low_color, high_color), trans)) ) size_index = array.size(pocs) - 1 for i = 0 to size_index POC = array.get(pocs, i) pocv = array.get(vpoc, i) colour = color.new(color.rgb((23 * (i + 4)) % 255, (79 * (i + 4)) % 255, (127 * (i + 4)) % 255), 60) line_a = line.new(edge, POC + RANGE, bar_index + 1, POC + RANGE, color = colour, extend = extend.right) line_b = line.new(edge, POC - RANGE, bar_index + 1, POC - RANGE, color = colour, extend = extend.right) array.unshift(lines, line_a) array.unshift(lines, line_b) if i == 0 point_of_control = line.new(edge, POC, bar_index + 1, POC, color = enable_levels != "None" ? POC_color : alpha, extend = extend.right) array.unshift(lines, point_of_control) if i != 0 point_of_control = line.new(edge, POC, bar_index + 1, POC, color = enable_levels == "All" ? level_color : alpha, extend = extend.right) array.unshift(lines, point_of_control) linefill.new(line_a, line_b, colour) zscore = (POC - mean)/(offset * 1.5) probability = math.round(t_dist_pdf(zscore, stdev_length - 1), 2) array.unshift(probs, box.new(bar_index + 32, POC + RANGE, bar_index + 48, POC - RANGE, border_color = color.new(color.black, 30), bgcolor = color.new(color.black, 30), text = "Mean Score" + "\n" + str.tostring(probability * 100 / 40 * 100), text_color = color.white)) array.unshift(volus, box.new(bar_index + 16, POC + RANGE, bar_index + 32, POC - RANGE, border_color = color.new(color.black, 30), bgcolor = color.new(color.black, 30), text = "Volume" + "\n" + rounder(pocv), text_color = color.white))
HighLowBox+220MAs[libHTF]
https://www.tradingview.com/script/bre2SbmX/
nazomobile
https://www.tradingview.com/u/nazomobile/
28
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© nazomobile //@description HighLowBox+220MAs [libHTF] // //This is a sample script of libHTF: use HTF values without request.security(). // // HTF candles are calculated internally using 'GMT+3' from current TF candles. //To calcurate Higher TF candles, please display many past bars at first. //The advantage and disadvantage is that the data can be generated at the current TF granularity. //Although the signal can be displayed more sensitively, plots such as MAs are not smooth. // //In this script, assigned ➊,βž‹,➌,➍ for htf1,htf2,htf3,htf4. // // - HTF candles // Draw candles for HTF1-4 on the right edge of the chart. 2 candles for each HTF. //They are updated with every current TF bar update. //Left edge of HTF candles is located at the x-postion latest bar_index + offset. // // - DMI HTF // ADX/+DI/DI arrows(8lines) are shown each timeframes range. //Current TF's is located at left side of the HighLowBox. //HTF's are located at HighLowBox of HTF candles. //The top of HighLowBox is 100, The bottom of HighLowBox is 0. // // - HighLowBox HTF //Enclose in a square high and low range in each timeframe. //Shows price range and duration of each box. // //In current timeframe, shows Fibonacci Scale inside(23.6%, 38.2%, 50.0%, 61.8%, 76.4%)/outside of each box. //Outside(161.8%,261.8,361.8%) would be shown as next target, if break top/bottom of each box. //In HTF, shows Fibonacci Level of the current price at latest box only. // //Boxes: // .1 for current timeframe. // .4 for higher timeframes.(Steps of timeframe: 5, 15, 60, 240, D, W, M, 3M, 6M, Y) // // - HighLowBox TrendLine //Draw TrendLine for each HighLow Range. TrendLine is drawn between high and return high(or low and return low) of each HighLowBox. //Style of TrendLine is same as each HighLowBox. // // - HighLowBox RSI // // RSI Signals are shown at the bottom(RSI<=30) or the top(RSI>=70) of HighLowBox in each timeframe. //RSI Signal is color coded by RSI9 and RSI14 in each timeframe.(current TF: ●, HTF1-4: βžŠβž‹βžŒβž) // //In case of RSI<=30, //. Location: bottom of the HighLowBox //.white: only RSI9 is <=30 //.aqua: RSI9&RSI14 <=30 and RSI9<RSI14 //.blue: RSI9&RSI14 <=30 and RSI9>RSI14 //.green: only RSI14 <=30 //In case of RSI>=70, //.Location: top of the HighLowBox //.white: only RSI9 is >=70 //.yellow: RSI9&RSI14 >=70 and RSI9>RSI14 //.orange: RSI9&RSI14 >=70 and RSI9<RSI14 //.red: only RSI14 >=70 // //blue/green and orange/red could be a oversold/overbought sign. // // - 20/200 MAs // Shows 20 and 200 MAs in each TFs(tfChart and 4 Higher). // //TFs: //current TF //HTF1-4 //MAs: //20SMA //20EMA //200SMA //200EMA // //@version=5 indicator(title="HighLowBox+220MAs[libHTF]",shorttitle="HiLo+220MA",overlay=true,explicit_plot_zorder=true,max_lines_count=500,max_labels_count=500,max_boxes_count=500) import nazomobile/libHTFwoRS/2 as H //***** //colors //***** colorSMA=color.new(color.aqua,5) colorEMA=color.new(color.yellow,5) colorRMA=color.new(#ffe4e1,5) colorLabelText=color.new(color.white,60) colorBoxT=color.new(color.white,5) colorBoxU=color.new(#aaffaa,5) colorBoxD=color.new(#ffaaaa,5) //minimap colors(exprimental) colorMinimap_middle_low= color.new(color.orange,20) colorMinimap_low=color.new(color.red,60) colorMinimap_low2=color.new(color.red,40) colorMinimap_break_bottom=color.new(color.red,20) colorMinimap_middle_high=color.new(color.yellow,20) colorMinimap_high=color.new(color.blue,60) colorMinimap_high2=color.new(color.blue,40) colorMinimap_break_top=color.new(color.blue,20) colorRSIi=color.new(color.white,5) colorRSIt1=color.new(color.yellow,5) colorRSIt2=color.new(color.orange,5) colorRSIt3=color.new(color.red,5) colorRSIb1=color.new(color.aqua,5) colorRSIb2=color.new(color.blue,5) colorRSIb3=color.new(color.green,5) colorTLresistance=color.new(#ba55d3,20) colorTLsupport=color.new(#7b68ee,20) colorCandleU =color.new(#53b987,20) colorCandleD =color.new(#eb4d5c,20) colorCandleT =color.new(color.white,20) //***** //end of colors //***** //***** //functions //***** l00="solid",l01="dashed",l02="dotted" f_linestyle (x) => x==l00?line.style_solid: x==l01?line.style_dashed: x==l02?line.style_dotted:na s00="auto",s01="huge",s02="large",s03="normal",s04="small",s05="tiny" f_textsize (x) => x==s00?size.auto: x==s01?size.huge: x==s02?size.large: x==s03?size.normal: x==s04?size.small: x==s05?size.tiny:na p01="top_left",p02="top_center",p03="top_right",p04="middle_left",p05="middle_center",p06="middle_right",p07="bottom_left",p08="bottom_center",p09="bottom_right" f_position(x) => x==p01?position.top_left: x==p02?position.top_center: x==p03?position.top_right: x==p04?position.middle_left: x==p05?position.middle_center: x==p06?position.middle_right: x==p07?position.bottom_left: x==p08?position.bottom_center: x==p09?position.bottom_right:na ps00="steplinebr",ps01="line",ps02="linebr",ps03="stepline",ps04="stepline_diamond",ps05="histogram",ps06="areabr",ps07="cross",ps08="columns",ps09="circles" f_plotstyle(x) => x==ps00?plot.style_steplinebr: x==ps01?plot.style_line: x==ps02?plot.style_linebr: x==ps03?plot.style_stepline: x==ps04?plot.style_stepline_diamond: x==ps05?plot.style_histogram: x==ps06?plot.style_areabr: x==ps07?plot.style_cross: x==ps08?plot.style_columns: x==ps09?plot.style_circles:na // t00,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15 t00="Chart", t01="1", t02="3", t03="5", t04="15", t05="30",t06="60",t07="120", t08="180",t09="240", t10="D", t11='W',t12="M",t13="3M", t14="6M",t15="Y" b_tfgt(_tfa,_tfb) => timeframe.in_seconds(_tfa)>timeframe.in_seconds(_tfb) b_tflt(_tfa,_tfb) => timeframe.in_seconds(_tfa)<timeframe.in_seconds(_tfb) f_line_delete_all (_array) => if array.size(_array)>0 for i = 0 to array.size(_array)-1 line.delete(array.get(_array,i)) f_fibo(a,z) => diff = z-a [z-diff*3.618,z-diff*2.618,z-diff*1.618, a+diff*0.236,a+diff*0.382,a+diff*0.5,a+diff*0.618,a+diff*0.786, a+diff*1.618,a+diff*2.618,a+diff*3.618] f_fibo_range(a,z,x) => diff = z-a _rti=-1 _rbi=-1 listfibo = array.from(z-diff*3.618,z-diff*2.618,z-diff*1.618,a,a+diff*0.236,a+diff*0.382,a+diff*0.5,a+diff*0.618,a+diff*0.786,z,a+diff*1.618,a+diff*2.618,a+diff*3.618) s_listfibo = array.from("3.618fromT","2.618fromT","1.618fromT","____Bottom","0.236fromB","0.382fromB","____Center","0.382fromT","0.236fromT","_______Top","1.618fromB","2.618fromB","3.618fromB") for i = 0 to array.size(listfibo)-1 if x<array.get(listfibo,i) _rti:=i break for i = array.size(listfibo)-1 to 0 if x>array.get(listfibo,i) _rbi:=i break [_rti==-1?na:array.get(listfibo,_rti),_rti==-1?na:array.get(s_listfibo,_rti), _rbi==-1?na:array.get(listfibo,_rbi),_rbi==-1?na:array.get(s_listfibo,_rbi)] f_time_ddhhmm (_t)=> _s=1000 _m=60*_s _h=60*_m _d=24*_h _sec = _t _day = int(_sec/_d) _mod = _sec%_d _hour= int(_mod/_h) _mod:= _mod%_h _min = int(_mod/_m) (_day>0?str.tostring(_day,"00")+"d":"")+str.tostring(_hour,"00")+"h"+str.tostring(_min,"00")+"m" f_draw_candle (_open,_close,_high,_low,_x1,_x2,_text,_colorUP,_colorDN,_colorT) => _c = _open<_close?_colorUP:_colorDN _t = _open>_close?_open:_close _b = _open>_close?_close:_open _center=int((_x1+_x2)/2) [box.new(_x1,_t,_x2,_b,xloc=xloc.bar_time,border_color=_c,bgcolor=_c,text=_text,text_color=_colorT,text_size=size.normal), line.new(_center,_high,_center,_low,xloc=xloc.bar_time,color=_c,width=2)] f_draw_candle_barindex (_open,_close,_high,_low,_offset,_x,_text,_colorUP,_colorDN,_colorT) => _c = _open<_close?_colorUP:_colorDN _t = _open>_close?_open:_close _b = _open>_close?_close:_open _x1 = _offset+_x _x2 = _offset+_x+2 _center=int((_x1+_x2)/2) _h=_high<=_t?na:_high _l=_low>=_b?na:_low [box.new(_x1,_t,_x2,_b,xloc=xloc.bar_index,border_color=_c,bgcolor=_c,text=_text,text_color=_colorT,text_size=size.normal), line.new(_center,_h,_center,_t,xloc=xloc.bar_index,color=_c,width=2), line.new(_center,_l,_center,_b,xloc=xloc.bar_index,color=_c,width=2) ] f_madev(val, ma) => (val - ma) / ma * 100 s_madev(val, ma) => str.tostring(val-ma,"0.0000")+"("+str.tostring(math.round(f_madev(val,ma),2))+"%)" f_ma_label (_s,_offset,_tf,_span,_type,_color,_b) => tp=s_madev(close,_s) info=_b?":"+tp:"" na(_s)?na:label.new(x=bar_index+_offset,y=_s, text=_tf+": "+str.tostring(_span)+_type+info,style=label.style_none,textcolor=_color,textalign=text.align_left,tooltip=tp) //***** //end of functions //***** group_HTF='HTFlib' TZ = input.string(defval="GMT+3", title="TZ for calculating HTF",options=["GMT+2","GMT+3"],group=group_HTF) tooltip_HTF='Steps of timeframe:\n[1, 5, 15, 60, 240, D, W, M, 3M, 6M, Y]\n' symbol_htf1 = input.string(defval="➊", title="Symbol for HTF1 (HigherTF of current Chart)",group=group_HTF,tooltip=tooltip_HTF) symbol_htf2 = input.string(defval="βž‹", title="Symbol for HTF2 (HigherTF of HTF1)",group=group_HTF,tooltip=tooltip_HTF) symbol_htf3 = input.string(defval="➌", title="Symbol for HTF3 (HigherTF of HTF2)",group=group_HTF,tooltip=tooltip_HTF) symbol_htf4 = input.string(defval="➍", title="Symbol for HTF4 (HigherTF of HTF3)",group=group_HTF,tooltip=tooltip_HTF) tooltip_SRC='Data soruce for HTFlib' sr0="open",sr1="high",sr2="low",sr3="close",sr4="hl2",sr5="hlc3",sr6="ohlc4",sr7="hlcc4" _src = input.string(title="src", defval=sr7,options=[sr0,sr1,sr2,sr3,sr4,sr5,sr6,sr7],group=group_HTF, tooltip=tooltip_SRC) tooltip_bartime_price='true: The price of peak/bottom is set by price of latest bar\nfalse: The price of peak/bottom is set by comparison of "last close" and "current open"' b_bartime_price = input.bool(defval=true,title="prioritize latest bars for peak/bottom instead of actural price.",group=group_HTF,tooltip=tooltip_bartime_price) var tfChart = timeframe.period var string htf1 = H.tf_higher(tfChart) var string htf2 = H.tf_higher(htf1) var string htf3 = H.tf_higher(htf2) var string htf4 = H.tf_higher(htf3) b_new_bar=ta.change(time) [b_new_bar1,m1]=H.htf_candle(htf1) [b_new_bar2,m2]=H.htf_candle(htf2) [b_new_bar3,m3]=H.htf_candle(htf3) [b_new_bar4,m4]=H.htf_candle(htf4) [i_renew,a_high,a_time_high,a_return_high,a_time_return_high,a_low,a_time_low,a_return_low,a_time_return_low] = H.highlow(b_bartime_price) [i_renew1,a_high1,a_time_high1,a_return_high1,a_time_return_high1,a_low1,a_time_low1,a_return_low1,a_time_return_low1] = H.htfhighlow(m1,b_bartime_price) [i_renew2,a_high2,a_time_high2,a_return_high2,a_time_return_high2,a_low2,a_time_low2,a_return_low2,a_time_return_low2] = H.htfhighlow(m2,b_bartime_price) [i_renew3,a_high3,a_time_high3,a_return_high3,a_time_return_high3,a_low3,a_time_low3,a_return_low3,a_time_return_low3] = H.htfhighlow(m3,b_bartime_price) [i_renew4,a_high4,a_time_high4,a_return_high4,a_time_return_high4,a_low4,a_time_low4,a_return_low4,a_time_return_low4] = H.htfhighlow(m4,b_bartime_price) src=H.set_src(_src) htf1src=H.set_htfsrc(_src,b_new_bar1,m1) htf2src=H.set_htfsrc(_src,b_new_bar2,m2) htf3src=H.set_htfsrc(_src,b_new_bar3,m3) htf4src=H.set_htfsrc(_src,b_new_bar4,m4) group_HTF_candle='HTF Candles' tooltip_HTF_candle='Draw candles for HTF1-4 on the right edge of the chart.\n2 candles for each HTF.' tooltip_HTF_candle_offset='Left edge of HTF candles is located at the x-postion latest bar_index + offset.' b_fake_candle = input.bool(defval=true,title="show HTF Candles",inline="HTFcandle",group=group_HTF_candle, tooltip=tooltip_HTF_candle) i_offset_candle = input.int(defval=15,title="offset of HTF candles",inline="HTCcandle",group=group_HTF_candle,tooltip=tooltip_HTF_candle_offset) trans_candle = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="text",group=group_HTF_candle) cCandleU = input.color(defval=colorCandleU,title="Bullish",inline="color",group=group_HTF_candle) cCandleD = input.color(defval=colorCandleD,title="Bearish",inline="color",group=group_HTF_candle) cCandleT = input.color(defval=colorCandleT,title="Text",inline="color",group=group_HTF_candle) group_DMI='DMI' b_DMI = input.bool(defval=true,title="show DMI",inline="DMI",group=group_DMI) cADX = input.color(defval=color.gray,title="ADX",inline="color",group=group_DMI) cDI = input.color(defval=color.green,title="+DI",inline="color",group=group_DMI) c_DI = input.color(defval=color.red,title="-DI",inline="color",group=group_DMI) group_HLBOX='HighLowBox' _cBoxU = input.color(defval=colorBoxU,title="newHigh",inline="color",group=group_HLBOX) _cBoxD = input.color(defval=colorBoxD,title="newLow",inline="color",group=group_HLBOX) _cBoxT = input.color(defval=colorBoxT,title="text",inline="color",group=group_HLBOX) b_info = input.bool(defval=true,title="range info",inline="text",group=group_HLBOX) transInfo = input.int(defval=30,minval=0,maxval=99,title="transpar",inline="text",group=group_HLBOX) _infoSize = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="size",inline="text",group=group_HLBOX) infoSize = f_textsize(_infoSize) cBoxT = color.new(_cBoxT,transInfo) tooltip_max_boxes='Max # of boxes@Current TF. 0 is no limit. Only 500 boxes can be shown in this script.' group_HLBOX_ctf="HighLowBox@Current TF" show0 = input.bool(defval=true,title="CTF",inline="Box",group=group_HLBOX_ctf) transBox = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="Box",group=group_HLBOX_ctf) cBoxU=color.new(_cBoxU,transBox) cBoxD=color.new(_cBoxD,transBox) widthBox = input.int(defval=1,minval=1,maxval=4,title="width",inline="Box",group=group_HLBOX_ctf) _styleBox = input.string(defval=l01,options=[l00,l01,l02],title="box style",inline="Box",group=group_HLBOX_ctf) styleBox = f_linestyle(_styleBox) tooltip_HLBOX_fill_box='Fill the HighLowBox(only current TF).' b_fibo = input.bool(defval=true,title="show fibonacci scale",inline="fibo",group=group_HLBOX_ctf) b_fibo_clear = input.bool(defval=true,title="delete fibonacci scale in past range",inline="fibo",group=group_HLBOX_ctf) i_maxBoxes = input.int(defval=100,minval=0,maxval=500,title="max# of Boxes",inline="Box",group=group_HLBOX_ctf,tooltip=tooltip_max_boxes) group_HLBOX_htf="HighLowBox@HTF" show1 = input.bool(defval=true,title="HTF1",group=group_HLBOX_htf) transBox1 = input.int(defval=45,minval=0,maxval=99,title="transpar",inline="tfH1",group=group_HLBOX_htf) cBoxU1=color.new(_cBoxU,transBox1) cBoxD1=color.new(_cBoxD,transBox1) widthBox1 = input.int(defval=2,minval=1,maxval=4,title="width",inline="tfH1",group=group_HLBOX_htf) _styleBox1 = input.string(defval=l00,options=[l00,l01,l02],title="box style",inline="tfH1",group=group_HLBOX_htf) styleBox1 = f_linestyle(_styleBox1) b_fibo1 = input.bool(defval=true,title="show fibonacci level",inline="tfH1",group=group_HLBOX_htf) show2 = input.bool(defval=true,title="HTF2",group=group_HLBOX_htf) transBox2 = input.int(defval=50,minval=0,maxval=99,title="transpar",inline="tfH2",group=group_HLBOX_htf) cBoxU2=color.new(_cBoxU,transBox2) cBoxD2=color.new(_cBoxD,transBox2) widthBox2 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH2",group=group_HLBOX_htf) _styleBox2 = input.string(defval=l01,options=[l00,l01,l02],title="box style",inline="tfH2",group=group_HLBOX_htf) styleBox2 = f_linestyle(_styleBox2) b_fibo2 = input.bool(defval=true,title="show fibonacci level",inline="tfH2",group=group_HLBOX_htf) show3 = input.bool(defval=true,title="HTF3",group=group_HLBOX_htf) transBox3 = input.int(defval=55,minval=0,maxval=99,title="transpar",inline="tfH3",group=group_HLBOX_htf) cBoxU3=color.new(_cBoxU,transBox3) cBoxD3=color.new(_cBoxD,transBox3) widthBox3 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH3",group=group_HLBOX_htf) _styleBox3 = input.string(defval=l00,options=[l00,l01,l02],title="box style",inline="tfH3",group=group_HLBOX_htf) styleBox3 = f_linestyle(_styleBox3) b_fibo3 = input.bool(defval=true,title="show fibonacci level",inline="tfH3",group=group_HLBOX_htf) show4 = input.bool(defval=true,title="HTF4",group=group_HLBOX_htf) transBox4 = input.int(defval=60,minval=0,maxval=99,title="transpar",inline="tfH4",group=group_HLBOX_htf) cBoxU4=color.new(_cBoxU,transBox4) cBoxD4=color.new(_cBoxD,transBox4) widthBox4 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH4",group=group_HLBOX_htf) _styleBox4 = input.string(defval=l02,options=[l00,l01,l02],title="box style",inline="tfH4",group=group_HLBOX_htf) styleBox4 = f_linestyle(_styleBox4) b_fibo4 = input.bool(defval=true,title="show fibonacci level",inline="tfH4",group=group_HLBOX_htf) group_HLBOX_tl="HighLowBox TrendLine" b_TL = input.bool(defval=true,title="show trend line",inline="TL",group=group_HLBOX_tl) b_TL_clear = input.bool(defval=true,title="delete lines in past range",inline="TL",group=group_HLBOX_tl) b_TL_obsolete = input.bool(defval=true,title="delete obsolete TL",inline="TL",group=group_HLBOX_tl) transTL = input.int(defval=80,minval=0,maxval=99,title="obsolete TL transpar",inline="TL",group=group_HLBOX_tl) cTLr = input.color(defval=colorTLresistance,title="bearish line",inline="TL",group=group_HLBOX_tl) cTLs = input.color(defval=colorTLsupport,title="bullish line",inline="TL",group=group_HLBOX_tl) cTLro =color.new(cTLr,transTL) cTLso =color.new(cTLs,transTL) //***** //HighLowBox //***** //current tf box var mybox=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na) var a_tl_resistance=array.new_line(0,na) var a_tl_support=array.new_line(0,na) var a_mybox=array.new_box(0,na) var myfibo23=line.new(na,na,na,na,xloc=xloc.bar_time) var myfibo38=line.new(na,na,na,na,xloc=xloc.bar_time) var myfibo50=line.new(na,na,na,na,xloc=xloc.bar_time) var myfibo61=line.new(na,na,na,na,xloc=xloc.bar_time) var myfibo78=line.new(na,na,na,na,xloc=xloc.bar_time) var myfibo161=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none) var myfibo261=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none) var myfibo361=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none) var myfibom161=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none) var myfibom261=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none) var myfibom361=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none) var i_breakT=0 var i_breakf161=0 var i_breakf261=0 var i_breakB=0 var i_breakfm161=0 var i_breakfm261=0 i_peak_bottom =H.peak_bottom(H.is_up(),H.last_is_up()) top= a_high.lastx() top_time= a_time_high.lastx() bottom= a_low.lastx() bottom_time= a_time_low.lastx() c_box=bottom_time<top_time?cBoxU:cBoxD _h = array.from(int(top_time),int(bottom_time)) _v = array.from(top,bottom) _t = array.max(_v) _b = array.min(_v) _l = array.min(_h) [fm361,fm261,fm161,f23,f38,f50,f61,f78,f161,f261,f361] = f_fibo(_b,_t) if show0 and i_renew!=0 if b_TL_clear f_line_delete_all(a_tl_resistance) f_line_delete_all(a_tl_support) if array.size(a_tl_resistance)>0 line.set_extend(array.last(a_tl_resistance),extend.none) array.clear(a_tl_resistance) if array.size(a_tl_support)>0 line.set_extend(array.last(a_tl_support),extend.none) array.clear(a_tl_support) mybox:=box.new(_l,na,na,na,xloc=xloc.bar_time,border_width=widthBox,text_halign=text.align_center,text_size=infoSize, border_color=c_box,text_color=cBoxT,bgcolor=na,border_style=styleBox) array.push(a_mybox,mybox) if i_maxBoxes >0 and array.size(a_mybox)>i_maxBoxes box.delete(array.shift(a_mybox)) if b_fibo if b_fibo_clear line.delete(myfibo23) line.delete(myfibo38) line.delete(myfibo50) line.delete(myfibo61) line.delete(myfibo78) label.delete(myfibo161),label.delete(myfibo261),label.delete(myfibo361) label.delete(myfibom161),label.delete(myfibom261),label.delete(myfibom361) myfibo23:=line.new(_l,f23,na,f23,xloc.bar_time,extend.none,c_box,line.style_dashed,1) myfibo38:=line.new(_l,f38,na,f38,xloc.bar_time,extend.none,c_box,line.style_dashed,1) myfibo50:=line.new(_l,f50,na,f50,xloc.bar_time,extend.none,c_box,line.style_solid,1) myfibo61:=line.new(_l,f61,na,f61,xloc.bar_time,extend.none,c_box,line.style_dashed,1) myfibo78:=line.new(_l,f78,na,f78,xloc.bar_time,extend.none,c_box,line.style_dashed,1) myfibo161:=label.new(na,f161,"___1.618:"+str.tostring(f161,"#.0000")+"___",xloc.bar_time,yloc.price,c_box,label.style_none,c_box,infoSize) myfibo261:=label.new(na,f261,"___2.618:"+str.tostring(f261,"#.0000")+"___",xloc.bar_time,yloc.price,c_box,label.style_none,c_box,infoSize) myfibo361:=label.new(na,f361,"___3.618:"+str.tostring(f361,"#.0000")+"___",xloc.bar_time,yloc.price,c_box,label.style_none,c_box,infoSize) myfibom161:=label.new(na,fm161,"___1.618:"+str.tostring(fm161,"#.0000")+"___",xloc.bar_time,yloc.price,c_box,label.style_none,c_box,infoSize) myfibom261:=label.new(na,fm261,"___2.618:"+str.tostring(fm261,"#.0000")+"___",xloc.bar_time,yloc.price,c_box,label.style_none,c_box,infoSize) myfibom361:=label.new(na,fm361,"___3.618:"+str.tostring(fm361,"#.0000")+"___",xloc.bar_time,yloc.price,c_box,label.style_none,c_box,infoSize) else label.delete(myfibo161),label.delete(myfibo261),label.delete(myfibo361) label.delete(myfibom161),label.delete(myfibom261),label.delete(myfibo361) i_breakT:=0 i_breakB:=0 i_breakf161:=0 i_breakf261:=0 i_breakfm161:=0 i_breakfm261:=0 else if show0 and i_peak_bottom==1 and b_TL if (array.size(a_high)>0) if array.size(a_tl_resistance) if b_TL_obsolete f_line_delete_all(a_tl_resistance) else line.set_style(array.last(a_tl_resistance),line.style_dotted) line.set_extend(array.last(a_tl_resistance),extend.none) line.set_color(array.last(a_tl_resistance),cTLro) if a_high.lastx()!=a_return_high.lastx() array.push(a_tl_resistance,line.new( a_time_high.lastx(), a_high.lastx(), a_time_return_high.lastx(), a_return_high.lastx(), xloc.bar_time,extend.right,cTLr,styleBox,widthBox)) else if show0 and i_peak_bottom==-1 and b_TL if (array.size(a_low)>0) if array.size(a_tl_support) if b_TL_obsolete f_line_delete_all(a_tl_support) else line.set_style(array.last(a_tl_support),line.style_dotted) line.set_extend(array.last(a_tl_support),extend.none) line.set_color(array.last(a_tl_support),cTLso) if a_low.lastx()!=a_return_low.lastx() array.push(a_tl_support,line.new( a_time_low.lastx(), a_low.lastx(), a_time_return_low.lastx(), a_return_low.lastx(), xloc.bar_time,extend.right,cTLs,styleBox,widthBox)) i_breakT+=high>_t?1:0 i_breakB+=low<_t?1:0 i_breakf161+=high>f161?1:0 i_breakf261+=high>f261?1:0 i_breakfm161+=low<fm161?1:0 i_breakfm261+=low<fm261?1:0 if show0 box.set_right(mybox,time_close) box.set_bottom(mybox,_b) box.set_top(mybox,_t) box.set_text(mybox, b_info? "TF="+tfChart+":"+f_time_ddhhmm(box.get_right(mybox)-box.get_left(mybox))+":"+ str.tostring(math.abs(box.get_top(mybox)-box.get_bottom(mybox))):na) line.set_x2(myfibo23,time_close) line.set_x2(myfibo38,time_close) line.set_x2(myfibo50,time_close) line.set_x2(myfibo61,time_close) line.set_x2(myfibo78,time_close) if i_breakT>0 label.set_xy(myfibo161,(_l+time_close)/2,f161) if i_breakf161>0 label.set_xy(myfibo261,(_l+time_close)/2,f261) if i_breakf261>0 label.set_xy(myfibo361,(_l+time_close)/2,f361) if i_breakB>0 label.set_xy(myfibom161,(_l+time_close)/2,fm161) if i_breakfm161>0 label.set_xy(myfibom261,(_l+time_close)/2,fm261) if i_breakfm261>0 label.set_xy(myfibom361,(_l+time_close)/2,fm361) //box htf1 var mybox1=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na) var a_tl_resistance1=array.new_line(0,na) var a_tl_support1=array.new_line(0,na) i_peak_bottom1 =H.peak_bottom(H.htf_is_up(m1),H.htf_last_is_up(m1)) top1= a_high1.lastx() top_time1= a_time_high1.lastx() bottom1= a_low1.lastx() bottom_time1= a_time_low1.lastx() c_box1=bottom_time1<top_time1?cBoxU1:cBoxD1 va1=bottom_time1<top_time1?text.align_top:text.align_bottom _h1 = array.from(int(top_time1),int(bottom_time1)) _v1 = array.from(top1,bottom1) _t1 = array.max(_v1) _b1 = array.min(_v1) _l1 = array.min(_h1) if show1 and i_renew1!=0 if b_TL_clear f_line_delete_all(a_tl_resistance1) f_line_delete_all(a_tl_support1) if array.size(a_tl_resistance1)>0 line.set_extend(array.last(a_tl_resistance1),extend.none) array.clear(a_tl_resistance1) if array.size(a_tl_support1)>0 line.set_extend(array.last(a_tl_support1),extend.none) array.clear(a_tl_support1) if not (_l1[1]==_l1 and (_b1[1]==_b1 or _t1[1]==_t1)) mybox1:=box.new(_l1,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox1,border_style=styleBox1, text_halign=text.align_right,text_valign=va1,text_size=infoSize,border_color=c_box1,text_color=cBoxT) else if show1 and i_peak_bottom1==1 and b_TL if (array.size(a_high1)>0) if array.size(a_tl_resistance1) if b_TL_obsolete f_line_delete_all(a_tl_resistance1) else line.set_style(array.last(a_tl_resistance1),line.style_dotted) line.set_extend(array.last(a_tl_resistance1),extend.none) line.set_color(array.last(a_tl_resistance1),cTLro) if a_high1.lastx()!=a_return_high1.lastx() array.push(a_tl_resistance1,line.new( a_time_high1.lastx(), a_high1.lastx(), a_time_return_high1.lastx(), a_return_high1.lastx(), xloc.bar_time,extend.right,cTLr,styleBox1,widthBox1)) else if show1 and i_peak_bottom1==-1 and b_TL if (array.size(a_low1)>0) if array.size(a_tl_support1) if b_TL_obsolete f_line_delete_all(a_tl_support1) else line.set_style(array.last(a_tl_support1),line.style_dotted) line.set_extend(array.last(a_tl_support1),extend.none) line.set_color(array.last(a_tl_support1),cTLso) if a_low1.lastx()!=a_return_low1.lastx() array.push(a_tl_support1,line.new( a_time_low1.lastx(), a_low1.lastx(), a_time_return_low1.lastx(), a_return_low1.lastx(), xloc.bar_time,extend.right,cTLs,styleBox1,widthBox1)) if show1 box.set_right(mybox1,int(m1.lastx("time_close"))) box.set_bottom(mybox1,_b1) box.set_top(mybox1,_t1) box.set_text(mybox1,b_info?"TF"+symbol_htf1+"="+htf1+"\n"+ f_time_ddhhmm(box.get_right(mybox1)-box.get_left(mybox1))+"\n"+ str.tostring(math.abs(box.get_top(mybox1)-box.get_bottom(mybox1))):na) //box htf2 var mybox2=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na) var a_tl_resistance2=array.new_line(0,na) var a_tl_support2=array.new_line(0,na) i_peak_bottom2 =H.peak_bottom(H.htf_is_up(m2),H.htf_last_is_up(m2)) top2= a_high2.lastx() top_time2= a_time_high2.lastx() bottom2= a_low2.lastx() bottom_time2= a_time_low2.lastx() c_box2=bottom_time2<top_time2?cBoxU2:cBoxD2 va2=bottom_time2<top_time2?text.align_top:text.align_bottom _h2 = array.from(int(top_time2),int(bottom_time2)) _v2 = array.from(top2,bottom2) _t2 = array.max(_v2) _b2 = array.min(_v2) _l2 = array.min(_h2) if show2 and i_renew2!=0 if b_TL_clear f_line_delete_all(a_tl_resistance2) f_line_delete_all(a_tl_support2) if array.size(a_tl_resistance2)>0 line.set_extend(array.last(a_tl_resistance2),extend.none) array.clear(a_tl_resistance2) if array.size(a_tl_support2)>0 line.set_extend(array.last(a_tl_support2),extend.none) array.clear(a_tl_support2) if not (_l2[1]==_l2 and (_b2[1]==_b2 or _t2[1]==_t2)) mybox2:=box.new(_l2,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox2,border_style=styleBox2, text_halign=text.align_right,text_valign=va2,text_size=infoSize,border_color=c_box2,text_color=cBoxT) else if show2 and i_peak_bottom2==1 and b_TL if (array.size(a_high2)>0) if array.size(a_tl_resistance2) if b_TL_obsolete f_line_delete_all(a_tl_resistance2) else line.set_style(array.last(a_tl_resistance2),line.style_dotted) line.set_extend(array.last(a_tl_resistance2),extend.none) line.set_color(array.last(a_tl_resistance2),cTLro) if a_high2.lastx()!=a_return_high2.lastx() array.push(a_tl_resistance2,line.new( a_time_high2.lastx(), a_high2.lastx(), a_time_return_high2.lastx(), a_return_high2.lastx(), xloc.bar_time,extend.right,cTLr,styleBox2,widthBox2)) else if show2 and i_peak_bottom2==-1 and b_TL if (array.size(a_low2)>0) if array.size(a_tl_support2) if b_TL_obsolete f_line_delete_all(a_tl_support2) else line.set_style(array.last(a_tl_support2),line.style_dotted) line.set_extend(array.last(a_tl_support2),extend.none) line.set_color(array.last(a_tl_support2),cTLso) if a_low2.lastx()!=a_return_low2.lastx() array.push(a_tl_support2,line.new( a_time_low2.lastx(), a_low2.lastx(), a_time_return_low2.lastx(), a_return_low2.lastx(), xloc.bar_time,extend.right,cTLs,styleBox2,widthBox2)) if show2 box.set_right(mybox2,int(m2.lastx("time_close"))) box.set_bottom(mybox2,_b2) box.set_top(mybox2,_t2) box.set_text(mybox2,b_info?"TF"+symbol_htf2+"="+htf2+"\n"+ f_time_ddhhmm(box.get_right(mybox2)-box.get_left(mybox2))+"\n"+ str.tostring(math.abs(box.get_top(mybox2)-box.get_bottom(mybox2))):na) //box htf3 var mybox3=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na) var a_tl_resistance3=array.new_line(0,na) var a_tl_support3=array.new_line(0,na) i_peak_bottom3 =H.peak_bottom(H.htf_is_up(m3),H.htf_last_is_up(m3)) top3= a_high3.lastx() top_time3= a_time_high3.lastx() bottom3= a_low3.lastx() bottom_time3= a_time_low3.lastx() c_box3=bottom_time3<top_time3?cBoxU3:cBoxD3 va3=bottom_time3<top_time3?text.align_top:text.align_bottom _h3 = array.from(int(top_time3),int(bottom_time3)) _v3 = array.from(top3,bottom3) _t3 = array.max(_v3) _b3 = array.min(_v3) _l3 = array.min(_h3) if show3 and i_renew3!=0 if b_TL_clear f_line_delete_all(a_tl_resistance3) f_line_delete_all(a_tl_support3) if array.size(a_tl_resistance3)>0 line.set_extend(array.last(a_tl_resistance3),extend.none) array.clear(a_tl_resistance3) if array.size(a_tl_support3)>0 line.set_extend(array.last(a_tl_support3),extend.none) array.clear(a_tl_support3) if not (_l3[1]==_l3 and (_b3[1]==_b3 or _t3[1]==_t3)) mybox3:=box.new(_l3,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox3,border_style=styleBox3, text_halign=text.align_right,text_valign=va3,text_size=infoSize,border_color=c_box3,text_color=cBoxT) else if show3 and i_peak_bottom3==1 and b_TL if (array.size(a_high3)>0) if array.size(a_tl_resistance3) if b_TL_obsolete f_line_delete_all(a_tl_resistance3) else line.set_style(array.last(a_tl_resistance3),line.style_dotted) line.set_extend(array.last(a_tl_resistance3),extend.none) line.set_color(array.last(a_tl_resistance3),cTLro) if a_high3.lastx()!=a_return_high3.lastx() array.push(a_tl_resistance3,line.new( a_time_high3.lastx(), a_high3.lastx(), a_time_return_high3.lastx(), a_return_high3.lastx(), xloc.bar_time,extend.right,cTLr,styleBox3,widthBox3)) else if show3 and i_peak_bottom3==-1 and b_TL if (array.size(a_low3)>0) if array.size(a_tl_support3) if b_TL_obsolete f_line_delete_all(a_tl_support3) else line.set_style(array.last(a_tl_support3),line.style_dotted) line.set_extend(array.last(a_tl_support3),extend.none) line.set_color(array.last(a_tl_support3),cTLso) if a_low3.lastx()!=a_return_low3.lastx() array.push(a_tl_support3,line.new( a_time_low3.lastx(), a_low3.lastx(), a_time_return_low3.lastx(), a_return_low3.lastx(), xloc.bar_time,extend.right,cTLs,styleBox3,widthBox3)) if show3 box.set_right(mybox3,int(m3.lastx("time_close"))) box.set_bottom(mybox3,_b3) box.set_top(mybox3,_t3) box.set_text(mybox3,b_info?"TF"+symbol_htf3+"="+htf3+"\n"+ f_time_ddhhmm(box.get_right(mybox3)-box.get_left(mybox3))+"\n"+ str.tostring(math.abs(box.get_top(mybox3)-box.get_bottom(mybox3))):na) //box htf4 var mybox4=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na) var a_tl_resistance4=array.new_line(0,na) var a_tl_support4=array.new_line(0,na) i_peak_bottom4=H.peak_bottom(H.htf_is_up(m4),H.htf_last_is_up(m4)) top4= a_high4.lastx() top_time4= a_time_high4.lastx() bottom4= a_low4.lastx() bottom_time4= a_time_low4.lastx() c_box4=bottom_time4<top_time4?cBoxU4:cBoxD4 va4=bottom_time4<top_time4?text.align_top:text.align_bottom _h4 = array.from(int(top_time4),int(bottom_time4)) _v4 = array.from(top4,bottom4) _t4 = array.max(_v4) _b4 = array.min(_v4) _l4 = array.min(_h4) if show4 and i_renew4!=0 if b_TL_clear f_line_delete_all(a_tl_resistance4) f_line_delete_all(a_tl_support4) if array.size(a_tl_resistance4)>0 line.set_extend(array.last(a_tl_resistance4),extend.none) array.clear(a_tl_resistance4) if array.size(a_tl_support4)>0 line.set_extend(array.last(a_tl_support4),extend.none) array.clear(a_tl_support4) if not (_l4[1]==_l4 and (_b4[1]==_b4 or _t4[1]==_t4)) mybox4:=box.new(_l4,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox4,border_style=styleBox4, text_halign=text.align_right,text_valign=va4,text_size=infoSize,border_color=c_box4,text_color=cBoxT) else if show4 and i_peak_bottom4==1 and b_TL if (array.size(a_high4)>0) if array.size(a_tl_resistance4) if b_TL_obsolete f_line_delete_all(a_tl_resistance4) else line.set_style(array.last(a_tl_resistance4),line.style_dotted) line.set_extend(array.last(a_tl_resistance4),extend.none) line.set_color(array.last(a_tl_resistance4),cTLro) if a_high4.lastx()!=a_return_high4.lastx() array.push(a_tl_resistance4,line.new( a_time_high4.lastx(), a_high4.lastx(), a_time_return_high4.lastx(), a_return_high4.lastx(), xloc.bar_time,extend.right,cTLr,styleBox4,widthBox4)) else if show4 and i_peak_bottom4==-1 and b_TL if (array.size(a_low4)>0) if array.size(a_tl_support4) if b_TL_obsolete f_line_delete_all(a_tl_support4) else line.set_style(array.last(a_tl_support4),line.style_dotted) line.set_extend(array.last(a_tl_support4),extend.none) line.set_color(array.last(a_tl_support4),cTLso) if a_low4.lastx()!=a_return_low4.lastx() array.push(a_tl_support4,line.new( a_time_low4.lastx(), a_low4.lastx(), a_time_return_low4.lastx(), a_return_low4.lastx(), xloc.bar_time,extend.right,cTLs,styleBox4,widthBox4)) if show4 box.set_right(mybox4,int(m4.lastx("time_close"))) box.set_bottom(mybox4,_b4) box.set_top(mybox4,_t4) box.set_text(mybox4,b_info?"TF"+symbol_htf2+"="+htf4+"\n"+ f_time_ddhhmm(box.get_right(mybox4)-box.get_left(mybox4))+"\n"+ str.tostring(math.abs(box.get_top(mybox4)-box.get_bottom(mybox4))):na) // //fibonacci levels of higher boxes // var l_mybox1_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox1_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox2_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox2_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox3_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox3_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox4_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) var l_mybox4_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize,text.align_left) if show1 and b_fibo1 [_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox1),box.get_top(mybox1),close) label.set_xy(l_mybox1_rt,box.get_right(mybox1),_top) label.set_textcolor(l_mybox1_rt,c_box1) label.set_text(l_mybox1_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@"+symbol_htf1+htf1) label.set_xy(l_mybox1_rb,box.get_right(mybox1),_bottom) label.set_textcolor(l_mybox1_rb,c_box1) label.set_text(l_mybox1_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@"+symbol_htf1+htf1) if show2 and b_fibo2 [_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox2),box.get_top(mybox2),close) label.set_xy(l_mybox2_rt,box.get_right(mybox2),_top) label.set_textcolor(l_mybox2_rt,c_box2) label.set_text(l_mybox2_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@"+symbol_htf2+htf2) label.set_xy(l_mybox2_rb,box.get_right(mybox2),_bottom) label.set_textcolor(l_mybox2_rb,c_box2) label.set_text(l_mybox2_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@"+symbol_htf2+htf2) if show3 and b_fibo3 [_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox3),box.get_top(mybox3),close) label.set_xy(l_mybox3_rt,box.get_right(mybox3),_top) label.set_textcolor(l_mybox3_rt,c_box3) label.set_text(l_mybox3_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@"+symbol_htf3+htf3) label.set_xy(l_mybox3_rb,box.get_right(mybox3),_bottom) label.set_textcolor(l_mybox3_rb,c_box3) label.set_text(l_mybox3_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@"+symbol_htf3+htf3) if show4 and b_fibo4 [_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox4),box.get_top(mybox4),close) label.set_xy(l_mybox4_rt,box.get_right(mybox4),_top) label.set_textcolor(l_mybox4_rt,c_box4) label.set_text(l_mybox4_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@"+symbol_htf4+htf4) label.set_xy(l_mybox4_rb,box.get_right(mybox4),_bottom) label.set_textcolor(l_mybox4_rb,c_box4) label.set_text(l_mybox4_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@"+symbol_htf4+htf4) //***** //end of HighLowBox //***** //***** //HighLowBox RSI //***** group_HLBOX_rsi="HighLowBox RSI" spanRSI_1 = input.int(defval=9,minval=1,maxval=30,title="span1", inline="span", group=group_HLBOX_rsi) spanRSI_2 = input.int(defval=14,minval=1,maxval=30,title="span2", inline="span", group=group_HLBOX_rsi) b_RSIchange = input.bool(defval=true,title="dont plot same SIGNAL condition",group=group_HLBOX_rsi) group_HLBOX_rsi_caution="HighLowBox RSI caution" _cRSIi = input.color(defval=colorRSIi,title="only span1>=70 or only span1<=30",inline="top",group=group_HLBOX_rsi_caution) group_HLBOX_rsi_overbought="HighLowBox RSI overbought" _cRSIt1 = input.color(defval=colorRSIt1,title="both>=70 and span1>span2",inline="top",group=group_HLBOX_rsi_overbought) _cRSIt2 = input.color(defval=colorRSIt2,title="both>=70 and span1<span2",inline="top",group=group_HLBOX_rsi_overbought) _cRSIt3 = input.color(defval=colorRSIt3,title="span1<70",inline="top",group=group_HLBOX_rsi_overbought) group_HLBOX_rsi_oversold="HighLowBox RSI oversold" _cRSIb1 = input.color(defval=colorRSIb1,title="both<=30 and span1<span2",inline="top",group=group_HLBOX_rsi_oversold) _cRSIb2 = input.color(defval=colorRSIb2,title="both<=30 and span1>span2",inline="top",group=group_HLBOX_rsi_oversold) _cRSIb3 = input.color(defval=colorRSIb3,title="span1>30",inline="top",group=group_HLBOX_rsi_oversold) showRSI = input.bool(defval=true,title="use RSI in current TF",inline="tf",group=group_HLBOX_rsi) transRSI = input.int(defval=50,minval=0,maxval=99,title="transpar",inline="tf",group=group_HLBOX_rsi) cRSIi=color.new(_cRSIi,transRSI) cRSIt1=color.new(_cRSIt1,transRSI) cRSIt2=color.new(_cRSIt2,transRSI) cRSIt3=color.new(_cRSIt3,transRSI) cRSIb1=color.new(_cRSIb1,transRSI) cRSIb2=color.new(_cRSIb2,transRSI) cRSIb3=color.new(_cRSIb3,transRSI) showRSI1 = input.bool(defval=true,title="use RSI in Higher TF1",inline="tf1",group=group_HLBOX_rsi) transRSI1 = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="tf1",group=group_HLBOX_rsi) cRSI1i=color.new(_cRSIi,transRSI1) cRSI1t1=color.new(_cRSIt1,transRSI1) cRSI1t2=color.new(_cRSIt2,transRSI1) cRSI1t3=color.new(_cRSIt3,transRSI1) cRSI1b1=color.new(_cRSIb1,transRSI1) cRSI1b2=color.new(_cRSIb2,transRSI1) cRSI1b3=color.new(_cRSIb3,transRSI1) showRSI2 = input.bool(defval=true,title="use RSI in Higher TF2",inline="tf2",group=group_HLBOX_rsi) transRSI2 = input.int(defval=35,minval=0,maxval=99,title="transpar",inline="tf2",group=group_HLBOX_rsi) cRSI2i=color.new(_cRSIi,transRSI2) cRSI2t1=color.new(_cRSIt1,transRSI2) cRSI2t2=color.new(_cRSIt2,transRSI2) cRSI2t3=color.new(_cRSIt3,transRSI2) cRSI2b1=color.new(_cRSIb1,transRSI2) cRSI2b2=color.new(_cRSIb2,transRSI2) cRSI2b3=color.new(_cRSIb3,transRSI2) showRSI3 = input.bool(defval=true,title="use RSI in Higher TF3",inline="tf3",group=group_HLBOX_rsi) transRSI3 = input.int(defval=30,minval=0,maxval=99,title="transpar",inline="tf3",group=group_HLBOX_rsi) cRSI3i=color.new(_cRSIi,transRSI3) cRSI3t1=color.new(_cRSIt1,transRSI3) cRSI3t2=color.new(_cRSIt2,transRSI3) cRSI3t3=color.new(_cRSIt3,transRSI3) cRSI3b1=color.new(_cRSIb1,transRSI3) cRSI3b2=color.new(_cRSIb2,transRSI3) cRSI3b3=color.new(_cRSIb3,transRSI3) showRSI4 = input.bool(defval=true,title="use RSI in Higher TF4",inline="tf4",group=group_HLBOX_rsi) transRSI4 = input.int(defval=25,minval=0,maxval=99,title="transpar",inline="tf4",group=group_HLBOX_rsi) cRSI4i=color.new(_cRSIi,transRSI4) cRSI4t1=color.new(_cRSIt1,transRSI4) cRSI4t2=color.new(_cRSIt2,transRSI4) cRSI4t3=color.new(_cRSIt3,transRSI4) cRSI4b1=color.new(_cRSIb1,transRSI4) cRSI4b2=color.new(_cRSIb2,transRSI4) cRSI4b3=color.new(_cRSIb3,transRSI4) // //RSI // var int RSIt =70 var int RSIb =30 var RSIchange=false var l_RSI=label.new(na,na,yloc=yloc.price,style=label.style_none) s_RSI_1= show0 and showRSI?ta.rsi(src,spanRSI_1):na s_RSI_2= show0 and showRSI?ta.rsi(src,spanRSI_2):na b_RSI_70 = s_RSI_1>=RSIt or s_RSI_2>=RSIt b_RSI_30 = s_RSI_1<=RSIb or s_RSI_2<=RSIb cRSI= s_RSI_1==s_RSI_1[1] and s_RSI_2==s_RSI_2[1]?na: b_RSI_70? s_RSI_1>s_RSI_2? s_RSI_2<RSIt?cRSIi: cRSIt1: s_RSI_1<RSIt?cRSIt3: cRSIt2: b_RSI_30? s_RSI_1<s_RSI_2? s_RSI_2>RSIb?cRSIi: cRSIb1: s_RSI_1>RSIb?cRSIb3: cRSIb2:na RSIchange:=cRSI!=cRSI[1]?true:RSIchange RSIy=b_RSI_70? box.get_top(mybox): b_RSI_30?box.get_bottom(mybox):na RSIchange:=RSIy!=RSIy[1]?true:RSIchange if not na(RSIy) if RSIchange if l_RSI.get_x()==bar_index l_RSI.set_color(cRSI) else l_RSI:=label.new(bar_index,RSIy,textcolor=cRSI,color=cRSI,yloc=yloc.price,style=label.style_none) if b_RSI_70 l_RSI.set_style(label.style_label_down) else if b_RSI_30 l_RSI.set_style(label.style_label_up) //H1 s_RSI1_1= show1 and showRSI1?H.htf_rsi(htf1src,b_new_bar1,spanRSI_1):na s_RSI1_2= show1 and showRSI1?H.htf_rsi(htf1src,b_new_bar1,spanRSI_2):na b_RSI1_70 = s_RSI1_1>=RSIt or s_RSI1_2>=RSIt b_RSI1_30 = s_RSI1_1<=RSIb or s_RSI1_2<=RSIb cRSI1= s_RSI1_1==s_RSI1_1[1] and s_RSI1_2==s_RSI1_2[1]?na: b_RSI1_70? s_RSI1_1>s_RSI1_2? s_RSI1_2<RSIt?cRSI1i: cRSI1t1: s_RSI1_1<RSIt?cRSI1t3: cRSI1t2: b_RSI1_30? s_RSI1_1<s_RSI1_2? s_RSI1_2>RSIb?cRSI1i: cRSI1b1: s_RSI1_1>RSIb?cRSI1b3: cRSI1b2:na RSI1y=b_RSI1_70? box.get_top(mybox1): b_RSI1_30?box.get_bottom(mybox1):na plotchar(b_RSIchange?ta.change(RSI1y)?RSI1y: cRSI1!=cRSI1[1]?RSI1y: b_new_bar1?RSI1y: na:RSI1y,"SIG_RSI1",char=symbol_htf1,location=location.absolute,color=cRSI1,size=size.small,text=" ΒΉ",textcolor=cRSI1) //l_RSI1=label.new(bar_index,b_RSIchange?ta.change(RSI1y)?RSI1y: cRSI1!=cRSI1[1]?RSI1y: b_new_bar1?RSI1y: na:RSI1y,symbol_htf1,textcolor=cRSI1,color=color.new(cRSI1,99),yloc=yloc.price,style=label.style_label_center,size=size.huge) //if b_RSI1_70 // l_RSI1.set_style(label.style_label_right) //else if b_RSI1_30 // l_RSI1.set_style(label.style_label_right) //H2 s_RSI2_1= show2 and showRSI2?H.htf_rsi(htf2src,b_new_bar2,spanRSI_1):na s_RSI2_2= show2 and showRSI2?H.htf_rsi(htf2src,b_new_bar2,spanRSI_2):na b_RSI2_70 = s_RSI2_1>=RSIt or s_RSI2_2>=RSIt b_RSI2_30 = s_RSI2_1<=RSIb or s_RSI2_2<=RSIb cRSI2= s_RSI2_1==s_RSI2_1[1] and s_RSI2_2==s_RSI2_2[1]?na: b_RSI2_70? s_RSI2_1>s_RSI2_2? s_RSI2_2<RSIt?cRSI2i: cRSI2t1: s_RSI2_1<RSIt?cRSI2t3: cRSI2t2: b_RSI2_30? s_RSI2_1<s_RSI2_2? s_RSI2_2>RSIb?cRSI2i: cRSI2b1: s_RSI2_1>RSIb?cRSI2b3: cRSI2b2:na RSI2y=b_RSI2_70? box.get_top(mybox2): b_RSI2_30?box.get_bottom(mybox2):na plotchar(b_RSIchange?ta.change(RSI2y)?RSI2y: cRSI2!=cRSI2[1]?RSI2y: b_new_bar2?RSI2y: na:RSI2y,"SIG_RSI2",char=symbol_htf2,location=location.absolute,color=cRSI2,textcolor=cRSI2,size=size.small,text=" β‚‚") //l_RSI2=label.new(bar_index,b_RSIchange?ta.change(RSI2y)?RSI2y: cRSI2!=cRSI2[1]?RSI2y: b_new_bar2?RSI2y: na:RSI2y,symbol_htf2,textcolor=cRSI2,color=color.new(cRSI2,99),yloc=yloc.price,style=label.style_label_center,size=size.huge) //if b_RSI2_70 // l_RSI2.set_style(label.style_label_down) //else if b_RSI2_30 // l_RSI2.set_style(label.style_label_up) //H3 s_RSI3_1= show3 and showRSI3?H.htf_rsi(htf3src,b_new_bar3,spanRSI_1):na s_RSI3_2= show3 and showRSI3?H.htf_rsi(htf3src,b_new_bar3,spanRSI_2):na b_RSI3_70 = s_RSI3_1>=RSIt or s_RSI3_2>=RSIt b_RSI3_30 = s_RSI3_1<=RSIb or s_RSI3_2<=RSIb cRSI3= s_RSI3_1==s_RSI3_1[1] and s_RSI3_2==s_RSI3_2[1]?na: b_RSI3_70? s_RSI3_1>s_RSI3_2? s_RSI3_2<RSIt?cRSI3i: cRSI3t1: s_RSI3_1<RSIt?cRSI3t3: cRSI3t2: b_RSI3_30? s_RSI3_1<s_RSI3_2? s_RSI3_2>RSIb?cRSI3i: cRSI3b1: s_RSI3_1>RSIb?cRSI3b3: cRSI3b2:na RSI3y=b_RSI3_70? box.get_top(mybox3): b_RSI3_30?box.get_bottom(mybox3):na plotchar(b_RSIchange?ta.change(RSI3y)?RSI3y: cRSI3!=cRSI3[1]?RSI3y: b_new_bar3?RSI3y: na:RSI3y,"SIG_RSI3",char=symbol_htf3,location=location.absolute,color=cRSI3,textcolor=cRSI3,size=size.small,text="₃") //l_RSI3=label.new(bar_index,b_RSIchange?ta.change(RSI3y)?RSI3y: cRSI3!=cRSI3[1]?RSI3y: b_new_bar3?RSI3y: na:RSI3y,symbol_htf3,textcolor=cRSI3,color=color.new(cRSI3,99),yloc=yloc.price,style=label.style_label_center,size=size.huge) //if b_RSI3_70 // l_RSI3.set_style(label.style_label_down) //else if b_RSI3_30 // l_RSI3.set_style(label.style_label_up) //H4 s_RSI4_1= show4 and showRSI4?H.htf_rsi(htf4src,b_new_bar4,spanRSI_1):na s_RSI4_2= show4 and showRSI4?H.htf_rsi(htf4src,b_new_bar4,spanRSI_2):na b_RSI4_70 = s_RSI4_1>=RSIt or s_RSI4_2>=RSIt b_RSI4_30 = s_RSI4_1<=RSIb or s_RSI4_2<=RSIb cRSI4= s_RSI4_1==s_RSI4_1[1] and s_RSI4_2==s_RSI4_2[1]?na: b_RSI4_70? s_RSI4_1>s_RSI4_2? s_RSI4_2<RSIt?cRSI4i: cRSI4t1: s_RSI4_1<RSIt?cRSI4t3: cRSI4t2: b_RSI4_30? s_RSI4_1<s_RSI4_2? s_RSI4_2>RSIb?cRSI4i: cRSI4b1: s_RSI4_1>RSIb?cRSI4b3: cRSI4b2:na RSI4y=b_RSI4_70? box.get_top(mybox4): b_RSI4_30?box.get_bottom(mybox4):na plotchar(b_RSIchange?ta.change(RSI4y)?RSI4y: cRSI4!=cRSI4[1]?RSI4y: b_new_bar4?RSI4y: na:RSI4y,"SIG_RSI4",char=symbol_htf4,location=location.absolute,color=cRSI4,textcolor=cRSI4,size=size.small,text="⁴") //l_RSI4=label.new(bar_index,b_RSIchange?ta.change(RSI4y)?RSI4y: cRSI4!=cRSI4[1]?RSI4y: b_new_bar4?RSI4y: na:RSI4y,symbol_htf4,textcolor=cRSI4,color=color.new(cRSI3,99),yloc=yloc.price,style=label.style_label_center,size=size.huge) //if b_RSI4_70 // l_RSI4.set_style(label.style_label_down) //else if b_RSI4_30 // l_RSI4.set_style(label.style_label_up) //***** //end of HighLowBox RSI //***** //***** //MAs //***** var spanS = 20 var spanL = 200 string limit200 = "3M" group_MA="20/200 MAs(sma/ema)" span1MA = input.int(defval=spanS,minval=1,maxval=200,title="span1",inline="span",group=group_MA) span2MA = input.int(defval=spanL,minval=1,maxval=200,title="span2",inline="span",group=group_MA) _cSMA = input.color(defval=colorSMA,title="SMA",inline="color",group=group_MA) _cEMA = input.color(defval=colorEMA,title="EMA",inline="color",group=group_MA) b_MAlabel = input.bool(defval=true,title="show MA label",inline="MA",group=group_MA) b_MAinfo = input.bool(defval=false,title="show MA info",inline="MA",group=group_MA) b_MAlimit = input.bool(defval=true,title="dont show SPAN2 MA if tf>",inline="MAlim",group=group_MA) _limit200 = input.timeframe(defval=t13, title="", options=[t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15],inline="MAlim",group=group_MA) limit200:=b_MAlimit?_limit200:"0S" b_MA = input.bool(defval=true,title="CTF",inline="ctf",group=group_MA) _transMA = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="ctf",group=group_MA) cSMA=color.new(_cSMA,_transMA) cEMA=color.new(_cEMA,_transMA) labeloffset = input.int(defval=10,minval=0,maxval=50,title="labeloffset",inline="ctf",group=group_MA) widthMAs = input.int(defval=1,minval=1,maxval=4,title="SPAN1:width",inline="ctf",group=group_MA) _styleMAs = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="ctf",group=group_MA) styleMAs = f_plotstyle(_styleMAs) widthMAl = input.int(defval=1,minval=1,maxval=4,title="SPAN2:width",inline="ctf",group=group_MA) _styleMAl = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="ctf",group=group_MA) styleMAl = f_plotstyle(_styleMAl) b_MA1 = input.bool(defval=true,title="HTF1",inline="htf1",group=group_MA) _transMA1 = input.int(defval=30,minval=0,maxval=99,title="transpar",inline="htf1",group=group_MA) cSMA1=color.new(_cSMA,_transMA1) cEMA1=color.new(_cEMA,_transMA1) labeloffset1 = input.int(defval=13,minval=0,maxval=50,title="labeloffset",inline="htf1",group=group_MA) widthMA1s = input.int(defval=2,minval=1,maxval=4,title="SPAN1:width",inline="htf1",group=group_MA) _styleMA1s = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf1",group=group_MA) styleMA1s = f_plotstyle(_styleMA1s) widthMA1l = input.int(defval=2,minval=1,maxval=4,title="SPAN2:width",inline="htf1",group=group_MA) _styleMA1l = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf1",group=group_MA) styleMA1l = f_plotstyle(_styleMA1l) b_MA2 = input.bool(defval=true,title="HTF2",inline="htf2",group=group_MA) _transMA2 = input.int(defval=20,minval=0,maxval=99,title="transpar",inline="htf2",group=group_MA) cSMA2=color.new(_cSMA,_transMA2) cEMA2=color.new(_cEMA,_transMA2) labeloffset2 = input.int(defval=16,minval=0,maxval=50,title="labeloffset",inline="htf2",group=group_MA) widthMA2s = input.int(defval=3,minval=1,maxval=4,title="SPAN1:width",inline="htf2",group=group_MA) _styleMA2s = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf2",group=group_MA) styleMA2s = f_plotstyle(_styleMA2s) widthMA2l = input.int(defval=3,minval=1,maxval=4,title="SPAN2:width",inline="htf2",group=group_MA) _styleMA2l = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf2",group=group_MA) styleMA2l = f_plotstyle(_styleMA2l) b_MA3 = input.bool(defval=true,title="HTF3",inline="htf3",group=group_MA) _transMA3 = input.int(defval=30,minval=0,maxval=99,title="transpar",inline="htf3",group=group_MA) cSMA3=color.new(_cSMA,_transMA3) cEMA3=color.new(_cEMA,_transMA3) labeloffset3 = input.int(defval=19,minval=0,maxval=50,title="labeloffset",inline="htf3",group=group_MA) widthMA3s = input.int(defval=4,minval=1,maxval=4,title="SPAN1:width",inline="htf3",group=group_MA) _styleMA3s = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf3",group=group_MA) styleMA3s = f_plotstyle(_styleMA3s) widthMA3l = input.int(defval=4,minval=1,maxval=4,title="SPAN2:width",inline="htf3",group=group_MA) _styleMA3l = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf3",group=group_MA) styleMA3l = f_plotstyle(_styleMA3l) b_MA4 = input.bool(defval=true,title="HTF4",inline="htf4",group=group_MA) _transMA4 = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="htf4",group=group_MA) cSMA4=color.new(_cSMA,_transMA4) cEMA4=color.new(_cEMA,_transMA4) labeloffset4 = input.int(defval=22,minval=0,maxval=50,title="labeloffset",inline="htf4",group=group_MA) widthMA4s = input.int(defval=4,minval=1,maxval=4,title="SPAN1:width",inline="htf4",group=group_MA) _styleMA4s = input.string(defval=ps07,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf4",group=group_MA) styleMA4s = f_plotstyle(_styleMA4s) widthMA4l = input.int(defval=4,minval=1,maxval=4,title="SPAN2:width",inline="htf4",group=group_MA) _styleMA4l = input.string(defval=ps09,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="htf4",group=group_MA) styleMA4l = f_plotstyle(_styleMA4l) //200MA s_200SMA = b_MA and b_tfgt(limit200,tfChart)?ta.sma(src,span2MA):na s_200EMA = b_MA and b_tfgt(limit200,tfChart)?ta.ema(src,span2MA):na //20MA s_20SMA = b_MA?ta.sma(src,span1MA):na s_20EMA = b_MA?ta.ema(src,span1MA):na //Higher s_200SMA1 = b_MA1 and b_tfgt(limit200,tfChart)?H.htf_sma(htf1src,span2MA):na s_200EMA1 = b_MA1 and b_tfgt(limit200,tfChart)?H.htf_ema(htf1src,b_new_bar1,span2MA):na s_20SMA1 = b_MA1?H.htf_sma(htf1src,span1MA):na s_20EMA1 = b_MA1?H.htf_ema(htf1src,b_new_bar1,span1MA):na s_200SMA2 = b_MA2 and b_tfgt(limit200,tfChart)?H.htf_sma(htf2src,span2MA):na s_200EMA2 = b_MA2 and b_tfgt(limit200,tfChart)?H.htf_ema(htf2src,b_new_bar2,span2MA):na s_20SMA2 = b_MA2?H.htf_sma(htf2src,span1MA):na s_20EMA2 = b_MA2?H.htf_ema(htf2src,b_new_bar2,span1MA):na s_200SMA3 = b_MA3 and b_tfgt(limit200,tfChart)?H.htf_sma(htf3src,span2MA):na s_200EMA3 = b_MA3 and b_tfgt(limit200,tfChart)?H.htf_ema(htf3src,b_new_bar3,span2MA):na s_20SMA3 = b_MA3?H.htf_sma(htf3src,span1MA):na s_20EMA3 = b_MA3?H.htf_ema(htf3src,b_new_bar3,span1MA):na s_200SMA4 = b_MA4 and b_tfgt(limit200,tfChart)?H.htf_sma(htf4src,span2MA):na s_200EMA4 = b_MA4 and b_tfgt(limit200,tfChart)?H.htf_ema(htf4src,b_new_bar4,span2MA):na s_20SMA4 = b_MA4?H.htf_sma(htf4src,span1MA):na s_20EMA4 = b_MA4?H.htf_ema(htf4src,b_new_bar4,span1MA):na //plot MAs plot(s_20SMA,linewidth=widthMAs,style=styleMAs,color=cSMA,title="SMA20") label_20SMA = f_ma_label(b_MAlabel?s_20SMA:na,labeloffset,tfChart,span1MA,"SMA",cSMA,b_MAinfo) label.delete(label_20SMA[1]) plot(s_20EMA,linewidth=widthMAs,style=styleMAs,color=cEMA,title="EMA20") label_20EMA = f_ma_label(b_MAlabel?s_20EMA:na,labeloffset,tfChart,span1MA,"EMA",cEMA,b_MAinfo) label.delete(label_20EMA[1]) plot(s_200SMA,linewidth=widthMAl,style=styleMAl,color=cSMA,title="SMA200") label_200SMA = f_ma_label(b_MAlabel?s_200SMA:na,labeloffset,tfChart,span2MA,"SMA",cSMA,b_MAinfo) label.delete(label_200SMA[1]) plot(s_200EMA,linewidth=widthMAl,style=styleMAl,color=cEMA,title="EMA200") label_200EMA = f_ma_label(b_MAlabel?s_200EMA:na,labeloffset,tfChart,span2MA,"EMA",cEMA,b_MAinfo) label.delete(label_200EMA[1]) //plot higher1 plot(s_20SMA1,linewidth=widthMA1s,style=styleMA1s,color=cSMA,title="SMA20htf1") label_20SMA1 = f_ma_label(b_MAlabel?s_20SMA1:na,labeloffset1,symbol_htf1+htf1,span1MA,"SMA",cSMA1,b_MAinfo) label.delete(label_20SMA1[1]) plot(s_20EMA1,linewidth=widthMA1s,style=styleMA1s,color=cEMA,title="EMA20htf1") label_20EMA1 = f_ma_label(b_MAlabel?s_20EMA1:na,labeloffset1,symbol_htf1+htf1,span1MA,"EMA",cEMA1,b_MAinfo) label.delete(label_20EMA1[1]) plot(s_200SMA1,linewidth=widthMA1l,style=styleMA1l,color=cSMA,title="SMA200htf1") label_200SMA1 = f_ma_label(b_MAlabel?s_200SMA1:na,labeloffset1,symbol_htf1+htf1,span2MA,"SMA",cSMA1,b_MAinfo) label.delete(label_200SMA1[1]) plot(s_200EMA1,linewidth=widthMA1l,style=styleMA1l,color=cEMA,title="EMA200htf1") label_200EMA1 = f_ma_label(b_MAlabel?s_200EMA1:na,labeloffset1,symbol_htf1+htf1,span2MA,"EMA",cEMA1,b_MAinfo) label.delete(label_200EMA1[1]) //plot higher2 plot(s_20SMA2,linewidth=widthMA2s,style=styleMA2s,color=cSMA,title="SMA20htf2") label_20SMA2 = f_ma_label(b_MAlabel?s_20SMA2:na,labeloffset2,symbol_htf2+htf2,span1MA,"SMA",cSMA2,b_MAinfo) label.delete(label_20SMA2[1]) plot(s_20EMA2,linewidth=widthMA2s,style=styleMA2s,color=cEMA,title="EMA20htf2") label_20EMA2 = f_ma_label(b_MAlabel?s_20EMA2:na,labeloffset2,symbol_htf2+htf2,span1MA,"EMA",cEMA2,b_MAinfo) label.delete(label_20EMA2[1]) plot(s_200SMA2,linewidth=widthMA2l,style=styleMA2l,color=cSMA,title="SMA200htf2") label_200SMA2 = f_ma_label(b_MAlabel?s_200SMA2:na,labeloffset2,symbol_htf2+htf2,span2MA,"SMA",cSMA2,b_MAinfo) label.delete(label_200SMA2[1]) plot(s_200EMA2,linewidth=widthMA2l,style=styleMA2l,color=cEMA,title="EMA200htf2") label_200EMA2 = f_ma_label(b_MAlabel?s_200EMA2:na,labeloffset2,symbol_htf2+htf2,span2MA,"EMA",cEMA2,b_MAinfo) label.delete(label_200EMA2[1]) //plot higher3 plot(s_20SMA3,linewidth=widthMA3s,style=styleMA2s,color=cSMA,title="SMA20htf3") label_20SMA3 = f_ma_label(b_MAlabel?s_20SMA3:na,labeloffset3,symbol_htf3+htf3,span1MA,"SMA",cSMA3,b_MAinfo) label.delete(label_20SMA3[1]) plot(s_20EMA3,linewidth=widthMA3s,style=styleMA2s,color=cEMA,title="EMA20htf3") label_20EMA3 = f_ma_label(b_MAlabel?s_20EMA3:na,labeloffset3,symbol_htf3+htf3,span1MA,"EMA",cEMA3,b_MAinfo) label.delete(label_20EMA3[1]) plot(s_200SMA3,linewidth=widthMA3l,style=styleMA2l,color=cSMA,title="SMA200htf3") label_200SMA3 = f_ma_label(b_MAlabel?s_200SMA3:na,labeloffset3,symbol_htf3+htf3,span2MA,"SMA",cSMA3,b_MAinfo) label.delete(label_200SMA3[1]) plot(s_200EMA3,linewidth=widthMA3l,style=styleMA2l,color=cEMA,title="EMA200htf3") label_200EMA3 = f_ma_label(b_MAlabel?s_200EMA3:na,labeloffset3,symbol_htf3+htf3,span2MA,"EMA",cEMA3,b_MAinfo) label.delete(label_200EMA3[1]) //plot higher4 plot(s_20SMA4,linewidth=widthMA4s,style=styleMA2s,color=cSMA,title="SMA20htf4") label_20SMA4 = f_ma_label(b_MAlabel?s_20SMA4:na,labeloffset4,symbol_htf4+htf4,span1MA,"SMA",cSMA4,b_MAinfo) label.delete(label_20SMA4[1]) plot(s_20EMA4,linewidth=widthMA4s,style=styleMA2s,color=cEMA,title="EMA20htf4") label_20EMA4 = f_ma_label(b_MAlabel?s_20EMA4:na,labeloffset4,symbol_htf4+htf4,span1MA,"EMA",cEMA4,b_MAinfo) label.delete(label_20EMA4[1]) plot(s_200SMA4,linewidth=widthMA4l,style=styleMA2l,color=cSMA,title="SMA200htf4") label_200SMA4 = f_ma_label(b_MAlabel?s_200SMA4:na,labeloffset4,symbol_htf4+htf4,span2MA,"SMA",cSMA4,b_MAinfo) label.delete(label_200SMA4[1]) plot(s_200EMA4,linewidth=widthMA4l,style=styleMA2l,color=cEMA,title="EMA200htf4") label_200EMA4 = f_ma_label(b_MAlabel?s_200EMA4:na,labeloffset4,symbol_htf4+htf4,span2MA,"EMA",cEMA4,b_MAinfo) label.delete(label_200EMA4[1]) //***** //end of MAs //***** //***** //draw fake candle //***** //βžŠβž‹βžŒβž var range1=box.new(na,na,na,na,bgcolor=na,border_width=widthBox1,border_style=styleBox1,text_size=infoSize,text_color=cBoxT) var range2=box.new(na,na,na,na,bgcolor=na,border_width=widthBox2,border_style=styleBox2,text_size=infoSize,text_color=cBoxT) var range3=box.new(na,na,na,na,bgcolor=na,border_width=widthBox3,border_style=styleBox3,text_size=infoSize,text_color=cBoxT) var range4=box.new(na,na,na,na,bgcolor=na,border_width=widthBox4,border_style=styleBox4,text_size=infoSize,text_color=cBoxT) if b_fake_candle _cu=color.new(cCandleU,trans_candle) _cd=color.new(cCandleD,trans_candle) _o = i_offset_candle _cw=3 _x = bar_index+40 [mybody4_2,mywicka4_2,mywickb4_2] = f_draw_candle_barindex(m4.lastx("open",2),m4.lastx("close",2),m4.lastx("high",2),m4.lastx("low",2),_o,_x,symbol_htf4+"\n"+htf4,_cu,_cd,cCandleT) box.delete(mybody4_2[1]) line.delete(mywicka4_2[1]) line.delete(mywickb4_2[1]) [mybody4_1,mywicka4_1,mywickb4_1] = f_draw_candle_barindex(m4.lastx("open",1),m4.lastx("close",1),m4.lastx("high",1),m4.lastx("low",1),_o,_x+_cw,symbol_htf4+"\n"+htf4,_cu,_cd,cCandleT) box.delete(mybody4_1[1]) line.delete(mywicka4_1[1]) line.delete(mywickb4_1[1]) [mybody4,mywicka4,mywickb4] = f_draw_candle_barindex(m4.lastx("open"),m4.lastx("close"),m4.lastx("high"),m4.lastx("low"),_o,_x+_cw*2,symbol_htf4+"\n"+htf4,_cu,_cd,cCandleT) box.delete(mybody4[1]) line.delete(mywicka4[1]) line.delete(mywickb4[1]) range4.set_lefttop(_o+_x-1,box.get_top(mybox4)) range4.set_rightbottom(_o+_x+_cw*3,box.get_bottom(mybox4)) range4.set_border_color(c_box4) _x := bar_index+30 [mybody3_2,mywicka3_2,mywickb3_2] = f_draw_candle_barindex(m3.lastx("open",2),m3.lastx("close",2),m3.lastx("high",2),m3.lastx("low",2),_o,_x,symbol_htf3+"\n"+htf3,_cu,_cd,cCandleT) box.delete(mybody3_2[1]) line.delete(mywicka3_2[1]) line.delete(mywickb3_2[1]) [mybody3_1,mywicka3_1,mywickb3_1] = f_draw_candle_barindex(m3.lastx("open",1),m3.lastx("close",1),m3.lastx("high",1),m3.lastx("low",1),_o,_x+_cw,symbol_htf3+"\n"+htf3,_cu,_cd,cCandleT) box.delete(mybody3_1[1]) line.delete(mywicka3_1[1]) line.delete(mywickb3_1[1]) [mybody3,mywick3a,mywick3b] = f_draw_candle_barindex(m3.lastx("open"),m3.lastx("close"),m3.lastx("high"),m3.lastx("low"),_o,_x+_cw*2,symbol_htf3+"\n"+htf3,_cu,_cd,cCandleT) box.delete(mybody3[1]) line.delete(mywick3a[1]) line.delete(mywick3b[1]) range3.set_lefttop(_o+_x-1,box.get_top(mybox3)) range3.set_rightbottom(_o+_x+_cw*3,box.get_bottom(mybox3)) range3.set_border_color(c_box3) _x := bar_index+20 [mybody2_2,mywicka2_2,mywickb2_2] = f_draw_candle_barindex(m2.lastx("open",2),m2.lastx("close",2),m2.lastx("high",2),m2.lastx("low",2),_o,_x,symbol_htf2+"\n"+htf2,_cu,_cd,cCandleT) box.delete(mybody2_2[1]) line.delete(mywicka2_2[1]) line.delete(mywickb2_2[1]) [mybody2_1,mywicka2_1,mywickb2_1] = f_draw_candle_barindex(m2.lastx("open",1),m2.lastx("close",1),m2.lastx("high",1),m2.lastx("low",1),_o,_x+_cw,symbol_htf2+"\n"+htf2,_cu,_cd,cCandleT) box.delete(mybody2_1[1]) line.delete(mywicka2_1[1]) line.delete(mywickb2_1[1]) [mybody2,mywick2a,mywick2b] = f_draw_candle_barindex(m2.lastx("open"),m2.lastx("close"),m2.lastx("high"),m2.lastx("low"),_o,_x+_cw*2,symbol_htf2+"\n"+htf2,_cu,_cd,cCandleT) box.delete(mybody2[1]) line.delete(mywick2a[1]) line.delete(mywick2b[1]) range2.set_lefttop(_o+_x-1,box.get_top(mybox2)) range2.set_rightbottom(_o+_x+_cw*3,box.get_bottom(mybox2)) range2.set_border_color(c_box2) _x := bar_index+10 [mybody1_2,mywicka1_2,mywickb1_2] = f_draw_candle_barindex(m1.lastx("open",2),m1.lastx("close",2),m1.lastx("high",2),m1.lastx("low",2),_o,_x,symbol_htf1+"\n"+htf1,_cu,_cd,cCandleT) box.delete(mybody1_2[1]) line.delete(mywicka1_2[1]) line.delete(mywickb1_2[1]) [mybody1_1,mywicka1_1,mywickb1_1] = f_draw_candle_barindex(m1.lastx("open",1),m1.lastx("close",1),m1.lastx("high",1),m1.lastx("low",1),_o,_x+_cw,symbol_htf1+"\n"+htf1,_cu,_cd,cCandleT) box.delete(mybody1_1[1]) line.delete(mywicka1_1[1]) line.delete(mywickb1_1[1]) [mybody1,mywick1a,mywick1b] = f_draw_candle_barindex(m1.lastx("open"),m1.lastx("close"),m1.lastx("high"),m1.lastx("low"),_o,_x+_cw*2,symbol_htf1+"\n"+htf1,_cu,_cd,cCandleT) box.delete(mybody1[1]) line.delete(mywick1a[1]) line.delete(mywick1b[1]) range1.set_lefttop(_o+_x-1,box.get_top(mybox1)) range1.set_rightbottom(_o+_x+_cw*3,box.get_bottom(mybox1)) range1.set_border_color(c_box1) //***** //end of draw fake candle //***** //***** //DMI //***** width_bar_time=timeframe.in_seconds()*1000 f_map2box(float val,box boxid)=> _base=boxid.get_bottom() _top=boxid.get_top() _diff = _top-_base _y = _base + _diff*val/100 f_line_set_xyz(line lineid,int offset,float val1,float val2) => lineid.set_xy1(offset-1,val1) lineid.set_xy2(offset,val2) [di9,_di9,adx9]=ta.dmi(9,9) [di14,_di14,adx14]=ta.dmi(14,14) var adxline1=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline2=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline3=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline4=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline5=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline6=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline7=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var adxline8=line.new(na,na,na,na,color=cADX,xloc=xloc.bar_time,style=line.style_arrow_right) var diline1=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline2=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline3=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline4=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline5=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline6=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline7=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var diline8=line.new(na,na,na,na,color=cDI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline1=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline2=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline3=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline4=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline5=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline6=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline7=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var _diline8=line.new(na,na,na,na,color=c_DI,xloc=xloc.bar_time,style=line.style_arrow_right) var dmibox=box.new(na,na,na,na,border_color=na,bgcolor=color.new(color.yellow,90),xloc=xloc.bar_time,text="DMI",text_color=cBoxT,text_size=size.normal) if b_DMI dmibox.set_lefttop(box.get_left(mybox)-width_bar_time*8,box.get_top(mybox)) dmibox.set_rightbottom(box.get_left(mybox),box.get_bottom(mybox)) adxline1.set_xy1(box.get_left(mybox)-width_bar_time,f_map2box(adx14,mybox)) adxline1.set_xy2(box.get_left(mybox),f_map2box(adx9,mybox)) adxline2.set_xy1(box.get_left(mybox)-width_bar_time*2,f_map2box(adx14[1],mybox)) adxline2.set_xy2(box.get_left(mybox)-width_bar_time,f_map2box(adx9[1],mybox)) adxline3.set_xy1(box.get_left(mybox)-width_bar_time*3,f_map2box(adx14[2],mybox)) adxline3.set_xy2(box.get_left(mybox)-width_bar_time*2,f_map2box(adx9[2],mybox)) adxline4.set_xy1(box.get_left(mybox)-width_bar_time*4,f_map2box(adx14[3],mybox)) adxline4.set_xy2(box.get_left(mybox)-width_bar_time*3,f_map2box(adx9[3],mybox)) adxline5.set_xy1(box.get_left(mybox)-width_bar_time*5,f_map2box(adx14[4],mybox)) adxline5.set_xy2(box.get_left(mybox)-width_bar_time*4,f_map2box(adx9[4],mybox)) adxline6.set_xy1(box.get_left(mybox)-width_bar_time*6,f_map2box(adx14[5],mybox)) adxline6.set_xy2(box.get_left(mybox)-width_bar_time*5,f_map2box(adx9[5],mybox)) adxline7.set_xy1(box.get_left(mybox)-width_bar_time*7,f_map2box(adx14[6],mybox)) adxline7.set_xy2(box.get_left(mybox)-width_bar_time*6,f_map2box(adx9[6],mybox)) adxline8.set_xy1(box.get_left(mybox)-width_bar_time*8,f_map2box(adx14[7],mybox)) adxline8.set_xy2(box.get_left(mybox)-width_bar_time*7,f_map2box(adx9[7],mybox)) diline1.set_xy1(box.get_left(mybox)-width_bar_time,f_map2box(di14,mybox)) diline1.set_xy2(box.get_left(mybox),f_map2box(di9,mybox)) diline2.set_xy1(box.get_left(mybox)-width_bar_time*2,f_map2box(di14[1],mybox)) diline2.set_xy2(box.get_left(mybox)-width_bar_time,f_map2box(di9[1],mybox)) diline3.set_xy1(box.get_left(mybox)-width_bar_time*3,f_map2box(di14[2],mybox)) diline3.set_xy2(box.get_left(mybox)-width_bar_time*2,f_map2box(di9[2],mybox)) diline4.set_xy1(box.get_left(mybox)-width_bar_time*4,f_map2box(di14[3],mybox)) diline4.set_xy2(box.get_left(mybox)-width_bar_time*3,f_map2box(di9[3],mybox)) diline5.set_xy1(box.get_left(mybox)-width_bar_time*5,f_map2box(di14[4],mybox)) diline5.set_xy2(box.get_left(mybox)-width_bar_time*4,f_map2box(di9[4],mybox)) diline6.set_xy1(box.get_left(mybox)-width_bar_time*6,f_map2box(di14[5],mybox)) diline6.set_xy2(box.get_left(mybox)-width_bar_time*5,f_map2box(di9[5],mybox)) diline7.set_xy1(box.get_left(mybox)-width_bar_time*7,f_map2box(di14[6],mybox)) diline7.set_xy2(box.get_left(mybox)-width_bar_time*6,f_map2box(di9[6],mybox)) diline8.set_xy1(box.get_left(mybox)-width_bar_time*8,f_map2box(di14[7],mybox)) diline8.set_xy2(box.get_left(mybox)-width_bar_time*7,f_map2box(di9[7],mybox)) _diline1.set_xy1(box.get_left(mybox)-width_bar_time,f_map2box(_di14,mybox)) _diline1.set_xy2(box.get_left(mybox),f_map2box(_di9,mybox)) _diline2.set_xy1(box.get_left(mybox)-width_bar_time*2,f_map2box(_di14[1],mybox)) _diline2.set_xy2(box.get_left(mybox)-width_bar_time,f_map2box(_di9[1],mybox)) _diline3.set_xy1(box.get_left(mybox)-width_bar_time*3,f_map2box(_di14[2],mybox)) _diline3.set_xy2(box.get_left(mybox)-width_bar_time*2,f_map2box(_di9[2],mybox)) _diline4.set_xy1(box.get_left(mybox)-width_bar_time*4,f_map2box(_di14[3],mybox)) _diline4.set_xy2(box.get_left(mybox)-width_bar_time*3,f_map2box(_di9[3],mybox)) _diline5.set_xy1(box.get_left(mybox)-width_bar_time*5,f_map2box(_di14[4],mybox)) _diline5.set_xy2(box.get_left(mybox)-width_bar_time*4,f_map2box(_di9[4],mybox)) _diline6.set_xy1(box.get_left(mybox)-width_bar_time*6,f_map2box(_di14[5],mybox)) _diline6.set_xy2(box.get_left(mybox)-width_bar_time*5,f_map2box(_di9[5],mybox)) _diline7.set_xy1(box.get_left(mybox)-width_bar_time*7,f_map2box(_di14[6],mybox)) _diline7.set_xy2(box.get_left(mybox)-width_bar_time*6,f_map2box(_di9[6],mybox)) _diline8.set_xy1(box.get_left(mybox)-width_bar_time*8,f_map2box(_di14[7],mybox)) _diline8.set_xy2(box.get_left(mybox)-width_bar_time*7,f_map2box(_di9[7],mybox)) [di9_1,_di9_1,adx9_1]=H.htf_dmi(m1,b_new_bar1,9) [di14_1,_di14_1,adx14_1]=H.htf_dmi(m1,b_new_bar1,14) var a_adx9_1=array.new_float(0,na) var a_adx14_1=array.new_float(0,na) var a_di9_1=array.new_float(0,na) var a_di14_1=array.new_float(0,na) var a__di9_1=array.new_float(0,na) var a__di14_1=array.new_float(0,na) a_adx9_1.htf_push(b_new_bar1,adx9_1) a_adx14_1.htf_push(b_new_bar1,adx14_1) a_di9_1.htf_push(b_new_bar1,di9_1) a_di14_1.htf_push(b_new_bar1,di14_1) a__di9_1.htf_push(b_new_bar1,_di9_1) a__di14_1.htf_push(b_new_bar1,_di14_1) var adxline1_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline2_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline3_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline4_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline5_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline6_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline7_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var adxline8_1=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=1) var diline1_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline2_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline3_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline4_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline5_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline6_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline7_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var diline8_1=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=1) var _diline1_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline2_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline3_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline4_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline5_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline6_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline7_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) var _diline8_1=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=1) if b_DMI range1.set_text(symbol_htf1+"DMI") f_line_set_xyz(adxline1_1,box.get_right(range1)-1,f_map2box(a_adx14_1.lastx(),range1),f_map2box(a_adx9_1.lastx(),range1)) f_line_set_xyz(adxline2_1,box.get_right(range1)-2,f_map2box(a_adx14_1.lastx(1),range1),f_map2box(a_adx9_1.lastx(1),range1)) f_line_set_xyz(adxline3_1,box.get_right(range1)-3,f_map2box(a_adx14_1.lastx(2),range1),f_map2box(a_adx9_1.lastx(2),range1)) f_line_set_xyz(adxline4_1,box.get_right(range1)-4,f_map2box(a_adx14_1.lastx(3),range1),f_map2box(a_adx9_1.lastx(3),range1)) f_line_set_xyz(adxline5_1,box.get_right(range1)-5,f_map2box(a_adx14_1.lastx(4),range1),f_map2box(a_adx9_1.lastx(4),range1)) f_line_set_xyz(adxline6_1,box.get_right(range1)-6,f_map2box(a_adx14_1.lastx(5),range1),f_map2box(a_adx9_1.lastx(5),range1)) f_line_set_xyz(adxline7_1,box.get_right(range1)-7,f_map2box(a_adx14_1.lastx(6),range1),f_map2box(a_adx9_1.lastx(6),range1)) f_line_set_xyz(adxline8_1,box.get_right(range1)-8,f_map2box(a_adx14_1.lastx(7),range1),f_map2box(a_adx9_1.lastx(7),range1)) f_line_set_xyz(diline1_1,box.get_right(range1)-1,f_map2box(a_di14_1.lastx(),range1),f_map2box(a_di9_1.lastx(),range1)) f_line_set_xyz(diline2_1,box.get_right(range1)-2,f_map2box(a_di14_1.lastx(1),range1),f_map2box(a_di9_1.lastx(1),range1)) f_line_set_xyz(diline3_1,box.get_right(range1)-3,f_map2box(a_di14_1.lastx(2),range1),f_map2box(a_di9_1.lastx(2),range1)) f_line_set_xyz(diline4_1,box.get_right(range1)-4,f_map2box(a_di14_1.lastx(3),range1),f_map2box(a_di9_1.lastx(3),range1)) f_line_set_xyz(diline5_1,box.get_right(range1)-5,f_map2box(a_di14_1.lastx(4),range1),f_map2box(a_di9_1.lastx(4),range1)) f_line_set_xyz(diline6_1,box.get_right(range1)-6,f_map2box(a_di14_1.lastx(5),range1),f_map2box(a_di9_1.lastx(5),range1)) f_line_set_xyz(diline7_1,box.get_right(range1)-7,f_map2box(a_di14_1.lastx(6),range1),f_map2box(a_di9_1.lastx(6),range1)) f_line_set_xyz(diline8_1,box.get_right(range1)-8,f_map2box(a_di14_1.lastx(7),range1),f_map2box(a_di9_1.lastx(7),range1)) f_line_set_xyz(_diline1_1,box.get_right(range1)-1,f_map2box(a__di14_1.lastx(),range1),f_map2box(a__di9_1.lastx(),range1)) f_line_set_xyz(_diline2_1,box.get_right(range1)-2,f_map2box(a__di14_1.lastx(1),range1),f_map2box(a__di9_1.lastx(1),range1)) f_line_set_xyz(_diline3_1,box.get_right(range1)-3,f_map2box(a__di14_1.lastx(2),range1),f_map2box(a__di9_1.lastx(2),range1)) f_line_set_xyz(_diline4_1,box.get_right(range1)-4,f_map2box(a__di14_1.lastx(3),range1),f_map2box(a__di9_1.lastx(3),range1)) f_line_set_xyz(_diline5_1,box.get_right(range1)-5,f_map2box(a__di14_1.lastx(4),range1),f_map2box(a__di9_1.lastx(4),range1)) f_line_set_xyz(_diline6_1,box.get_right(range1)-6,f_map2box(a__di14_1.lastx(5),range1),f_map2box(a__di9_1.lastx(5),range1)) f_line_set_xyz(_diline7_1,box.get_right(range1)-7,f_map2box(a__di14_1.lastx(6),range1),f_map2box(a__di9_1.lastx(6),range1)) f_line_set_xyz(_diline8_1,box.get_right(range1)-8,f_map2box(a__di14_1.lastx(7),range1),f_map2box(a__di9_1.lastx(7),range1)) [di9_2,_di9_2,adx9_2]=H.htf_dmi(m2,b_new_bar2,9) [di14_2,_di14_2,adx14_2]=H.htf_dmi(m2,b_new_bar2,14) var a_adx9_2=array.new_float(0,na) var a_adx14_2=array.new_float(0,na) var a_di9_2=array.new_float(0,na) var a_di14_2=array.new_float(0,na) var a__di9_2=array.new_float(0,na) var a__di14_2=array.new_float(0,na) a_adx9_2.htf_push(b_new_bar2,adx9_2) a_adx14_2.htf_push(b_new_bar2,adx14_2) a_di9_2.htf_push(b_new_bar2,di9_2) a_di14_2.htf_push(b_new_bar2,di14_2) a__di9_2.htf_push(b_new_bar2,_di9_2) a__di14_2.htf_push(b_new_bar2,_di14_2) var adxline1_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline2_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline3_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline4_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline5_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline6_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline7_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var adxline8_2=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=2) var diline1_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline2_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline3_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline4_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline5_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline6_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline7_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var diline8_2=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=2) var _diline1_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline2_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline3_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline4_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline5_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline6_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline7_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) var _diline8_2=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=2) if b_DMI range2.set_text(symbol_htf2+"DMI") f_line_set_xyz(adxline1_2,box.get_right(range2)-1,f_map2box(a_adx14_2.lastx(),range2),f_map2box(a_adx9_2.lastx(),range2)) f_line_set_xyz(adxline2_2,box.get_right(range2)-2,f_map2box(a_adx14_2.lastx(1),range2),f_map2box(a_adx9_2.lastx(1),range2)) f_line_set_xyz(adxline3_2,box.get_right(range2)-3,f_map2box(a_adx14_2.lastx(2),range2),f_map2box(a_adx9_2.lastx(2),range2)) f_line_set_xyz(adxline4_2,box.get_right(range2)-4,f_map2box(a_adx14_2.lastx(3),range2),f_map2box(a_adx9_2.lastx(3),range2)) f_line_set_xyz(adxline5_2,box.get_right(range2)-5,f_map2box(a_adx14_2.lastx(4),range2),f_map2box(a_adx9_2.lastx(4),range2)) f_line_set_xyz(adxline6_2,box.get_right(range2)-6,f_map2box(a_adx14_2.lastx(5),range2),f_map2box(a_adx9_2.lastx(5),range2)) f_line_set_xyz(adxline7_2,box.get_right(range2)-7,f_map2box(a_adx14_2.lastx(6),range2),f_map2box(a_adx9_2.lastx(6),range2)) f_line_set_xyz(adxline8_2,box.get_right(range2)-8,f_map2box(a_adx14_2.lastx(7),range2),f_map2box(a_adx9_2.lastx(7),range2)) f_line_set_xyz(diline1_2,box.get_right(range2)-1,f_map2box(a_di14_2.lastx(),range2),f_map2box(a_di9_2.lastx(),range2)) f_line_set_xyz(diline2_2,box.get_right(range2)-2,f_map2box(a_di14_2.lastx(1),range2),f_map2box(a_di9_2.lastx(1),range2)) f_line_set_xyz(diline3_2,box.get_right(range2)-3,f_map2box(a_di14_2.lastx(2),range2),f_map2box(a_di9_2.lastx(2),range2)) f_line_set_xyz(diline4_2,box.get_right(range2)-4,f_map2box(a_di14_2.lastx(3),range2),f_map2box(a_di9_2.lastx(3),range2)) f_line_set_xyz(diline5_2,box.get_right(range2)-5,f_map2box(a_di14_2.lastx(4),range2),f_map2box(a_di9_2.lastx(4),range2)) f_line_set_xyz(diline6_2,box.get_right(range2)-6,f_map2box(a_di14_2.lastx(5),range2),f_map2box(a_di9_2.lastx(5),range2)) f_line_set_xyz(diline7_2,box.get_right(range2)-7,f_map2box(a_di14_2.lastx(6),range2),f_map2box(a_di9_2.lastx(6),range2)) f_line_set_xyz(diline8_2,box.get_right(range2)-8,f_map2box(a_di14_2.lastx(7),range2),f_map2box(a_di9_2.lastx(7),range2)) f_line_set_xyz(_diline1_2,box.get_right(range2)-1,f_map2box(a__di14_2.lastx(),range2),f_map2box(a__di9_2.lastx(),range2)) f_line_set_xyz(_diline2_2,box.get_right(range2)-2,f_map2box(a__di14_2.lastx(1),range2),f_map2box(a__di9_2.lastx(1),range2)) f_line_set_xyz(_diline3_2,box.get_right(range2)-3,f_map2box(a__di14_2.lastx(2),range2),f_map2box(a__di9_2.lastx(2),range2)) f_line_set_xyz(_diline4_2,box.get_right(range2)-4,f_map2box(a__di14_2.lastx(3),range2),f_map2box(a__di9_2.lastx(3),range2)) f_line_set_xyz(_diline5_2,box.get_right(range2)-5,f_map2box(a__di14_2.lastx(4),range2),f_map2box(a__di9_2.lastx(4),range2)) f_line_set_xyz(_diline6_2,box.get_right(range2)-6,f_map2box(a__di14_2.lastx(5),range2),f_map2box(a__di9_2.lastx(5),range2)) f_line_set_xyz(_diline7_2,box.get_right(range2)-7,f_map2box(a__di14_2.lastx(6),range2),f_map2box(a__di9_2.lastx(6),range2)) f_line_set_xyz(_diline8_2,box.get_right(range2)-8,f_map2box(a__di14_2.lastx(7),range2),f_map2box(a__di9_2.lastx(7),range2)) [di9_3,_di9_3,adx9_3]=H.htf_dmi(m3,b_new_bar3,9) [di14_3,_di14_3,adx14_3]=H.htf_dmi(m3,b_new_bar3,14) var a_adx9_3=array.new_float(0,na) var a_adx14_3=array.new_float(0,na) var a_di9_3=array.new_float(0,na) var a_di14_3=array.new_float(0,na) var a__di9_3=array.new_float(0,na) var a__di14_3=array.new_float(0,na) a_adx9_3.htf_push(b_new_bar3,adx9_3) a_adx14_3.htf_push(b_new_bar3,adx14_3) a_di9_3.htf_push(b_new_bar3,di9_3) a_di14_3.htf_push(b_new_bar3,di14_3) a__di9_3.htf_push(b_new_bar3,_di9_3) a__di14_3.htf_push(b_new_bar3,_di14_3) var adxline1_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline2_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline3_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline4_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline5_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline6_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline7_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var adxline8_3=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=3) var diline1_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline2_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline3_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline4_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline5_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline6_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline7_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var diline8_3=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=3) var _diline1_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline2_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline3_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline4_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline5_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline6_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline7_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) var _diline8_3=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=3) if b_DMI range3.set_text(symbol_htf3+"DMI") f_line_set_xyz(adxline1_3,box.get_right(range3)-1,f_map2box(a_adx14_3.lastx(),range3),f_map2box(a_adx9_3.lastx(),range3)) f_line_set_xyz(adxline2_3,box.get_right(range3)-2,f_map2box(a_adx14_3.lastx(1),range3),f_map2box(a_adx9_3.lastx(1),range3)) f_line_set_xyz(adxline3_3,box.get_right(range3)-3,f_map2box(a_adx14_3.lastx(2),range3),f_map2box(a_adx9_3.lastx(2),range3)) f_line_set_xyz(adxline4_3,box.get_right(range3)-4,f_map2box(a_adx14_3.lastx(3),range3),f_map2box(a_adx9_3.lastx(3),range3)) f_line_set_xyz(adxline5_3,box.get_right(range3)-5,f_map2box(a_adx14_3.lastx(4),range3),f_map2box(a_adx9_3.lastx(4),range3)) f_line_set_xyz(adxline6_3,box.get_right(range3)-6,f_map2box(a_adx14_3.lastx(5),range3),f_map2box(a_adx9_3.lastx(5),range3)) f_line_set_xyz(adxline7_3,box.get_right(range3)-7,f_map2box(a_adx14_3.lastx(6),range3),f_map2box(a_adx9_3.lastx(6),range3)) f_line_set_xyz(adxline8_3,box.get_right(range3)-8,f_map2box(a_adx14_3.lastx(7),range3),f_map2box(a_adx9_3.lastx(7),range3)) f_line_set_xyz(diline1_3,box.get_right(range3)-1,f_map2box(a_di14_3.lastx(),range3),f_map2box(a_di9_3.lastx(),range3)) f_line_set_xyz(diline2_3,box.get_right(range3)-2,f_map2box(a_di14_3.lastx(1),range3),f_map2box(a_di9_3.lastx(1),range3)) f_line_set_xyz(diline3_3,box.get_right(range3)-3,f_map2box(a_di14_3.lastx(2),range3),f_map2box(a_di9_3.lastx(2),range3)) f_line_set_xyz(diline4_3,box.get_right(range3)-4,f_map2box(a_di14_3.lastx(3),range3),f_map2box(a_di9_3.lastx(3),range3)) f_line_set_xyz(diline5_3,box.get_right(range3)-5,f_map2box(a_di14_3.lastx(4),range3),f_map2box(a_di9_3.lastx(4),range3)) f_line_set_xyz(diline6_3,box.get_right(range3)-6,f_map2box(a_di14_3.lastx(5),range3),f_map2box(a_di9_3.lastx(5),range3)) f_line_set_xyz(diline7_3,box.get_right(range3)-7,f_map2box(a_di14_3.lastx(6),range3),f_map2box(a_di9_3.lastx(6),range3)) f_line_set_xyz(diline8_3,box.get_right(range3)-8,f_map2box(a_di14_3.lastx(7),range3),f_map2box(a_di9_3.lastx(7),range3)) f_line_set_xyz(_diline1_3,box.get_right(range3)-1,f_map2box(a__di14_3.lastx(),range3),f_map2box(a__di9_3.lastx(),range3)) f_line_set_xyz(_diline2_3,box.get_right(range3)-2,f_map2box(a__di14_3.lastx(1),range3),f_map2box(a__di9_3.lastx(1),range3)) f_line_set_xyz(_diline3_3,box.get_right(range3)-3,f_map2box(a__di14_3.lastx(2),range3),f_map2box(a__di9_3.lastx(2),range3)) f_line_set_xyz(_diline4_3,box.get_right(range3)-4,f_map2box(a__di14_3.lastx(3),range3),f_map2box(a__di9_3.lastx(3),range3)) f_line_set_xyz(_diline5_3,box.get_right(range3)-5,f_map2box(a__di14_3.lastx(4),range3),f_map2box(a__di9_3.lastx(4),range3)) f_line_set_xyz(_diline6_3,box.get_right(range3)-6,f_map2box(a__di14_3.lastx(5),range3),f_map2box(a__di9_3.lastx(5),range3)) f_line_set_xyz(_diline7_3,box.get_right(range3)-7,f_map2box(a__di14_3.lastx(6),range3),f_map2box(a__di9_3.lastx(6),range3)) f_line_set_xyz(_diline8_3,box.get_right(range3)-8,f_map2box(a__di14_3.lastx(7),range3),f_map2box(a__di9_3.lastx(7),range3)) [di9_4,_di9_4,adx9_4]=H.htf_dmi(m4,b_new_bar4,9) [di14_4,_di14_4,adx14_4]=H.htf_dmi(m4,b_new_bar4,14) var a_adx9_4=array.new_float(0,na) var a_adx14_4=array.new_float(0,na) var a_di9_4=array.new_float(0,na) var a_di14_4=array.new_float(0,na) var a__di9_4=array.new_float(0,na) var a__di14_4=array.new_float(0,na) a_adx9_4.htf_push(b_new_bar4,adx9_4) a_adx14_4.htf_push(b_new_bar4,adx14_4) a_di9_4.htf_push(b_new_bar4,di9_4) a_di14_4.htf_push(b_new_bar4,di14_4) a__di9_4.htf_push(b_new_bar4,_di9_4) a__di14_4.htf_push(b_new_bar4,_di14_4) var adxline1_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline2_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline3_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline4_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline5_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline6_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline7_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var adxline8_4=line.new(na,na,na,na,color=cADX,style=line.style_arrow_right,width=4) var diline1_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline2_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline3_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline4_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline5_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline6_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline7_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var diline8_4=line.new(na,na,na,na,color=cDI,style=line.style_arrow_right,width=4) var _diline1_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline2_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline3_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline4_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline5_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline6_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline7_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) var _diline8_4=line.new(na,na,na,na,color=c_DI,style=line.style_arrow_right,width=4) if b_DMI range4.set_text(symbol_htf4+"DMI") f_line_set_xyz(adxline1_4,box.get_right(range4)-1,f_map2box(a_adx14_4.lastx(),range4),f_map2box(a_adx9_4.lastx(),range4)) f_line_set_xyz(adxline2_4,box.get_right(range4)-2,f_map2box(a_adx14_4.lastx(1),range4),f_map2box(a_adx9_4.lastx(1),range4)) f_line_set_xyz(adxline3_4,box.get_right(range4)-3,f_map2box(a_adx14_4.lastx(2),range4),f_map2box(a_adx9_4.lastx(2),range4)) f_line_set_xyz(adxline4_4,box.get_right(range4)-4,f_map2box(a_adx14_4.lastx(3),range4),f_map2box(a_adx9_4.lastx(3),range4)) f_line_set_xyz(adxline5_4,box.get_right(range4)-5,f_map2box(a_adx14_4.lastx(4),range4),f_map2box(a_adx9_4.lastx(4),range4)) f_line_set_xyz(adxline6_4,box.get_right(range4)-6,f_map2box(a_adx14_4.lastx(5),range4),f_map2box(a_adx9_4.lastx(5),range4)) f_line_set_xyz(adxline7_4,box.get_right(range4)-7,f_map2box(a_adx14_4.lastx(6),range4),f_map2box(a_adx9_4.lastx(6),range4)) f_line_set_xyz(adxline8_4,box.get_right(range4)-8,f_map2box(a_adx14_4.lastx(7),range4),f_map2box(a_adx9_4.lastx(7),range4)) f_line_set_xyz(diline1_4,box.get_right(range4)-1,f_map2box(a_di14_4.lastx(),range4),f_map2box(a_di9_4.lastx(),range4)) f_line_set_xyz(diline2_4,box.get_right(range4)-2,f_map2box(a_di14_4.lastx(1),range4),f_map2box(a_di9_4.lastx(1),range4)) f_line_set_xyz(diline3_4,box.get_right(range4)-3,f_map2box(a_di14_4.lastx(2),range4),f_map2box(a_di9_4.lastx(2),range4)) f_line_set_xyz(diline4_4,box.get_right(range4)-4,f_map2box(a_di14_4.lastx(3),range4),f_map2box(a_di9_4.lastx(3),range4)) f_line_set_xyz(diline5_4,box.get_right(range4)-5,f_map2box(a_di14_4.lastx(4),range4),f_map2box(a_di9_4.lastx(4),range4)) f_line_set_xyz(diline6_4,box.get_right(range4)-6,f_map2box(a_di14_4.lastx(5),range4),f_map2box(a_di9_4.lastx(5),range4)) f_line_set_xyz(diline7_4,box.get_right(range4)-7,f_map2box(a_di14_4.lastx(6),range4),f_map2box(a_di9_4.lastx(6),range4)) f_line_set_xyz(diline8_4,box.get_right(range4)-8,f_map2box(a_di14_4.lastx(7),range4),f_map2box(a_di9_4.lastx(7),range4)) f_line_set_xyz(_diline1_4,box.get_right(range4)-1,f_map2box(a__di14_4.lastx(),range4),f_map2box(a__di9_4.lastx(),range4)) f_line_set_xyz(_diline2_4,box.get_right(range4)-2,f_map2box(a__di14_4.lastx(1),range4),f_map2box(a__di9_4.lastx(1),range4)) f_line_set_xyz(_diline3_4,box.get_right(range4)-3,f_map2box(a__di14_4.lastx(2),range4),f_map2box(a__di9_4.lastx(2),range4)) f_line_set_xyz(_diline4_4,box.get_right(range4)-4,f_map2box(a__di14_4.lastx(3),range4),f_map2box(a__di9_4.lastx(3),range4)) f_line_set_xyz(_diline5_4,box.get_right(range4)-5,f_map2box(a__di14_4.lastx(4),range4),f_map2box(a__di9_4.lastx(4),range4)) f_line_set_xyz(_diline6_4,box.get_right(range4)-6,f_map2box(a__di14_4.lastx(5),range4),f_map2box(a__di9_4.lastx(5),range4)) f_line_set_xyz(_diline7_4,box.get_right(range4)-7,f_map2box(a__di14_4.lastx(6),range4),f_map2box(a__di9_4.lastx(6),range4)) f_line_set_xyz(_diline8_4,box.get_right(range4)-8,f_map2box(a__di14_4.lastx(7),range4),f_map2box(a__di9_4.lastx(7),range4)) //***** //end of DMI //*****
Tri-State Supertrend
https://www.tradingview.com/script/IsQ5dxza-Tri-State-Supertrend/
StefanReich
https://www.tradingview.com/u/StefanReich/
47
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© StefanReich // A supertrend with 3 states: Buy, Sell, Range // Based on Pivot Point SuperTrend by LonesomeTheblue //@version=5 indicator("Tri-State Supertrend", overlay=true) prd = input.int(defval=10, title='Pivot Point Period', minval=1, maxval=50) Factor = input.float(defval=3, title='ATR Factor', minval=1, step=0.1) Pd = input.int(defval=10, title='ATR Period', minval=1) rangeFilter = input.bool(true, "Range filter", tooltip="Filter signals for ranges") rangeSize = input.float(1.3, "Range size", step=0.1, tooltip="Maximal movement (%) allowed in a range") showpivot = input(false, 'Show Pivot Points', group="Display") showlabel = input(defval=true, title='Show Buy/Sell Labels', group="Display") showsr = input(defval=false, title='Show Support/Resistance', group="Display") showRanges = input(defval=false, title='Show (non-) trendline for ranges', group="Display") showSuppressedSignals = input.bool(false, "Show suppressed signals", tooltip="Show buy/sell signals that were suppressed during a range", group="Display") // get Pivot High/Low float ph = ta.pivothigh(prd, prd) float pl = ta.pivotlow(prd, prd) // draw Pivot Points if "showpivot" is enabled plotshape(ph and showpivot, title="High", text='H', style=shape.labeldown, color=na, textcolor=color.new(color.red, 0), location=location.abovebar, offset=-prd, display=display.all-display.status_line) plotshape(pl and showpivot, title="Low", text='L', style=shape.labeldown, color=na, textcolor=color.new(color.lime, 0), location=location.belowbar, offset=-prd, display=display.all-display.status_line) // calculate the Center line using pivot points var float center = na float lastpp = ph ? ph : pl ? pl : na if lastpp if na(center) center := lastpp center else //weighted calculation center := (center * 2 + lastpp) / 3 center // upper/lower bands calculation atr = ta.atr(Pd) Up = center - Factor * atr Dn = center + Factor * atr plotchar(atr/close*100, "ATR (%)", "", display=display.data_window) // get the trend float TUp = na float TDown = na Trend = 0 TUp := close[1] > TUp[1] ? math.max(Up, TUp[1]) : Up TDown := close[1] < TDown[1] ? math.min(Dn, TDown[1]) : Dn Trend := close > TDown[1] ? 1 : close < TUp[1] ? -1 : nz(Trend[1], 1) Trailingsl = Trend == 1 ? TUp : TDown // check and plot the signals bsignal = Trend == 1 and Trend[1] == -1 ssignal = Trend == -1 and Trend[1] == 1 //get S/R levels using Pivot Points float resistance = na float support = na support := pl ? pl : support[1] resistance := ph ? ph : resistance[1] // if enabled then show S/R levels plot(showsr and support ? support : na, color=showsr and support ? color.lime : na, style=plot.style_circles, offset=-prd, title="Support", display=display.all-display.status_line) plot(showsr and resistance ? resistance : na, color=showsr and resistance ? color.red : na, style=plot.style_circles, offset=-prd, title="Resistance", display=display.all-display.status_line) // max function with direction (direction > 0 for max, direction < 0 for min) directionalMax(direction, a, b) => d = math.sign(direction) d*math.max(a*d, b*d) var bool inRange = false // Are we in a range? // Furthest price move in % since last buy/sell signal (suppressed or non-suppressed) // This is the central value that determines whether we are in a range. var float crest = 0 var float entryPrice = na // Entry price at last buy/sell signal // Record last trend change trendChange = Trend != Trend[1] lastTrendChange = bar_index-ta.barssince(trendChange) // Calculate current price move in direction of trend currentMove = Trend*(directionalMax(Trend, low, high)/entryPrice-1)*100 // Update crest value if currentMove is above it if currentMove > crest crest := currentMove // Core range detection logic. Uses crest[1] because crest may already be pertaining to the new trend // The check for currentMove makes sure to ignore the trend beginning at the very first bar in the history inRange_calc = not na(currentMove) and crest[1] <= rangeSize plotchar(currentMove, "currentMove", "", display=display.data_window) plotchar(crest, "crest", "", display=display.data_window) if rangeFilter and barstate.isconfirmed // On buy/sell signal, check if last trend was an actual trend or range-like if bsignal or ssignal inRange := inRange_calc // Reset variables to record new trend entryPrice := close crest := 0 // End range as soon as a trend is of notable size (this will trigger a buy/sell signal) if crest[1] > rangeSize inRange := false rsignal = inRange and not inRange[1] // Range signal occurs when inRange turns true isBuy = Trend > 0 and not inRange // Suppress buy signal when in range isSell = Trend < 0 and not inRange // Suppress sell signal when in range buy = isBuy and isBuy[1] == false // Actual filtered buy signal (only true for one bar when the trend begins) sell = isSell and isSell[1] == false // Actual filtered sell signal (only true for one bar when the trend begins) // Plot the trend line - green for buy, red for sell, gray for range rangeColor = color.gray linecolor = inRange ? rangeColor : Trend == 1 and nz(Trend[1]) == 1 ? color.lime : Trend == -1 and nz(Trend[1]) == -1 ? color.red : na plot(not inRange or showRanges ? Trailingsl : na, color=linecolor, linewidth=2, title='Trendline', style=plot.style_linebr, display=display.all-display.status_line) // Show buy/sell labels plotshape(buy and showlabel ? Trailingsl : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=inRange ? rangeColor : color.lime, textcolor=color.black, display=display.all-display.status_line) plotshape(sell and showlabel ? Trailingsl : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=inRange ? rangeColor : color.red, textcolor=color.white, display=display.all-display.status_line) // [Non-suppressed mode] Show range labels, either above or below the bar, depending on what the last trend was (looks better this way) plotshape(rsignal and showlabel and not showSuppressedSignals and Trend[1] > 0 ? Trailingsl : na, title='Range', text='Range', location=location.absolute, style=shape.labeldown, size=size.tiny, color=rangeColor, textcolor=color.white, display=display.all-display.status_line) plotshape(rsignal and showlabel and not showSuppressedSignals and Trend[1] < 0 ? Trailingsl : na, title='Range', text='Range', location=location.absolute, style=shape.labelup, size=size.tiny, color=rangeColor, textcolor=color.white, display=display.all-display.status_line) // Show signals suppressed during range if selected showSupp = showlabel and showSuppressedSignals and inRange and not rsignal plotshape(bsignal and showSupp ? Trailingsl : na, title='Buy (suppressed)', text='Buy\n(suppressed)', location=location.absolute, style=shape.labelup, size=size.tiny, color=rangeColor, textcolor=color.white, display=display.all-display.status_line) plotshape(ssignal and showSupp ? Trailingsl : na, title='Sell (suppressed)', text='Sell\n(suppressed)', location=location.absolute, style=shape.labeldown, size=size.tiny, color=rangeColor, textcolor=color.white, display=display.all-display.status_line) plotshape(rsignal and showlabel and showSuppressedSignals and Trend[1] > 0 ? Trailingsl : na, title='Range (suppressed sell)', text='Range\n(suppressed sell)', location=location.absolute, style=shape.labeldown, size=size.tiny, color=rangeColor, textcolor=color.white, display=display.all-display.status_line) plotshape(rsignal and showlabel and showSuppressedSignals and Trend[1] < 0 ? Trailingsl : na, title='Range (suppressed Buy)', text='Range\n(suppressed buy)', location=location.absolute, style=shape.labelup, size=size.tiny, color=rangeColor, textcolor=color.white, display=display.all-display.status_line) // If you embed this indicator into a strategy, you can use this variable to always query // the Tri-State Supertrend's current state (1 for buy, -1 for sell, 0 for range) tristateTrend = inRange ? 0 : Trend plotchar(tristateTrend, "Tri-State Trend", "", display=display.all-display.status_line) // Alerts alertcondition(buy, title='Buy Signal', message='Buy Signal') alertcondition(sell, title='Sell Signal', message='Sell Signal') alertcondition(rsignal, title='Sell Signal', message='Range Signal') alertcondition(buy or sell or rsignal, title='Trend Changed', message='Trend Changed')
EMA Deviation Rebound
https://www.tradingview.com/script/P8qyuZsf/
zamansiz74
https://www.tradingview.com/u/zamansiz74/
21
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© zamansiz74 //@version=5 indicator("EMA Deviation Rebound", overlay=true) periods = input.int(defval = 20, title="Periods") length = input.int(defval = 10, title="Length") var float avghighest = 0.0 var float avglowest = 0.0 var float xyz1 = 0.0 var float xyz2 = 0.0 var colorValue = color.black // Calculation of the scatter deviation = ta.stdev(close, periods) // Highest and lowest spread highestDeviation = ta.highest(deviation, periods) lowestDeviation = ta.lowest(deviation, periods) if bar_index % periods == 0 xyz1 := close + highestDeviation xyz2 := close - lowestDeviation ema1 = ta.ema((xyz1+xyz2)/2,length) ema2 = ta.ema(ema1, length) u_double_prime_approx = ema1 - ema2 colorValue := low > ema1 and open < close ? color.green : high < ema1 and open > close ? color.red : colorValue // Plot plot(ema1, "ED", color=colorValue, linewidth=4)
MTF Break of Structure(BOS) & Market Structure Shift(MSS)
https://www.tradingview.com/script/1LrVbh1I-MTF-Break-of-Structure-BOS-Market-Structure-Shift-MSS/
Lenny_Kiruthu
https://www.tradingview.com/u/Lenny_Kiruthu/
500
study
5
MPL-2.0
// 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 Break of Structure(BOS) & Market Structure Shift(MSS)", shorttitle = "MTF BOS & MSS", overlay = true, max_labels_count=500, max_lines_count = 500, max_bars_back = 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 Hide_MS_Tooltip = "If true will hide all MS plots such as \"HH 2H\" or \"HH 15min\"" Hide_Breaks_Tooltip = "If true will hide all MS breaks such as \"BOS 1H\" or \"MSS 15min\"" 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, structure will not display. Note plotting ltf structure on a htf will provide inaccurate plots." Use_High_Low_Tooltip = "If set to true high and low values will be used to confirm market structure else if set to false close will be used." Display_TF_Pivots = "If true the script will display the timeframe declared in the TF inputs" Display_TF_MS = "If true the script will display the timeframe's market structure declared in the TF inputs if Hide all Market Structure is false in general settings." BOS_Alert_Tooltip = "Set to true to activate BOS alerts then proceed to set the any alert function specifically on this script." MSS_Alert_Tooltip = "Set to true to activate MSS alerts then proceed to set the any alert function specifically on this script." BOS_Plot_Tooltip = "If set to true the TF BOS plots will be plotted else if false they will be hidden." MSS_Plot_Tooltip = "If set to true the TF MSS plots will be plotted else if false they will be hidden." // General Settings Hide_All_MS = input.bool(defval = true, title = "Hide all Market Structure", group = General_Settings_group, tooltip = Hide_MS_Tooltip) Hide_All_Breaks = input.bool(defval = false, title = "Hide all Structure Breaks", group = General_Settings_group, tooltip = Hide_Breaks_Tooltip) Show_Only_On_Lower_Timeframes = input.bool(defval = true, title = "Show Structure only on a lower Timeframe", group = General_Settings_group, tooltip = Lower_Timeframe_Tooltip) // User Inputs // Timeframe 1 Settings TF_1_Use_Bos_Plot = input.bool(defval = true, title = "Show TF 1 BOS Plots", group = Timeframe_1_Group, tooltip = BOS_Plot_Tooltip) TF_1_Use_MSS_Plot = input.bool(defval = true, title = "Show TF 1 MSS Plots", group = Timeframe_1_Group, tooltip = MSS_Plot_Tooltip) 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 for Bos & Mss", group = Timeframe_1_Group, tooltip = Use_High_Low_Tooltip) TF_1_Display_Pivots = input.bool(defval = true, title = "Display Market Structure", group = Timeframe_1_Group, tooltip = Display_TF_MS) TF_1_Display_Timeframe = input.bool(defval = true, title = "Display Timeframe", group = Timeframe_1_Group, tooltip = Display_TF_Pivots) TF_1_BOS_Alert = input.bool(defval = true, title = "Use TF 1 BOS Alert", group = Timeframe_1_Group, tooltip = BOS_Alert_Tooltip) TF_1_MSS_Alert = input.bool(defval = true, title = "Use TF 1 MSS Alert", group = Timeframe_1_Group, tooltip = MSS_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_Line_Width = input.int(defval = 2, title = "Line Width", 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_Bul_Bos_Col = input.color(defval = color.green, title = "Bullish Bos/Mss Color", group = Timeframe_1_Group, inline = "TF 1 Color") TF_1_Bear_Bos_Col = input.color(defval = color.red, title = "Bearish Bos/Mss Color", group = Timeframe_1_Group, inline = "TF 1 Color") TF_1_Bul_MS_Col = input.color(defval = color.white, title = "Bullish Text MS Color", group = Timeframe_1_Group, inline = "TF 1 Ms Color") TF_1_Bear_MS_Col = input.color(defval = color.white, title = "Bearish Text MS Color", group = Timeframe_1_Group, inline = "TF 1 Ms Color") // Timeframe 2 Settings TF_2_Use_Bos_Plot = input.bool(defval = true, title = "Show TF 2 BOS Plots", group = Timeframe_2_Group, tooltip = BOS_Plot_Tooltip) TF_2_Use_MSS_Plot = input.bool(defval = true, title = "Show TF 2 MSS Plots", group = Timeframe_2_Group, tooltip = MSS_Plot_Tooltip) TF_2_Chart_Feature = input.bool(defval = true, 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 for Bos & Mss", group = Timeframe_2_Group, tooltip = Use_High_Low_Tooltip) TF_2_Display_Pivots = input.bool(defval = true, title = "Display Market Structure", group = Timeframe_2_Group, tooltip = Display_TF_MS) TF_2_Display_Timeframe = input.bool(defval = true, title = "Display Timeframe", group = Timeframe_2_Group, tooltip = Display_TF_Pivots) TF_2_BOS_Alert = input.bool(defval = true, title = "Use TF 2 BOS Alert", group = Timeframe_2_Group, tooltip = BOS_Alert_Tooltip) TF_2_MSS_Alert = input.bool(defval = true, title = "Use TF 2 MSS Alert", group = Timeframe_2_Group, tooltip = MSS_Alert_Tooltip) TF_2_Multip = input.int(defval=2, minval=1, maxval=1440, title="Timeframe 2", group=Timeframe_2_Group, inline="T2") TF_2_Period = input.string(defval="Hour", 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 = "Dashed", title = "Border Type", options = ["Solid", "Dashed", "Dotted"], group = Timeframe_2_Group) TF_2_Line_Width = input.int(defval = 1, title = "Line Width", 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_Bul_Bos_Col = input.color(defval = color.green, title = "Bullish Bos/Mss Color", group = Timeframe_2_Group, inline = "TF 2 Color") TF_2_Bear_Bos_Col = input.color(defval = color.red, title = "Bearish Bos/Mss Color", group = Timeframe_2_Group, inline = "TF 2 Color") TF_2_Bul_MS_Col = input.color(defval = color.white, title = "Bullish MS Color", group = Timeframe_2_Group, inline = "TF 2 Ms Color") TF_2_Bear_MS_Col = input.color(defval = color.white, title = "Bearish MS Color", group = Timeframe_2_Group, inline = "TF 2 Ms Color") // Timeframe 3 Settings TF_3_Use_Bos_Plot = input.bool(defval = true, title = "Show TF 3 BOS Plots", group = Timeframe_3_Group, tooltip = BOS_Plot_Tooltip) TF_3_Use_MSS_Plot = input.bool(defval = true, title = "Show TF 3 MSS Plots", group = Timeframe_3_Group, tooltip = MSS_Plot_Tooltip) TF_3_Chart_Feature = input.bool(defval = false, title = "Set Timeframe to Chart", group = Timeframe_3_Group, tooltip = Set_To_Chart_Tooltip) TF_3_Use_High_Low = input.bool(defval = false, title = "Use High/Low for Bos & Mss", group = Timeframe_3_Group, tooltip = Use_High_Low_Tooltip) TF_3_Display_Pivots = input.bool(defval = false, title = "Display Market Structure", group = Timeframe_3_Group, tooltip = Display_TF_MS) TF_3_Display_Timeframe = input.bool(defval = false, title = "Display Timeframe", group = Timeframe_3_Group, tooltip = Display_TF_Pivots) TF_3_BOS_Alert = input.bool(defval = true, title = "Use TF 3 BOS Alert", group = Timeframe_3_Group, tooltip = BOS_Alert_Tooltip) TF_3_MSS_Alert = input.bool(defval = true, title = "Use TF 3 MSS Alert", group = Timeframe_3_Group, tooltip = MSS_Alert_Tooltip) TF_3_Multip = input.int(defval=1, minval=1, maxval=1440, title="Timeframe 3", group=Timeframe_3_Group, inline="T3") TF_3_Period = input.string(defval="Hour", title="", options=["Minute", "Hour", "Day", "Week", "Month"], group=Timeframe_3_Group, inline="T3", tooltip=Timeframe_Tooltip) TF_3_Swing_Length = input.int(defval = 7, title = "Swing Length", minval = 1, group = Timeframe_3_Group) TF_3_Line_Type = input.string(defval = "Dotted", title = "Border Type", options = ["Solid", "Dashed", "Dotted"], group = Timeframe_3_Group) TF_3_Line_Width = input.int(defval = 1, title = "Line Width", group = Timeframe_3_Group) TF_3_Text_Size = input.string(defval = "Small", title = "Text Size", options = ["Normal", "Tiny", "Small", "Large", "Huge", "Auto"], group = Timeframe_3_Group) TF_3_Bul_Bos_Col = input.color(defval = color.green, title = "Bullish Bos/Mss Color", group = Timeframe_3_Group, inline = "TF 3 Color") TF_3_Bear_Bos_Col = input.color(defval = color.red, title = "Bearish Bos/Mss Color", group = Timeframe_3_Group, inline = "TF 3 Color") TF_3_Bul_MS_Col = input.color(defval = color.white, title = "Bullish MS Color", group = Timeframe_3_Group, inline = "TF 3 Ms Color") TF_3_Bear_MS_Col = input.color(defval = color.white, title = "Bearish MS Color", group = Timeframe_3_Group, inline = "TF 3 Ms Color") // 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 // Calculating the Mtf BOS and MSS // Getting the high and low values [TF_1_SH, TF_1_SL] = 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)], gaps = barmerge.gaps_on) [TF_2_SH, TF_2_SL] = 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)], gaps = barmerge.gaps_on) [TF_3_SH, TF_3_SL] = request.security(symbol = syminfo.tickerid, 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) Count_Candles_For_Structure(Direction, Condition) => var int High_Count = 0 var int Low_Count = 0 if Direction == "Bullish" for i = 0 to Condition High_Count := i High_Count else if Direction == "Bearish" for i = 0 to Condition Low_Count := i Low_Count Market_Structure(TF_SH, TF_SL, Swing_Length, Chart_as_Timeframe, TF_Period, TF_Multip , Line_Type, Line_Width, Display_Timeframe, Display_Structure, Bul_Bos_Col, Bear_Bos_Col , Bul_Ms_Col, Bear_Ms_Col, TF_Text_Size, Use_High_Low, Use_BOS_Alert, Use_MSS_Alert , Use_Bos_Plot, Use_MSS_Plot) => // 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 High_Count = 0 Low_Count = 0 //Tracking whether previous levels have been broken var bool TF_High_Present = false var bool TF_Low_Present = false //Tracking prev breakout var int Prev_Breakout_Type = 0 //Varibales for generating BOS and CHOCH bool High_Broken = false bool Low_Broken = false End_High_Time = 0 End_Low_Time = 0 // Variables for Market Structure bool HH = false bool LH = false bool HL = false bool LL = false TF_High_Close_Price = request.security(symbol = syminfo.tickerid, timeframe = (Chart_as_Timeframe ? timeframe.period : TF(TF_Period, TF_Multip)), expression = (Use_High_Low ? high : close)) TF_Low_Close_Price = request.security(symbol = syminfo.tickerid, timeframe = (Chart_as_Timeframe ? timeframe.period : TF(TF_Period, TF_Multip)), expression = (Use_High_Low ? low : close)) 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 if TF_High_Close_Price > TF_Prev_High and TF_High_Present High_Broken := true TF_High_Present := false End_High_Time := time if TF_Low_Close_Price < TF_Prev_Low and TF_Low_Present Low_Broken := true TF_Low_Present := false End_Low_Time := time // Displaying Swing Levels if HH and Display_Timeframe and Display_Structure and not Hide_All_MS label.new(TF_Prev_High_Time, TF_Prev_High, "HH \n" + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , xloc = xloc.bar_time, color=Transparent_Color, style=label.style_label_down, textcolor=Bul_Ms_Col, size = Text_Size_Switch(TF_Text_Size)) if HL and Display_Timeframe and Display_Structure and not Hide_All_MS label.new(TF_Prev_Low_Time, TF_Prev_Low, "HL \n" + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , xloc = xloc.bar_time, color=Transparent_Color, style=label.style_label_up, textcolor=Bul_Ms_Col, size = Text_Size_Switch(TF_Text_Size)) if LH and Display_Timeframe and Display_Structure and not Hide_All_MS label.new(TF_Prev_High_Time, TF_Prev_High, "LH \n" + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , xloc = xloc.bar_time, color=Transparent_Color, style=label.style_label_down, textcolor=Bear_Ms_Col, size = Text_Size_Switch(TF_Text_Size)) if LL and Display_Timeframe and Display_Structure and not Hide_All_MS label.new(TF_Prev_Low_Time, TF_Prev_Low, "LL \n" + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , xloc = xloc.bar_time, color=Transparent_Color, style=label.style_label_up, textcolor=Bear_Ms_Col, size = Text_Size_Switch(TF_Text_Size)) High_Count := ta.barssince(HH == true or LH == true) + MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length) Low_Count := ta.barssince(HL == true or LL == true) + MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length) High_Count_Function = Count_Candles_For_Structure("Bullish", High_Count) Low_Count_Function = Count_Candles_For_Structure("Bearish", Low_Count) //Generating the BOS Lines if High_Broken and Display_Timeframe and not Hide_All_Breaks and HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) if Prev_Breakout_Type == 1 and Use_Bos_Plot line.new(x1 = time[High_Count_Function] , y1 = TF_Prev_High, x2 =End_High_Time , y2 = TF_Prev_High , xloc = xloc.bar_time, color = Bul_Bos_Col, style=Line_Type_Control(Line_Type), width= Line_Width) label.new(x = time[High_Count_Function/2], y = TF_Prev_High , xloc = xloc.bar_time, text = 'BOS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , color=Transparent_Color, style=label.style_label_down, textcolor=Bul_Bos_Col, size = Text_Size_Switch(TF_Text_Size)) else if Prev_Breakout_Type == -1 and Use_MSS_Plot line.new(x1 = time[High_Count_Function] , y1 = TF_Prev_High, x2 =End_High_Time , y2 = TF_Prev_High , xloc = xloc.bar_time, color = Bul_Bos_Col, style=Line_Type_Control(Line_Type), width= Line_Width) label.new(x = time[High_Count_Function/2], y = TF_Prev_High , xloc = xloc.bar_time, text = 'MSS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , color=Transparent_Color, style=label.style_label_down, textcolor=Bul_Bos_Col, size = Text_Size_Switch(TF_Text_Size)) if Prev_Breakout_Type == -1 and Use_MSS_Alert alert(message = "New bullish MSS formed on " + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) else if Prev_Breakout_Type == 1 and Use_BOS_Alert alert(message = "New bullish BOS formed on " + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) Prev_Breakout_Type := 1 if Low_Broken and Display_Timeframe and not Hide_All_Breaks and HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) if Prev_Breakout_Type == -1 and Use_Bos_Plot line.new(x1 = time[Low_Count_Function] , y1 = TF_Prev_Low, x2 = End_Low_Time, y2 = TF_Prev_Low , xloc = xloc.bar_time, color= Bear_Bos_Col, style=Line_Type_Control(Line_Type), width= Line_Width) label.new(x = time[Low_Count_Function/2], y = TF_Prev_Low , xloc = xloc.bar_time, text = 'BOS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , color=Transparent_Color, textcolor=Bear_Bos_Col, style=label.style_label_up, size = Text_Size_Switch(TF_Text_Size)) else if Prev_Breakout_Type == 1 and Use_MSS_Plot line.new(x1 = time[Low_Count_Function] , y1 = TF_Prev_Low, x2 = End_Low_Time, y2 = TF_Prev_Low , xloc = xloc.bar_time, color= Bear_Bos_Col, style=Line_Type_Control(Line_Type), width= Line_Width) label.new(x = time[Low_Count_Function/2], y = TF_Prev_Low , xloc = xloc.bar_time, text = 'MSS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip) , color=Transparent_Color, textcolor=Bear_Bos_Col, style=label.style_label_up, size = Text_Size_Switch(TF_Text_Size)) if Prev_Breakout_Type == 1 and Use_MSS_Alert alert(message = "New bearish MSS formed on " + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) else if Prev_Breakout_Type == -1 and Use_BOS_Alert alert(message = "New bearish BOS formed on " + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close) Prev_Breakout_Type := -1 // Calling functions Market_Structure(TF_1_SH, TF_1_SL, TF_1_Swing_Length, TF_1_Chart_Feature, TF_1_Period, TF_1_Multip, TF_1_Line_Type, TF_1_Line_Width , TF_1_Display_Timeframe, TF_1_Display_Pivots, TF_1_Bul_Bos_Col, TF_1_Bear_Bos_Col, TF_1_Bul_MS_Col, TF_1_Bear_MS_Col, TF_1_Text_Size , TF_1_Use_High_Low, TF_1_BOS_Alert, TF_1_MSS_Alert , TF_1_Use_Bos_Plot, TF_1_Use_MSS_Plot) Market_Structure(TF_2_SH, TF_2_SL, TF_2_Swing_Length, TF_2_Chart_Feature, TF_2_Period, TF_2_Multip, TF_2_Line_Type, TF_2_Line_Width , TF_2_Display_Timeframe, TF_2_Display_Pivots, TF_2_Bul_Bos_Col, TF_2_Bear_Bos_Col, TF_2_Bul_MS_Col, TF_2_Bear_MS_Col, TF_2_Text_Size , TF_2_Use_High_Low, TF_2_BOS_Alert, TF_2_MSS_Alert , TF_2_Use_Bos_Plot, TF_2_Use_MSS_Plot) Market_Structure(TF_3_SH, TF_3_SL, TF_3_Swing_Length, TF_3_Chart_Feature, TF_3_Period, TF_3_Multip, TF_3_Line_Type, TF_3_Line_Width , TF_3_Display_Timeframe, TF_3_Display_Pivots, TF_3_Bul_Bos_Col, TF_3_Bear_Bos_Col, TF_3_Bul_MS_Col, TF_3_Bear_MS_Col, TF_3_Text_Size , TF_3_Use_High_Low, TF_3_BOS_Alert, TF_3_MSS_Alert , TF_3_Use_Bos_Plot, TF_3_Use_MSS_Plot)
LNL Trend System
https://www.tradingview.com/script/m0G2Xv7r-LNL-Trend-System/
lnlcapital
https://www.tradingview.com/u/lnlcapital/
875
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // // @version=5 // // L&L Trend System // // L&L Trend System is an ATR based day trading system specifically designed for intra-day traders and scalpers. // // The System works on any chart time frame & can be applied to any market. The study involves two components: 1.) Trend Line which is basically a fast gauge // represented by the 13 EMA. 2.) Stop Line is an ATR deviaton line with special calculation based on the previous bar ATRs and position of the price in relation // to the current and previous values of 13 EMA. // // There are 5 different trend modes available. Each mode is visualizing different ATR settings which provides either aggressive or more conservative approach. The // more "tigher" modes such as tight or normal can be used on less volatile markets such as S&P Futures (ES). Looses & FOMC modes are designed for active high volatility // markets such as NQ or YM futures or BTC or perhaps some currency pairs. Then there is the "Net" mode. The net mode is basically the combination of all modes in one // stop line system which creates "the net" effect. The system also includes additional higher time frame (HTF) trend system. This can be set to any time frame by manual // HTF mode. HTF mode set to "auto" will automatically choose the best suitable higher time frame trend system based on my backtesting results. // // By default, the bars are colored (Trend Bars) based on the DMI and ADX indicators. Whenever the DMI is bearish and ADX is above 20 the candles paint themselfs red. // And vice versa for the green candles and bullish DMI. Whenever the ADX falls below the 20, candles are netural which means there is no real trend in place. // // In terms of visualization, each trend system is fully customizable through the inputs settings. There is also an option to turn on/off the background clouds behind the // stop lines. These clouds can make the charts more clean & visible. // // Created by Β© L&L Capital // indicator("LNL Trend System", shorttitle = "LNL Trend System", overlay=true) // Inputs string TrendMode = input.string("Normal", "Trend Mode", options = ["Tight", "Normal", "Loose", "FOMC", "Net"], group = "Settings", tooltip = "There are several trend modes available. The mods are lined up based on the aggressiveness of the ATR. Tight & Normal modes are the going to flip way much often whereas the Loose or FOMC will provide much higher wiggle room. The good rule of thumb to use is to just stick with first two modes when trading less volatile sessions or ranges, and use the other two on fast moving expanding environments. The Net mode provides the combination of all modes in one giant net. Some might prefer this mode since it suits well to the scale in scale out methods. ") string HTFMode = input.string("Auto", "HTF Mode", options = ["Auto", "Manual"], group = "Settings", tooltip = "Changes the higher time frame mode. The HTF mode set to auto will automatically change the HTF Trend System time frame for you. The auto mode is choosing the most suitable time frames based on the pre-defined time frame pairs that are the most suitable ones. If you prefer your own time frame choose the manual mode.") TimeFrameM = input.timeframe('60', "HTF Aggregation", options = ['1','2','3','5','10','15','20','30','45','60','120','180','240','D','2D','3D','4D','W','2W','3W','M','2M','3M'], group = "Settings", tooltip = "Set the manual time frame for the HTF Trend System.") ShowTrendBars = input(defval=true, title="Show Trend Bars", group = "Trend Bars", tooltip = "Trend Bars are based on the DMI and ADX indicators. Whenever the DMI is bearish and ADX is above 20 the candles paint themselfs red. And vice versa for the green candles and bullish DMI. Whenever the ADX falls below the 20, candles are netural which means there is no real trend in place.") TrendBarBullish = input(#27c22e, title="Bullish", group = "Trend Bars") TrendBarBearish = input(#ff0000, title="Bearish", group = "Trend Bars") TrendBarNeutral = input(#434651, title="Neutral", group = "Trend Bars") ShowTrend = input(defval=true, title="Show Trend Line", group = "Trend Line", tooltip = "Trend Line is the first part of the L&L Trend System. The trend line is nothing simplier than the 13 exponential moving average. The color of the Trend Line depends on the position of multiple exponential averages and whether they are stacked on top of each other or not.") TrendBullish = input(#27c22e, title="Bullish", group = "Trend Line") TrendBearish = input(#ff0000, title="Bearish", group = "Trend Line") TrendNeutral = input(#434651, title="Neutral", group = "Trend Line") ShowStop = input(defval=true, title="Show Stop Line", group = "Stop Line", tooltip = "Stop Line is the main and most important part of the system. It is based on a special ATR calculation that takes into consideration the past ATRs and prices of the 13 EMA. Stop Line provides zones that no moving average can. To make it simple it is something like a moving average that uses the ATR not the average price of the previous bars.") StopBullish = input(#27c22e, title="Bullish", group = "Stop Line") StopBearish = input(#ff0000, title="Bearish", group = "Stop Line") ShowTrend2 = input(defval=false, title="Show HTF Trend Line", group = "Higher Time Frame Trend Line", tooltip = "Higher Time Frame Trend Line.") TrendBullish2 = input(#27c22e, title="Bullish", group = "Higher Time Frame Trend Line") TrendBearish2 = input(#ff0000, title="Bearish", group = "Higher Time Frame Trend Line") TrendNeutral2 = input(#434651, title="Neutral", group = "Higher Time Frame Trend Line") ShowStop2 = input(defval=false, title="Show HTF Stop Line", group = "Higher Time Frame Stop Line", tooltip = "Higher Time Frame Stop Line") StopBullish2 = input(#27c22e, title="Bullish", group = "Higher Time Frame Stop Line") StopBearish2 = input(#ff0000, title="Bearish", group = "Higher Time Frame Stop Line") ShowCloud = input(defval=true, title="Show Cloud", group = "Trend Cloud", tooltip = "Cloud will paint the area behind the Trend Line and Stop Line with custom color.") CloudBullish = input(color.rgb(39,194,46,85), title="Bullish", group = "Trend Cloud") CloudBearish = input(color.rgb(255,0,0,85), title="Bearish", group = "Trend Cloud") ShowHTFCloud = input(defval=false, title="Show HTF Cloud", group = "Higher Time Frame Trend Cloud", tooltip = "Higher Time Frame Cloud.") CloudBullish2 = input(color.rgb(39,194,46,85), title="Bullish", group = "Higher Time Frame Trend Cloud") CloudBearish2 = input(color.rgb(255,0,0,85), title="Bearish", group = "Higher Time Frame Trend Cloud") // Trend Bars (DMI Colored Candles) BullishDMI = (high - high[1]) > (low[1] - low) and (high - high[1]) > 0 ? (high - high[1]) : 0 BearishDMI = (low[1] - low) > (high - high[1]) and (low[1] - low) > 0 ? (low[1] - low) : 0 DMIUp = 100 * ta.rma(BullishDMI,14) / ta.rma(ta.tr(true),14) DMIDown = 100 * ta.rma(BearishDMI,14) / ta.rma(ta.tr(true),14) ADXx = (DMIUp + DMIDown) > 0 ? 100 * math.abs(DMIUp - DMIDown) / (DMIUp + DMIDown) : na ADX = ta.rma(ADXx,14) ColorBars = ShowTrendBars and (DMIUp > DMIDown and ADX > 20) ? TrendBarBullish : ShowTrendBars and (DMIUp < DMIDown and ADX > 20) ? TrendBarBearish : ShowTrendBars ? TrendBarNeutral : na barcolor(color = ColorBars, editable = false) // Trend System (First Time Frame) ema8 = ta.vwma(close, 8) ema13 = ta.vwma(close, 13) ema21 = ta.vwma(close, 21) ema34 = ta.vwma(close, 34) emaup = ema8 > ema13 and ema13 > ema21 and ema21 > ema34 emadn = ema8 < ema13 and ema13 < ema21 and ema21 < ema34 Trend = ta.ema(close, 13) TrendColor = ShowTrend and emadn and close <= Trend ? TrendBearish : ShowTrend and emaup and close >= Trend ? TrendBullish : ShowTrend ? TrendNeutral : na plot(Trend,title = "Trend", color = TrendColor, linewidth = 2, editable = false) ATRLength = if TrendMode == "Tight" 60 else if TrendMode == "Normal" 80 else if TrendMode == "Loose" 100 else if TrendMode == "FOMC" 120 else if TrendMode == "Net" 140 ATR = (ATRLength/100) * ta.ema(ta.tr(true),8) Up = close > (Trend + ATR) Down = close < (Trend - ATR) var T = 0.0 T := Up ? 1 : Down ? -1 : T[1] StopLineColor = ShowStop and T == 1 ? StopBullish : ShowStop ? StopBearish : na plotchar(T == 1 ? (Trend-ATR) : T == -1 ? (Trend+ATR) : T[1], title = "StopLine",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor, editable = false) ATRA = (ATRLength - 20) /100 * ta.ema(ta.tr(true),8) Up11 = close > (Trend + ATRA) Down11 = close < (Trend - ATRA) var T11 = 0.0 T11 := Up11 ? 1 : Down11 ? -1 : T11[1] StopLineColor1 = ShowStop and T11 == 1 ? StopBullish : ShowStop ? StopBearish : na plotchar(T11 == 1 ? (Trend-ATRA) : T11 == -1 ? (Trend+ATRA) : T11[1], title = "StopLine2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor1, editable = false) ATRNET = TrendMode == "Net" ? (ATRLength - 40) /100 * ta.ema(ta.tr(true),8) : na UpNET = close > (Trend + ATRNET) DownNET = close < (Trend - ATRNET) var TNET = 0.0 TNET := UpNET ? 1 : DownNET ? -1 : TNET[1] StopLineColorNET = ShowStop and TNET == 1 ? StopBullish : ShowStop ? StopBearish : na plotchar(TNET == 1 ? (Trend-ATRNET) : TNET == -1 ? (Trend+ATRNET) : TNET[1], title = "StopLineNET",char = "-", location = location.absolute, size = size.tiny, color = StopLineColorNET, editable = false) ATRNET1 = TrendMode == "Net" ? (ATRLength - 60) /100 * ta.ema(ta.tr(true),8) : na UpNET1 = close > (Trend + ATRNET1) DownNET1 = close < (Trend - ATRNET1) var TNET1 = 0.0 TNET1 := UpNET1 ? 1 : DownNET1 ? -1 : TNET1[1] StopLineColorNET1 = ShowStop and TNET1 == 1 ? StopBullish : ShowStop ? StopBearish : na plotchar(TNET1 == 1 ? (Trend-ATRNET1) : TNET1 == -1 ? (Trend+ATRNET1) : TNET1[1], title = "StopLineNET1",char = "-", location = location.absolute, size = size.tiny, color = StopLineColorNET1, editable = false) ATRNET2 = TrendMode == "Net" ? (ATRLength - 80) /100 * ta.ema(ta.tr(true),8) : na UpNET2 = close > (Trend + ATRNET2) DownNET2 = close < (Trend - ATRNET2) var TNET2 = 0.0 TNET2 := UpNET2 ? 1 : DownNET2 ? -1 : TNET2[1] StopLineColorNET2 = ShowStop and TNET2 == 1 ? StopBullish : ShowStop ? StopBearish : na plotchar(TNET2 == 1 ? (Trend-ATRNET2) : TNET2 == -1 ? (Trend+ATRNET2) : TNET2[1], title = "StopLineNET2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColorNET2, editable = false) // Higher Time Frame Aggregations TimeFrameA = timeframe.period == '1' ? '5' : timeframe.period == '2' ? '5' : timeframe.period == '3' ? '5' : timeframe.period == '4' ? '5' : timeframe.period == '5' ? '30' : timeframe.period == '10' ? '30' : timeframe.period == '15' ? '30' : timeframe.period == '30' ? '240' : timeframe.period == '60' ? '240' : timeframe.period == '120' ? '240' : timeframe.period == '180' ? 'D' : timeframe.period == '240' ? 'D' : timeframe.period == 'D' ? 'W' : timeframe.period == 'W' ? 'M' : timeframe.period == 'M' ? '3M' : timeframe.period TimeFrame = if HTFMode == "Auto" TimeFrameA else if HTFMode == "Manual" TimeFrameM // Trend System (Second Time Frame) ema82 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 8)) ema132 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 13)) ema212 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 21)) ema342 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 34)) emaup2 = ema82 > ema132 and ema132 > ema212 and ema212 > ema342 emadn2 = ema82 < ema132 and ema132 < ema212 and ema212 < ema342 Trend2 = request.security(syminfo.tickerid, TimeFrame, ta.ema(close, 13)) TrendColor2 = ShowTrend2 and emadn2 and request.security(syminfo.tickerid, TimeFrame, close) <= Trend2 ? TrendBearish2 : ShowTrend2 and emaup2 and request.security(syminfo.tickerid, TimeFrame, close) >= Trend2 ? TrendBullish2 : ShowTrend2 ? TrendNeutral2 : na plot(Trend2, title = "Trend2", color = TrendColor2, linewidth = 2, editable = false) ATRLength2 = if TrendMode == "Tight" 60 else if TrendMode == "Normal" 80 else if TrendMode == "Loose" 100 else if TrendMode == "FOMC" 120 else if TrendMode == "Net" 140 ATR2 = (ATRLength2/100) * request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) Up2 = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2) Down2 = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2) var T2 = 0.0 T2 := Up2 ? 1 : Down2 ? -1 : T2[1] StopLineColor2 = ShowStop2 and T2 == 1 ? StopBullish2 : ShowStop2 ? StopBearish2 : na plotchar(T2 == 1 ? (Trend2-ATR2) : T2 == -1 ? (Trend2+ATR2) : T2[1], title = "StopLine2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor2, editable = false) ATR2A = (ATRLength2 - 20) /100 * request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) Up2A = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2A) Down2A = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2A) var T2A = 0.0 T2A := Up2A ? 1 : Down2A[1] ? -1 : T2A[1] StopLineColor2A = ShowStop2 and T2A == 1 ? StopBullish2 : ShowStop2 ? StopBearish2 : na plotchar(T2A == 1 ? (Trend2-ATR2A) : T2A == -1 ? (Trend2+ATR2A) : T2A[1], title = "StopLine2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor2A, editable = false) ATR2ANET = TrendMode == "Net" ? (ATRLength2 - 40) /100 * request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) : na Up2ANET = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2ANET) Down2ANET = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2ANET) var T2ANET = 0.0 T2ANET := Up2ANET ? 1 : Down2ANET[1] ? -1 : T2ANET[1] StopLineColor2ANET = ShowStop2 and T2ANET == 1 ? StopBullish2 : ShowStop2 ? StopBearish2 : na plotchar(T2ANET == 1 ? (Trend2-ATR2ANET) : T2ANET == -1 ? (Trend2+ATR2ANET) : T2ANET[1], title = "StopLine2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor2ANET, editable = false) ATR2ANET1 = TrendMode == "Net" ? (ATRLength2 - 60) /100 * request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) : na Up2ANET1 = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2ANET1) Down2ANET1 = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2ANET1) var T2ANET1 = 0.0 T2ANET1 := Up2ANET1 ? 1 : Down2ANET1[1] ? -1 : T2ANET1[1] StopLineColor2ANET1 = ShowStop2 and T2ANET1 == 1 ? StopBullish2 : ShowStop2 ? StopBearish2 : na plotchar(T2ANET1 == 1 ? (Trend2-ATR2ANET1) : T2ANET1 == -1 ? (Trend2+ATR2ANET1) : T2ANET1[1], title = "StopLine2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor2ANET1, editable = false) ATR2ANET2 = TrendMode == "Net" ? (ATRLength2 - 80) /100 * request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) : na Up2ANET2 = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2ANET2) Down2ANET2 = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2ANET2) var T2ANET2 = 0.0 T2ANET2 := Up2ANET2 ? 1 : Down2ANET2[1] ? -1 : T2ANET2[1] StopLineColor2ANET2 = ShowStop2 and T2ANET2 == 1 ? StopBullish2 : ShowStop2 ? StopBearish2 : na plotchar(T2ANET2 == 1 ? (Trend2-ATR2ANET2) : T2ANET2 == -1 ? (Trend2+ATR2ANET2) : T2ANET2[1], title = "StopLine2",char = "-", location = location.absolute, size = size.tiny, color = StopLineColor2ANET2, editable = false) // Trend Clouds p1 = plot(Trend, title = "Trend Line", color = TrendColor, linewidth = 2, display = display.none, editable = false) p2 = plot(T == 1 ? (Trend-ATR) : T == -1 ? (Trend+ATR) : T[1],title ="StopLine ", color = StopLineColor, linewidth = 2, display = display.none, editable = false) Cloud = ShowCloud and T == 1 ? CloudBullish : ShowCloud ? CloudBearish : na fill(p1,p2,title="TrendCloud",color = Cloud, editable = false) p3 = plot(Trend2, title = "Trend Line 2", color = TrendColor2, linewidth = 2, display = display.none, editable = false) p4 = plot(T2 == 1 ? (Trend2-ATR2) : T2 == -1 ? (Trend2+ATR2) : T2[1],title ="StopLine 2", color = StopLineColor2, linewidth = 2, display = display.none, editable = false) Cloud2 = ShowHTFCloud and T2 == 1 ? CloudBullish2 : ShowHTFCloud ? CloudBearish2 : na fill(p3,p4,title="TrendCloud2",color = Cloud2, editable = false)
Realized Profit & Loss [StratifyTrade]
https://www.tradingview.com/script/yLF2xSar-Realized-Profit-Loss-StratifyTrade/
StratifyTrade
https://www.tradingview.com/u/StratifyTrade/
149
study
5
CC-BY-NC-SA-4.0
// 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/ // Β© HunterAlgos //@version=5 indicator("Realized Profit & Loss [HunterAlgos]", shorttitle = "Realized Profit & Loss [1.0.0]", overlay = false) //----------------------------------------} //Type //----------------------------------------{ type bar float o = open float c = close float h = high float l = low bar b = bar.new() //----------------------------------------} //Inputs //----------------------------------------{ calc = input.string("Loss", "Calculation", group = "Settings", options = ["Loss", "Profit"]) zlen = input.int (7, "Z-Score Lenght", group = "Settings", minval = 2, tooltip = "Avg. Lenght of the Losses / Profit") thresh = input.float (2, "Threshold", group = "Settings", minval = 2, tooltip = "Filter out value over a tot. threshold", step = 0.1) width = input.int (4, "Histogram Width", group = "Settings", minval = 1) show_css = input.bool (false, "Show candle coloring", group = "Settings") css_low = input.color(color.green, "Low Loss / Profit", group = "Colors") css_normal = input.color(color.yellow, "Normal Loss / Profit", group = "Colors") css_medium = input.color(color.orange, "Medium Loss / Profit", group = "Colors") css_high = input.color(color.red, "High Loss / Profit", group = "Colors") lvl_low = input.float(2, "Low Level", minval = 1, step = 0.1, group = "Levels") lvl_normal = input.float(3, "Normal Level", minval = 1, step = 0.1, group = "Levels") lvl_medium = input.float(4, "Medium Level", minval = 1, step = 0.1, group = "Levels") lvl_high = input.float(5, "High Level", minval = 1, step = 0.1, group = "Levels") lvl_css = input.color(color.rgb(255, 255, 255, 80), "Levels Colors", group = "Levels") //----------------------------------------} //Functions //----------------------------------------{ //calculate loss/profit method loss(string calc, int zlen) => float out = na ticker = syminfo.basecurrency + "_LOSSESADDRESSES" id = request.security(ticker, "1D", b.c) b = (id / b.c) / ta.cum(id / b.c) out := switch calc "Profit" => ta.sma((b - b[1]), zlen) "Loss" => ta.sma((b - b[1]), zlen) * -1 out > 0 ? 0 : out //calculate colors method css(float ratio, color css1, color css2, color css3, color css4, float lvl1, float lvl2, float lvl3, float lvl4) => color col = na col := ratio >= lvl4 ? css4 : ratio >= lvl3 ? css3 : ratio >= lvl2 ? css2 : ratio >= lvl1 ? css1 : col col //calculate z-score based on a moving window windows(int zlen, float thresh) => var float[] id = array.new<float>(zlen) id.shift() id.push(calc.loss(zlen)) ratio = (0 - id.avg() / id.stdev()) < thresh ? na : (0 - id.avg() / id.stdev()) ratio //----------------------------------------} //Plotting //----------------------------------------{ out = windows(zlen, thresh) css = out.css(css_low, css_normal, css_medium, css_high, lvl_low, lvl_normal, lvl_medium, lvl_high) hline(lvl_low, color = lvl_css , linestyle = hline.style_solid) hline(lvl_normal, color = lvl_css , linestyle = hline.style_solid) hline(lvl_medium, color = lvl_css , linestyle = hline.style_solid) hline(lvl_high, color = lvl_css , linestyle = hline.style_solid) plot(out, "Realized Loss & Profit", color = css, linewidth = width, style = plot.style_histogram) barcolor(show_css ? css : na, title = "Bar coloring")
Custom EMA from X Days Ago
https://www.tradingview.com/script/1Ys4WWoh-Custom-EMA-from-X-Days-Ago/
firos_meethal
https://www.tradingview.com/u/firos_meethal/
12
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© firos_meethal //@version=5 indicator("Custom EMA from X Days Ago", overlay = true) // Input options daysAgo = input.int(4, title = "Days Ago", minval = 1) emaPeriod = input.int(10, title = "EMA Period") // Calculate the selected EMA ema = ta.ema(close, emaPeriod) // Get the value of the selected EMA from X days ago on the current timeframe emaXDaysAgo = request.security(syminfo.tickerid, timeframe.period, ema[daysAgo]) // Plot the selected EMA value from X days ago on today's candle plot(emaXDaysAgo, color = color.blue, title = "Custom EMA", style = plot.style_stepline, linewidth = 2) var bool sellSignal = na // Check if candle opens above and closes below the indicator, and plot a "SELL" label if open > emaXDaysAgo and close < emaXDaysAgo label.new(x=bar_index, y=low, text="Sell", style=label.style_label_up, color=color.red, textcolor=color.black) sellSignal := true
Market Sessions and TPO (+Forecast)
https://www.tradingview.com/script/y6jyaS39-Market-Sessions-and-TPO-Forecast/
MXWLL-Capital-Trading
https://www.tradingview.com/u/MXWLL-Capital-Trading/
695
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Mxwll Mxwll Capital //@version=5 indicator("Mxwll Sessions" , overlay = true , max_bars_back = 500, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500) proj = input.string(defval = "Bars", title = "Show Projection", options = ["Bars", "Line", "None"]) profileType = input.string(defval = "Bars", options = ["Letters", "Bars", "None"], title = "Profile Type") mult = input.int (defval = 1, title = "Profile Bar Multiplier", minval = 1) use = input.bool (defval = true, title = "Use ATR in Projection") removeBor = input.bool (defval = false, title = "Remove Box Border Color") prep = input.bool (defval = true, title = "Show Pre-Market") posp = input.bool (defval = true, title = "Show Post-Market") poc = input.bool (defval = true, title = "Show Naked POCs") showNY = input (true, title = '', inline = 'NY', group = 'New York') NYcol = input.color (#6929F2, title = '', inline = 'NY', group = 'New York') showLONDON = input (true, title = '', inline = 'LONDON', group = 'LONDON') LONDONcol = input.color (#F24968, title = '', inline = 'LONDON', group = 'LONDON') showAS = input (true, title = '', inline = 'ASIA', group = 'ASIA') AScol = input.color (#39FF14, title = '', inline = 'ASIA', group = 'ASIA') req() => cont = switch str.contains(syminfo.ticker, "T.P") true => syminfo.ticker + "_OI" => str.endswith(syminfo.ticker, "USDT") ? syminfo.ticker + ".P_OI" : syminfo.ticker + "T.P_OI" switch syminfo.type "crypto" => cont => string(na) oi = request.security(req(), timeframe.period, close - close[1]), var timeLevels = matrix.new<float>(2, 0) method conditional_add(matrix <float> id) => if timeframe.multiplier >= 30 timeLevels.add_col(timeLevels.columns(), array.from(high, low)) else max = 0., min = 1e8 if timeframe.change("30") for i = 0 to math.floor(30 / timeframe.multiplier) max := math.max(high[i], max) min := math.min(low [i], min) id.add_col(timeLevels.columns(), array.from(max, min)) timeLevels.conditional_add() type objects box sessionBox label sessionLabel box preSessionBox label preSessionLabel box postSessionBox label postSessionLabel var objNY = matrix.new<objects>(0, 6), var objLON = matrix.new<objects>(0, 6), var objAS = matrix.new<objects>(0, 6) method newObject(matrix <objects> id, titleTime, title, color col, bool condition)=> if condition and last_bar_index - bar_index <= 7000 var timE = 0, var HIGH = high, var LOW = low, var vol = 0., var delta = 0., var oiD = 0. if titleTime > titleTime[1] timE := bar_index, HIGH := high, LOW := low, vol := volume, oiD := oi calc = math.sign(close - open) delta := switch calc -1 => -volume => volume id.add_row(id.rows(), array.from( objects.new(sessionBox = box.new(bar_index, HIGH, bar_index, LOW, bgcolor = color.new(col, 90), border_color = removeBor ? na : col )), objects.new(sessionLabel = label.new(timE, HIGH, title, textcolor = col, color = #ffffff00, size = size.tiny)), objects.new(preSessionBox = box (na)), objects.new(preSessionLabel = label(na)), objects.new(postSessionBox = box (na)), objects.new(postSessionLabel= label(na)) )) if titleTime and titleTime == titleTime[1] HIGH := math.max(high, HIGH), vol += volume, oiD += oi LOW := math.min(low , LOW) , calc = math.sign(close - open) switch calc -1 => delta -= volume => delta += volume if id.rows() > 0 if not na(id.get(id.rows() - 1, 0)) id.get(id.rows() - 1, 0).sessionBox.set_top(HIGH) id.get(id.rows() - 1, 0).sessionBox.set_rightbottom(bar_index, LOW) rang1 = id.get(id.rows() - 1, 0).sessionBox.get_top() - id.get(id.rows() - 1, 0) .sessionBox.get_bottom() rang2 = (id.get(id.rows() - 1, 0).sessionBox.get_top() + id.get(id.rows() - 1, 0).sessionBox.get_bottom()) / 2 finrang = rang1 / rang2 * 100 if not na(id.get(id.rows() - 1, 1)) id.get(id.rows() - 1, 1).sessionLabel.set_xy(int(math.avg(timE, bar_index)), HIGH) id.get(id.rows() - 1, 1).sessionLabel.set_text(title + "\nRange: " + str.tostring(finrang, format.percent) + "\nVol: " + str.tostring(vol , format.volume ) + "\nβˆ†: " + str.tostring(delta , format.volume ) + "\nOI: " + str.tostring(oiD , format.mintick)) signTime(TIME) => int(math.sign(nz(time(timeframe.period, TIME, "America/New_York")))) [preny, prel, pres] = switch timeframe.multiplier <= 5 => ["0630-0931", "0005-0301", "1900-2001"] timeframe.multiplier <= 30 => ["0630-0931", "0000-0301", "1900-2001"] => ["0600-1000", "0000-0301", "1900-2001"] [nyT, lonT] = switch timeframe.multiplier <= 30 => ['0930-1601', '0300-1131'] timeframe.multiplier => ['0900-1601', '0300-1101'] nytrue = signTime(nyT ), prenytrue = signTime(preny) lontrue = signTime(lonT ), prelontrue = signTime(prel ) astrue = signTime('2000-0501' ), preaustrue = signTime(pres ) objNY .newObject(nytrue ,"New York" , NYcol, showNY), objLON.newObject(lontrue , "London", LONDONcol, showLONDON), objAS .newObject(astrue ,"Asia", AScol, showAS) method preSessionDraw(matrix <objects> id, int time1, int time2, int time3, color col, bool condition, bool activate) => if prep if last_bar_index - bar_index <= 5000 and condition and activate if not na(id.get(id.rows() - 1, 0)) var preBar = 0 preBar := switch not time2[1] and time2 true => bar_index => preBar == 0 ? bar_index : preBar if not time1[1] and time1 id.set(id.rows() - 1, 2, objects.new(preSessionBox = box.new(preBar, high, bar_index, low, border_style = line.style_dashed, border_color = removeBor ? na : col, bgcolor = color.new(col, 90) ))) id.set(id.rows() - 1, 3, objects.new(preSessionLabel = label.new(bar_index, high, color = #00000000, text = "OPEN", textcolor = color.white, size = size.tiny, style = label.style_label_down ))) if id.rows() > 0 and time3 == 1 if not na(id.get(id.rows() - 1, 0)) id.get(id.rows() - 1, 2).preSessionBox .set_top (id.get(id.rows() - 1, 0).sessionBox.get_top()) id.get(id.rows() - 1, 2).preSessionBox .set_bottom(id.get(id.rows() - 1, 0).sessionBox.get_bottom()) id.get(id.rows() - 1, 3).preSessionLabel.set_y (id.get(id.rows() - 1, 0).sessionBox.get_top()) [nyP, lonP, nyP1, lonP1] = switch timeframe.multiplier <= 30 => ['0930-0931', '0300-0301', "0931-1601", "0301-1130"] timeframe.multiplier => ['0900-0901', '0300-0301', "0901-1601", "0301-1100"] objNY .preSessionDraw(signTime(nyP), signTime(preny), signTime(nyP1), NYcol, showNY, true) objLON.preSessionDraw(signTime(lonP), signTime(prel ), signTime(lonP1), LONDONcol, showLONDON, true) objAS .preSessionDraw(signTime("2000-2001"), signTime(pres ), signTime("2001-0501"), AScol, showAS, false) var string [] strx = array.from( " A", " B", " C", " D", " E", " F", " G", " H", " I", " J", " K", " L", " M", " N", " O", " P", " Q", " R", " S", " T", " U", " V", " W", " X", " Y", " Z", " a", " b", " c", " d", " e", " f", " g", " h", " i", " j", " k", " l", " m", " n", " o", " p", " q", " r", " s", " t", " u", " v", " w", " x", " y", " z" ) if barstate.isfirst and profileType == "Letters" sX = "" for i = 0 to 1275 index = i % 52 sX := strx.get(index) strx.push(sX) var POCLINES = array.new_line(), earliest = array.new_int(), calcTime = 600 / timeframe.multiplier + 5 method postSessionDraw(matrix <objects> id, int time1, int time2, color col, bool condition, bool activate) => level = array.new_float(), lab = array.new_string(), bsize = array.new_int() if last_bar_index - bar_index <= 5000 and condition if not na(id.get(id.rows() - 1, 0)) if not time1[1] and time1 if profileType != "None" calc = (id.get(id.rows() - 1, 0).sessionBox.get_top() - id.get(id.rows() - 1, 0).sessionBox.get_bottom()) / 20 index = 0, for i = 0 to 20 level.push(id.get(id.rows() - 1, 0).sessionBox.get_bottom() + (calc * i)) switch profileType "Letters" => lab.push("") , bsize.push(0) "Bars" => bsize.push(0), index := 1 increment = switch timeframe.multiplier >= 30 => 1 => 30 / timeframe.multiplier for i = math.ceil(id.get(id.rows() - 1, 0).sessionBox.get_left() / increment) to timeLevels.columns() - 1 highest = level.binary_search_leftmost (timeLevels.row(0).get(i)) lowest = level.binary_search_rightmost(timeLevels.row(1).get(i)) for x = lowest to highest switch profileType "Letters" => lab .set(x, lab.get(x) + strx.get(i - math.ceil(id.get(id.rows() - 1, 0).sessionBox.get_left() / increment))) "Bars" => bsize.set(x, bsize.get(x) + 1) nearest = 1000. if profileType == "Letters" for i = 0 to 20 split = str.split(lab.get(i), " ") bsize.set(i, split.size()) if bsize.indexof(bsize.max()) != bsize.lastindexof(bsize.max()) mid = math.round(bsize.size() / 2) for i = 0 to 20 if math.abs(mid - bsize.get(i)) < nearest and bsize.get(i) == bsize.max() nearest := i for i = index to 20 colorCond = switch nearest == 1000 => bsize.get(i) == bsize.max() => i == nearest COL = switch colorCond => #6929F2 bsize.get(i) == 1 => #F24968 => profileType == "Bars" ? col : color.white if colorCond and poc mid = switch profileType "Letters" => level.get(i) => math.avg(level.get(i), level.get(i - 1)) POCLINES.push(line.new(id.get(id.rows() - 1, 0).sessionBox.get_left(), mid, bar_index, mid, color = color.new(color.red, 60), width = 2 )) switch profileType "Letters" => label.new(id.get(id.rows() - 1, 0).sessionBox.get_left(), level.get(i), lab.get(i), style = label.style_label_left, textcolor = COL, text_font_family = font.family_monospace, size = size.tiny, color = #00000000) "Bars" => box.new( id.get(id.rows() - 1, 0).sessionBox.get_left(), level.get(i), id.get(id.rows() - 1, 0).sessionBox.get_left() + (bsize.get(i) * mult), level.get(i - 1), bgcolor = color.new(COL, 80), border_color = removeBor ? na : color.new(COL, 80) ) if activate and posp id.set(id.rows() - 1, 4, objects.new( postSessionBox = box.new(bar_index, high, bar_index, low, border_style = line.style_dashed, border_color = removeBor ? na : col, bgcolor = color.new(col, 90) ))) id.set(id.rows() - 1, 5, objects.new(postSessionLabel = label.new(bar_index, high, color = #00000000, text = "CLOSE", textcolor = color.white, size = size.tiny, style = label.style_label_down ))) if activate if time2 and id.rows() > 0 if not na(id.get(id.rows() - 1, 0)) and not na(id.get(id.rows() - 1, 2)) max = math.max(high, id.get(id.rows() - 1, 0).sessionBox.get_top ()) min = math.min(low, id.get(id.rows() - 1, 0).sessionBox.get_bottom()) id.get(id.rows() - 1, 5).postSessionLabel.set_y (max), id.get(id.rows() - 1, 4).postSessionBox .set_top (max) id.get(id.rows() - 1, 4).postSessionBox .set_right (bar_index), id.get(id.rows() - 1, 4).postSessionBox .set_bottom(min) id.get(id.rows() - 1, 2).preSessionBox .set_top (max), id.get(id.rows() - 1, 2).preSessionBox .set_bottom(min) id.get(id.rows() - 1, 0).sessionBox .set_bottom(min), id.get(id.rows() - 1, 0).sessionBox .set_top (max) id.get(id.rows() - 1, 1).sessionLabel .set_y (max), id.get(id.rows() - 1, 3).preSessionLabel .set_y (max) lonAf = switch timeframe.multiplier <= 30 => "1130-1131" => "1100-1101" [aftny, aftl, afts] = switch timeframe.multiplier <= 15 => ["1600-2001", "1130-1245", "0200-0500"] timeframe.multiplier <= 30 => ["1600-2001", "1130-1300", "0200-0500"] => ["1600-2001", "1100-1300", "0200-0500"] objNY .postSessionDraw(signTime("1600-1601"), signTime(aftny), NYcol, showNY , true) objLON.postSessionDraw(signTime(lonAf), signTime(aftl ), LONDONcol, showLONDON, true) objAS .postSessionDraw(signTime("0500-0501"), signTime(afts ), AScol, showAS ,false), var cloMat = matrix.new<float>(0, calcTime), var hiMat = matrix.new<float>(0, calcTime), var loMat = matrix.new<float>(0, calcTime) var cloMatl = matrix.new<float>(0, calcTime), var hiMatl = matrix.new<float>(0, calcTime), var loMatl = matrix.new<float>(0, calcTime) var cloMata = matrix.new<float>(0, calcTime), var hiMata = matrix.new<float>(0, calcTime), var loMata = matrix.new<float>(0, calcTime) method collectData(matrix<float> id, TIME, matrix<float> id2, matrix<float> id3, color col, bool condition) => if proj != "None" var int columnPlace = -1, var maxPlace = 0 , atr = ta.atr(14) cond1 = signTime(TIME), cond2 = cond1[1], var index = 0 var project = array.new_line(), var projectBox = array.new_box(), var hlMat = matrix.new<line>(2, 0) if cond1 == 1 columnPlace += 1 maxPlace := math.max(columnPlace, maxPlace) if cond2 == 0 id.add_row(id.rows()), id2.add_row(id2.rows()), id3.add_row(id3.rows()), index := bar_index id.set (id.rows() - 1, columnPlace, ((close - close[1]) / close[1])) id2.set(id2.rows() - 1, columnPlace, (high - math.max(open, close)) / math.max(open, close)) id3.set(id3.rows() - 1, columnPlace, (low - math.min(open, close)) / math.min(open, close)) if cond1 != 1 columnPlace := 0 if project.size() > 0 for i = 0 to project.size() - 1 project.shift().delete() if projectBox.size() > 0 for i = 0 to projectBox.size() - 1 projectBox.shift().delete() if hlMat.columns() > 0 for i = 0 to hlMat.columns() - 1 hlMat.get(0, i).delete() hlMat.get(1, i).delete() hlMat .remove_col() if barstate.islast if not condition or condition and signTime("0300-0501") != 1 finClo = id .submatrix(0, id.rows (), 0, maxPlace + 1) finHi = id2.submatrix(0, id2.rows(), 0, maxPlace + 1) finLo = id3.submatrix(0, id3.rows(), 0, maxPlace + 1) if cond1 == 1 start = bar_index - index if proj == "Line" if project.size() > 0 for i = 0 to project.size() - 1 project.shift().delete() project.push(line.new(last_bar_index, close, last_bar_index + 1, close[1] * (1 + finClo.col(start).median()), style = line.style_dotted, color = col)) for i = start + 1 to finClo.columns() - 1 x = project.last().get_x2() y = project.last().get_y2() project.push(line.new(x, y, x + 1, y * (1 + finClo.col(i).median()), style = line.style_dotted, color = col)) if proj == "Bars" if projectBox.size() > 0 for i = 0 to projectBox.size() - 1 projectBox.shift().delete() if hlMat.columns() > 0 for i = 0 to hlMat.columns() - 1 hlMat.get(0, i).delete() hlMat.get(1, i).delete() for i = 0 to hlMat.columns() - 1 hlMat.remove_col() projectBox.push(box.new(last_bar_index, close[1], last_bar_index + 2, close[1] * (1 + finClo.col(start).median()), bgcolor = color.new(col, 80), border_color = col )) if use switch math.sign(projectBox.last().get_bottom() - projectBox.last().get_top()) 1 => projectBox.last().set_bottom(projectBox.last().get_bottom() + atr) -1 => projectBox.last().set_bottom(projectBox.last().get_bottom() - atr) hlMat.add_col(hlMat.columns(), array.from( line.new( last_bar_index + 1, math.max(projectBox.last().get_top(), projectBox.last().get_bottom()), last_bar_index + 1, math.max(projectBox.last().get_top(), projectBox.last().get_bottom()) * (1 + finHi.col(start).median()), color = col ), line.new( last_bar_index + 1, math.min(projectBox.last().get_top(), projectBox.last().get_bottom()), last_bar_index + 1, math.min(projectBox.last().get_top(), projectBox.last().get_bottom()) * (1 + finLo.col(start).median()), color = col ))) if start + 1 < finClo.columns() - 2 for i = start + 1 to math.min(start + 26, finClo.columns() - 1) x = projectBox.last().get_right () y = projectBox.last().get_bottom() projectBox.push(box.new(x, y, x + 2, y * (1 + finClo.col(i).median()), bgcolor = color.new(col, 80), border_color = col)) switch math.sign(projectBox.last().get_bottom() - projectBox.last().get_top()) 1 => projectBox.last().set_bottom(projectBox.last().get_bottom() + atr) -1 => projectBox.last().set_bottom(projectBox.last().get_bottom() - atr) hlMat.add_col(hlMat.columns(), array.from( line.new( x + 1, math.max(projectBox.last().get_top(), projectBox.last().get_bottom()), x + 1, math.max(projectBox.last().get_top(), projectBox.last().get_bottom()) * (1 + finHi.col(i).median()), color = col ), line.new( x + 1, math.min(projectBox.last().get_top(), projectBox.last().get_bottom()), x + 1, math.min(projectBox.last().get_top(), projectBox.last().get_bottom()) * (1 + finLo.col(i).median()), color = col ))) cloMat .collectData(nyP1, hiMat, loMat, NYcol, false), cloMatl.collectData(lonP1, hiMatl, loMatl, LONDONcol, false), cloMata.collectData("2001-0501", hiMata, loMata, AScol, true) method lineDelete (array <line> id) => if id.size() > 0 for i = 0 to id.size() - 1 if id.get(i).get_y1() == id.get(i).get_y2() if high >= id.get(i).get_y1() and low <= id.get(i).get_y1() id.get(i).set_y2(id.get(i).get_y2() + syminfo.mintick) if id.get(i).get_y1() == id.get(i).get_y2() id.get(i).set_x2(bar_index) method leftCheck(matrix <objects> id) => if id.rows() > 0 for i = 0 to id.rows() - 1 if not na(id.get(i, 2)) earliest.push(id.get(i, 2).preSessionBox.get_left()) POCLINES.lineDelete() if barstate.islast objNY .leftCheck(), objLON.leftCheck(), objAS .leftCheck() lin = line.all, bo = box.all, lab = label.all if lin.size() > 0 for i = 0 to lin.size() - 1 if lin.get(i).get_x1() < earliest.min() lin.get(i).delete() if bo.size() > 0 for i = 0 to bo.size() - 1 if bo.get(i).get_left() < earliest.min() bo.get(i).delete() if lab.size() > 0 for i = 0 to lab.size() - 1 if lab.get(i).get_x() < earliest.min() lab.get(i).delete()
ATR + Momentum Shifts w/Take Profit
https://www.tradingview.com/script/IdXK6yLz-ATR-Momentum-Shifts-w-Take-Profit/
DraftVenture
https://www.tradingview.com/u/DraftVenture/
16
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 // Β© DraftVenture //@version=5 indicator(title="ATR + Momentum Shifts w/Take Profit", overlay=true, timeframe="", timeframe_gaps=true) // Inputs atr_length = input(9, title="ATR Length") atr_mult = input.float(2, step=0.1, title="ATR Multiplier") momentum_length = input.int(18, minval=1, title="Momentum Length") take_profit_above = input(2.0, title="Take Profit Long") take_profit_below = input(2.0, title="Take Profit Short") source = input(close, title="Source") // Calculate ATR atr_ = atr_mult * ta.atr(atr_length) // Calculate Momentum mom = source - source[momentum_length] // Custom Colors upperColor = color.new(#ff9393, 25) lowerColor = color.new(#ff9393, 25) longArrowColor = color.new(#fffc3f, 0) shortArrowColor = color.new(#fffc3f, 1) takeProfitColor = color.new(#a1ffa5, 50) // Plot ATR Bands plot(source + atr_, color=upperColor, linewidth=2, style=plot.style_steplinebr, title="Upper Trailing Stop") plot(source - atr_, color=lowerColor, linewidth=2, style=plot.style_steplinebr, title="Lower Trailing Stop") // Plot Shift Arrows plotshape(mom > 0 and ta.crossover(mom, 0), style=shape.triangleup, location=location.belowbar, color=longArrowColor, size=size.small, title="Potential Long Entry") plotshape(mom < 0 and ta.crossunder(mom, 0), style=shape.triangledown, location=location.abovebar, color=shortArrowColor, size=size.small, title="Potential Short Entry") // Calculate Take Profit Levels takeProfitLevelAbove = source + take_profit_above * atr_ takeProfitLevelBelow = source - take_profit_below * atr_ // Plot Take Profit Levels plot(takeProfitLevelAbove, title="Take Profit Long", color=takeProfitColor, linewidth=2, style=plot.style_steplinebr) plot(takeProfitLevelBelow, title="Take Profit Short", color=takeProfitColor, linewidth=2, style=plot.style_steplinebr) // Indicator by KP
MTF Key Levels [Mxwll]
https://www.tradingview.com/script/qfNwtsJS-MTF-Key-Levels-Mxwll/
MXWLL-Capital-Trading
https://www.tradingview.com/u/MXWLL-Capital-Trading/
215
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© MxwllCapital // //@version=5 indicator("Mxwll MTF S/R", overlay = true, max_lines_count = 500) extend = input.string(defval = "Both", options = ["Left", "Right", "Both", "None"], title = "Extend Lines") style = input.string(defval = "Dotted", title = "Line Style", options = ["Dotted", "Solid", "Dashed"]) min5Show = input.bool (title = "5 Min Levelsβ€€", defval = true,group = "S/R Levels", inline = "40") min5col = input.color (title = "", defval = color.blue , group = "S/R Levels", inline = "40") min15Show = input.bool (title = "15 Min Levels", defval = true ,group = "S/R Levels", inline = "40") min15col = input.color (title = "", defval = color.yellow , group = "S/R Levels", inline = "40") min30Show = input.bool (title = "30 Min Levels", defval = true ,group = "S/R Levels", inline = "42") min30col = input.color (title = "", defval = color.orange , group = "S/R Levels", inline = "42") min60Show = input.bool (title = "1 Hour Levels", defval = true, group = "S/R Levels", inline = "42") min60col = input.color (title = "", defval = color.lime, group = "S/R Levels", inline = "42") min240Show = input.bool (title = "4 Hour Levels", defval = true, group = "S/R Levels", inline = "44") min240col = input.color (title = "", defval = color.white, group = "S/R Levels", inline = "44") min1440Show = input.bool (title = "Daily Levelsβ€€β€€", defval = true, group = "S/R Levels", inline = "44") min1440col = input.color (title = "", defval = color.purple, group = "S/R Levels", inline = "44") minWShow = input.bool (title = "Weekly Levels", defval = true, group = "S/R Levels", inline = "46") minWcol = input.color (title = "", defval = color.aqua, group = "S/R Levels", inline = "46") finStyle = switch style "Dotted" => line.style_dotted "Dashed" => line.style_dashed => line.style_solid type priceValues float higH float loW int hiIndex int loIndex var pv = matrix.new<priceValues>(7, 4) if barstate.isfirst for x = 0 to 6 for i = 0 to 3 value = switch i == 0 => priceValues.new(higH = 0 ) i == 1 => priceValues.new(loW = 1e8) i == 2 => priceValues.new(hiIndex = 0 ) i == 3 => priceValues.new(loIndex = 0 ) pv.set(x, i, value), pv.set(x, i, value) pv.set(x, i, value), pv.set(x, i, value) method determine (float id, int A, int B, float C) => switch id == C true => A => B method append (matrix <priceValues> id, int length, int row) => if barstate.islastconfirmedhistory for i = 0 to length id.set(row, 0, priceValues.new(higH = math.max(math.avg(close[i], high[i]), nz(id.get(row, 0).higH, 0)))), id.set(row, 2, priceValues.new(hiIndex = math.avg(close[i], high[i]).determine(math.round(time[i]), nz(id.get(row, 2).hiIndex, 0), id.get(row, 0).higH))) id.set(row, 1, priceValues.new(loW = math.min(math.avg(close[i], low[i] ), nz(id.get(row, 1).loW, 1e8)))), id.set(row, 3, priceValues.new(loIndex = math.avg(close[i], low[i]).determine(math.round(time[i]), nz(id.get(row, 3).loIndex, 0), id.get(row, 1).loW))) req(int length, int row) => pv .append(length, row) loW = pv.get (row, 1).loW higH = pv.get (row, 0).higH hiIndex = pv.get (row, 2).hiIndex loIndex = pv.get (row, 3).loIndex [loW, higH, hiIndex, loIndex] [min5S, min5R, min5Rtime, min5Stime] = request.security(syminfo.tickerid, "5", req(60, 0), lookahead = barmerge.lookahead_on) [min15S, min15R, min15Rtime, min15Stime] = request.security(syminfo.tickerid, "15", req(60, 1), lookahead = barmerge.lookahead_on) [min30S, min30R, min30Rtime, min30Stime] = request.security(syminfo.tickerid, "30", req(60, 2), lookahead = barmerge.lookahead_on) [min60S, min60R, min60Rtime, min60Stime] = request.security(syminfo.tickerid, "60", req(60, 3), lookahead = barmerge.lookahead_on) [min240S, min240R, min240Rtime, min240Stime] = request.security(syminfo.tickerid, "240", req(30, 4), lookahead = barmerge.lookahead_on) [min1440S, min1440R, min1440Rtime, min1440Stime] = request.security(syminfo.tickerid, "1440", req(30, 5), lookahead = barmerge.lookahead_on) [minWS, minWR, minWRtime, minWStime] = request.security(syminfo.tickerid, "W", req(15, 6), lookahead = barmerge.lookahead_on) ex = switch extend "None" => extend.none "Left" => extend.left "Right" => extend.right "Both" => extend.both type objects line support line resistance var obj = matrix.new<objects>(7, 2) method condS (float id) => not na(id) and id != 1e8 method condR (float id) => not na(id) and id != 0 method lineSetSupport(matrix <objects> id, int row, int column, line ) => if not na(id.get(row, column)) id.get(row, column).support.delete() id.set(row, column, objects.new( support = line )) method lineSetResistance(matrix <objects> id, int row, int column, line ) => if not na(obj.get(row, column)) obj.get(row, column).resistance.delete() id.set(row, column, objects.new( resistance = line )) if barstate.islast if min5Show if min5S.condS() obj.lineSetSupport( 0, 0, line.new( min5Stime, min5S, last_bar_time + (time - time[5]), min5S, extend = ex, xloc = xloc.bar_time, width = 1, style = finStyle, color = min5col )) if min5R.condR() obj.lineSetResistance(0, 1, line.new(min5Rtime, min5R, last_bar_time + (time - time[5]), min5R, extend = ex, xloc = xloc.bar_time, width = 1, style = finStyle, color = min5col )) if min15Show if min15S.condS() obj.lineSetSupport(1, 0, line.new(min15Stime, min15S, last_bar_time+ (time - time[5]), min15S, extend = ex, xloc = xloc.bar_time, color = min15col, width = 1, style = finStyle )) if min15R.condR() obj.lineSetResistance(1, 1, line.new(min15Rtime, min15R, last_bar_time+ (time - time[5]), min15R, extend = ex, xloc = xloc.bar_time, color = min15col, width = 1, style = finStyle )) if min30Show if min30S.condS() obj.lineSetSupport(2, 0, line.new(min30Stime, min30S, last_bar_time+ (time - time[5]), min30S, extend = ex, xloc = xloc.bar_time, color = min30col, style = finStyle )) if min30R.condS() obj.lineSetResistance(2, 1, line.new(min30Rtime, min30R, last_bar_time+ (time - time[5]), min30R, extend = ex, xloc = xloc.bar_time, color = min30col, style = finStyle )) if min60Show if min60S.condS() obj.lineSetSupport(3, 0, line.new(min60Stime, min60S, last_bar_time+ (time - time[5]), min60S, extend = ex, xloc = xloc.bar_time, color = min60col, style = finStyle )) if min60R.condR() obj.lineSetResistance(3, 1, line.new(min60Rtime, min60R, last_bar_time+ (time - time[5]), min60R, extend = ex, xloc = xloc.bar_time, color = min60col, style = finStyle )) if min240Show if min240S.condS() obj.lineSetSupport(4, 0, line.new(min240Stime, min240S, last_bar_time+ (time - time[5]), min240S, extend = ex, xloc = xloc.bar_time, color = min240col, style = finStyle )) if min240R.condR() obj.lineSetResistance(4, 1, line.new(min240Rtime, min240R, last_bar_time+ (time - time[5]), min240R, extend = ex, xloc = xloc.bar_time, color = min240col, style = finStyle )) if min1440Show if min1440S.condS() obj.lineSetSupport(5, 0, line.new(min1440Stime, min1440S, last_bar_time+ (time - time[5]), min1440S, extend = ex, xloc = xloc.bar_time, color = min1440col, style = finStyle )) if min1440R.condR() obj.lineSetResistance(5, 1, line.new(min1440Rtime, min1440R, last_bar_time+ (time - time[5]), min1440R, extend = ex, xloc = xloc.bar_time, color = min1440col, style = finStyle )) if minWShow if minWS.condS() obj.lineSetSupport(6, 0, line.new(minWStime, minWS, last_bar_time+ (time - time[5]), minWS, extend = ex, xloc = xloc.bar_time, color = minWcol, style = finStyle )) if minWR.condR() obj.lineSetResistance(6, 1, line.new(minWRtime, minWR, last_bar_time+ (time - time[5]), minWR, extend = ex, xloc = xloc.bar_time, color = minWcol, style = finStyle )) res = array.from("5 Min: ♦", "15 Min: ♦", "30 Min: ♦", "1 Hour: ♦", "4 Hour: ♦", "Daily: ♦", "Weekly: ♦") resCol = array.from (min5col ,min15col ,min30col ,min60col ,min240col ,min1440col ,minWcol) valS = array.from(min5S, min15S, min30S, min60S, min240S, min1440S, minWS) valR = array.from(min5R, min15R, min30R, min60R, min240R, min1440R, minWR) var table tab = table.new(position.bottom_right, 10, 10, bgcolor = #102739, frame_color = color.white, frame_width = 1, border_color = color.white, border_width = 1) tab.cell(1, 0, "Resolution", text_color = color.white), tab.cell(2, 0, "Support", text_color = color.white), tab.cell(3, 0, "Resistance", text_color = color.white) for i = 0 to 6 tab.cell(1, i + 1, text = res.get(i), text_halign = text.align_right, text_size = size.small, text_color = resCol.get(i)) finS = switch valS.get(i).condS() true => str.tostring(valS.get(i), format.mintick) => "Calculating" finR = switch valR.get(i).condR() true => str.tostring(valR.get(i), format.mintick) => "Calculating" tab.cell(2, i + 1, text = finS, text_size = size.small, text_color = resCol.get(i)) tab.cell(3, i + 1, text = finR, text_size = size.small, text_color = resCol.get(i))
Indicator Based Market Exposure (IBME)
https://www.tradingview.com/script/7OkUA5dc-Indicator-Based-Market-Exposure-IBME/
Amphibiantrading
https://www.tradingview.com/u/Amphibiantrading/
297
study
5
MPL-2.0
// This source code is subject to the teratioMults of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Amphibiantrading //@version=5 indicator('Indicator Based Market Exposure', shorttitle = 'IBME', overlay = true) //---------inputs---------// showRunTime = input.bool(true, 'Show Time Frame Error', tooltip = 'The IBME signal is meant to be shown on a daily chart. Selecting this option will warn you if you are on a different time frame.') var g0 = 'Display Options' bgHighlight = input.bool(true, 'Highlight Chart Background', group = g0) bgColG = input(color.rgb(76, 175, 80, 85), 'Background Color Green') bgColY = input(color.rgb(246, 191, 32, 85),'Background Color Yellow') bgColR = input(color.rgb(255, 82, 82, 85), 'Background Color Red') var g1 = 'Table Options' showTable = input.bool(true, 'Show IBME Data Table', group = g1) showSep = input.bool(false, 'Show Individual Signals', group = g1) yPos = input.string('Top', 'Table Position ', options = ['Top', 'Middle', 'Bottom'], inline = '1', group= g1) xPos = input.string('Right', ' ', options = ['Right','Center', 'Left'], inline = '1', group = g1) tableTextSize = input.string('Normal', 'Text Size', options = ['Small','Normal','Large','Huge'], inline = '2', group = g1) tableTextColor = input.color(color.black, 'Text Color', inline = '2', group = g1) tableBgColor = input.color(color.white, 'Table Background Color', group = g1) var g2 = 'MSI Settings' advIssues = input.symbol('ADVN', 'Advancing Stocks Symbol', group = g2) decIssues = input.symbol('DECN', 'Declining Stocks Symbol', group = g2) isRA = input.bool(true, 'Stockcharts version (Ratio Adjusted)?', group = g2) ratioMult = input.int(1000, 'RANA ratio multiplier', group = g2) msiMaLen = input.int(10, 'SMA Length', group = g2) var g3 = 'Net High / Lows Settings' inas = input.bool(true,'Nasdaq', inline = '1', group = g3) inyse = input.bool(false,'NYSE', inline = '1', group = g3) nhlMaLen = input.int(50, 'SMA Length', group = g3) var g4 = 'Price Action Settings' maSym = input.symbol('QQQ', 'Moving Average Symbol', group = g4) ma1len = input.int(10, 'Fast MA', inline = '1', group = g4) ma1Type = input.string('SMA', ' ', options = ['EMA', 'SMA'], inline = '1', group = g4) ma2len = input.int(20, 'Fast MA', inline = '2', group = g4) ma2Type = input.string('SMA', ' ', options = ['EMA', 'SMA'], inline = '2', group = g4) //----------functions & switch----------// txtSize = switch tableTextSize 'Small' => size.small 'Normal' => size.normal 'Large' => size.large 'Huge' => size.huge getArrayValue(arr, idx) => if array.size(arr) > idx array.get(arr, idx) else na //---------msi---------// ai = request.security(advIssues, 'D', close) di = request.security(decIssues, 'D', close) rana = ratioMult * (ai-di)/(ai+di) e1 = isRA ? ta.ema(rana, 19) : ta.ema(ai-di, 19) e2 = isRA ? ta.ema(rana, 39) : ta.ema(ai-di, 39) mo = e1 - e2 msi = 0. msi := nz(msi[1]) + mo ma = ta.sma(msi,msiMaLen) greenMsi = msi > ma //---------net high lows---------// hq = request.security('HIGQ', 'D', close) lq = request.security('LOWQ', 'D', close) hn = request.security('HIGN', 'D', close) ln = request.security('LOWN', 'D', close) higq = inas ? hq : 0 lowq = inas ? lq : 0 hign = inyse ? hn : 0 lown = inyse ? ln : 0 nhighs = hign + higq - lown - lowq greenNhl = nhighs > 0 nhlMA = ta.sma(nhighs, nhlMaLen) greenXover = nhighs >= nhlMA //---------moving averages---------// ma1 = ma1Type == 'EMA' ? ta.ema(close,ma1len) : ta.sma(close,ma1len) ma2 = ma2Type == 'EMA' ? ta.ema(close,ma2len) : ta.sma(close,ma2len) symMa1 = request.security(maSym, 'D', ma1) symMa2 = request.security(maSym, 'D', ma2) symCl = request.security(maSym, 'D', close) stacked = symMa1 > symMa2 and symCl >= symMa1 //---------signals---------// sig1 = greenMsi and greenNhl and greenXover and stacked sig2 = greenMsi and greenNhl and greenXover and not stacked sig3 = greenMsi and greenNhl and not greenXover sig4 = greenMsi and not greenNhl and greenXover sig5 = greenMsi and not greenNhl and not greenXover sig6 = not greenMsi and greenNhl and greenXover sig7 = not greenMsi and greenNhl and not greenXover and stacked sig8 = not greenMsi and not greenNhl and greenXover and stacked sig9 = not greenMsi and not greenNhl and not greenXover and stacked sig10 = not greenMsi and greenNhl and not greenXover and not stacked sig11 = not greenMsi and not greenNhl and greenXover and not stacked sig12 = not greenMsi and not greenNhl and not greenXover and not stacked green = sig1 yellow = sig2 or sig3 or sig4 or sig5 or sig6 or sig7 or sig8 or sig9 red = sig10 or sig11 or sig12 action = green ? '🟒' : yellow ? '🟑' : 'πŸ”΄' txtMsi = greenMsi ? 'Above MA' : 'Below MA' txtNhl = greenNhl ? 'Positive' : 'Negative' txtXover = greenXover ? 'Positive' : 'Negative' txtMa = stacked ? 'Yes' : 'No' actionTxt = green ? 'Full-Sized Longs' : yellow ? 'Pilot Positions' : 'No Longs' signalArray = array.new<string>() signalToolTip = '' if sig1 signalArray.push('#1') if sig2 signalArray.push('#2') if sig3 signalArray.push('#3') if sig4 signalArray.push('#4') if sig5 signalArray.push('#5') if sig6 signalArray.push('#6') if sig7 signalArray.push('#7') if sig8 signalArray.push('#8') if sig9 signalArray.push('#9') if sig10 signalArray.push('#10') if sig11 signalArray.push('#11') if sig12 signalArray.push('#12') if signalArray.size() > 0 for i = 0 to signalArray.size() - 1 signalToolTip := signalToolTip + getArrayValue(signalArray, i) //---------data table---------// var table data = table.new(str.lower(yPos) + '_' + str.lower(xPos), 2, 8,color.new(color.white,100), color.new(color.white,100), 2, color.new(color.white,100), 2) if barstate.islast and timeframe.isdaily and showTable and yPos == 'Top' data.cell(0,0,'') data.merge_cells(0,0,1,0) data.cell(0,1, actionTxt + ' ' + signalToolTip, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.merge_cells(0,1,1,1) data.cell(0,2, 'IBME: ', text_halign = text.align_left, bgcolor = tableBgColor, text_size = txtSize, text_color = tableTextColor) data.cell(1,2, action, text_halign = text.align_center, bgcolor = tableBgColor, text_size = txtSize) if showSep data.cell(0,4,'Uptrend: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(0,5, 'MSI: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(0,6, 'NNHL: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(0,7, 'NNHC: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,4, txtMa, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,5, txtMsi, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,6, txtNhl, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,7, txtXover, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) else if barstate.islast and timeframe.isdaily and showTable data.cell(0,0, actionTxt + ' ' + signalToolTip, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.merge_cells(0,0,1,0) data.cell(0,1, 'IBME: ', text_halign = text.align_left, bgcolor = tableBgColor, text_size = txtSize, text_color = tableTextColor) data.cell(1,1, action, text_halign = text.align_center, bgcolor = tableBgColor, text_size = txtSize) if showSep data.cell(0,3,'Uptrend: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(0,4, 'MSI: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(0,5, 'NNHL: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(0,6, 'NNHC: ', text_halign = text.align_left, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,3, txtMa, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,4, txtMsi, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,5, txtNhl, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) data.cell(1,6, txtXover, text_halign = text.align_center, bgcolor = tableBgColor, text_color = tableTextColor, text_size = txtSize) else if not timeframe.isdaily and showRunTime runtime.error('Please switch to a daily time frame chart to see the IBME signal') bgcolor(green and timeframe.isdaily and bgHighlight ? bgColG : na) bgcolor(yellow and timeframe.isdaily and bgHighlight ? bgColY : na) bgcolor(red and timeframe.isdaily and bgHighlight ? bgColR : na) //----------alerts----------// if green and not green[1] alert('IBME has turned green! Full-sized longs allowed', alert.freq_once_per_bar_close) if yellow and not yellow[1] alert('IBME has turned yellow! Pilot positions permitted', alert.freq_once_per_bar_close) if red and not red[1] alert('IBME has turned red! No new longs reccommended', alert.freq_once_per_bar_close)
Strategy - Relative Volume Gainers
https://www.tradingview.com/script/ndW9kWOC-Strategy-Relative-Volume-Gainers/
Arun_K_Bhaskar
https://www.tradingview.com/u/Arun_K_Bhaskar/
264
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Arun_K_Bhaskar //@version=5 // Acknowledgement: This strategy is developed based on the idea shared by "Vikram Prabhu" of "Pivot Call", // through his video "Volume gainers Strategy". // Note that there are additional rules for this strategy for that necessary data is not available. // Source Code Reference for Cumulative Volume: //// Trader Profile: https://www.tradingview.com/u/danilogalisteu/ //// Indicator Name: "Cumulative Volume" by danilogalisteu //// Indicator Link: https://www.tradingview.com/script/GV4I6F7M-Cumulative-Volume/ //// Acknowledgement: "danilogalisteu" // Strategy Rules: //// The indicator is only for Long Entry //// Day Volume > or = Previous Day Volume //// % Change > or = 2.5% //// LTP > or = EMA 200 //// Relative Volume (30) > or = SMA (30) of Relative Volume //// Current candle is Green or Bullish // Strategy Requirement: //// Add EMA 200 to the chart. //// The indicator works in every timeframe. //// For intraday use 1min timeframe. indicator(title='Strategy - Relative Volume Gainers', shorttitle='Strategy - Relative Volume Gainers')//, format=format.volume) ////////////////////////////////////////////////////////////// Menu Start i_timeframe = input.timeframe(defval='D', title='Timeframe') gpRV = "Relative Volume" i_avg_vol_length = input.int(defval=90, title='Length', minval=2, inline='1', group=gpRV) i_rel_vol_pos_color = input.color(defval=#00FF00, title='', inline='1', group=gpRV) i_rel_vol_neu_color = input.color(defval=#505050, title='', inline='1', group=gpRV) i_show_avg_vol = input.bool(defval=false, title="Avg Vol Multiplier", inline='2', group=gpRV) i_avg_vol_muli = input.float(defval=5, title='', minval=0, inline='2', group=gpRV) i_avg_vol_color = input.color(defval=#0000FF, title='', inline='2', group=gpRV) gpCV = 'Cumulative Volume' i_show_cum_vol = input.bool(defval=true, title="Cumulative Volume", inline='1', group=gpCV) i_cum_vol_pos_color = input.color(defval=#FFFF00, title='', inline='1', group=gpCV) i_cum_vol_neu_color = input.color(defval=#505050, title='', inline='1', group=gpCV) gpSi = "Signal" i_show_bgcolor = input.bool(defval=true, title="Signal", inline='1', group=gpSi) i_show_candle = input.bool(defval=true, title="Candle", inline='1', group=gpSi) i_candle_color = input.color(defval=#0000FF, title='', inline='1', group=gpSi) ttPC = "Consider only the stocks which are trading above the given % Change" i_pchg_val = input.float(defval=2.5, title='%Chg Above', tooltip='', inline='2', group=gpSi) i_vol_pchg_val = input.float(defval=250, title='Vol %Chg Above', tooltip='', inline='3', group=gpSi) gpTb = 'Table' i_show_table = input.bool(defval=true, title="Table", inline='1', group=gpTb) i_table_text_size = input.string(defval='small', title='Size', options=['tiny','small','normal','large','huge'], inline='1', group=gpTb) i_pos_color = input.color(defval=#00FF00, title='', inline='1', group=gpTb) i_neu_color = input.color(defval=#FFFFFF, title='', inline='1', group=gpTb) i_show_note = input.bool(defval=false, title="Important Note", inline='', group='') ////////////////////////////////////////////////////////////// Menu End ////////////////////////////////////////////////////////////// Calculations Start ///////////////////////////////// Get Data get_ohlcv(timeframe, value) => request.security(symbol=syminfo.tickerid, timeframe=timeframe, expression=value, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) prev_close = get_ohlcv(i_timeframe, close[1]) day_volume = get_ohlcv(i_timeframe, volume) prev_volume = get_ohlcv(i_timeframe, volume[1]) ///////////////////////////////// Calculate Percentage Change percentage_change(current_value, previous_value) => pchg = (current_value / previous_value - 1) * 100 pchg // Calculate % Change day_pchg = percentage_change(close, prev_close) // Calculate Volume % Change volume_pchg = percentage_change(day_volume, prev_volume) // Calculate EMA price_ema = ta.ema(open, 200) ///////////////////////////////// Calculate Relative Volume average_volume = ta.sma(volume, i_avg_vol_length) relative_volume = volume / average_volume[1] average_volume_sma = ta.sma(relative_volume, i_avg_vol_length) * i_avg_vol_muli // Relative Volume Signal var bool long_condition = na var bool show_long = na long_condition := day_volume >= prev_volume and day_pchg >= i_pchg_val and volume_pchg >= i_vol_pchg_val and close >= price_ema and relative_volume >= average_volume_sma and open < close and barstate.isconfirmed show_long := long_condition and not long_condition[1] ? long_condition : na // Plot Relative Volume rel_vol_color = long_condition ? i_rel_vol_pos_color : i_rel_vol_neu_color plot(series=relative_volume, title='Relative Volume', color=rel_vol_color, style=plot.style_columns) bgcolor(color=i_show_bgcolor and show_long ? color.new(rel_vol_color, 85) : na, title='Long Signal') barcolor(color=i_show_candle and show_long ? i_candle_color : na, title='Long Signal Candle') plot(series=i_show_avg_vol ? average_volume_sma : na, title='Average Volume SMA', color=i_avg_vol_color, style=plot.style_line) ///////////////////////////////// Calculate Cumulative Volume cumulative_volume(timeframe) => is_new_day = ta.change(time(timeframe)) != 0 ? 1 : 0 cnt_new_day = ta.barssince(is_new_day) var float cum_vol = 0.0 cum_vol := volume + (is_new_day ? 0 : cum_vol) cum_vol cum_vol = cumulative_volume(i_timeframe) cum_vol_percentage = cum_vol / prev_volume // Plot Cumulative Volume cum_vol_col = cum_vol > prev_volume ? i_cum_vol_pos_color : i_cum_vol_neu_color plot(series=i_show_cum_vol ? cum_vol_percentage : na, title='Cumulative Volume', color=cum_vol_col, linewidth=2, style=plot.style_line) ////////////////////////////////////////////////////////////// Calculations End ////////////////////////////////////////////////////////////// Table Start // To String volume_pchg_str = str.tostring(volume_pchg,"#.##") + ' %' day_volume_str = str.tostring(day_volume/100000,"#.##") + ' L' prev_day_volume_str = str.tostring(prev_volume/100000,"#.##") + ' L' day_pchg_str = str.tostring(day_pchg,"#.##") + ' %' // Color bgcolor_1 = color.new(i_neu_color, 85) bgcolor_2 = color.new(i_neu_color, 95) vol_pchg_col = day_volume > prev_volume ? i_pos_color : i_neu_color pchg_col = day_pchg > i_pchg_val ? i_pos_color : i_neu_color // Plot Table var table plot_table = table.new(position=position.bottom_right, columns=2, rows=4, border_width=2) if barstate.islast and i_show_table table.cell(plot_table, column=0, row=0, text=day_pchg_str, text_color=pchg_col, text_halign=text.align_right, bgcolor=bgcolor_2, text_size=i_table_text_size) table.cell(plot_table, column=1, row=0, text="Chg", text_color=i_neu_color, text_halign=text.align_left, bgcolor=bgcolor_2, text_size='small') table.cell(plot_table, column=0, row=1, text=volume_pchg_str, text_color=vol_pchg_col, text_halign=text.align_right, bgcolor=bgcolor_1, text_size=i_table_text_size) table.cell(plot_table, column=1, row=1, text="Vol Chg", text_color=i_neu_color, text_halign=text.align_left, bgcolor=bgcolor_1, text_size='small') table.cell(plot_table, column=0, row=2, text=day_volume_str, text_color=i_neu_color, text_halign=text.align_right, bgcolor=bgcolor_2, text_size=i_table_text_size) table.cell(plot_table, column=1, row=2, text="Vol", text_color=i_neu_color, text_halign=text.align_left, bgcolor=bgcolor_2, text_size='small') table.cell(plot_table, column=0, row=3, text=prev_day_volume_str, text_color=i_neu_color, text_halign=text.align_right, bgcolor=bgcolor_1, text_size=i_table_text_size) table.cell(plot_table, column=1, row=3, text="Prev Vol", text_color=i_neu_color, text_halign=text.align_left, bgcolor=bgcolor_1, text_size='small') ////////////////////////////////////////////////////////////// Table End ////////////////////////////////////////////////////////////// Note note_text = "Note:\nThe indicator works in every timeframe.\n" + "Add EMA 200 to the chart.\n" + "For intraday use 1min timeframe.\n" + "The indicator is only for Long Entry." note_label = label(na) if i_show_note note_label := label.new(x=bar_index - 75, y=20, text=note_text, color=#FF0000, style=label.style_label_center, textcolor=#FFFFFF, size=size.large) label.delete(note_label[1]) ////////////////////////////////////////////////////////////// CODE END
Dynamic Levels Breakouts [Angel Algo]
https://www.tradingview.com/script/FwJOjpzv-Dynamic-Levels-Breakouts-Angel-Algo/
AngelAlgo
https://www.tradingview.com/u/AngelAlgo/
324
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Angel Algo //@version=5 indicator("Dynamic Levels Breakouts", overlay = true) // Script inputs length = input.int(defval=20, title="Period", minval=2, maxval=30) // 20 or 15 // Calculate maximum and minimum price in the rolling window max_level = ta.highest(high, length) min_level = ta.lowest(low, length) // Define condtions for dynamic support and resistance levels detection and plotting max_color_cond = (max_level[1]==max_level[2]) and (close[1]<=max_level[1]) and (close[1]>=min_level[1]) min_color_cond = (min_level[1]==min_level[2]) and (close[1]<=max_level[1]) and (close[1]>=min_level[1]) // Define conditional coloring for dynamic support and resistance levels max_level_color = max_color_cond ? color.new(color.red,70):na min_level_color = min_color_cond ? color.new(color.green,70):na // Define bullish and bearish breakouts condition bullish_breakout = ta.crossover (close, max_level[1]) bearish_breakout = ta.crossunder (close, min_level[1]) //Plot dynamic support and resistance levels plot(max_level[1], color = max_level_color,linewidth=2) plot(min_level[1], color = min_level_color,linewidth=2) // Define a current market regime condition not_bullish = ta.barssince(bullish_breakout[1])>ta.barssince(bearish_breakout[1]) not_bearish = ta.barssince(bullish_breakout[1])<ta.barssince(bearish_breakout[1]) // Plot dynamic support and resistance levels breakout signals plotshape(bullish_breakout and not_bullish, text="β–²", style=shape.labelup, color=color.green, textcolor=color.white, location=location.belowbar, size=size.small) plotshape(bearish_breakout and not_bearish, text="β–Ό", style=shape.labeldown, color=color.red, textcolor=color.white, location=location.abovebar, size=size.small)
Book Value Per Share Overlay
https://www.tradingview.com/script/uvTdSde3/
Eur0pa
https://www.tradingview.com/u/Eur0pa/
27
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Eur0pa //@version=5 indicator("BVPS", overlay=true) // Define inputs //total_assets = input.float(title="Total Assets", defval=0) //total_liabilities = input.float(title="Total Liabilities", defval=0) //num_shares = input.float(title="Number of Shares", defval=0) // //Formula: // //Book value per share = Total common equity / Total common shares outstanding // TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ") // TTA = request.financial(syminfo.tickerid, "TOTAL_ASSETS", "FQ") // TTL = request.financial(syminfo.tickerid, "TOTAL_LIABILITIES", "FQ") // TCE = request.financial(syminfo.tickerid, "COMMON_EQUITY_TOTAL", "FQ") // // Calculate book value per share // book_value_per_share = (TTA - TTL) / TSO // BVPS = (TCE) / TSO BVPS=request.financial(syminfo.tickerid,"BOOK_VALUE_PER_SHARE","FQ") PriceBookRatio =close /BVPS // Display book value per share on chart plot(BVPS, color=color.aqua, linewidth=2, title="Book Value per Share") //plot(book_value_per_share, color=color.blue, linewidth=2, title="Book Value per Share") //plot(PriceBookRatio, color=color.lime, linewidth=2, title="Price Book Ratio")
YTD & Drawdown
https://www.tradingview.com/script/uQitLDpo-YTD-Drawdown/
ChartingCycles
https://www.tradingview.com/u/ChartingCycles/
22
study
5
MPL-2.0
//This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //Β©ChartingCycles //@version=5 indicator('YTD', scale=scale.none, overlay=true, precision=0, format=format.percent) //YTD % Calc specificDate = time >= timestamp(year(timenow), 1, 1, 00, 00) var float closeOnDate = na if specificDate and not specificDate[1] closeOnDate := close[1] // Get the close of the last day of the prior year // Check if closeOnDate is still na, if so, use the first available close price if na(closeOnDate) closeOnDate := close[0] YTD = (close - closeOnDate) / closeOnDate //ATH % Calc GetATH(dataSeries = high) => var float ATH = -1e10 if dataSeries > ATH ATH := dataSeries ATH // Calculate drawdown athValue = GetATH() drawdown = -1*(athValue - close) / athValue //Panel var string GP2 = 'Display' show_header = timeframe.isdaily ? input.bool(true, title='Show Table Header', inline='10', group=GP2) : false string i_tableYpos = input.string('top', 'Panel Position', inline='11', options=['top', 'middle', 'bottom'], group=GP2) string i_tableXpos = input.string('right', '', inline='11', options=['left', 'center', 'right'], group=GP2) string textsize = input.string('normal', 'Text Size', inline='12', options=['small', 'normal', 'large'], group=GP2) var table dtrDisplay = table.new(i_tableYpos + '_' + i_tableXpos, 3, 3, frame_width=1, frame_color=color.black, border_width=1, border_color=color.black) if barstate.islast // We only populate the table on the last bar. if show_header == true table.cell(dtrDisplay, 1, 0, 'YTD %', bgcolor=color.black, text_size=textsize, text_color=color.white) table.cell(dtrDisplay, 1, 1, str.tostring(math.round((YTD*100),1)) + '%', bgcolor= YTD>0 ? color.teal : color.red, text_size=textsize, text_color=color.white) table.cell(dtrDisplay, 2, 0, 'Drawdown %', bgcolor=color.black, text_size=textsize, text_color=color.white) table.cell(dtrDisplay, 2, 1, str.tostring(math.round((drawdown*100),1)) + '%', bgcolor= drawdown<0 ? color.red : color.teal, text_size=textsize, text_color=color.white)
Machine Learning Momentum Index (MLMI) [Zeiierman]
https://www.tradingview.com/script/I2X9DE84-Machine-Learning-Momentum-Index-MLMI-Zeiierman/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
2,264
study
5
CC-BY-NC-SA-4.0
// 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(title='Machine Learning Momentum Index (MLMI) [Zeiierman]', shorttitle='Machine Learning Momentum Index (MLMI)', overlay=false, precision=1) // ~~ ToolTips { t1 ="This parameter controls the number of neighbors to consider while making a prediction using the k-Nearest Neighbors (k-NN) algorithm. By modifying the value of k, you can change how sensitive the prediction is to local fluctuations in the data. \n\nA smaller value of k will make the prediction more sensitive to local variations and can lead to a more erratic prediction line. \n\nA larger value of k will consider more neighbors, thus making the prediction more stable but potentially less responsive to sudden changes." t2 ="The parameter controls the length of the trend used in computing the momentum. This length refers to the number of periods over which the momentum is calculated, affecting how quickly the indicator reacts to changes in the underlying price movements. \n\nA shorter trend length (smaller momentumWindow) will make the indicator more responsive to short-term price changes, potentially generating more signals but at the risk of more false alarms. \n\nA longer trend length (larger momentumWindow) will make the indicator smoother and less responsive to short-term noise, but it may lag in reacting to significant price changes." //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Input Parameters { numNeighbors = input(200, title='Prediction Data (k)', tooltip=t1) momentumWindow = input.int(20, step=2, minval=10, maxval=200, title='Trend Length', tooltip=t2) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Moving Averages & RSI { MA_quick = ta.wma(close, 5) MA_slow = ta.wma(close, 20) rsi_quick = ta.wma(ta.rsi(close, 5),momentumWindow) rsi_slow = ta.wma(ta.rsi(close, 20),momentumWindow) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Crossover Conditions { pos = ta.crossover(MA_quick, MA_slow) neg = ta.crossunder(MA_quick, MA_slow) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Type Definition { type Data array<float> parameter1 array<float> parameter2 array<float> priceArray array<float> resultArray // Create a Data object var data = Data.new(array.new_float(1, 0), array.new_float(1, 0), array.new_float(1, 0), array.new_float(1, 0)) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Method that saves the last trade and temporarily holds the current one. { method storePreviousTrade(Data d, p1, p2) => d.parameter1.push(d.parameter1.get(d.parameter1.size() - 1)) d.parameter2.push(d.parameter2.get(d.parameter2.size() - 1)) d.priceArray.push(d.priceArray.get(d.priceArray.size() - 1)) d.resultArray.push(close >= d.priceArray.get(d.priceArray.size() - 1) ? 1 : -1) d.parameter1.set(d.parameter1.size() - 1, p1) d.parameter2.set(d.parameter2.size() - 1, p2) d.priceArray.set(d.priceArray.size() - 1, close) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Method to Make Prediction { method knnPredict(Data d, p1, p2, k) => // Create a Distance Array distances = array.new_float(0) n = d.parameter1.size() - 1 for i = 0 to n distance = math.sqrt(math.pow(p1 - d.parameter1.get(i), 2) + math.pow(p2 - d.parameter2.get(i), 2)) distances.push(distance) // Get Neighbors sortedDistances = distances.copy() sortedDistances.sort() selectedDistances = sortedDistances.slice( 0, math.min(k, sortedDistances.size())) maxDist = selectedDistances.max() neighbors = array.new_float(0) for i = 0 to distances.size() - 1 if distances.get(i) <= maxDist neighbors.push(d.resultArray.get(i)) // Return Prediction prediction = neighbors.sum() prediction if pos or neg data.storePreviousTrade(rsi_slow, rsi_quick) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Plots { prediction = data.knnPredict(rsi_slow, rsi_quick, numNeighbors) prediction_ = plot(prediction, color=color.new(#426eff, 0), title="MLMI Prediction") prediction_ma = ta.wma(prediction, 20) plot(prediction_ma, color=color.new(#31ffc8, 0), title="WMA of MLMI Prediction") hline(0, title="Mid Level") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Gradient Fill { upper = ta.highest(prediction,2000) lower = ta.lowest(prediction,2000) upper_ = upper - ta.ema(ta.stdev(prediction,20),20) lower_ = lower + ta.ema(ta.stdev(prediction,20),20) channel_upper = plot(upper, color = na, editable = false, display = display.none) channel_lower = plot(lower, color = na, editable = false, display = display.none) channel_mid = plot(0, color = na, editable = false, display = display.none) // ~~ Channel Gradient Fill { fill(channel_mid, channel_upper, top_value = upper, bottom_value = 0, bottom_color = na, top_color = color.new(color.lime,75),title = "Channel Gradient Fill") fill(channel_mid, channel_lower, top_value = 0, bottom_value = lower, bottom_color = color.new(color.red,75) , top_color = na,title = "Channel Gradient Fill") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Overbought/Oversold Gradient Fill { fill(prediction_, channel_mid, upper, upper_, top_color = color.new(color.lime, 0), bottom_color = color.new(color.green, 100),title = "Overbought Gradient Fill") fill(prediction_, channel_mid, lower_, lower, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0),title = "Oversold Gradient Fill") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Alerts { P_OB_Over = ta.crossover(prediction,upper_) P_OB_Under = ta.crossunder(prediction,upper_) P_OS_Over = ta.crossover(prediction,lower_) P_OS_Under = ta.crossunder(prediction,lower_) P_Mid_Over = ta.crossover(prediction,0) P_Mid_Under = ta.crossunder(prediction,0) P_MA_Over = ta.crossover(prediction,prediction_ma) P_MA_Under = ta.crossunder(prediction,prediction_ma) alertcondition(P_OB_Over, title = "MLMI Crossover OB", message = "MLMI Crossover OB") alertcondition(P_OB_Under, title = "MLMI Crossunder OB", message = "MLMI Crossunder OB") alertcondition(P_OS_Over, title = "MLMI Crossover OS", message = "MLMI Crossover OS") alertcondition(P_OS_Under, title = "MLMI Crossunder OS", message = "MLMI Crossunder OS") alertcondition(P_Mid_Over, title = "MLMI Crossover 50", message = "MLMI Crossover 50") alertcondition(P_Mid_Under,title = "MLMI Crossunder 50", message = "MLMI Crossunder 50") alertcondition(P_MA_Over, title = "MLMI Crossover Ma", message = "MLMI Crossover Ma") alertcondition(P_MA_Under, title = "MLMI Crossunder Ma", message = "MLMI Crossunder Ma") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
QQE Weighted Oscillator [LuxAlgo]
https://www.tradingview.com/script/aRxQ1g82-QQE-Weighted-Oscillator-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
1,704
study
5
CC-BY-NC-SA-4.0
// 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("QQE Weighted Oscillator [LuxAlgo]", "LuxAlgo - QQE Weighted Oscillator") //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ length = input.int(14, minval = 1) factor = input.float(4.236, minval = 0) smooth = input.int(5, minval = 1) weight = input.float(2) src = input(close) //Style rsiCss = input(#3179f5, 'RSI', group = 'Style') tsBearCss = input(color.red, 'Trailing Stop', group = 'Style', inline = 'inline1') tsBullCss = input(color.teal, '', group = 'Style', inline = 'inline1') //-----------------------------------------------------------------------------} //Weighted QQE //-----------------------------------------------------------------------------{ var ts = 0. var rsi = 0. delta = src - src[1] w = nz(delta * (rsi - ts) > 0 ? weight : 1, 1) //Rsi num = ta.rma(delta * w, length) den = ta.rma(math.abs(delta * w), length) rsi := 50 * ta.ema(num / den, smooth) + 50 //Trailing stop diff = ta.rma(math.abs(rsi - rsi[1]), length) crossover = ta.crossover(rsi, ts) crossunder = ta.crossunder(rsi, ts) ts := nz(crossover ? rsi - diff * factor : crossunder ? rsi + diff * factor : rsi > ts ? math.max(rsi - diff * factor, ts) : math.min(rsi + diff * factor, ts), rsi) //-----------------------------------------------------------------------------} //Plots //-----------------------------------------------------------------------------{ css = rsi > ts ? tsBullCss : tsBearCss plot_rsi = plot(rsi, 'RSI', rsiCss) plot_ts = plot(ts, 'Traling Stop', css) fill(plot_rsi, plot_ts, rsi, ts, color.new(rsiCss, 50), color.new(css, 50)) hline(70) hline(30) //-----------------------------------------------------------------------------}
FIRST-HOUR TOOL V.1.8.08.23
https://www.tradingview.com/script/yh4RHcxk/
tumiza999
https://www.tradingview.com/u/tumiza999/
54
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // author: Β© tumiza999 //@version=5 indicator("1H FIRST-HOUR TOOL V.2.01", overlay = true) // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β©tumiza999 //@version=5 //strategy("1H FIRST-HOUR V.2.01", overlay=true, pyramiding = 1, slippage = 1, // initial_capital=10000, // default_qty_type=strategy.percent_of_equity, default_qty_value=10, // commission_type=strategy.commission.percent, commission_value=0.0750, use_bar_magnifier = false) // ----------------------------------------------------------------------------- // Trigger Point // ----------------------------------------------------------------------------- open_1H = request.security(syminfo.tickerid, "60", open) high_1H = request.security(syminfo.tickerid, "60", high) low_1H= request.security(syminfo.tickerid, "60", low) SessionHigh(sessionTime, sessionTimeZone=syminfo.timezone) => insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone)) var float sessionHighPrice = na if insideSession and not insideSession[1] sessionHighPrice := high else if insideSession sessionHighPrice := high_1H sessionHighPrice SessionLow(sessionTime, sessionTimeZone=syminfo.timezone) => insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone)) var float sessionLowPrice = na if insideSession and not insideSession[1] sessionLowPrice := low else if insideSession sessionLowPrice := low_1H sessionLowPrice SessionOpen(sessionTime, sessionTimeZone=syminfo.timezone) => insideSession = not na(time(timeframe.period, sessionTime, sessionTimeZone)) var float sessionOpenPrice = na if insideSession and not insideSession[1] sessionOpenPrice := open else if insideSession sessionOpenPrice := open_1H sessionOpenPrice InSession(sessionTimes, sessionTimeZone=syminfo.timezone) => not na(time(timeframe.period, sessionTimes, sessionTimeZone)) session = input.session("0000-0100", title="Data Session") timeZone = input.string("GMT", title="Time Zone") sessHigh = SessionHigh(session, timeZone) sessLow= SessionLow(session, timeZone) sessOpen= SessionOpen(session, timeZone) plot(sessHigh, color=color.rgb(92, 217, 255), title="Session High") plot(sessOpen, color=color.rgb(255, 244, 92), title="Session Open") plot(sessLow, color=color.rgb(255, 117, 244), title="Session Low") bgcolor(InSession(session, timeZone) ? color.new(#00ffdd, 95) : na) if ta.crossover(close,sessHigh) alert(message = "High First Hour Crossover", freq = alert.freq_once_per_bar) if ta.crossunder(close, sessOpen) alert(message = "Open First Hour Crossunder", freq = alert.freq_once_per_bar) if ta.crossunder(close,sessLow) alert(message = "Low First Hour Crossunder", freq = alert.freq_once_per_bar) if ta.crossover(close, sessLow) alert(message = "Low First Hour Crossover", freq = alert.freq_once_per_bar) plotshape(ta.crossover(close, sessHigh), "CrossOvHIGH", shape.triangleup, location = location.belowbar, color=color.yellow) plotshape(ta.crossover(close, sessOpen), "CrossOvOPEN",shape.triangleup, location = location.belowbar, color= color.red) plotshape(ta.crossover(close, sessLow), "CrossoOvLOW",shape.triangleup, location = location.belowbar, color = color.green) //plotshape(ta.crossunder(close, sessHigh), "CrossovHigh",shape.triangleup, location = location.belowbar) //plotshape(ta.crossunder(close, sessHigh), "CrossovHigh",shape.triangleup, location = location.belowbar) //plotshape(ta.crossunder(close, sessHigh), "CrossovHigh",shape.triangleup, location = location.belowbar)
MACD HTF - Dynamic Smoothing
https://www.tradingview.com/script/rQbmGtAx-MACD-HTF-Dynamic-Smoothing/
Harrocop
https://www.tradingview.com/u/Harrocop/
191
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Harrocop //////////////////////////////////////////////////////////////////////////////////////// // HTF Trend Filter - Dynamic Smoothing // - Option to change high time frame settings // - Option to choose from different moving average types to calculate MACD // - The Dynamic smoothing makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame // - Color green with uptrend, color red with downtrend // - options for notification in case of crossover / crossunder of MACD //////////////////////////////////////////////////////////////////////////////////////// //@version=5 indicator("MACD HTF - Dynamic Smoothing", "MACD HTF", overlay = false) ////////////////////////////////////////////////////// ////////// Input MACD HTF //////////// ////////////////////////////////////////////////////// MACD_settings = "Higher Time Frame MACD Settings" MA_Type = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA"], title="MA type", inline = "1", group = MACD_settings) TimeFrame_MACD = input.timeframe(title='Higher Time Frame', defval='240', inline = "1", group = MACD_settings) fastlength = input.int(12, title="Fast MA Length", minval=1, inline = "2", group = MACD_settings) slowlength = input.int(26, title="Slow MA Length", minval=1, inline = "2", group = MACD_settings) signallength = input.int(9, title="Length Signal MA", minval=1, inline = "3", group = MACD_settings) Plot_Signal = input.bool(true, title = "Plot Signal?", inline = "3", group = MACD_settings) ma(type, src, length) => float result = 0 if type == 'TMA' // Triangular Moving Average result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1) result if type == 'LSMA' // Least Squares Moving Average result := ta.linreg(src, length, 0) result if type == 'SMA' // Simple Moving Average result := ta.sma(src, length) result if type == 'EMA' // Exponential Moving Average result := ta.ema(src, length) result if type == 'DEMA' // Double Exponential Moving Average e = ta.ema(src, length) result := 2 * e - ta.ema(e, length) result if type == 'TEMA' // Triple Exponentiale e = ta.ema(src, length) result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length) result if type == 'WMA' // Weighted Moving Average result := ta.wma(src, length) result if type == 'HMA' // Hull Moving Average result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length))) result result // MACD function for calculation higher timeframe macd_function() => fast_ma = ma(MA_Type, close, fastlength) slow_ma = ma(MA_Type, close, slowlength) macd = fast_ma - slow_ma macd signal_function() => fast_ma = ma(MA_Type, close, fastlength) slow_ma = ma(MA_Type, close, slowlength) macd = fast_ma - slow_ma signal = ma(MA_Type, macd, signallength) signal hist_function() => fast_ma = ma(MA_Type, close, fastlength) slow_ma = ma(MA_Type, close, slowlength) macd = fast_ma - slow_ma signal = ma(MA_Type, macd, signallength) hist = macd - signal hist MACD_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, macd_function()) SIGNAL_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, signal_function()) HIST_Value_HTF = MACD_Value_HTF - SIGNAL_Value_HTF // Get minutes for current and higher timeframes // Function to convert a timeframe string to its equivalent in minutes timeframeToMinutes(tf) => multiplier = 1 if (str.endswith(tf, "D")) multiplier := 1440 else if (str.endswith(tf, "W")) multiplier := 10080 else if (str.endswith(tf, "M")) multiplier := 43200 else if (str.endswith(tf, "H")) multiplier := int(str.tonumber(str.replace(tf, "H", ""))) else multiplier := int(str.tonumber(str.replace(tf, "m", ""))) multiplier // Get minutes for current and higher timeframes currentTFMinutes = timeframeToMinutes(timeframe.period) higherTFMinutes = timeframeToMinutes(TimeFrame_MACD) // Calculate the smoothing factor dynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes) MACD_Value_HTF_Smooth = ta.sma(MACD_Value_HTF, dynamicSmoothing) SIGNAL_Value_HTF_Smooth = ta.sma(SIGNAL_Value_HTF, dynamicSmoothing) HIST_Value_HTF_Smooth = ta.sma(HIST_Value_HTF, dynamicSmoothing) // Determin Long and Short Conditions LongCondition = ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth < 0 ShortCondition = ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth > 0 ///////////////////////////////////////////////// /////////// Plots //////////////// ///////////////////////////////////////////////// hline(0, "Zero Line", color=color.new(#787B86, 50)) plot(HIST_Value_HTF_Smooth, title="Histogram", style=plot.style_columns, color=(HIST_Value_HTF_Smooth>=0 ? (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(0, 255, 8) : color.rgb(0, 100, 5)) : (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(150, 35, 35) : color.rgb(255, 0, 0)))) plot(SIGNAL_Value_HTF_Smooth, title="Signal", color=color.orange) plot(MACD_Value_HTF_Smooth, title="MACD", color=color.blue) plot(Plot_Signal ? LongCondition ? MACD_Value_HTF_Smooth : na : na, "Long Condition", style = plot.style_circles, color = color.rgb(0, 255, 8), linewidth = 4) plot(Plot_Signal ? ShortCondition ? MACD_Value_HTF_Smooth : na : na, "Short Condition", style = plot.style_circles, color = color.rgb(255, 0, 0), linewidth = 4) ////////////////////////////////////////////////// /////////// Alerts //////////////// ////////////////////////////////////////////////// // Alert conditions for Crossover alertcondition(LongCondition, title="Long Condition MACD", message="MACD Crossover!") alertcondition(ShortCondition, title="Short Condition MACD", message="MACD Crossunder!")
External Indicator Analysis Overlay | Buy/Sell | HTF Heikin-Ashi
https://www.tradingview.com/script/MHYeKwKT/
metka183
https://www.tradingview.com/u/metka183/
243
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© metka183 //@version=5 indicator('External Indicator Analysis Overlay', "EIAO1.7", overlay=true, max_bars_back=5000, max_boxes_count=500, max_labels_count=500) //Functions ------------------------------ is_newBar(_res) => t = time(_res) not na(t) and (na(t[1]) or t > t[1]) calcPeriod(_fact, _exp) => int(timeframe.multiplier * math.pow(_fact, _exp) * 1000 * ( timeframe.isseconds ? 1. : timeframe.isminutes ? 60. : timeframe.isdaily ? 86400. : timeframe.isweekly ? 86400. * 7 : timeframe.ismonthly ? 86400. * 30.4375 : 0.)) showPeriod(_unix) => sign = math.sign(_unix) check = math.abs(_unix / 1000) if check < 60 str.tostring(sign*math.round(check,0)) + "s" else if check < 3600 str.tostring(sign*math.round(check/60,0)) + "m" else if check < 86400 str.tostring(sign*math.round(check/3600,2)) + "h" else if check < 86400 * 7 str.tostring(sign*math.round(check/86400,2)) + "D" else if check < 86400 * 30.4375 str.tostring(sign*math.round(check/(86400*7),2)) + "W" else if check < 86400 * 365.25 str.tostring(sign*math.round(check/(86400*30.4375),2)) + "M" else str.tostring(sign*math.round(check/(86400*365.25),2)) + "Y" convertPeriod(_res) => mult = 0. if _res == "" mult := calcPeriod(1, 1) else mult := 1000. if array.size(str.split(_res, "D")) > 1 mult *= str.tonumber(array.get(str.split(_res, "D"), 0)) * 86400. else if array.size(str.split(_res, "W")) > 1 mult *= str.tonumber(array.get(str.split(_res, "W"), 0)) * 86400. * 7 else if array.size(str.split(_res, "M")) > 1 mult *= str.tonumber(array.get(str.split(_res, "M"), 0)) * 86400. * 30.4375 else if _res == "D" mult *= 86400. else if _res == "W" mult *= 86400. * 7 else if _res == "M" mult *= 86400. * 30.4375 else mult *= str.tonumber(_res) * 60. mult is_singleBar(_newBar, _res) => (convertPeriod(_res) <= convertPeriod(timeframe.period)) or (_newBar and barstate.islast and not barstate.isconfirmed) or (_newBar and barstate.islastconfirmedhistory) drawLabel(_offset, _pivot, _style, _color, _textColor) => if not na(_pivot) label.new(bar_index[_offset], _pivot, str.tostring(_pivot, format.mintick), style=_style, color=_color, textcolor=_textColor) drawCandle(_left, _right, _open, _close, _high, _low, _color_up, _color_down, _color_extrema, _erase) => box bodyBox = na, box extremaBox = na if _left < _right and _left >= 0 extremaBox := box.new(_left, _high, _right, _low) box.set_border_color(extremaBox, _color_extrema) box.set_bgcolor(extremaBox, _color_extrema) bodyColor = _close - _open >= 0 ? _color_up : _color_down bodyBox := box.new(_left, _close, _right, _open) box.set_border_color(bodyBox, bodyColor) box.set_bgcolor(bodyBox, bodyColor) if _erase > 0 box.delete(bodyBox[_erase]), box.delete(extremaBox[_erase]) [extremaBox, bodyBox] selectCandle(_type) => switch _type "None" => -1 "Regular" => 0 "Heikin-Ashi" => 1 "Mari-Ashi" => 2 "Velocity" => 3 selectSignal(_type) => switch _type "None" => -1 "Buy = positiv | Sell = negative" => 0 "Buy = rising | Sell = falling" => 1 showYield(_yield) => y = math.round(_yield*100,2) if y > 0 "+" + str.tostring(y) else str.tostring(y) //---------------------------------------- //Input Variables ------------------------ category1 = "Candle Control" candle_type = input.string("None", title="Type", options=["None", "Regular", "Heikin-Ashi", "Mari-Ashi", "Velocity"], group=category1) timeres = input.timeframe("", title="Period", group=category1) category2 = "Buy/Sell Indication" signal_src = input.source(close, title="Source", group=category2, tooltip="Choose an external indicator like a moving average to utilize Buy/Sell signals.") signal_type = input.string("Buy = rising | Sell = falling", title="Type", options=["Buy = positiv | Sell = negative", "Buy = rising | Sell = falling"], group=category2, tooltip="The type of signal that provides a Buy/Sell indication. For example, moving averages are rising and falling.") signal_rev = input.bool(false, "Reverse signal indication?", group=category2) category3 = "Investment Control" invest_type = input.string("Rebalancing", title="Type", options=["None", "Only Long", "Only Short", "Long and Short", "Rebalancing"], group=category3, tooltip="Rebalancing means that the selected portfolio size for investments is rebalanced at every Buy and Sell signal. With this setting, the portfolio remains always invested.") invest_begin = input.time(timestamp("1 Jan 2000 00:00"), "Starting Point", group=category3, tooltip="Choose a starting point for the beginning of the investment calculation.") invest_spec = input.float(50, "Size %", minval=0, maxval=100, step=10, group=category3, tooltip="The percentage of the portfolio to be used for investments. The Avoid-Sleepless-Nights setting is Rebalancing with 50%.") invest_average = input.bool(false, "Show average investment results?", group=category3) category4 = "Peak Labeling" dist = input.int(0, "Distance", minval=0, group=category4, tooltip="Set a distance length between highs/lows to see them.") category5 = "Style Settings" tab_type = input.string("Compact", "Table Type|Position", options=["Normal", "Compact"], group=category5, inline="Table") tab_pos = input.string("Bottom Right", "", options=["Top Center", "Top Right", "Middle Right", "Bottom Right", "Bottom Center", "Bottom Left", "Middle Left", "Top Left"], group=category5, inline="Table") color_candle_up = input.color(color.new(color.green, 30), "Candle Up|Down|Edge", group=category5, inline="Candle") color_candle_down = input.color(color.new(color.red, 30), "" , group=category5, inline="Candle") color_candle_bord = input.color(color.new(color.gray, 85), "", group=category5, inline="Candle") color_peaks = input.color(color.white, "Peak Background|Text", group=category5, inline="Peak") color_peaks_text = input.color(color.black, "", group=category5, inline="Peak") color_signal_up = input.color(color.new(#00CCFF, 30), "Signal Up|Down|Text", group=category5, inline="Signal") color_signal_down = input.color(color.new(#FF00CC, 30), "" , group=category5, inline="Signal") color_signal_text = input.color(color.white, "", group=category5, inline="Signal") typeS = selectSignal(signal_type) typeC = selectCandle(candle_type) //---------------------------------------- //Candle Input Data ---------------------- id = syminfo.tickerid id2 = id, nr = str.pos(id2, 'type":"') if nr > 0 id2 := str.substring(id2, nr+7) nr := str.pos(id2, '"') id2 := str.lower(str.substring(id2, 0, nr)) nr := str.pos(id2, 'heikenashi') nr := nr > 0 ? nr : str.pos(id2, 'heikinashi') if nr > 0 typeC := convertPeriod(timeres) == convertPeriod(timeframe.period) and (typeC == 0 or typeC == 1) ? 0 : -1 else typeC := -1 typeC := convertPeriod(timeres) >= convertPeriod(timeframe.period) ? typeC : -1 //---------------------------------------- //Candle Overlay Data -------------------- float candO = na, float candC = na, float candH = na, float candL = na [realO, realC, realH, realL] = request.security(id, timeframe.period, [open, close, high, low]) realG = not na(realC[1]) ? realO-realC[1] : 0. newPeriod = is_newBar(timeres) shortPeriod = is_singleBar(newPeriod, timeres) //Japanese Candles japaO = 0., japaC = 0., japaH = 0., japaL = 0. if newPeriod japaO := realO japaC := realC japaH := realH japaL := realL else japaO := japaO[1] japaC := realC japaH := math.max(realH, japaH[1]) japaL := math.min(realL, japaL[1]) //Heikin-Ashi Candles heikO = 0., heikC = 0., heikH = 0., heikL = 0. if newPeriod heikO := na(heikO[1]) ? realO : (nz(heikO[1]) + nz(heikC[1])) / 2 heikH := math.max(realO, realC, realH) heikL := math.min(realO, realC, realL) heikC := (realO+realC+realH+realL)/4 else heikO := heikO[1] heikH := math.max(japaO, japaC, japaH, heikO) heikL := math.min(japaO, japaC, japaL, heikO) heikC := (japaO+japaC+japaH+japaL)/4 //Mari-Ashi Candles mariO = 0., mariC = 0., mariH = 0., mariL = 0. var lastC = open diffC = (nz(japaH)-nz(japaL))/2 if typeC == 2 shortPeriod := false if bar_index > 0 if math.abs(mariC[1]-mariO[1]) >= diffC[1] or shortPeriod[1] lastC := mariC[1] newPeriod := true else newPeriod := false if (math.abs(close-lastC) >= diffC or (barstate.islast and not barstate.isconfirmed) or (barstate.islastconfirmedhistory)) and newPeriod shortPeriod := true if newPeriod mariO := na(mariO[1]) ? realO : mariC[1] mariC := realC mariH := math.max(mariO, realO, realC, realH) mariL := math.min(mariO, realO, realC, realL) else mariO := mariO[1] mariC := realC mariH := math.max(mariH[1], realO, realC, realH) mariL := math.min(mariL[1], realO, realC, realL) //Velocity Candles veloO = 0., veloC = 0., veloH = 0., veloL = 0., fact = 0.25 veloC0 = 0., veloH0 = 0., veloL0 = 0. veloC1 = 0., veloH1 = 0., veloL1 = 0. if newPeriod veloO := na(veloO[1]) ? realO : veloO[1] + veloC1[1] veloC0 := veloC1[1] veloH0 := veloH1[1] veloL0 := veloL1[1] veloC1 := (1-fact)*nz(veloC0) + fact*(realC-veloO) veloH1 := (1-fact)*nz(veloH0) + fact*(realH-veloO) veloL1 := (1-fact)*nz(veloL0) + fact*(realL-veloO) veloC := realC veloH := math.max(realH+veloH1, veloO, veloC) veloL := math.min(realL+veloL1, veloO, veloC) else veloO := veloO[1] veloC0 := veloC0[1] veloH0 := veloH0[1] veloL0 := veloL0[1] veloC1 := (1-fact)*nz(veloC0) + fact*(realC-veloO) veloH1 := (1-fact)*nz(veloH0) + fact*(japaH-veloO) veloL1 := (1-fact)*nz(veloL0) + fact*(japaL-veloO) veloC := realC veloH := math.max(japaH+veloH1, veloO, veloC) veloL := math.min(japaL+veloL1, veloO, veloC) //Candle Type Selection if typeC == 0 candO := japaO candC := japaC candH := japaH candL := japaL else if typeC == 1 candO := heikO candC := heikC candH := heikH candL := heikL else if typeC == 2 candO := mariO candC := mariC candH := mariH candL := mariL else if typeC == 3 candO := veloO candC := veloC candH := veloH candL := veloL //---------------------------------------- //Calculate Extrema ---------------------- lenLL = dist, lenHL = lenLL lenLR = 0, lenHR = lenLR pivotH = ta.pivothigh(lenHL, lenHR) pivotL = ta.pivotlow(lenLL, lenLR) pivotLL = false, pivotLH = false pivotD = 0, pivotD := nz(pivotD[1]) var maxH = high, var minL = low if not na(pivotH) if pivotD >= 0 if pivotH > minL pivotD := -1 maxH := pivotH else pivotH := na else if pivotH > maxH pivotLH := true maxH := pivotH else pivotH := na if not na(pivotL) if pivotD <= 0 if pivotL < maxH pivotD := 1 minL := pivotL else pivotL := na else if pivotL < minL pivotLL := true minL := pivotL else pivotL := na //---------------------------------------- //Buy/Sell Detection --------------------- var src_check = 0, use_src = false, var src_delta = 2 if bar_index < src_delta if signal_src == 0 and src_check == 0 src_delta += 1 else if signal_src == 1 src_check += 1 else if signal_src == -1 src_check += 2 else if signal_src < -1 or signal_src > 1 src_check -= 3 if signal_src == 0 or src_check > 0 use_src := true float vma = na, src = 0. if bar_index > 0 if signal_src == open or signal_src == close or signal_src == high or signal_src == low or signal_src == hl2 or signal_src == hlc3 or signal_src == ohlc4 or signal_src == hlcc4 vma := na else vma := nz(signal_src) vma_diff = ta.change(nz(vma)) if typeS == 0 or use_src src := nz(vma) else if typeS == 1 src := vma_diff src := signal_rev ? -1 * src : src //Buy/Sell Indication var counter = 0, var stateS = 0, buy_or_sell = 0. if src > 0 if stateS <= 0 buy_or_sell := 1.0 else if src < 0 if stateS >= 0 buy_or_sell := -1.0 //---------------------------------------- //Buy/Sell/Strength Signal --------------- rise = false, fall = false, buy = false, sell = false, buy1 = false, sell1 = false signal = use_src ? src : buy_or_sell if time > invest_begin if signal == 1.0 if counter > 0 buy := true else buy1 := true counter += 1 stateS := 1 alert("Buy") else if signal == -1.0 if counter > 0 sell := true else sell1 := true counter += 1 stateS := -1 alert("Sell") else if signal > 0 rise := true else if signal < 0 fall := true //---------------------------------------- //Create Candle -------------------------- bodyColor = candC >= candO ? color_candle_up : color_candle_down var barI = 0, barL = 0, barR = 0, boxO = 0., boxC = 0., boxH = 0., boxL = 0., boxE = 0 plotcandle(shortPeriod ? candO : na, candH, candL, candC, color=bodyColor, bordercolor=color_candle_bord) if newPeriod barI := bar_index barL := barI[1], barR := barI-1, boxO := candO[1], boxC := candC[1], boxH := candH[1], boxL := candL[1], boxE := shortPeriod[1] ? 0 : 1 else if barstate.islast barL := barI, barR := bar_index, boxO := candO, boxC := candC, boxH := candH, boxL := candL, boxE := newPeriod[1] ? 0 : 1 drawCandle(barL, barR, boxO, boxC, boxH, boxL, color_candle_up, color_candle_down, color_candle_bord, boxE) //---------------------------------------- //Plot Buy/Sell Label -------------------- plotshape(buy1, location=location.belowbar, title="Buy Label", text="B\nu\ny\n#1", style=shape.labelup, size=size.tiny, color=color_signal_up, textcolor=color_signal_text) plotshape(sell1, location=location.abovebar, title="Sell Label", text="S\ne\nl\nl\n#1", style=shape.labeldown, size=size.tiny, color=color_signal_down, textcolor=color_signal_text) plotshape(buy, location=location.belowbar, title="Buy Label", text="B\nu\ny", style=shape.labelup, size=size.tiny, color=color_signal_up, textcolor=color_signal_text) plotshape(sell, location=location.abovebar, title="Sell Label", text="S\ne\nl\nl", style=shape.labeldown, size=size.tiny, color=color_signal_down, textcolor=color_signal_text) plotshape(rise, location=location.belowbar, title="Rise Label", style=shape.triangleup, size=size.tiny, color=color.new(color_signal_up, (1-math.abs(src))*100)) plotshape(fall, location=location.abovebar, title="Fall Label", style=shape.triangledown, size=size.tiny, color=color.new(color_signal_down, (1-math.abs(src))*100)) //---------------------------------------- //Draw High/Low Label -------------------- if dist > 0 var label lastLabelH = na, var label lastLabelL = na labelH = drawLabel(lenHR, pivotH, label.style_label_down, color_peaks, color_peaks_text) labelL = drawLabel(lenLR, pivotL, label.style_label_up, color_peaks, color_peaks_text) if not na(labelH) if pivotLH label.delete(lastLabelH) lastLabelH := labelH if not na(labelL) if pivotLL label.delete(lastLabelL) lastLabelL := labelL //---------------------------------------- //Profit Calculation --------------------- profit = 0., deltaT = 0 var profit_up = 1., var profit_down = 1. var number_up = 0, var number_down = 0 var time_up = 0, var time_down = 0 var cancelB = 0, var cancelS = 0 var invest_sum = 1., var invest_stake = 0. var invest_start = time, var invest_run = false var invest_open = close, var invest_time = time var invest_long = invest_type == "Only Long" or invest_type == "Long and Short" ? true : false var invest_short = invest_type == "Only Short" or invest_type == "Long and Short" ? true : false var invest_rebalance = invest_type == "Rebalancing" ? true : false if time > invest_begin and not invest_run if (stateS > 0 and invest_long) or (stateS < 0 and invest_short) or (stateS != 0 and invest_rebalance) invest_stake := invest_sum*invest_spec/100 invest_start := time, invest_run := true invest_open := close, invest_time := time number_up := stateS < 0 ? -1 : 0 number_down := stateS > 0 ? -1 : 0 if not na(stateS[1]) and invest_run if stateS > 0 if stateS[1] > 0 if cancelB < 2 profit := close/invest_open-1 deltaT := time-invest_time else cancelB := 3 else if cancelS < 2 profit := invest_rebalance ? close/invest_open-1 : 1-close/invest_open deltaT := time-invest_time profit_down *= 1+profit number_down += 1, time_down += deltaT invest_sum += invest_stake*profit invest_stake := 0 if invest_long or invest_rebalance invest_stake := invest_sum*invest_spec/100 cancelS := 2 else cancelS := 3 invest_open := close, invest_time := time, cancelB := 0 else if stateS < 0 if stateS[1] < 0 if cancelS < 2 profit := invest_rebalance ? close/invest_open-1 : 1-close/invest_open deltaT := time-invest_time else cancelS := 3 else if cancelB < 2 profit := close/invest_open-1 deltaT := time-invest_time profit_up *= 1+profit number_up += 1, time_up += deltaT invest_sum += invest_stake*profit invest_stake := 0 if invest_short or invest_rebalance invest_stake := invest_sum*invest_spec/100 cancelB := 2 else cancelB := 3 invest_open := close, invest_time := time, cancelS := 0 average_time_up = number_up > 0 ? time_up/number_up : 0. average_time_down = number_down > 0 ? time_down/number_down : 0. average_profit_up = number_up > 0 ? (profit_up-1)/number_up : 0. average_profit_down = number_down > 0 ? (profit_down-1)/number_down : 0. invest_result = invest_sum + (stateS == nz(stateS[1]) ? invest_stake*profit : 0) invest_factor = (time-invest_start) > 365.25*86400000 ? 365.25*86400000/(time-invest_start) : 1 invest_yield = invest_result > 0 ? math.pow(invest_result, invest_factor)-1 : -1 //---------------------------------------- //Yield Potential Table ------------------ var version = tab_type == "Normal" ? 1 : 0 var splt = version == 0 ? " " : "|", var splt2 = version == 0 ? "/" : splt var str_new = "", var str_next = "", str_old = str_next, str = "", arrStr = array.new_string(1, "") var str_long_opening = invest_rebalance ? "Rebalancing:" : "Long opening:" var str_long_opened = invest_rebalance ? "Uptrend:" : "Long opened:" var str_long_closing = invest_rebalance ? "Rebalancing:" : "Long closing:" var str_long_closed = invest_rebalance ? "Rebalanced:" : "Long closed:" var str_long_average = invest_rebalance ? "βˆ…-Uptrend:" : "βˆ…-Long:" var str_short_opening = invest_rebalance ? "Rebalancing:" : "Short opening:" var str_short_opened = invest_rebalance ? "Downtrend:" : "Short opened:" var str_short_closing = invest_rebalance ? "Rebalancing:" : "Short closing:" var str_short_closed = invest_rebalance ? "Rebalanced:" : "Short closed:" var str_short_average = invest_rebalance ? "βˆ…-Downtrend:" : "βˆ…-Short:" tab_color = color.rgb(120, 123, 134, 30) showB = invest_long or invest_rebalance ? cancelB : -1 showS = invest_short or invest_rebalance ? cancelS : -1 if stateS > 0 if nz(stateS[1]) <= 0 if nz(stateS[1]) < 0 and showS == 2 str := str_short_closing + splt str_next := str_short_closed + splt + showYield(profit) + "%" + splt2 + showPeriod(deltaT) else if showB == 0 tab_color := color.new(color_signal_up,30) str := str_long_opening + splt profit := 0, deltaT := 0 else if showB == 0 tab_color := color.new(color_signal_up,30) str := str_long_opened + splt else if showB == 2 str := str_long_closing + splt str_next := str_long_closed + splt + showYield(profit) + "%" + splt2 + showPeriod(deltaT) else if stateS < 0 if nz(stateS[1]) >= 0 if nz(stateS[1]) > 0 and showB == 2 str := str_long_closing + splt str_next := str_long_closed + splt + showYield(profit) + "%" + splt2 + showPeriod(deltaT) else if showS == 0 tab_color := color.new(color_signal_down,30) str := str_short_opening + splt profit := 0, deltaT := 0 else if showS == 0 tab_color := color.new(color_signal_down,30) str := str_short_opened + splt else if showS == 2 str := str_short_closing + splt str_next := str_short_closed + splt + showYield(profit) + "%" + splt2 + showPeriod(deltaT) str_new := str == "" ? "Waiting for opportunity..." : str + showYield(profit) + "%" + splt2 + showPeriod(deltaT) str_buy = str_long_average + splt + showYield(average_profit_up) + "%" + splt2 + showPeriod(average_time_up) str_sell = str_short_average + splt + showYield(average_profit_down) + "%" + splt2+ showPeriod(average_time_down) str_invest = "Result:" + splt + showYield(invest_yield) + "%"+ splt2 + "Y" //---------------------------------------- //Show Timeframe Periods Table ----------- if invest_type != "None" and tab_type != "None" and barstate.islast and not na(vma) posTB = position.top_center if tab_pos == "Top Right" posTB := position.top_right else if tab_pos == "Middle Right" posTB := position.middle_right else if tab_pos == "Bottom Right" posTB := position.bottom_right else if tab_pos == "Bottom Center" posTB := position.bottom_center else if tab_pos == "Bottom Left" posTB := position.bottom_left else if tab_pos == "Middle Left" posTB := position.middle_left else if tab_pos == "Top Left" posTB := position.top_left invest_comment = "" if invest_yield >= 0.01 invest_comment := "β˜… Good Strategy β˜…" else if invest_yield <= -0.01 invest_comment := "β†― Bad Strategy β†―" else invest_comment := "- Unclear Result -" if version == 1 TB = table.new(posTB, 3, 7, bgcolor=tab_color, border_width=0) n = 0, str0 = "Subject", str1 = "Yield", str2 = "Duration" table.cell(TB, 0, 0, text=str0, text_color=color_signal_text) table.cell(TB, 1, 0, text=str1, text_color=color_signal_text) table.cell(TB, 2, 0, text=str2, text_color=color_signal_text) if str_new != "Waiting for opportunity..." n += 1 arrStr := str.split(str_new, splt) str0 := array.get(arrStr, 0), str1 := array.get(arrStr, 1), str2 := array.get(arrStr, 2) table.cell(TB, 0, n, text=str0, text_color=color_signal_text, text_halign=text.align_right) table.cell(TB, 1, n, text=str1, text_color=color_signal_text) table.cell(TB, 2, n, text=str2, text_color=color_signal_text) table.cell_set_text_halign(TB, 0, n, text.align_right) else n += 1 table.merge_cells(TB, 0, n, 2, n) table.cell(TB, 0, n, text=str_new, text_color=color_signal_text) if str_old != "" n += 1 arrStr := str.split(str_old, splt) str0 := array.get(arrStr, 0), str1 := array.get(arrStr, 1), str2 := array.get(arrStr, 2) table.cell(TB, 0, n, text=str0, text_color=color_signal_text, text_halign=text.align_right) table.cell(TB, 1, n, text=str1, text_color=color_signal_text) table.cell(TB, 2, n, text=str2, text_color=color_signal_text) table.cell_set_text_halign(TB, 0, n, text.align_right) if invest_average and (invest_long or invest_rebalance) n += 1 arrStr := str.split(str_buy, splt) str0 := array.get(arrStr, 0), str1 := array.get(arrStr, 1), str2 := array.get(arrStr, 2) table.cell(TB, 0, n, text=str0, text_color=color_signal_text, text_halign=text.align_right) table.cell(TB, 1, n, text=str1, text_color=color_signal_text) table.cell(TB, 2, n, text=str2, text_color=color_signal_text) table.cell_set_text_halign(TB, 0, n, text.align_right) if invest_average and (invest_short or invest_rebalance) n += 1 arrStr := str.split(str_sell, splt) str0 := array.get(arrStr, 0), str1 := array.get(arrStr, 1), str2 := array.get(arrStr, 2) table.cell(TB, 0, n, text=str0, text_color=color_signal_text, text_halign=text.align_right) table.cell(TB, 1, n, text=str1, text_color=color_signal_text) table.cell(TB, 2, n, text=str2, text_color=color_signal_text) table.cell_set_text_halign(TB, 0, n, text.align_right) n += 1 arrStr := str.split(str_invest, splt) str0 := array.get(arrStr, 0), str1 := array.get(arrStr, 1), str2 := "1Y" table.cell(TB, 0, n, text=str0, text_color=color_signal_text, text_halign=text.align_right) table.cell(TB, 1, n, text=str1, text_color=color_signal_text) table.cell(TB, 2, n, text=str2, text_color=color_signal_text) table.cell_set_text_halign(TB, 0, n, text.align_right) n += 1 table.merge_cells(TB, 0, n, 2, n) table.cell(TB, 0, n, text=invest_comment, text_color=color_signal_text) else TB = table.new(posTB, 1, 1, bgcolor=tab_color, border_width=0) str := str_new str += str_old == "" ? "" : (str == "" ? "" : "\n") + str_old str += invest_average and (invest_long or invest_rebalance) ? (str == "" ? "" : "\n") + str_buy : "" str += invest_average and (invest_short or invest_rebalance) ? (str == "" ? "" : "\n") + str_sell : "" str += (str == "" ? "" : "\n") + str_invest str += invest_comment == "" ? "" : "\n" + invest_comment table.cell(TB, 0, 0, text=str, text_color=color_signal_text) //----------------------------------------
MMA mainpanel
https://www.tradingview.com/script/mhZFGFgv-MMA-mainpanel/
eykpunter
https://www.tradingview.com/u/eykpunter/
94
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© eykpunter //@version=5 indicator("MMA mainpanel","MMA main",true) //short group ema3=ta.ema(close,3) ema5=ta.ema(close,5) ema8=ta.ema(close,8) ema10=ta.ema(close,10) ema12=ta.ema(close, 12) ema15=ta.ema(close,15) //long group ema30=ta.ema(close,30) ema35=ta.ema(close,35) ema40=ta.ema(close,40) ema45=ta.ema(close,45) ema50=ta.ema(close,50) ema60=ta.ema(close,60) //logic ut=ema15>ema30 and ema30>ema60 and ema50>ema50[1] dt=ema15<ema30 and ema30<ema60 and ema50<ema50[1] nt=not ut and not dt //plots shortgroup=plot(ema15,"ema15",color=nt?color.new(color.gray,70):color.navy,linewidth=2) longgroup= plot(ema30,"ema30",color=nt?color.black:color.fuchsia,linewidth=2) //fill fill(shortgroup,longgroup,color=ut?color.new(color.aqua, 50):dt?color.new(color.purple,50):na) //plots plot(ema5,"ema5",color=nt?color.new(color.gray,70):color.blue,linewidth=1) plot(ema8,"ema8",color=nt?color.new(color.gray,70):color.blue,linewidth=1) plot(ema10,"ema10",color=nt?color.new(color.gray,70):color.blue,linewidth=1) plot(ema12,"ema12",color=nt?color.new(color.gray,70):color.blue,linewidth=1) plot(ema35,"ema35",color=nt?color.new(color.black,70):color.red,linewidth=1) plot(ema40,"ema40",color=nt?color.new(color.black,70):color.red,linewidth=1) plot(ema45,"ema45",color=nt?color.new(color.black,70):color.red,linewidth=1) plot(ema50,"ema50",color=nt?color.new(color.black,70):color.red,linewidth=1) plot(ema60,"ema60",color=nt?color.new(color.black,70):color.maroon,linewidth=2) plot(ema3,"ema3",color=nt?color.new(color.gray,70):color.aqua,linewidth=2)
EMA Angle Trend Strength
https://www.tradingview.com/script/UtBPMHof/
undisputed140188
https://www.tradingview.com/u/undisputed140188/
17
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© undisputed140188 //@version=5 indicator("EMA Angle Trend Strength", "EATS", overlay = false) emaLength = input(10, "EMA Length", "Number of candles for EMA") eatsLength = input.int(3, "Precision", minval = 1, tooltip = "How many candles for angle calculation") ema = ta.ema(close, emaLength) emaSlope(int x2) => emaSlope = math.abs(math.atan((ema[0] - ema[x2]) / -x2) * 180.0 / math.pi) eats(float slope) => eats = (math.abs(slope) / 90) *100 sig = eats(emaSlope(eatsLength)) plot(sig, "EATS")
AI Trend Navigator [K-Neighbor]
https://www.tradingview.com/script/30aLnPNh-AI-Trend-Navigator-K-Neighbor/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
1,656
study
5
CC-BY-NC-SA-4.0
// 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('AI Trend Navigator', overlay=true) // ~~ Tooltips { t1 ="PriceValue selects the method of price computation. \n\nSets the smoothing period for the PriceValue. \n\nAdjusting these settings will change the input values for the K-Nearest Neighbors algorithm, influencing how the trend is calculated." t2 = "TargetValue specifies the target to evaluate. \n\nSets the smoothing period for the TargetValue." t3 ="numberOfClosestValues sets the number of closest values that are considered when calculating the KNN Moving Average. Adjusting this number will affect the sensitivity of the trend line, with a higher value leading to a smoother line and a lower value resulting in a line that is more responsive to recent price changes." t4 ="smoothingPeriod sets the period for the moving average applied to the KNN classifier. Adjusting the smoothing period will affect how rapidly the trend line responds to price changes, with a larger smoothing period leading to a smoother line that may lag recent price movements, and a smaller smoothing period resulting in a line that more closely tracks recent changes." t5 ="This option controls the background color for the trend prediction. Enabling it will change the background color based on the prediction, providing visual cues on the direction of the trend. A green color indicates a positive prediction, while red indicates a negative prediction." //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Inputs { PriceValue = input.string("hl2", options = ["hl2","VWAP", "sma", "wma", "ema", "hma"], group="", inline="Value") maLen = input.int(5, minval=2, maxval=200, title="", group="", inline="Value", tooltip=t1) TargetValue = input.string("Price Action", options = ["Price Action","VWAP", "Volatility", "sma", "wma", "ema", "hma"], group="", inline="Target") maLen_ = input.int(5, minval=2, maxval=200, title="", group="", inline="Target", tooltip=t2) // Input parameters for the KNN Moving Average numberOfClosestValues = input.int(3, "Number of Closest Values", 2, 200, tooltip=t3) smoothingPeriod = input.int(50, "Smoothing Period", 2, 500, tooltip=t4) windowSize = math.max(numberOfClosestValues, 30) // knn Color Upknn_col = input.color(color.lime, title="", group="KNN Color", inline="knn col") Dnknn_col = input.color(color.red, title="", group="KNN Color", inline="knn col") Neuknn_col = input.color(color.orange, title="", group="KNN Color", inline="knn col") // MA knn Color Maknn_col = input.color(color.teal, title="", group="MA KNN Color", inline="MA knn col") // BG Color bgcolor = input.bool(false, title="Trend Prediction Color", group="BG Color", inline="bg", tooltip=t5) Up_col = input.color(color.lime, title="", group="BG Color", inline="bg") Dn_col = input.color(color.red, title="", group="BG Color", inline="bg") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ kNN Classifier { value_in = switch PriceValue "hl2" => ta.sma(hl2,maLen) "VWAP" => ta.vwap(close[maLen]) "sma" => ta.sma(close,maLen) "wma" => ta.wma(close,maLen) "ema" => ta.ema(close,maLen) "hma" => ta.hma(close,maLen) meanOfKClosest(value_,target_) => closestDistances = array.new_float(numberOfClosestValues, 1e10) closestValues = array.new_float(numberOfClosestValues, 0.0) for i = 1 to windowSize value = value_[i] distance = math.abs(target_ - value) maxDistIndex = 0 maxDistValue = closestDistances.get(0) for j = 1 to numberOfClosestValues - 1 if closestDistances.get(j) > maxDistValue maxDistIndex := j maxDistValue := closestDistances.get(j) if distance < maxDistValue closestDistances.set(maxDistIndex, distance) closestValues.set(maxDistIndex, value) closestValues.sum() / numberOfClosestValues // Choose the target input based on user selection target_in = switch TargetValue "Price Action" => ta.rma(close,maLen_) "VWAP" => ta.vwap(close[maLen_]) "Volatility" => ta.atr(14) "sma" => ta.sma(close,maLen_) "wma" => ta.wma(close,maLen_) "ema" => ta.ema(close,maLen_) "hma" => ta.hma(close,maLen_) knnMA = meanOfKClosest(value_in,target_in) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ kNN Prediction { // Function to calculate KNN Classifier price = math.avg(knnMA, close) c = ta.rma(knnMA[1], smoothingPeriod) o = ta.rma(knnMA, smoothingPeriod) // Defines KNN function to perform classification knn(price) => Pos_count = 0 Neg_count = 0 min_distance = 10e10 nearest_index = 0 for j = 1 to 10 distance = math.sqrt(math.pow(price[j] - price, 2)) if distance < min_distance min_distance := distance nearest_index := j Neg = c[nearest_index] > o[nearest_index] Pos = c[nearest_index] < o[nearest_index] if Pos Pos_count += 1 if Neg Neg_count += 1 output = Pos_count>Neg_count?1:-1 // Calls KNN function and smooths the prediction knn_prediction_raw = knn(price) knn_prediction = ta.wma(knn_prediction_raw, 3) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Plots { // Plots for display on the chart knnMA_ = ta.wma(knnMA,5) knnMA_col = knnMA_>knnMA_[1]?Upknn_col:knnMA_<knnMA_[1]?Dnknn_col:Neuknn_col Classifier_Line = plot(knnMA_,"Knn Classifier Line", knnMA_col) MAknn_ = ta.rma(knnMA, smoothingPeriod) plot(MAknn_,"Average Knn Classifier Line" ,Maknn_col) green = knn_prediction < 0.5 red = knn_prediction > -0.5 bgcolor( green and bgcolor? color.new(Dn_col,80) : red and bgcolor ? color.new(Up_col,80) : na) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Alerts { knnMA_cross_Over_Ma = ta.crossover(knnMA_,MAknn_) knnMA_cross_Under_Ma = ta.crossunder(knnMA_,MAknn_) knnMA_cross_Over_Close = ta.crossover(knnMA_,close) knnMA_cross_Under_Close = ta.crossunder(knnMA_,close) knnMA_Switch_Up = knnMA_[1]<knnMA_ and knnMA_[1]<=knnMA_[2] knnMA_Switch_Dn = knnMA_[1]>knnMA_ and knnMA_[1]>=knnMA_[2] knnMA_Neutral = knnMA_col==Neuknn_col and knnMA_col[1]!=Neuknn_col greenBG = green and not green[1] redBG = red and not red[1] alertcondition(knnMA_cross_Over_Ma, title = "Knn Crossover Average Knn", message = "Knn Crossover Average Knn") alertcondition(knnMA_cross_Under_Ma, title = "Knn Crossunder Average Knn", message = "Knn Crossunder Average Knn") alertcondition(knnMA_cross_Over_Close, title = "Knn Crossover Close", message = "Knn Crossover Close") alertcondition(knnMA_cross_Under_Close, title = "Knn Crossunder Close", message = "Knn Crossunder Close") alertcondition(knnMA_Switch_Up, title = "Knn Switch Up", message = "Knn Switch Up") alertcondition(knnMA_Switch_Dn, title = "Knn Switch Dn", message = "Knn Switch Dn") alertcondition(knnMA_Neutral, title = "Knn is Neutral", message = "Knn is Neutral") alertcondition(greenBG, title = "Positive Prediction", message = "Positive Prediction") alertcondition(redBG, title = "Negative Prediction", message = "Negative Prediction") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
Liquidity Pools
https://www.tradingview.com/script/YHQBWfXw/
FX365_Thailand
https://www.tradingview.com/u/FX365_Thailand/
685
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© FX365_Thailand //Revision history //v100.0 First release //v101.0 Added alert conditions for swing high/low creation //v107.0 Added alert conditions for liquidity raid //@version=5 indicator('Liquidity Pools', shorttitle='Liquidity Pools(SABAI SABAI FX)', max_lines_count=500,overlay=true) //Users' input ------ len_l = input.int(4, 'Left bar&Right bar', minval=1,group="Swing High Low Setting") flg_shsl = input.bool(false, 'Show Swing High Swing Low') i_width = input.int(1, 'Line Width', minval=1,maxval=6,group="Liquidity Pools Settings") i_linestyle = input.string(defval=line.style_dotted,options=[line.style_solid,line.style_dashed,line.style_dotted],title="Line Style") i_linecolor_bs = input.color(color.new(#ff5252,65),title="Buy Side Liquidity Color") i_linecolor_ss = input.color(color.new(#0ef30e,65),title="Sell Side Liquidity Color") h = high l = low //Identify swingh high/low ----- swing_h = barstate.isconfirmed ? ta.pivothigh(h, len_l, len_l) : na swing_l = barstate.isconfirmed ? ta.pivotlow(l, len_l, len_l) : na //Value of Swing High/Swing Low LSH = ta.valuewhen(swing_h, high[len_l], 0) LSL = ta.valuewhen(swing_l, low[len_l], 0) plotshape(flg_shsl ? swing_h : na, color=color.new(color.gray, 0), style=shape.labeldown, title='Swing High', text='SH', textcolor=color.new(color.white, 0), location=location.abovebar, offset=-len_l,size=size.tiny) plotshape(flg_shsl ? swing_l : na, color=color.new(color.gray, 0), style=shape.labelup, title='Swing Low', text='SL', textcolor=color.new(color.white, 0), location=location.belowbar, offset=-len_l,size=size.tiny) //Draw liquidity pools //Variables var line lin_BSLQ_upper = na var line lin_BSLQ_lower = na var line lin_SSLQ_upper = na var line lin_SSLQ_lower = na //Threshold thresh = timeframe.isseconds ? 1.0001 : (timeframe.period == "60" and timeframe.period=="240") ? 3 : (timeframe.isminutes and timeframe.period != "60" and timeframe.period != "240") ? 1.0001 : timeframe.isdaily ? 1.005 : timeframe.isweekly ? 1.01 : timeframe.ismonthly ? 1.01 : 1.001 thresh_ = timeframe.isseconds ? 0.9999 : (timeframe.period == "60" and timeframe.period=="240") ? 3 : (timeframe.isminutes and timeframe.period != "60" and timeframe.period != "240") ? 0.9999 : timeframe.isdaily ? 0.995 : timeframe.isweekly ? 0.99 : timeframe.ismonthly ? 0.99 : 0.999 //Lines if swing_h lin_BSLQ_lower := line.new(x1=bar_index-len_l,x2=bar_index, y1=LSH,y2=LSH,color=i_linecolor_bs,style= i_linestyle,width = i_width) if swing_h lin_BSLQ_upper := line.new(x1=bar_index-len_l,x2=bar_index, y1=LSH*thresh,y2=LSH*thresh,color=i_linecolor_bs,style= i_linestyle,width = i_width) if swing_l lin_SSLQ_lower := line.new(x1=bar_index-len_l,x2=bar_index, y1=LSL*thresh_,y2=LSL*thresh_,color=i_linecolor_ss,style=i_linestyle,width = i_width) if swing_l lin_SSLQ_upper := line.new(x1=bar_index-len_l,x2=bar_index, y1=LSL,y2=LSL,color=i_linecolor_ss,style= i_linestyle,width = i_width) //Fill linefill.new(lin_BSLQ_upper,lin_BSLQ_lower,color=i_linecolor_bs) linefill.new(lin_SSLQ_upper,lin_SSLQ_lower,color=i_linecolor_ss) //Alert conditions //Swing high low creation alertcondition(swing_h,message="Swing High Created", title="Swing High") alertcondition(swing_l,message="Swing Low Created", title="Swing Low") //Reach liquidity zone alertcondition(ta.crossover(high,LSH),message="Price reached buy side liquidity", title="Buy Side Liquidity Raid") alertcondition(ta.crossunder(low,LSL),message="Price reached sell side liquidity", title="Sell Side Liquidity Raid")
Candles In Row (Expo)
https://www.tradingview.com/script/PZKNUpQx-Candles-In-Row-Expo/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
831
study
5
CC-BY-NC-SA-4.0
// 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("Candles In Row (Expo)",overlay=true) //~~} // ~~ ToolTips { t0 ="Select the price input to determine the basis for calculation. You can choose between the regular close and open prices or opt for Heikin Ashi candles." t1 = "This option allows you to select between displaying the full data window or only the active data. Additionally, you can choose to display a counter that keeps track of the number of candles." t2 = "Select the desired number of consecutive candles with a specific color to trigger an alert. Choose the color, either green or red, that the sequence of candles must match for the alert to be created." t3 ="Set the location and size for the display table, allowing you to position it according to your preferences." //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Inputs { price = input.string("Candles","Select Price",["Candles","Heikin Ashi Candles"],t0,"price") window = input.string("All Data","Display Data",["All Data","Active Data"],inline="window") count = input.bool(true,"Candle Counter",t1,"window") inRow = input.int(5,"Alert Candles in Row",group="Alerts",inline="alert") candle = input.string("Green","",["Green","Red"],t2,"alert","Alerts") pos = input.string(position.top_right, title="Location",options =[position.top_right,position.top_center, position.top_left,position.bottom_right,position.bottom_center,position.bottom_left,position.middle_right,position.middle_left],group="Table",inline="table") size = input.string(size.normal, title="Size",options =[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],group="Table",inline="table",tooltip=t3) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Variables { var data = matrix.new<int>(1,4,0) var labs = array.new<label>() var counter = int(na) tbl = table.new(pos, data.columns()+1, data.rows()+1,chart.bg_color,color.black,1,color(na),1) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Price { haClose = hlcc4 haOpen = float(na) haOpen := na(haOpen[1])?(open + close)/2:(nz(haOpen[1])+nz(haClose[1]))/2 c = price=="Candles"?close:haClose o = price=="Candles"?open:haOpen green = c>o red = c<o //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Label Count Function { Numbers(c,b)=> if count lab = label.new(bar_index,b?low-ta.ema(ta.tr,100):high+ta.ema(ta.tr,100),str.tostring(c+1), color=na,style=b?label.style_label_up:label.style_label_down,textcolor=green?color.rgb(61, 212, 139,10):red?color.rgb(230, 103, 103,10):chart.fg_color) labs.unshift(lab) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Counter Code { if green and green[1] counter += 1 if data.rows()<=counter data.add_row(counter,array.from(1,0,0,0)) else data.set(counter,0,data.get(counter,0)+1) data.set(counter-1,2,data.get(counter-1,2)+1) Numbers(counter,true) else if red and red[1] counter += 1 if data.rows()<=counter data.add_row(counter,array.from(0,1,0,0)) else data.set(counter,1,data.get(counter,1)+1) data.set(counter-1,3,data.get(counter-1,3)+1) Numbers(counter,false) else counter := 0 for element in labs element.delete() labs.clear() if green data.set(counter,0,data.get(counter,0)+1) data.set(counter[1],2,data.get(counter[1],2)+1) Numbers(counter,true) if red data.set(counter,1,data.get(counter,1)+1) data.set(counter[1],3,data.get(counter[1],3)+1) Numbers(counter,false) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Table { if barstate.islast headerColor = color.rgb(56, 80, 255) headerTextColor = color.rgb(255, 255, 255) tbl.cell(0,0,"Candles in Row",bgcolor=headerColor,text_color=headerTextColor,text_size=size) tbl.cell(1,0,"Green",bgcolor=headerColor,text_color=headerTextColor,text_size=size) tbl.cell(2,0,"Red",bgcolor=headerColor,text_color=headerTextColor,text_size=size) tbl.cell(3,0,"Next Candle is Green",bgcolor=headerColor,text_color=headerTextColor,text_size=size) tbl.cell(4,0,"Next Candle is Red",bgcolor=headerColor,text_color=headerTextColor,text_size=size) for i=0 to data.rows()-1 x = i if window!="All Data" x:=counter total = data.get(x,2)+data.get(x,3) predictionGreen = (data.get(x,2)/total)*100 predictionRed = (data.get(x,3)/total)*100 posColor = color.rgb(61, 212, 139,10) negColor = color.rgb(230, 103, 103,10) bgColor = color.from_gradient(value=i, bottom_value=1, top_value=20, bottom_color=color.new(color.teal,100) , top_color=color.new(color.teal, 0))//top_color=color.new(#f6ff4e, 100)) rowTextColor = chart.fg_color tbl.cell(0,x+1,str.tostring(x+1), bgcolor=counter==x and green? posColor:counter==x and red?negColor:bgColor, text_color=rowTextColor,text_size=size) tbl.cell(1,x+1,str.tostring(data.get(x,0)), bgcolor=counter==x and green?posColor:bgColor, text_color=rowTextColor,text_size=size) tbl.cell(2,x+1,str.tostring(data.get(x,1)), bgcolor=counter==x and red?negColor:bgColor, text_color=rowTextColor,text_size=size) tbl.cell(3,x+1,str.tostring(predictionGreen,format.percent), bgcolor=counter==x and predictionGreen>predictionRed?posColor:bgColor, text_color=rowTextColor,text_size=size) tbl.cell(4,x+1,str.tostring(predictionRed,format.percent), bgcolor=counter==x and predictionGreen<predictionRed?negColor:bgColor, text_color=rowTextColor,text_size=size) if window!="All Data" break //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Alert { if counter==inRow if green and candle=="Green" alert(str.tostring(counter)+" Green Candles in Row on: "+syminfo.ticker+" ["+timeframe.period+"]") if red and candle=="Red" alert(str.tostring(counter)+" Red Candles in Row on: "+syminfo.ticker+" ["+timeframe.period+"]") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
CPR (Central Pivot Range)
https://www.tradingview.com/script/R6lRetr0-CPR-Central-Pivot-Range/
ajithcpas
https://www.tradingview.com/u/ajithcpas/
166
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© ajithcpas //@version=5 indicator("Central Pivot Range", "CPR", overlay=true, max_lines_count=500, max_labels_count=500) AUTO = "Auto" DAILY = "Daily" WEEKLY = "Weekly" MONTHLY = "Monthly" QUARTERLY = "Quarterly" YEARLY = "Yearly" TRADITIONAL = "Traditional" FIBONACCI = "Fibonacci" CLASSIC = "Classic" CAMARILLA = "Camarilla" kind = input.string(title="Type", defval="Traditional", options=[TRADITIONAL, FIBONACCI, CLASSIC, CAMARILLA]) cpr_time_frame = input.string(title="CPR Timeframe", defval=AUTO, options=[AUTO, DAILY, WEEKLY, MONTHLY, QUARTERLY, YEARLY]) look_back = input.int(title="Number of CPR Back", defval=2, minval=1, maxval=5000) is_daily_based = input.bool(title="Use Daily-based Values", defval=true, tooltip="When this option is unchecked, CPR will use intraday data while calculating on intraday charts. If Extended Hours are displayed on the chart, they will be taken into account during the CPR level calculation. If intraday OHLC values are different from daily-based values (normal for stocks), the CPR levels will also differ.") show_labels = input.bool(title="Show Labels", defval=true, group="labels") show_prices = input.bool(title="Show Prices", defval=true, group="labels") position_labels = input.string("Right", "Labels Position", options=["Left", "Right"], group="labels") line_width = input.int(title="Line Width", defval=1, minval=1, maxval=100, group="labels") var arr_time = array.new_int() var p = array.new_float() var tp = array.new_float() var bp = array.new_float() cpr_show = input.bool(true, "", inline="CPR", group="CPR levels") cpr_color = input.color(color.purple, "CPR", inline="CPR", group="CPR levels") var SR_COLOR = #FB8C00 sr_show = input.bool(false, "Show SR Levels", inline="Show SR Levels", group="CPR levels") var r1 = array.new_float() var s1 = array.new_float() s1_show = input.bool(true, "", inline="S1/R1", group="CPR levels") s1_color = input.color(SR_COLOR, "S1", inline="S1/R1" , group="CPR levels") r1_show = input.bool(true, "", inline="S1/R1", group="CPR levels") r1_color = input.color(SR_COLOR, "R1", inline="S1/R1", group="CPR levels") var r1_5 = array.new_float() var s1_5 = array.new_float() s1_5_show = input.bool(true, "", inline="S1.5/R1.5", group="CPR levels") s1_5_color = input.color(SR_COLOR, "S1.5", inline="S1.5/R1.5" , group="CPR levels") r1_5_show = input.bool(true, "", inline="S1.5/R1.5", group="CPR levels") r1_5_color = input.color(SR_COLOR, "R1.5", inline="S1.5/R1.5", group="CPR levels") var r2 = array.new_float() var s2 = array.new_float() s2_show = input.bool(true, "", inline="S2/R2", group="CPR levels") s2_color = input.color(SR_COLOR, "S2", inline="S2/R2", group="CPR levels") r2_show = input.bool(true, "", inline="S2/R2", group="CPR levels") r2_color = input.color(SR_COLOR, "R2", inline="S2/R2", group="CPR levels") var r2_5 = array.new_float() var s2_5 = array.new_float() s2_5_show = input.bool(true, "", inline="S2.5/R2.5", group="CPR levels") s2_5_color = input.color(SR_COLOR, "S2.5", inline="S2.5/R2.5" , group="CPR levels") r2_5_show = input.bool(true, "", inline="S2.5/R2.5", group="CPR levels") r2_5_color = input.color(SR_COLOR, "R2.5", inline="S2.5/R2.5", group="CPR levels") var r3 = array.new_float() var s3 = array.new_float() s3_show = input.bool(true, "", inline="S3/R3", group="CPR levels") s3_color = input.color(SR_COLOR, "S3", inline="S3/R3", group="CPR levels") r3_show = input.bool(true, "", inline="S3/R3", group="CPR levels") r3_color = input.color(SR_COLOR, "R3", inline="S3/R3", group="CPR levels") var r4 = array.new_float() var s4 = array.new_float() s4_show = input.bool(true, "", inline="S4/R4", group="CPR levels") s4_color = input.color(SR_COLOR, "S4", inline="S4/R4", group="CPR levels") r4_show = input.bool(true, "", inline="S4/R4", group="CPR levels") r4_color = input.color(SR_COLOR, "R4", inline="S4/R4", group="CPR levels") var r5 = array.new_float() var s5 = array.new_float() s5_show = input.bool(true, "", inline="S5/R5", group="CPR levels") s5_color = input.color(SR_COLOR, "S5", inline="S5/R5", group="CPR levels") r5_show = input.bool(true, "", inline="S5/R5", group="CPR levels") r5_color = input.color(SR_COLOR, "R5", inline="S5/R5", group="CPR levels") dev_cpr_show = input.bool(true, "", inline="Dev CPR", group="Developing CPR levels") dev_cpr_color = input.color(color.teal, "Dev CPR", inline="Dev CPR", group="Developing CPR levels") var dev_r1 = array.new_float() var dev_s1 = array.new_float() dev_s1_show = input.bool(true, "", inline="S1/R1", group="Developing CPR levels") dev_s1_color = input.color(SR_COLOR, "S1", inline="S1/R1" , group="Developing CPR levels") dev_r1_show = input.bool(true, "", inline="S1/R1", group="Developing CPR levels") dev_r1_color = input.color(SR_COLOR, "R1", inline="S1/R1", group="Developing CPR levels") extend_dev_cpr_line = input.bool(false, "", inline="extend", group="Developing CPR levels") dev_cpr_line_days = input.int(title="Extend line by days", defval=1, minval=1, maxval=10, inline="extend", group="Developing CPR levels", tooltip="Enable this when the Dev CPR lines are not visible(i.e. there is a trading holiday in upcoming session).") check_holidays = input.bool(true, "Check NSE/BSE holidays", group="Developing CPR levels", tooltip="Enable this when the Dev CPR lines are not visible(i.e. there is a trading holiday in upcoming session).") pivotX_open = float(na) pivotX_open := nz(pivotX_open[1], open) pivotX_high = float(na) pivotX_high := nz(pivotX_high[1], high) pivotX_low = float(na) pivotX_low := nz(pivotX_low[1], low) pivotX_prev_open = float(na) pivotX_prev_open := nz(pivotX_prev_open[1]) pivotX_prev_high = float(na) pivotX_prev_high := nz(pivotX_prev_high[1]) pivotX_prev_low = float(na) pivotX_prev_low := nz(pivotX_prev_low[1]) pivotX_prev_close = float(na) pivotX_prev_close := nz(pivotX_prev_close[1]) get_pivot_resolution() => resolution = "M" if cpr_time_frame == AUTO if timeframe.isintraday resolution := timeframe.multiplier <= 15 ? "D" : "W" else if timeframe.isweekly or timeframe.ismonthly resolution := "12M" else if cpr_time_frame == DAILY resolution := "D" else if cpr_time_frame == WEEKLY resolution := "W" else if cpr_time_frame == MONTHLY resolution := "M" else if cpr_time_frame == QUARTERLY resolution := "3M" else if cpr_time_frame == YEARLY resolution := "12M" resolution var lines = array.new_line() var labels = array.new_label() draw_line(i, pivot, col, line_style=line.style_solid) => line aLine = na if array.size(arr_time) > 1 aLine := line.new(array.get(arr_time, i), array.get(pivot, i), array.get(arr_time, i + 1), array.get(pivot, i), color=col, xloc=xloc.bar_time, width=line_width, style=line_style) array.push(lines, aLine) aLine draw_label(i, y, txt, txt_color) => if show_labels or show_prices display_text = "" if show_labels and show_prices and txt != '' display_text := str.format(" {0} - {1}", txt, math.round_to_mintick(y)) else if show_labels and txt != '' display_text := " " + txt else display_text := str.format(" {0}", math.round_to_mintick(y)) x = position_labels == "Left" ? array.get(arr_time, i) : array.get(arr_time, i + 1) array.push(labels, label.new(x=x, y=y, text=display_text, textcolor=txt_color, style=label.style_none, color=#00000000, xloc=xloc.bar_time)) traditional() => pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3 _r1 = pivotX_Median * 2 - pivotX_prev_low _s1 = pivotX_Median * 2 - pivotX_prev_high _r2 = pivotX_Median + 1 * (pivotX_prev_high - pivotX_prev_low) _s2 = pivotX_Median - 1 * (pivotX_prev_high - pivotX_prev_low) _r3 = pivotX_Median * 2 + (pivotX_prev_high - 2 * pivotX_prev_low) _s3 = pivotX_Median * 2 - (2 * pivotX_prev_high - pivotX_prev_low) array.push(r1, _r1) array.push(s1, _s1) array.push(r1_5, (_r1 + _r2) / 2) array.push(s1_5, (_s1 + _s2) / 2) array.push(r2, _r2) array.push(s2, _s2) array.push(r2_5, (_r2 + _r3) / 2) array.push(s2_5, (_s2 + _s3) / 2) array.push(r3, _r3) array.push(s3, _s3) array.push(r4, pivotX_Median * 3 + (pivotX_prev_high - 3 * pivotX_prev_low)) array.push(s4, pivotX_Median * 3 - (3 * pivotX_prev_high - pivotX_prev_low)) array.push(r5, pivotX_Median * 4 + (pivotX_prev_high - 4 * pivotX_prev_low)) array.push(s5, pivotX_Median * 4 - (4 * pivotX_prev_high - pivotX_prev_low)) fibonacci() => pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3 pivot_range = pivotX_prev_high - pivotX_prev_low array.push(r1, pivotX_Median + 0.382 * pivot_range) array.push(s1, pivotX_Median - 0.382 * pivot_range) array.push(r2, pivotX_Median + 0.618 * pivot_range) array.push(s2, pivotX_Median - 0.618 * pivot_range) array.push(r3, pivotX_Median + 1 * pivot_range) array.push(s3, pivotX_Median - 1 * pivot_range) classic() => pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3 pivot_range = pivotX_prev_high - pivotX_prev_low array.push(r1, pivotX_Median * 2 - pivotX_prev_low) array.push(s1, pivotX_Median * 2 - pivotX_prev_high) array.push(r2, pivotX_Median + 1 * pivot_range) array.push(s2, pivotX_Median - 1 * pivot_range) array.push(r3, pivotX_Median + 2 * pivot_range) array.push(s3, pivotX_Median - 2 * pivot_range) array.push(r4, pivotX_Median + 3 * pivot_range) array.push(s4, pivotX_Median - 3 * pivot_range) camarilla() => pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3 pivot_range = pivotX_prev_high - pivotX_prev_low array.push(r1, pivotX_prev_close + pivot_range * 1.1 / 12.0) array.push(s1, pivotX_prev_close - pivot_range * 1.1 / 12.0) array.push(r2, pivotX_prev_close + pivot_range * 1.1 / 6.0) array.push(s2, pivotX_prev_close - pivot_range * 1.1 / 6.0) array.push(r3, pivotX_prev_close + pivot_range * 1.1 / 4.0) array.push(s3, pivotX_prev_close - pivot_range * 1.1 / 4.0) array.push(r4, pivotX_prev_close + pivot_range * 1.1 / 2.0) array.push(s4, pivotX_prev_close - pivot_range * 1.1 / 2.0) r5_val = pivotX_prev_high / pivotX_prev_low * pivotX_prev_close array.push(r5, r5_val) array.push(s5, 2 * pivotX_prev_close - r5_val) calc_pivot() => pivotX_Median = (pivotX_prev_high + pivotX_prev_low + pivotX_prev_close) / 3 pivotX_Bottom = (pivotX_prev_high + pivotX_prev_low) / 2 pivotX_Top = pivotX_Median * 2 - pivotX_Bottom if pivotX_Bottom > pivotX_Top temp = pivotX_Bottom pivotX_Bottom := pivotX_Top pivotX_Top := temp array.push(p, pivotX_Median) array.push(tp, pivotX_Top) array.push(bp, pivotX_Bottom) if kind == TRADITIONAL traditional() else if kind == FIBONACCI fibonacci() else if kind == CLASSIC classic() else if kind == CAMARILLA camarilla() resolution = get_pivot_resolution() calc_high(prev, curr) => if na(prev) or na(curr) nz(prev, nz(curr, na)) else math.max(prev, curr) calc_low(prev, curr) => if not na(prev) and not na(curr) math.min(prev, curr) else nz(prev, nz(curr, na)) [sec_open, sec_high, sec_low, prev_sec_open, prev_sec_high, prev_sec_low, prev_sec_close, prev_sec_time] = request.security(syminfo.tickerid, resolution, [open, high, low, open[1], high[1], low[1], close[1], time[1]], lookahead = barmerge.lookahead_on) sec_open_gaps_on = request.security(syminfo.tickerid, resolution, open, gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_on) var is_change = false var uses_current_bar = false var change_time = int(na) is_time_change = ta.change(time(resolution)) if is_time_change change_time := time var start_time = time without_time_change = barstate.islast and array.size(arr_time) == 0 is_can_calc_pivot = (not uses_current_bar and is_time_change) or (uses_current_bar and not na(sec_open_gaps_on)) or without_time_change enough_bars_for_calculate = prev_sec_time >= start_time or is_daily_based if is_can_calc_pivot and enough_bars_for_calculate if array.size(arr_time) == 0 and is_daily_based pivotX_prev_open := prev_sec_open[1] pivotX_prev_high := prev_sec_high[1] pivotX_prev_low := prev_sec_low[1] pivotX_prev_close := prev_sec_close[1] pivotX_open := sec_open[1] pivotX_high := sec_high[1] pivotX_low := sec_low[1] array.push(arr_time, start_time) calc_pivot() if is_daily_based pivotX_prev_open := prev_sec_open pivotX_prev_high := prev_sec_high pivotX_prev_low := prev_sec_low pivotX_prev_close := prev_sec_close pivotX_open := sec_open pivotX_high := sec_high pivotX_low := sec_low else pivotX_prev_high := pivotX_high pivotX_prev_low := pivotX_low pivotX_prev_open := pivotX_open pivotX_prev_close := close[1] pivotX_open := open pivotX_high := high pivotX_low := low if barstate.islast and not is_change and array.size(arr_time) > 0 and not without_time_change array.set(arr_time, array.size(arr_time) - 1, change_time) else if without_time_change array.push(arr_time, start_time) else array.push(arr_time, nz(change_time, time)) calc_pivot() if array.size(arr_time) > look_back if array.size(arr_time) > 0 array.shift(arr_time) if array.size(p) > 0 and cpr_show array.shift(p) if array.size(tp) > 0 and cpr_show array.shift(tp) if array.size(bp) > 0 and cpr_show array.shift(bp) if sr_show if array.size(r1) > 0 and r1_show array.shift(r1) if array.size(s1) > 0 and s1_show array.shift(s1) if array.size(r1_5) > 0 and r1_5_show array.shift(r1_5) if array.size(s1_5) > 0 and s1_5_show array.shift(s1_5) if array.size(r2) > 0 and r2_show array.shift(r2) if array.size(s2) > 0 and s2_show array.shift(s2) if array.size(r2_5) > 0 and r2_5_show array.shift(r2_5) if array.size(s2_5) > 0 and s2_5_show array.shift(s2_5) if array.size(r3) > 0 and r3_show array.shift(r3) if array.size(s3) > 0 and s3_show array.shift(s3) if array.size(r4) > 0 and r4_show array.shift(r4) if array.size(s4) > 0 and s4_show array.shift(s4) if array.size(r5) > 0 and r5_show array.shift(r5) if array.size(s5) > 0 and s5_show array.shift(s5) is_change := true else if not is_daily_based pivotX_high := math.max(pivotX_high, high) pivotX_low := math.min(pivotX_low, low) if barstate.islast and not is_daily_based and array.size(arr_time) == 0 runtime.error("Not enough intraday data to calculate CPR. Lower the CPR Timeframe or turn on the 'Use Daily-based Values' option in the indicator settings.") if barstate.islast and array.size(arr_time) > 0 and is_change is_change := false array.push(arr_time, time_close(resolution)) for i = 0 to array.size(lines) - 1 if array.size(lines) > 0 line.delete(array.shift(lines)) if array.size(labels) > 0 label.delete(array.shift(labels)) for i = 0 to array.size(arr_time) - 2 if array.size(p) > 0 and cpr_show draw_line(i, p, cpr_color) if array.size(tp) > 0 and array.size(bp) > 0 and cpr_show tp_line = draw_line(i, tp, cpr_color) bp_line = draw_line(i, bp, cpr_color) linefill.new(tp_line, bp_line, color.new(cpr_color, 70)) for i = array.size(arr_time) - 2 to array.size(arr_time) - 2 if array.size(p) > 0 and cpr_show draw_label(i, array.get(p, i), "CPR", cpr_color) if array.size(tp) > 0 and cpr_show draw_label(i, array.get(tp, i), "", cpr_color) if array.size(bp) > 0 and cpr_show draw_label(i, array.get(bp, i), "", cpr_color) if sr_show if array.size(r1) > 0 and r1_show draw_line(i, r1, r1_color) draw_label(i, array.get(r1, i), "R1", r1_color) if array.size(s1) > 0 and s1_show draw_line(i, s1, s1_color) draw_label(i, array.get(s1, i), "S1", s1_color) if array.size(r1_5) > 0 and r1_5_show draw_line(i, r1_5, r1_5_color, line.style_dashed) draw_label(i, array.get(r1_5, i), "R1.5", r1_5_color) if array.size(s1_5) > 0 and s1_5_show draw_line(i, s1_5, s1_5_color, line.style_dashed) draw_label(i, array.get(s1_5, i), "S1.5", s1_5_color) if array.size(r2) > 0 and r2_show draw_line(i, r2, r2_color) draw_label(i, array.get(r2, i), "R2", r2_color) if array.size(s2) > 0 and s2_show draw_line(i, s2, s2_color) draw_label(i, array.get(s2, i), "S2", s2_color) if array.size(r2_5) > 0 and r2_5_show draw_line(i, r2_5, r2_5_color, line.style_dashed) draw_label(i, array.get(r2_5, i), "R2.5", r2_5_color) if array.size(s2_5) > 0 and s2_5_show draw_line(i, s2_5, s2_5_color, line.style_dashed) draw_label(i, array.get(s2_5, i), "S2.5", s2_5_color) if array.size(r3) > 0 and r3_show draw_line(i, r3, r3_color) draw_label(i, array.get(r3, i), "R3", r3_color) if array.size(s3) > 0 and s3_show draw_line(i, s3, s3_color) draw_label(i, array.get(s3, i), "S3", s3_color) if array.size(r4) > 0 and r4_show draw_line(i, r4, r4_color) draw_label(i, array.get(r4, i), "R4", r4_color) if array.size(s4) > 0 and s4_show draw_line(i, s4, s4_color) draw_label(i, array.get(s4, i), "S4", s4_color) if array.size(r5) > 0 and r5_show draw_line(i, r5, r5_color) draw_label(i, array.get(r5, i), "R5", r5_color) if array.size(s5) > 0 and s5_show draw_line(i, s5, s5_color) draw_label(i, array.get(s5, i), "S5", s5_color) isHoliday(_date) => is_holiday = (_date == timestamp(2023, 01, 26, 15, 30) or _date == timestamp(2023, 03, 07, 15, 30) or _date == timestamp(2023, 03, 30, 15, 30) or _date == timestamp(2023, 04, 04, 15, 30) or _date == timestamp(2023, 04, 07, 15, 30) or _date == timestamp(2023, 04, 14, 15, 30) or _date == timestamp(2023, 05, 01, 15, 30) or _date == timestamp(2023, 06, 29, 15, 30) or _date == timestamp(2023, 08, 15, 15, 30) or _date == timestamp(2023, 09, 19, 15, 30) or _date == timestamp(2023, 10, 02, 15, 30) or _date == timestamp(2023, 10, 24, 15, 30) or _date == timestamp(2023, 11, 14, 15, 30) or _date == timestamp(2023, 11, 27, 15, 30) or _date == timestamp(2023, 12, 25, 15, 30)) is_holiday getDevEndTime() => ONE_DAY = 1000 * 60 * 60 * 24 var dev_end_time = 0 if resolution == "D" dev_end_time := time_close(resolution) + ONE_DAY else if resolution == "W" dev_end_time := time_close(resolution) + (ONE_DAY * 7) else if resolution == "M" dev_end_time := time_close(resolution) + (ONE_DAY * 30) else dev_end_time := time_close(resolution) + (ONE_DAY * 30 * 12) while dayofweek(dev_end_time) == dayofweek.saturday or dayofweek(dev_end_time) == dayofweek.sunday or (check_holidays and isHoliday(dev_end_time)) dev_end_time := dev_end_time + ONE_DAY if extend_dev_cpr_line dev_end_time := dev_end_time + (ONE_DAY * dev_cpr_line_days) dev_end_time drawCPRLine(_price, _line_color, _text, _text_color) => var dev_start_time = 0 dev_start_time := time_close(resolution) var dev_end_time = 0 dev_end_time := getDevEndTime() _aLine = line.new(x1=dev_start_time, y1=_price, x2=dev_end_time, y2=_price, xloc=xloc.bar_time, color=_line_color, width=line_width) line.delete(_aLine[1]) if show_labels or show_prices display_text = "" if show_labels and show_prices and _text != '' display_text := str.format(" {0} - {1}", _text, math.round_to_mintick(_price)) else if show_labels and _text != '' display_text := " " + _text else display_text := str.format(" {0}", math.round_to_mintick(_price)) _aLabel = label.new(dev_end_time, _price, xloc=xloc.bar_time, text=display_text, textcolor=_text_color, style=label.style_none) label.delete(_aLabel[1]) _aLine drawDevCPR(resolution, cpr_text, line_color) => _high = request.security(syminfo.tickerid, resolution, high) _low = request.security(syminfo.tickerid, resolution, low) _close = request.security(syminfo.tickerid, resolution, close) dpp = (_high + _low + _close) / 3.0 dbc = (_high + _low) / 2.0 dtc = (dpp * 2) - dbc dtp_line = drawCPRLine(dtc > dbc? dtc : dbc, line_color, '', line_color) drawCPRLine(dpp, line_color, cpr_text, line_color) dbp_line = drawCPRLine(dbc < dtc? dbc : dtc, line_color, '', line_color) linefill.new(dtp_line, dbp_line, color.new(line_color, 70)) if dev_cpr_show drawDevCPR(resolution, "Dev CPR", dev_cpr_color) _high = request.security(syminfo.tickerid, resolution, high) _low = request.security(syminfo.tickerid, resolution, low) _close = request.security(syminfo.tickerid, resolution, close) dpp = (_high + _low + _close) / 3.0 if dev_r1_show _dev_r1 = dpp * 2 - _low if kind == FIBONACCI _dev_r1 := dpp + 0.382 * (_high - _low) drawCPRLine(_dev_r1, dev_r1_color, "Dev R1", dev_r1_color) if dev_s1_show _dev_s1 = dpp * 2 - _high if kind == FIBONACCI _dev_s1 := dpp - 0.382 * (_high - _low) drawCPRLine(_dev_s1, dev_s1_color, "Dev S1", dev_s1_color)
Support & Resistance Dynamic [LuxAlgo]
https://www.tradingview.com/script/yRHQ9ufY-Support-Resistance-Dynamic-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
3,242
study
5
CC-BY-NC-SA-4.0
// 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("Support & Resistance Dynamic [LuxAlgo]", "LuxAlgo - Support & Resistance Dynamic", overlay = true) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ mult = input.float(8., 'Multiplicative Factor', minval = 0, step = .5) atrLen = input.int(50, 'ATR Length', minval = 0) extLast = input.int(4, 'Extend Last', minval = 0) //Style supCss = input.color(#089981, 'Support    ', inline = 'sup', group = 'Style') supAreaCss = input(color.new(#089981, 80), 'Areas', inline = 'sup', group = 'Style') resCss = input.color(#f23645, 'Resistance', inline = 'res', group = 'Style') resAreaCss = input(color.new(#f23645, 80), 'Areas', inline = 'res', group = 'Style') extLvls = input(true, 'Extend Levels', group = 'Style') extArea = input(true, 'Extend Areas', group = 'Style') //-----------------------------------------------------------------------------} //UDT //-----------------------------------------------------------------------------{ type sr float y float area int x bool support //-----------------------------------------------------------------------------} //Calculation //-----------------------------------------------------------------------------{ var records = array.new<sr>(0) var float avg = close var hold_atr = 0. var os = 0 n = bar_index breakout_atr = nz(ta.atr(atrLen)) * mult avg := math.abs(close - avg) > breakout_atr ? close : avg hold_atr := avg == close ? breakout_atr : hold_atr os := avg > avg[1] ? 1 : avg < avg[1] ? 0 : os upper_res = os == 0 ? avg + hold_atr / mult : na lower_res = os == 0 ? avg + hold_atr / mult / 2 : na upper_sup = os == 1 ? avg - hold_atr / mult / 2: na lower_sup = os == 1 ? avg - hold_atr / mult : na if close == avg if os == 1 records.unshift(sr.new(lower_sup, upper_sup, time, true)) else records.unshift(sr.new(upper_res, lower_res, time, false)) //-----------------------------------------------------------------------------} //Extensions //-----------------------------------------------------------------------------{ var lines = array.new<line>(0) var boxes = array.new<box>(0) if barstate.isfirst and extLast > 0 for i = 0 to extLast-1 if extLvls lines.push(line.new(na,na,na,na, xloc.bar_time, style = line.style_dashed)) if extArea boxes.push(box.new(na,na,na,na,na, xloc = xloc.bar_time)) if barstate.islast and extLast > 0 for i = 0 to extLast-1 get_sr = records.get(i) if extLvls get_line = lines.get(i) get_line.set_xy1(get_sr.x, get_sr.y) get_line.set_xy2(time, get_sr.y) get_line.set_color(get_sr.support ? supCss : resCss) if extArea get_box = boxes.get(i) get_box.set_lefttop(get_sr.x, get_sr.area) get_box.set_rightbottom(time, get_sr.y) get_box.set_bgcolor(get_sr.support ? supAreaCss : resAreaCss) //-----------------------------------------------------------------------------} //Plots //-----------------------------------------------------------------------------{ //Plot supports plot_upper_sup = plot(upper_sup, 'Upper Support', na , style = plot.style_linebr) plot_lower_sup = plot(lower_sup, 'Lower Support', close == avg ? na : supCss , style = plot.style_linebr) //Plot resistances plot_upper_res = plot(upper_res, 'Upper Resistance', close == avg ? na : resCss , style = plot.style_linebr) plot_lower_res = plot(lower_res, 'Lower Resistance', na , style = plot.style_linebr) //Fills fill(plot_upper_sup, plot_lower_sup, supAreaCss, 'Support Area') fill(plot_upper_res, plot_lower_res, resAreaCss, 'Resistance Area') //-----------------------------------------------------------------------------}
True Range/Expected Move
https://www.tradingview.com/script/MI2BTSqb-True-Range-Expected-Move/
robertsullivan1956
https://www.tradingview.com/u/robertsullivan1956/
34
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© robertsullivan1956 //@version=5 name="True Range/Expected Move" indicator(name, overlay=false) volSymbol = input.string("VOLI", "VOL Symbol", ["VIX", "VIX1D", "VIX9D", "VIXMO", "VXW3", "VXW4", "VXW5", "VXW6", "VINXE", "UVXY", "VOLI"]) tradingDaysInYear = input.int(365, "Trading days in year", minval=200, maxval=365, step=1, tooltip="Use 256 for Rule Of 16") colorShift = input.float(1, "Color shift value", minval=0, maxval=2.00, step=0.01, tooltip="Ratio value for the bar color changes.") shortTradingDay = input.bool(false, "Short trading session?") displayShading = input.bool(true, "Display color between 1 STD and 1/2 STD?") volValue = request.security(volSymbol, "1", open) // ApplyRange() applies the given minimum and maximum // to the range of the specified value. Returns value // unchanged when it's inside the minimum-maximum range. // This will limit the upper and lower boundaries of the study. ApplyRange(value, minimum, maximum) => math.min(math.max(value, minimum), maximum) // Calculate a 1 standard deviation move on SPX using the chosen volatility. // first calculate the fraction of the trading day remaining. minsInTradingDay = shortTradingDay ? 3.5 * 60 : 6.5 * 60 // 3.5 hour session or 6.5 hour session lastSessionMinute = shortTradingDay ? 13 * 60 : 16 * 60 // Session ends at 1 pm or 4 pm frac = (lastSessionMinute - (hour * 60 + minute)) / minsInTradingDay timeRemaining = math.sqrt(frac) / math.sqrt(tradingDaysInYear) sd = close * (volValue/100) * timeRemaining // True Range vs Expected Move var maxExpectedMove = 10e-10 var hi = 10e-10 var lo = 10e10 taHigh = ta.highest(1) taLow = ta.lowest(1) if dayofmonth(time) != dayofmonth(time[1]) hi := 10e-10 lo := 10e10 maxExpectedMove := 10e-10 maxExpectedMove := math.max(maxExpectedMove, sd) hi := math.max(taHigh, hi) lo := math.min(taLow, lo) tr = hi - lo trueRangeAbove = close + tr trueRangeBelow = close - tr trueRangeRelativeToExpectedMove = ApplyRange(tr/maxExpectedMove, 0, 4) trVsEmColor = trueRangeRelativeToExpectedMove > colorShift ? color.green : color.red plot(trueRangeRelativeToExpectedMove, "True Range vs Expected Move", style = plot.style_columns, color = trVsEmColor)
Volume Delta Candles
https://www.tradingview.com/script/SwuQ4BZ2-Volume-Delta-Candles/
LeafAlgo
https://www.tradingview.com/u/LeafAlgo/
89
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© LeafAlgo //@version=5 indicator("Volume Delta Candles", overlay=false) // Calculate volume delta (buying volume - selling volume) buyVolume = na(volume) ? na : (close > open) ? volume : 0 sellVolume = na(volume) ? na : (close < open) ? volume : 0 volumeDelta = buyVolume - sellVolume // Custom OHLC values based on volume delta customOpen = close - volumeDelta customClose = close + volumeDelta customHigh = close > customOpen ? close : customOpen customLow = close > customOpen ? customOpen : close // Plot the custom candles plotcandle(open=customOpen, high=customHigh, low=customLow, close=customClose, title="Volume Delta Candles", color=volumeDelta >= 0 ? color.lime : color.fuchsia, wickcolor=color.gray, bordercolor=color.white, editable=false) barcolor(volumeDelta >= 0 ? color.lime : color.fuchsia) hline(0)
Magic Trend By Market Mindset - Zero To Endless
https://www.tradingview.com/script/bcZ7UQ4u-Magic-Trend-By-Market-Mindset-Zero-To-Endless/
marketmindset
https://www.tradingview.com/u/marketmindset/
116
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© marketmindset //ChangeLog //v2.0 //Added Timeframe gaps //v3.0 //Added Magic Fill //Changed default Line Width //v4.0 //Bug Fixes //@version=5 indicator('Magic Trend By Market Mindset - Zero To Endless', 'MT-Z2E', overlay=true, format=format.price, precision=2, timeframe='', timeframe_gaps = false) src = input(close, 'CCI Source') period = input(21, 'CCI period') AP = input(14, 'ATR Period') mult1 = input.float(1.5, 'ATR Multiplier #1',-5,5,0.25 ) mult2 = input.float(3.0 , 'ATR Multiplier #2',-5,5,0.25 ) ATR = ta.atr(AP) cci = ta.cci(src, period) mt(coff) => upT = hl2 - ATR * coff downT = hl2 + ATR * coff MagicTrend = 0. MagicTrend := cci >= 0 ? upT < nz(MagicTrend[1]) ? nz(MagicTrend[1]) : upT : downT > nz(MagicTrend[1]) ? nz(MagicTrend[1]) : downT MagicTrend MagicTrend1 = mt(mult1) MagicTrend2 = mt(mult2) Color = cci >= 0 ? #0000FF : #FF0000 MT1 = plot(MagicTrend1, color=Color, linewidth=2) MT2 = plot(MagicTrend2, color=Color, linewidth=1) cond = (MagicTrend1 > MagicTrend2 and cci >= 0) or (MagicTrend1 < MagicTrend2 and cci <= 0) fill(MT1, MT2, color = cond ? color.new(Color, 75) : na, title = "Magic Fill")
Feigenbaum Projections
https://www.tradingview.com/script/sBxacXPK-Feigenbaum-Projections/
syntaxgeek
https://www.tradingview.com/u/syntaxgeek/
168
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© syntaxgeek // Credit for the theory of price delivery using Feigenbaum Projections goes to https://twitter.com/TRSTNGLRD // _____ _____ _____ _____ _____ _____ _____ _____ _____ // /\ \ |\ \ /\ \ /\ \ /\ \ ______ /\ \ /\ \ /\ \ /\ \ // /::\ \ |:\____\ /::\____\ /::\ \ /::\ \ |::| | /::\ \ /::\ \ /::\ \ /::\____\ // /::::\ \ |::| | /::::| | \:::\ \ /::::\ \ |::| | /::::\ \ /::::\ \ /::::\ \ /:::/ / // /::::::\ \ |::| | /:::::| | \:::\ \ /::::::\ \ |::| | /::::::\ \ /::::::\ \ /::::::\ \ /:::/ / // /:::/\:::\ \ |::| | /::::::| | \:::\ \ /:::/\:::\ \ |::| | /:::/\:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/ / // /:::/__\:::\ \ |::| | /:::/|::| | \:::\ \ /:::/__\:::\ \ |::| | /:::/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ /:::/____/ // \:::\ \:::\ \ |::| | /:::/ |::| | /::::\ \ /::::\ \:::\ \ |::| | /:::/ \:::\ \ /::::\ \:::\ \ /::::\ \:::\ \ /::::\ \ // ___\:::\ \:::\ \ |::|___|______ /:::/ |::| | _____ /::::::\ \ /::::::\ \:::\ \ |::| | /:::/ / \:::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /::::::\____\________ // /\ \:::\ \:::\ \ /::::::::\ \ /:::/ |::| |/\ \ /:::/\:::\ \ /:::/\:::\ \:::\ \ ______|::|___|___ ____ /:::/ / \:::\ ___\ /:::/\:::\ \:::\ \ /:::/\:::\ \:::\ \ /:::/\:::::::::::\ \ // /::\ \:::\ \:::\____\/::::::::::\____/:: / |::| /::\____\/:::/ \:::\____/:::/ \:::\ \:::\____|:::::::::::::::::| /:::/____/ ___\:::| /:::/__\:::\ \:::\____/:::/__\:::\ \:::\____/:::/ |:::::::::::\____\ // \:::\ \:::\ \::/ /:::/~~~~/~~ \::/ /|::| /:::/ /:::/ \::/ \::/ \:::\ /:::/ |:::::::::::::::::|____\:::\ \ /\ /:::|____\:::\ \:::\ \::/ \:::\ \:::\ \::/ \::/ |::|~~~|~~~~~ // \:::\ \:::\ \/____/:::/ / \/____/ |::| /:::/ /:::/ / \/____/ \/____/ \:::\/:::/ / ~~~~~~|::|~~~|~~~ \:::\ /::\ \::/ / \:::\ \:::\ \/____/ \:::\ \:::\ \/____/ \/____|::| | // \:::\ \:::\ \ /:::/ / |::|/:::/ /:::/ / \::::::/ / |::| | \:::\ \:::\ \/____/ \:::\ \:::\ \ \:::\ \:::\ \ |::| | // \:::\ \:::\____\/:::/ / |::::::/ /:::/ / \::::/ / |::| | \:::\ \:::\____\ \:::\ \:::\____\ \:::\ \:::\____\ |::| | // \:::\ /:::/ /\::/ / |:::::/ /\::/ / /:::/ / |::| | \:::\ /:::/ / \:::\ \::/ / \:::\ \::/ / |::| | // \:::\/:::/ / \/____/ |::::/ / \/____/ /:::/ / |::| | \:::\/:::/ / \:::\ \/____/ \:::\ \/____/ |::| | // \::::::/ / /:::/ / /:::/ / |::| | \::::::/ / \:::\ \ \:::\ \ |::| | // \::::/ / /:::/ / /:::/ / |::| | \::::/ / \:::\____\ \:::\____\ \::| | // \::/ / \::/ / \::/ / |::|___| \::/____/ \::/ / \::/ / \:| | // \/____/ \/____/ \/____/ ~~ \/____/ \/____/ \|___| //@version=5 indicator("Feigenbaum Projections", overlay=true, precision=6) //{ consts var c_trendLineStyle = line.style_dashed var c_levelsLineStyle = line.style_solid var c_levelsLineThickness = 1 //} //{ inputs i_price1 = input.price(0, '#1 (price, bar)', group='Range', inline='price1', confirm=true) i_time1 = input.time(0, '', group='Range', inline='price1', confirm=true) i_price2 = input.price(0, '#2 (price, bar)', group='Range', inline='price2', confirm=true) i_time2 = input.time(0, '', group='Range', inline='price2', confirm=true) i_trendLineEnabled = input.bool(true, 'Trend line', inline='trendLine') i_trendLineThickness = input.int(1, '', minval=1, maxval=5, step=1, inline='trendLine') i_trendLineColor = input.color(color.new(color.gray, 50), '', inline='trendLine') i_trendLineStyle = input.string('Dotted line', '', options=['Line', 'Dashed line', 'Dotted line'], inline='trendLine') i_levelsLineThickness = input.int(1, 'Levels line', minval=1, maxval=5, step=1, inline='levelsLine') i_levelsLineStyle = input.string('Line', '', options=['Line', 'Dashed line', 'Dotted line'], inline='levelsLine') i_targetZoneColor = input.color(color.new(color.white, 90), 'Target Zone Color') i_fib1Enabled = input.bool(true, '', group='Levels', inline='fib1') i_fib1Multiplier = input.float(0, '', group='Levels', inline='fib1') i_fib1Color = input.color(color.white, '', group='Levels', inline='fib1') i_fib3Enabled = input.bool(true, '', group='Levels', inline='fib2') i_fib3Multiplier = input.float(1.6714, '', group='Levels', inline='fib2') i_fib3Color = input.color(color.white, '', group='Levels', inline='fib2') i_fib5Enabled = input.bool(true, '', group='Levels', inline='fib3') i_fib5Multiplier = input.float(3.5699, '', group='Levels', inline='fib3') i_fib5Color = input.color(color.white, '', group='Levels', inline='fib3') i_fib7Enabled = input.bool(true, '', group='Levels', inline='fib4') i_fib7Multiplier = input.float(7.1398, '', group='Levels', inline='fib4') i_fib7Color = input.color(color.white, '', group='Levels', inline='fib4') i_fib9Enabled = input.bool(true, '', group='Levels', inline='fib5') i_fib9Multiplier = input.float(14.2796, '', group='Levels', inline='fib5') i_fib9Color = input.color(color.white, '', group='Levels', inline='fib5') i_fib11Enabled = input.bool(true, '', group='Levels', inline='fib6') i_fib11Multiplier = input.float(-0.6714, '', group='Levels', inline='fib6') i_fib11Color = input.color(color.white, '', group='Levels', inline='fib6') i_fib13Enabled = input.bool(true, '', group='Levels', inline='fib7') i_fib13Multiplier = input.float(-2.5699, '', group='Levels', inline='fib7') i_fib13Color = input.color(color.white, '', group='Levels', inline='fib7') i_fib15Enabled = input.bool(true, '', group='Levels', inline='fib8') i_fib15Multiplier = input.float(-6.1398, '', group='Levels', inline='fib8') i_fib15Color = input.color(color.white, '', group='Levels', inline='fib8') i_fib17Enabled = input.bool(true, '', group='Levels', inline='fib9') i_fib17Multiplier = input.float(-13.2796, '', group='Levels', inline='fib9') i_fib17Color = input.color(color.white, '', group='Levels', inline='fib9') i_fib2Enabled = input.bool(true, '', group='Levels', inline='fib1') i_fib2Multiplier = input.float(1, '', group='Levels', inline='fib1') i_fib2Color = input.color(color.white, '', group='Levels', inline='fib1') i_fib4Enabled = input.bool(true, '', group='Levels', inline='fib2') i_fib4Multiplier = input.float(2.5029, '', group='Levels', inline='fib2') i_fib4Color = input.color(color.white, '', group='Levels', inline='fib2') i_fib6Enabled = input.bool(true, '', group='Levels', inline='fib3') i_fib6Multiplier = input.float(4.6692, '', group='Levels', inline='fib3') i_fib6Color = input.color(color.white, '', group='Levels', inline='fib3') i_fib8Enabled = input.bool(true, '', group='Levels', inline='fib4') i_fib8Multiplier = input.float(9.3384, '', group='Levels', inline='fib4') i_fib8Color = input.color(color.white, '', group='Levels', inline='fib4') i_fib10Enabled = input.bool(true, '', group='Levels', inline='fib5') i_fib10Multiplier = input.float(18.6768, '', group='Levels', inline='fib5') i_fib10Color = input.color(color.white, '', group='Levels', inline='fib5') i_fib12Enabled = input.bool(true, '', group='Levels', inline='fib6') i_fib12Multiplier = input.float(-1.5029, '', group='Levels', inline='fib6') i_fib12Color = input.color(color.white, '', group='Levels', inline='fib6') i_fib14Enabled = input.bool(true, '', group='Levels', inline='fib7') i_fib14Multiplier = input.float(-3.6692, '', group='Levels', inline='fib7') i_fib14Color = input.color(color.white, '', group='Levels', inline='fib7') i_fib16Enabled = input.bool(true, '', group='Levels', inline='fib8') i_fib16Multiplier = input.float(-8.3384, '', group='Levels', inline='fib8') i_fib16Color = input.color(color.white, '', group='Levels', inline='fib8') i_fib18Enabled = input.bool(true, '', group='Levels', inline='fib9') i_fib18Multiplier = input.float(-17.6768, '', group='Levels', inline='fib9') i_fib18Color = input.color(color.white, '', group='Levels', inline='fib9') i_labelHasValue = input.bool(true, 'Show Price?', group='Labels') i_labelHasPercent = input.bool(false, 'Show Percentage?', group='Labels') i_labelLocation = input.string('Right', 'Location', group='Labels', options=['Left', 'Right']) i_reverseEnabled = input.bool(false, 'Reverse', group='Labels') i_fib1Note = input.string('Initial Condition', 'Note 1', group='Labels', inline='fibL1') i_fib3Note = input.string('+F1: #1 Positive Target', 'Note 3', group='Labels', inline='fibL2') i_fib5Note = input.string('+F2: #2 Positive Target', 'Note 5', group='Labels', inline='fibL3') i_fib7Note = input.string('+F3: #3 Positive Target', 'Note 7', group='Labels', inline='fibL4') i_fib9Note = input.string('+F4: #4 Positive Target', 'Note 9', group='Labels', inline='fibL5') i_fib11Note = input.string('-F1: #1 Negative Target', 'Note 11', group='Labels', inline='fibL6') i_fib13Note = input.string('-F2: #2 Negative Target', 'Note 13', group='Labels', inline='fibL7') i_fib15Note = input.string('-F3: #3 Negative Target', 'Note 15', group='Labels', inline='fibL8') i_fib17Note = input.string('-F4: #4 Negative Target', 'Note 17', group='Labels', inline='fibL9') i_fib2Note = input.string('', 'Note 2', group='Labels', inline='fibL1') i_fib4Note = input.string('', 'Note 4', group='Labels', inline='fibL2') i_fib6Note = input.string('', 'Note 6', group='Labels', inline='fibL3') i_fib8Note = input.string('', 'Note 8', group='Labels', inline='fibL4') i_fib10Note = input.string('', 'Note 10', group='Labels', inline='fibL5') i_fib12Note = input.string('', 'Note 12', group='Labels', inline='fibL6') i_fib14Note = input.string('', 'Note 14', group='Labels', inline='fibL7') i_fib16Note = input.string('', 'Note 16', group='Labels', inline='fibL8') i_fib18Note = input.string('', 'Note 18', group='Labels', inline='fibL9') //} //{ funcs f_lineStyle(_styleSetting) => switch _styleSetting 'Line' => line.style_solid 'Dashed line' => line.style_dashed 'Dotted line' => line.style_dotted f_highest(_a, _b) => _a > _b ? _a : _b f_lowest(_a, _b) => _a > _b ? _b : _a f_range(_a, _b) => v_high = f_highest(_a, _b) v_low = f_lowest(_a, _b) v_high - v_low f_rangeMid(_price1, _price2) => v_priceHigh = f_highest(_price1, _price2) v_priceHigh - (f_range(_price1, _price2) / 2) f_fib(n) => i_reverseEnabled ? (i_price2) - ((i_price2 - i_price1) * -n) + (i_price1 - i_price2) : i_price2 - ((i_price2 - i_price1) * n) f_fibLine(value, color) => var line1 = line.new(0, value, bar_index, value, color=color, style=c_levelsLineStyle, width=c_levelsLineThickness) line.set_x2(line1, 0) line.set_xloc(line1, i_time2, i_time1, xloc.bar_time) line1 f_fibLabelText(note, value, multiplier) => var fibText = '' if i_labelHasValue fibText := fibText + (fibText != '' ? " " : "") + str.tostring(value, format.mintick) if i_labelHasPercent fibText := fibText + (fibText != '' ? " (" : "") + str.tostring(multiplier * 100) + "%" + (fibText != '' ? ")" : "") if note != '' fibText := fibText + ' (' + note + ')' fibText f_fibLabel(value, txt, color, textColor) => v_time = i_time1 > i_time2 ? i_time1 : i_time2 v_labelStyle = label.style_label_left if i_labelLocation == 'Left' v_time := i_time1 > i_time2 ? i_time2 : i_time1 v_labelStyle := label.style_label_right if i_labelLocation == 'Center' v_time := i_time1 + ((i_time2 - i_time1) / 2) v_labelStyle := label.style_label_center label.new(v_time, value, txt, textcolor=textColor, color=color, style=v_labelStyle, yloc=yloc.price, xloc=xloc.bar_time) //} //{ vars c_trendLineStyle := f_lineStyle(i_trendLineStyle) c_levelsLineStyle := f_lineStyle(i_levelsLineStyle) c_levelsLineThickness := i_levelsLineThickness var v_highPrice = f_highest(i_price1, i_price2) var v_priceRange = f_range(i_price1, i_price2) var v_fib1Value = f_fib(i_fib1Multiplier) var v_fib2Value = f_fib(i_fib2Multiplier) var v_fib3Value = f_fib(i_fib3Multiplier) var v_fib4Value = f_fib(i_fib4Multiplier) var v_fib5Value = f_fib(i_fib5Multiplier) var v_fib6Value = f_fib(i_fib6Multiplier) var v_fib7Value = f_fib(i_fib7Multiplier) var v_fib8Value = f_fib(i_fib8Multiplier) var v_fib9Value = f_fib(i_fib9Multiplier) var v_fib10Value = f_fib(i_fib10Multiplier) var v_fib11Value = f_fib(i_fib11Multiplier) var v_fib12Value = f_fib(i_fib12Multiplier) var v_fib13Value = f_fib(i_fib13Multiplier) var v_fib14Value = f_fib(i_fib14Multiplier) var v_fib15Value = f_fib(i_fib15Multiplier) var v_fib16Value = f_fib(i_fib16Multiplier) var v_fib17Value = f_fib(i_fib17Multiplier) var v_fib18Value = f_fib(i_fib18Multiplier) //} //{ plots if i_trendLineEnabled var trendLine = line.new(0, i_price1, bar_index, i_price2, color=i_trendLineColor, style=c_trendLineStyle, width=i_trendLineThickness) line.set_x2(trendLine, 0) line.set_xloc(trendLine, i_time1, i_time2, xloc.bar_time) var v_fib1Line = i_fib1Enabled ? f_fibLine(v_fib1Value, i_fib1Color) : na var v_fib2Line = i_fib2Enabled ? f_fibLine(v_fib2Value, i_fib2Color) : na var v_fib3Line = i_fib3Enabled ? f_fibLine(v_fib3Value, i_fib3Color) : na var v_fib4Line = i_fib4Enabled ? f_fibLine(v_fib4Value, i_fib4Color) : na var v_fib5Line = i_fib5Enabled ? f_fibLine(v_fib5Value, i_fib5Color) : na var v_fib6Line = i_fib6Enabled ? f_fibLine(v_fib6Value, i_fib6Color) : na var v_fib7Line = i_fib7Enabled ? f_fibLine(v_fib7Value, i_fib7Color) : na var v_fib8Line = i_fib8Enabled ? f_fibLine(v_fib8Value, i_fib8Color) : na var v_fib9Line = i_fib9Enabled ? f_fibLine(v_fib9Value, i_fib9Color) : na var v_fib10Line = i_fib10Enabled ? f_fibLine(v_fib10Value, i_fib10Color) : na var v_fib11Line = i_fib11Enabled ? f_fibLine(v_fib11Value, i_fib11Color) : na var v_fib12Line = i_fib12Enabled ? f_fibLine(v_fib12Value, i_fib12Color) : na var v_fib13Line = i_fib13Enabled ? f_fibLine(v_fib13Value, i_fib13Color) : na var v_fib14Line = i_fib14Enabled ? f_fibLine(v_fib14Value, i_fib14Color) : na var v_fib15Line = i_fib15Enabled ? f_fibLine(v_fib15Value, i_fib15Color) : na var v_fib16Line = i_fib16Enabled ? f_fibLine(v_fib16Value, i_fib16Color) : na var v_fib17Line = i_fib17Enabled ? f_fibLine(v_fib17Value, i_fib17Color) : na var v_fib18Line = i_fib18Enabled ? f_fibLine(v_fib18Value, i_fib18Color) : na var v_fib1Text = f_fibLabelText(i_fib1Note, v_fib1Value, i_fib1Multiplier) var v_fib2Text = f_fibLabelText(i_fib2Note, v_fib2Value, i_fib2Multiplier) var v_fib3Text = f_fibLabelText(i_fib3Note, v_fib3Value, i_fib3Multiplier) var v_fib4Text = f_fibLabelText(i_fib4Note, v_fib4Value, i_fib4Multiplier) var v_fib5Text = f_fibLabelText(i_fib5Note, v_fib5Value, i_fib5Multiplier) var v_fib6Text = f_fibLabelText(i_fib6Note, v_fib6Value, i_fib6Multiplier) var v_fib7Text = f_fibLabelText(i_fib7Note, v_fib7Value, i_fib7Multiplier) var v_fib8Text = f_fibLabelText(i_fib8Note, v_fib8Value, i_fib8Multiplier) var v_fib9Text = f_fibLabelText(i_fib9Note, v_fib9Value, i_fib9Multiplier) var v_fib10Text = f_fibLabelText(i_fib10Note, v_fib10Value, i_fib10Multiplier) var v_fib11Text = f_fibLabelText(i_fib11Note, v_fib11Value, i_fib11Multiplier) var v_fib12Text = f_fibLabelText(i_fib12Note, v_fib12Value, i_fib12Multiplier) var v_fib13Text = f_fibLabelText(i_fib13Note, v_fib13Value, i_fib13Multiplier) var v_fib14Text = f_fibLabelText(i_fib14Note, v_fib14Value, i_fib14Multiplier) var v_fib15Text = f_fibLabelText(i_fib15Note, v_fib15Value, i_fib15Multiplier) var v_fib16Text = f_fibLabelText(i_fib16Note, v_fib16Value, i_fib16Multiplier) var v_fib17Text = f_fibLabelText(i_fib17Note, v_fib17Value, i_fib17Multiplier) var v_fib18Text = f_fibLabelText(i_fib18Note, v_fib18Value, i_fib18Multiplier) var v_fib1Label = i_fib1Enabled ? f_fibLabel(v_fib1Value, v_fib1Text, color.new(color.red, 100), i_fib1Color) : na var v_fib2Label = i_fib2Enabled ? f_fibLabel(v_fib2Value, v_fib2Text, color.new(color.red, 100), i_fib2Color) : na var v_fib3Label = i_fib3Enabled ? f_fibLabel(v_fib3Value, v_fib3Text, color.new(color.red, 100), i_fib3Color) : na var v_fib4Label = i_fib4Enabled ? f_fibLabel(v_fib4Value, v_fib4Text, color.new(color.red, 100), i_fib4Color) : na var v_fib5Label = i_fib5Enabled ? f_fibLabel(v_fib5Value, v_fib5Text, color.new(color.red, 100), i_fib5Color) : na var v_fib6Label = i_fib6Enabled ? f_fibLabel(v_fib6Value, v_fib6Text, color.new(color.red, 100), i_fib6Color) : na var v_fib7Label = i_fib7Enabled ? f_fibLabel(v_fib7Value, v_fib7Text, color.new(color.red, 100), i_fib7Color) : na var v_fib8Label = i_fib8Enabled ? f_fibLabel(v_fib8Value, v_fib8Text, color.new(color.red, 100), i_fib8Color) : na var v_fib9Label = i_fib9Enabled ? f_fibLabel(v_fib9Value, v_fib9Text, color.new(color.red, 100), i_fib9Color) : na var v_fib10Label = i_fib10Enabled ? f_fibLabel(v_fib10Value, v_fib10Text, color.new(color.red, 100), i_fib10Color) : na var v_fib11Label = i_fib11Enabled ? f_fibLabel(v_fib11Value, v_fib11Text, color.new(color.red, 100), i_fib11Color) : na var v_fib12Label = i_fib12Enabled ? f_fibLabel(v_fib12Value, v_fib12Text, color.new(color.red, 100), i_fib12Color) : na var v_fib13Label = i_fib13Enabled ? f_fibLabel(v_fib13Value, v_fib13Text, color.new(color.red, 100), i_fib13Color) : na var v_fib14Label = i_fib14Enabled ? f_fibLabel(v_fib14Value, v_fib14Text, color.new(color.red, 100), i_fib14Color) : na var v_fib15Label = i_fib15Enabled ? f_fibLabel(v_fib15Value, v_fib15Text, color.new(color.red, 100), i_fib15Color) : na var v_fib16Label = i_fib16Enabled ? f_fibLabel(v_fib16Value, v_fib16Text, color.new(color.red, 100), i_fib16Color) : na var v_fib17Label = i_fib17Enabled ? f_fibLabel(v_fib17Value, v_fib17Text, color.new(color.red, 100), i_fib17Color) : na var v_fib18Label = i_fib18Enabled ? f_fibLabel(v_fib18Value, v_fib18Text, color.new(color.red, 100), i_fib18Color) : na linefill.new(v_fib1Line, v_fib2Line, i_targetZoneColor) linefill.new(v_fib3Line, v_fib4Line, i_targetZoneColor) linefill.new(v_fib5Line, v_fib6Line, i_targetZoneColor) linefill.new(v_fib7Line, v_fib8Line, i_targetZoneColor) linefill.new(v_fib9Line, v_fib10Line, i_targetZoneColor) linefill.new(v_fib11Line, v_fib12Line, i_targetZoneColor) linefill.new(v_fib13Line, v_fib14Line, i_targetZoneColor) linefill.new(v_fib15Line, v_fib16Line, i_targetZoneColor) linefill.new(v_fib17Line, v_fib18Line, i_targetZoneColor) //}
Volume as a Percent of Float by 3iau
https://www.tradingview.com/script/QM76G0VW-Volume-as-a-Percent-of-Float-by-3iau/
insideandup
https://www.tradingview.com/u/insideandup/
13
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Nathan J. Hart (insideandup) // // Plot the difference between: 1) the current Chart Volume as a percent of Float or Common Outstanding and 2) the moving average of the same. // Apply a multiplier to this difference. // Plot the moving average of this difference with applied multiplier. // Plot as culumns, line or area. // // Created: August 7, 2023 // Last edited: September 4, 2023 // // @version=5 indicator(title = "Volume as a Percent of Float by 3iau", shorttitle = "Vol % of Float", overlay = false, precision = 2) // MOVING AVERAGE TYPE // Tillson's Moving Average a = 0.618033989 // Tillson applied a = 0.7, here applying the Golden ratio conjugate = |(1-√5)/2| = 0.618033989 a1 = -1 * math.pow(a, 3) a2 = 3 * math.pow(a, 2) + 3 * math.pow(a, 3) a3 = -6 * math.pow(a, 2) - 3 * a - 3 * math.pow(a, 3) a4 = 1 + 3 * a + math.pow(a, 3) + 3 * math.pow(a, 2) // Moving averages ma(source, length, type) => type == "SMA" ? ta.sma(source, length) : type == "EMA" ? ta.ema(source, length) : type == "DEMA" ? 2 * ta.ema(source, length) - ta.ema(ta.ema(source, length), length) : type == "TEMA" ? 3 * ta.ema(source, length) - 3 * ta.ema(ta.ema(source, length), length) + ta.ema(ta.ema(ta.ema(source, length), length), length) : type == "QEMA" ? 5 * ta.ema(source, length) - 10 * ta.ema(ta.ema(source, length), length) + 10 * ta.ema(ta.ema(ta.ema(source, length), length), length) - 5 * ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length) + ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length) : type == "PEMA" ? 8 * ta.ema(source, length) - 28 * ta.ema(ta.ema(source, length), length) + 56 * ta.ema(ta.ema(ta.ema(source, length), length), length) - 70 * ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length) + 56 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length) - 28 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length) + 8 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length), length) - ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length), length), length) : type == "ZLEMA" ? ta.ema(source + (source - source[math.round((length - 1) / 2)]), length) : type == "T3" ? a1 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length) + a2 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length) + a3 * ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length) + a4 * ta.ema(ta.ema(ta.ema(source, length), length), length) : type == "HMA" ? ta.hma(source, length) : type == "SMMA" ? ta.rma(source, length) : type == "WMA" ? ta.wma(source, length) : type == "VWMA" ? ta.vwma(source, length) : type == "SWMA" ? ta.swma(source) : na // SETTINGS GROUP NAMES group1_name = "Plot the Volume traded as a percent of Float / Outstanding" group2_name = "Plot the Volume traded as a percent of Float / Outstanding relative a Moving Average of the same values" tooltip2_text = "This moving average will become the zero line about which Volume as a Percent of Float / Outstanding are plotted. The values below the moving average will plot negative, and values above the moving average will plot positive regardless closing up or down." group3_name = "Apply a multiplier to the values plotted" group4_name = "Plot values as columns, area, or continuous line" group5_name = "Plot a Moving Average of the values plotted" group6_name = "Plot Moving Averages of the High / Low values--those Above >= / Below < the Moving Average of the values plotted" group7_name = "Display Volume / Price Percent Change at specified Lookback Periods" group7b_name = "Display a comparison of Closing Volume / Price to the Moving Average of the same" group8_name = "Display Exchange data Percent Upside / Downside / Unchanged and Breadth data as Tick or Trin" tooltip8_text = "The Number of Names that are Advancing ADVN / Declining DECL (reported for NYSE or NASDAQ exchanges, the DJIA30, or all U.S. names). Up-Volume UPVOL / Down-Volume DNVOL of Shares in the group 'ADVN / DECL Number of Names'. ADV / DECL Number of Names Advancing or Declining (not applicabale for 'DJIA' or 'US' selections). UVOL/DVOL Up-Volume or Down-Volume of Shares in the group 'ADV/DECL Number of Names'" // VARIABLES show_chart_vol_percent = input.string(defval = "Float", title = "Volume as a percent of", options = ["Float", "Outstanding"], inline = "Chart Volume", group = group1_name) chart_outstanding_FQ = request.financial(syminfo.tickerid, financial_id = "total_shares_outstanding", period = "FQ", ignore_invalid_symbol = true) // FQ or FY possible chart_outstanding_FY = request.financial(syminfo.tickerid, financial_id = "total_shares_outstanding", period = "FY", ignore_invalid_symbol = true) // FQ or FY possible chart_float_FY = request.financial(syminfo.tickerid, financial_id = "float_shares_outstanding", period = "FY", ignore_invalid_symbol = true) // Only FY possible chart_float = chart_float_FY chart_outstanding = chart_outstanding_FY if (chart_outstanding_FY != chart_outstanding_FQ) chart_float := chart_float_FY chart_outstanding := chart_outstanding_FY else if (chart_outstanding_FY == chart_outstanding_FQ) chart_float := chart_float_FY chart_outstanding := chart_outstanding_FQ total_shares = chart_outstanding if (show_chart_vol_percent == "Float") total_shares := chart_float else if (show_chart_vol_percent == "Outstanding") total_shares := chart_outstanding // CALCULATIONS // Volume as a Percent of Float or Commmon Outstanding // Calculate the Difference between: 1) Current Names's Volume as a Percent of Name's Float or Total Outstanding Shares and 2) the Moving Average of the Same. // Multiply the difference by a specified "multiplier" value. chart_vol = volume chart_vol_percent = 100 * chart_vol / total_shares show_smoothed_chart_vol_percent = input(defval = false, title = "", inline = "Smoothed Chart Volume", group = group2_name) smoothed_chart_vol_percent_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA", "SWMA"], inline = "Smoothed Chart Volume", group = group2_name) smoothed_chart_vol_percent_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, tooltip = tooltip2_text, inline = "Smoothed Chart Volume", group = group2_name) smoothed_chart_vol_percent = ma(chart_vol_percent, smoothed_chart_vol_percent_length, smoothed_chart_vol_percent_type) // Float to outstanding ratio // NOTES: low floating stock to outstanding shares implies higher number of shares held by insiders or controlling investors; whereas floating stock to outstanding shares implies a higher number shares available for immediate trading. chart_float_to_outstanding = chart_float / chart_outstanding // Multiplier value_multiplier = input.int(defval = 1, title = "Value multiplier 0 to 1000", minval = 0, maxval = 1000, inline = "Value Multiplier", group = group3_name) display_chart_vol_percent = 0.00 if (show_smoothed_chart_vol_percent == true) display_chart_vol_percent := value_multiplier * (chart_vol_percent - smoothed_chart_vol_percent) else if (show_smoothed_chart_vol_percent == false) display_chart_vol_percent := value_multiplier * (chart_vol_percent) // PLOTS // Plot the Difference between: 1) Current Names's Volume as a Percent of Name's Float or Total Outstanding Shares and 2) the Moving Average of the Same. show_columns_smoothed_chart_vol_percent = input(defval = false, title = "Columns", tooltip = "Color scheme based on current period close vs previous period close (close-to-close) or current period close vs current period open (open-to-close).", inline = "Columns", group = group4_name) show_area_smoothed_chart_vol_percent = input(defval = false, title = "Area", inline = "Area", group = group4_name) show_line_smoothed_chart_vol_percent = input(defval = true, title = "Line", inline = "Line", group = group4_name) //// Plot colors plotcolor_columns_none_smoothed_chart_vol_percent = display_chart_vol_percent >= 0 ? color.rgb(97, 175, 239, 40) : color.rgb(97, 175, 239, 40) plotcolor_columns_up_smoothed_chart_vol_percent = display_chart_vol_percent >= 0 ? color.rgb(97, 175, 239, 40) : color.rgb(97, 175, 239, 40) plotcolor_columns_down_smoothed_chart_vol_percent = display_chart_vol_percent >= 0 ? color.rgb(97, 175, 239, 80) : color.rgb(97, 175, 239, 80) plotcolor_columns_color_scheme = input.string(defval = "Close-to-Close", title = "Color scheme", options = ["None", "Close-to-Close", "Open-to-Close"], inline = "Color scheme", group = group4_name) plotcolor_columns_smoothed_chart_vol_percent = plotcolor_columns_up_smoothed_chart_vol_percent if (plotcolor_columns_color_scheme == "None") plotcolor_columns_smoothed_chart_vol_percent := plotcolor_columns_none_smoothed_chart_vol_percent else if (plotcolor_columns_color_scheme == "Close-to-Close" and close >= close[1]) plotcolor_columns_smoothed_chart_vol_percent := plotcolor_columns_up_smoothed_chart_vol_percent else if (plotcolor_columns_color_scheme == "Close-to-Close" and close < close[1]) plotcolor_columns_smoothed_chart_vol_percent := plotcolor_columns_down_smoothed_chart_vol_percent else if (plotcolor_columns_color_scheme == "Open-to-Close" and close >= open) plotcolor_columns_smoothed_chart_vol_percent := plotcolor_columns_up_smoothed_chart_vol_percent else if (plotcolor_columns_color_scheme == "Open-to-Close" and close < open) plotcolor_columns_smoothed_chart_vol_percent := plotcolor_columns_down_smoothed_chart_vol_percent plotcolor_line_smoothed_chart_vol_percent = display_chart_vol_percent >= 0 ? color.rgb(97, 175, 239, 10) : color.rgb(97, 175, 239, 10) plotcolor_area_smoothed_chart_vol_percent = display_chart_vol_percent >= 0 ? color.rgb(97, 175, 239, 70) : color.rgb(97, 175, 239, 70) //// Plot plot_columns_smoothed_chart_vol_percent = plot(show_columns_smoothed_chart_vol_percent ? display_chart_vol_percent : na, "Chart Volume Moving Average", plotcolor_columns_smoothed_chart_vol_percent, style=plot.style_columns) plot_line_smoothed_chart_vol_percent = plot(show_line_smoothed_chart_vol_percent ? display_chart_vol_percent : na, "Chart Volume Moving Average", plotcolor_line_smoothed_chart_vol_percent, style=plot.style_line) plot_area_smoothed_chart_vol_percent = plot(show_area_smoothed_chart_vol_percent ? display_chart_vol_percent : na, "Chart Volume Moving Average", plotcolor_area_smoothed_chart_vol_percent, style=plot.style_area) // Plot Moving Average of All Values show_smoothed_display_chart_vol_percent = input(defval = true, title = "", inline = "MA Chart Volume", group = group5_name) smoothed_display_chart_vol_percent_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA", "SWMA"], inline = "MA Chart Volume", group = group5_name) smoothed_display_chart_vol_percent_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "MA Chart Volume", group = group5_name) smoothed_display_chart_vol_percent = ma(display_chart_vol_percent, smoothed_display_chart_vol_percent_length, smoothed_display_chart_vol_percent_type) plotcolor_smoothed_display_chart_vol_percent01 = display_chart_vol_percent >= 0 ? color.rgb(229, 192, 123, 0) : color.rgb(229, 192, 123, 0) plot_smoothed_display_chart_vol_percent01 = plot(show_smoothed_display_chart_vol_percent ? smoothed_display_chart_vol_percent : na, "Display Moving Average", plotcolor_smoothed_display_chart_vol_percent01, linewidth = 1, style=plot.style_line) // Plot Moving Averages of only High/Low Values chart_vol_percent_high = 0.00 chart_vol_percent_low = 0.00 if (show_smoothed_chart_vol_percent == true) chart_vol_percent_high := display_chart_vol_percent >= smoothed_display_chart_vol_percent ? display_chart_vol_percent : na chart_vol_percent_low := display_chart_vol_percent <= smoothed_display_chart_vol_percent ? display_chart_vol_percent : na else if (show_smoothed_chart_vol_percent == false) chart_vol_percent_high := display_chart_vol_percent >= smoothed_display_chart_vol_percent ? display_chart_vol_percent : na chart_vol_percent_low := display_chart_vol_percent <= smoothed_display_chart_vol_percent ? display_chart_vol_percent : na show_chart_vol_percent_high_ma = input(defval = true, title = "", inline = "High MA", group = group6_name) chart_vol_percent_high_ma_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA", "SWMA"], inline = "High MA", group = group6_name) chart_vol_percent_high_ma_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "High MA", group = group6_name) show_chart_vol_percent_low_ma = input(defval = true, title = "", inline = "Low MA", group = group6_name) chart_vol_percent_low_ma_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA", "SWMA"], inline = "Low MA", group = group6_name) chart_vol_percent_low_ma_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "Low MA", group = group6_name) chart_vol_percent_high_ma = ma(chart_vol_percent_high, chart_vol_percent_high_ma_length, chart_vol_percent_high_ma_type) chart_vol_percent_low_ma = ma(chart_vol_percent_low, chart_vol_percent_low_ma_length, chart_vol_percent_low_ma_type) plot_chart_vol_percent_high_ma = plot(show_chart_vol_percent_high_ma ? chart_vol_percent_high_ma : na, "Moving Average", color.rgb(97, 175, 239, 80), style=plot.style_line) plot_chart_vol_percent_low_ma = plot(show_chart_vol_percent_low_ma ? chart_vol_percent_low_ma : na, "Moving Average", color.rgb(97, 175, 239, 80), style=plot.style_line) show_chart_vol_percent_ma_fill = input(defval = true, title = "High/Low MA Fill", inline = "", group = group6_name) plot_chart_vol_percent_high_ma_fill = plot(show_chart_vol_percent_ma_fill ? chart_vol_percent_high_ma : na, "Moving Average", color.rgb(97, 175, 239, 90), style=plot.style_line) plot_chart_vol_percent_low_ma_fill = plot(show_chart_vol_percent_ma_fill ? chart_vol_percent_low_ma : na, "Moving Average", color.rgb(97, 175, 239, 90), style=plot.style_line) fill(plot1 = plot_chart_vol_percent_low_ma_fill, plot2 = plot_chart_vol_percent_high_ma_fill, title = "fill", editable = true, fillgaps = true, color = color.rgb(97, 175, 239, 90)) // TABLE // Table display Float or Outstanding // Table display value = to the actual volume as a precent of float/outstanding regardless the multiplier table_text_vol_percent_lable = " %f" if (show_chart_vol_percent == "Float") table_text_vol_percent_lable := " %f" else if (show_chart_vol_percent == "Outstanding") table_text_vol_percent_lable := " %o" table_text_vol_percent_value = display_chart_vol_percent / value_multiplier // Table display value = to the percent change of volume or price at a specified lookback period percent_change = input.string(defval = "Price", title = "Percent change", options = ["Volume", "Price"], inline = "Percent Change", group = group7_name) show_percent_change1 = input(defval = true, title = "", inline = "Volume Percent Change 1", group = group7_name) lookback1 = input.int(defval = 1, title = "", minval = 1, maxval = 2000, tooltip = "A value of 1 measures change between the current period and the previous period", inline = "Volume Percent Change 1", group = group7_name) show_percent_change2 = input(defval = true, title = "", inline = "Volume Percent Change 2", group = group7_name) lookback2 = input.int(defval = 2, title = "", minval = 1, maxval = 2000, inline = "Volume Percent Change 2", group = group7_name) show_percent_change3 = input(defval = true, title = "", inline = "Volume Percent Change 3", group = group7_name) lookback3 = input.int(defval = 3, title = "", minval = 1, maxval = 2000, inline = "Volume Percent Change 3", group = group7_name) show_percent_change4 = input(defval = true, title = "", inline = "Volume Percent Change 4", group = group7_name) lookback4 = input.int(defval = 4, title = "", minval = 1, maxval = 2000, inline = "Volume Percent Change 4", group = group7_name) show_percent_change5 = input(defval = true, title = "", inline = "Volume Percent Change 5", group = group7_name) lookback5 = input.int(defval = 5, title = "", minval = 1, maxval = 2000, inline = "Volume Percent Change 5", group = group7_name) percent_change_show_ma_comparison = input(defval = false, title = "", inline = "Percent Change MA Compare", group = group7b_name) percent_change_show_ma_comparison_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA", "SWMA"], inline = "Percent Change MA Compare", group = group7b_name) percent_change_show_ma_comparison_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "Percent Change MA Compare", group = group7b_name) // Sort percent change inputs - Begin show_percent_change1_new = false show_percent_change2_new = false show_percent_change3_new = false show_percent_change4_new = false show_percent_change5_new = false lookback1_new = lookback1 lookback2_new = lookback2 lookback3_new = lookback3 lookback4_new = lookback4 lookback5_new = lookback5 // lookback5_new if (show_percent_change1 == true and lookback1 > lookback2 and lookback1 > lookback3 and lookback1 > lookback4 and lookback1 > lookback5) lookback5_new := lookback1 show_percent_change5_new := true else if (show_percent_change2 == true and lookback2 > lookback1 and lookback2 > lookback3 and lookback2 > lookback4 and lookback2 > lookback5) lookback5_new := lookback2 show_percent_change5_new := true else if (show_percent_change3 == true and lookback3 > lookback1 and lookback3 > lookback2 and lookback3 > lookback4 and lookback3 > lookback5) lookback5_new := lookback3 show_percent_change5_new := true else if (show_percent_change4 == true and lookback4 > lookback1 and lookback4 > lookback2 and lookback4 > lookback3 and lookback4 > lookback5) lookback5_new := lookback4 show_percent_change5_new := true else if (show_percent_change5 == true and lookback5 > lookback1 and lookback5 > lookback2 and lookback5 > lookback3 and lookback5 > lookback4) lookback5_new := lookback5 show_percent_change5_new := true // lookback4_new if (show_percent_change1 == true and ((lookback1 > lookback2 and lookback1 > lookback3 and lookback1 > lookback4 and lookback1 <= lookback5) or (lookback1 > lookback2 and lookback1 > lookback3 and lookback1 > lookback5 and lookback1 <= lookback4) or (lookback1 > lookback2 and lookback1 > lookback4 and lookback1 > lookback5 and lookback1 <= lookback3) or (lookback1 > lookback3 and lookback1 > lookback4 and lookback1 > lookback5 and lookback1 <= lookback2))) lookback4_new := lookback1 show_percent_change4_new := true else if (show_percent_change2 == true and ((lookback2 > lookback1 and lookback2 > lookback3 and lookback2 > lookback4 and lookback2 <= lookback5) or (lookback2 > lookback1 and lookback2 > lookback3 and lookback2 > lookback5 and lookback2 <= lookback4) or (lookback2 > lookback1 and lookback2 > lookback4 and lookback2 > lookback5 and lookback2 <= lookback3) or (lookback2 > lookback3 and lookback2 > lookback4 and lookback2 > lookback5 and lookback2 <= lookback1))) lookback4_new := lookback2 show_percent_change4_new := true else if (show_percent_change3 == true and ((lookback3 > lookback1 and lookback3 > lookback2 and lookback3 > lookback4 and lookback3 <= lookback5) or (lookback3 > lookback1 and lookback3 > lookback2 and lookback3 > lookback5 and lookback3 <= lookback4) or (lookback3 > lookback1 and lookback3 > lookback4 and lookback3 > lookback5 and lookback3 <= lookback2) or (lookback3 > lookback2 and lookback3 > lookback4 and lookback3 > lookback5 and lookback3 <= lookback1))) lookback4_new := lookback3 show_percent_change4_new := true else if (show_percent_change4 == true and ((lookback4 > lookback1 and lookback4 > lookback2 and lookback4 > lookback3 and lookback4 <= lookback5) or (lookback4 > lookback1 and lookback4 > lookback2 and lookback4 > lookback5 and lookback4 <= lookback3) or (lookback4 > lookback1 and lookback4 > lookback3 and lookback4 > lookback5 and lookback4 <= lookback2) or (lookback4 > lookback2 and lookback4 > lookback3 and lookback4 > lookback5 and lookback4 <= lookback1))) lookback4_new := lookback4 show_percent_change4_new := true else if (show_percent_change5 == true and ((lookback5 > lookback1 and lookback5 > lookback2 and lookback5 > lookback3 and lookback5 <= lookback4) or (lookback5 > lookback1 and lookback5 > lookback2 and lookback5 > lookback4 and lookback5 <= lookback3) or (lookback5 > lookback1 and lookback5 > lookback3 and lookback5 > lookback4 and lookback5 <= lookback2) or (lookback5 > lookback2 and lookback5 > lookback3 and lookback5 > lookback4 and lookback5 <= lookback1))) lookback4_new := lookback5 show_percent_change4_new := true // lookback3_new if (show_percent_change1 == true and ((lookback1 > lookback2 and lookback1 > lookback3 and lookback1 <= lookback4 and lookback1 <= lookback5) or (lookback1 > lookback2 and lookback1 > lookback4 and lookback1 <= lookback3 and lookback1 <= lookback5) or (lookback1 > lookback2 and lookback1 > lookback5 and lookback1 <= lookback3 and lookback1 <= lookback4) or (lookback1 > lookback3 and lookback1 > lookback4 and lookback1 <= lookback2 and lookback1 <= lookback5) or (lookback1 > lookback3 and lookback1 > lookback5 and lookback1 <= lookback2 and lookback1 <= lookback4) or (lookback1 > lookback4 and lookback1 > lookback5 and lookback1 <= lookback2 and lookback1 <= lookback3))) lookback3_new := lookback1 show_percent_change3_new := true else if (show_percent_change2 == true and ((lookback2 > lookback1 and lookback2 > lookback3 and lookback2 <= lookback4 and lookback2 <= lookback5) or (lookback2 > lookback1 and lookback2 > lookback4 and lookback2 <= lookback3 and lookback2 <= lookback5) or (lookback2 > lookback1 and lookback2 > lookback5 and lookback2 <= lookback3 and lookback2 <= lookback4) or (lookback2 > lookback3 and lookback2 > lookback4 and lookback2 <= lookback1 and lookback2 <= lookback5) or (lookback2 > lookback3 and lookback2 > lookback5 and lookback2 <= lookback1 and lookback2 <= lookback4) or (lookback2 > lookback4 and lookback2 > lookback5 and lookback2 <= lookback1 and lookback2 <= lookback3))) lookback3_new := lookback2 show_percent_change3_new := true else if (show_percent_change3 == true and ((lookback3 > lookback1 and lookback3 > lookback2 and lookback3 <= lookback4 and lookback3 <= lookback5) or (lookback3 > lookback1 and lookback3 > lookback4 and lookback3 <= lookback2 and lookback3 <= lookback5) or (lookback3 > lookback1 and lookback3 > lookback5 and lookback3 <= lookback2 and lookback3 <= lookback4) or (lookback3 > lookback2 and lookback3 > lookback4 and lookback3 <= lookback1 and lookback3 <= lookback5) or (lookback3 > lookback2 and lookback3 > lookback5 and lookback3 <= lookback1 and lookback3 <= lookback4) or (lookback3 > lookback4 and lookback3 > lookback5 and lookback3 <= lookback1 and lookback3 <= lookback2))) lookback3_new := lookback3 show_percent_change3_new := true else if (show_percent_change4 == true and ((lookback4 > lookback1 and lookback4 > lookback2 and lookback4 <= lookback3 and lookback4 <= lookback5) or (lookback4 > lookback1 and lookback4 > lookback3 and lookback4 <= lookback2 and lookback4 <= lookback5) or (lookback4 > lookback1 and lookback4 > lookback5 and lookback4 <= lookback2 and lookback4 <= lookback3) or (lookback4 > lookback2 and lookback4 > lookback3 and lookback4 <= lookback1 and lookback4 <= lookback5) or (lookback4 > lookback2 and lookback4 > lookback5 and lookback4 <= lookback1 and lookback4 <= lookback3) or (lookback4 > lookback3 and lookback4 > lookback5 and lookback4 <= lookback1 and lookback4 <= lookback2))) lookback3_new := lookback4 show_percent_change3_new := true else if (show_percent_change5 == true and ((lookback5 > lookback1 and lookback5 > lookback2 and lookback5 <= lookback3 and lookback5 <= lookback4) or (lookback5 > lookback1 and lookback5 > lookback3 and lookback5 <= lookback2 and lookback5 <= lookback4) or (lookback5 > lookback1 and lookback5 > lookback4 and lookback5 <= lookback2 and lookback5 <= lookback3) or (lookback5 > lookback2 and lookback5 > lookback3 and lookback5 <= lookback1 and lookback5 <= lookback4) or (lookback5 > lookback2 and lookback5 > lookback4 and lookback5 <= lookback1 and lookback5 <= lookback3) or (lookback5 > lookback3 and lookback5 > lookback4 and lookback5 <= lookback1 and lookback5 <= lookback2))) lookback3_new := lookback5 show_percent_change3_new := true // lookback2_new if (show_percent_change1 == true and ((lookback1 > lookback2 and lookback1 <= lookback3 and lookback1 <= lookback4 and lookback1 <= lookback5) or (lookback1 > lookback3 and lookback1 <= lookback2 and lookback1 <= lookback4 and lookback1 <= lookback5) or (lookback1 > lookback4 and lookback1 <= lookback2 and lookback1 <= lookback3 and lookback1 <= lookback5) or (lookback1 > lookback5 and lookback1 <= lookback2 and lookback1 <= lookback3 and lookback1 <= lookback4))) lookback2_new := lookback1 show_percent_change2_new := true else if (show_percent_change2 == true and ((lookback2 > lookback1 and lookback2 <= lookback3 and lookback2 <= lookback4 and lookback2 <= lookback5) or (lookback2 > lookback3 and lookback2 <= lookback1 and lookback2 <= lookback4 and lookback2 <= lookback5) or (lookback2 > lookback4 and lookback2 <= lookback1 and lookback2 <= lookback3 and lookback1 <= lookback5) or (lookback2 > lookback5 and lookback2 <= lookback3 and lookback2 <= lookback3 and lookback2 <= lookback4))) lookback2_new := lookback2 show_percent_change2_new := true else if (show_percent_change3 == true and ((lookback3 > lookback1 and lookback3 <= lookback2 and lookback3 <= lookback4 and lookback3 <= lookback5) or (lookback3 > lookback2 and lookback3 <= lookback1 and lookback3 <= lookback4 and lookback3 <= lookback5) or (lookback3 > lookback4 and lookback3 <= lookback1 and lookback3 <= lookback2 and lookback3 <= lookback5) or (lookback3 > lookback5 and lookback3 <= lookback1 and lookback3 <= lookback2 and lookback3 <= lookback4))) lookback2_new := lookback3 show_percent_change2_new := true else if (show_percent_change4 == true and ((lookback4 > lookback1 and lookback4 <= lookback2 and lookback4 <= lookback3 and lookback4 <= lookback5) or (lookback4 > lookback2 and lookback4 <= lookback1 and lookback4 <= lookback3 and lookback4 <= lookback5) or (lookback4 > lookback3 and lookback4 <= lookback1 and lookback4 <= lookback2 and lookback4 <= lookback5) or (lookback4 > lookback5 and lookback4 <= lookback1 and lookback4 <= lookback2 and lookback4 <= lookback3))) lookback2_new := lookback4 show_percent_change2_new := true else if (show_percent_change5 == true and ((lookback5 > lookback1 and lookback5 <= lookback2 and lookback5 <= lookback3 and lookback5 <= lookback4) or (lookback5 > lookback2 and lookback5 <= lookback1 and lookback5 <= lookback3 and lookback5 <= lookback4) or (lookback5 > lookback3 and lookback5 <= lookback1 and lookback5 <= lookback2 and lookback5 <= lookback4) or (lookback5 > lookback4 and lookback5 <= lookback1 and lookback5 <= lookback2 and lookback5 <= lookback3))) lookback2_new := lookback5 show_percent_change2_new := true // lookback1_new if (show_percent_change1 == true and lookback1 <= lookback2 and lookback1 <= lookback3 and lookback1 <= lookback4 and lookback1 <= lookback5) lookback1_new := lookback1 show_percent_change1_new := true else if (show_percent_change2 == true and lookback2 <= lookback1 and lookback2 <= lookback3 and lookback2 <= lookback4 and lookback2 <= lookback5) lookback1_new := lookback2 show_percent_change1_new := true else if (show_percent_change3 == true and lookback3 <= lookback1 and lookback3 <= lookback2 and lookback3 <= lookback4 and lookback3 <= lookback5) lookback1_new := lookback3 show_percent_change1_new := true else if (show_percent_change4 == true and lookback4 <= lookback1 and lookback4 <= lookback2 and lookback4 <= lookback3 and lookback4 <= lookback5) lookback1_new := lookback4 show_percent_change1_new := true else if (show_percent_change5 == true and lookback5 <= lookback1 and lookback5 <= lookback2 and lookback5 <= lookback3 and lookback5 <= lookback4) lookback1_new := lookback5 show_percent_change1_new := true // Sort percent change inputs - End // Percent change = 100% * (new - old) / old volume_percent_change1 = lookback1_new > 0 ? 100 * (volume[lookback1_new - 1] - volume[lookback1_new]) / volume[lookback1_new] : 0 price_percent_change1 = lookback1_new > 0 ? 100 * (close[lookback1_new - 1] - close[lookback1_new]) / close[lookback1_new] : 0 volume_percent1_above_ma = 100 * math.abs((volume[lookback1_new - 1] - ma(volume[lookback1_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(volume[lookback1_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) volume_percent_change1_ma_comparison = volume[lookback1_new - 1] >= ma(volume[lookback1_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" price_percent1_above_ma = 100 * math.abs((close[lookback1_new - 1] - ma(close[lookback1_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(close[lookback1_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) price_percent_change1_ma_comparison = close[lookback1_new - 1] >= ma(close[lookback1_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" volume_percent_change2 = lookback2_new > 0 ? 100 * (volume[lookback2_new - 1] - volume[lookback2_new])/volume[lookback2_new] : 0 price_percent_change2 = lookback2_new > 0 ? 100 * (close[lookback2_new - 1] - close[lookback2_new]) / close[lookback2_new] : 0 volume_percent2_above_ma = 100 * math.abs((volume[lookback2_new - 1] - ma(volume[lookback2_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(volume[lookback2_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) volume_percent_change2_ma_comparison = volume[lookback2_new - 1] >= ma(volume[lookback2_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" price_percent2_above_ma = 100 * math.abs((close[lookback2_new - 1] - ma(close[lookback2_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(close[lookback2_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) price_percent_change2_ma_comparison = close[lookback2_new - 1] >= ma(close[lookback2_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" volume_percent_change3 = lookback3_new > 0 ? 100 * (volume[lookback3_new - 1] - volume[lookback3_new])/volume[lookback3_new] : 0 price_percent_change3 = lookback3_new > 0 ? 100 * (close[lookback3_new - 1] - close[lookback3_new]) / close[lookback3_new] : 0 volume_percent3_above_ma = 100 * math.abs((volume[lookback3_new - 1] - ma(volume[lookback3_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(volume[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) volume_percent_change3_ma_comparison = volume[lookback3_new - 1] >= ma(volume[lookback3_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" price_percent3_above_ma = 100 * math.abs((close[lookback3_new - 1] - ma(close[lookback3_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(close[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) price_percent_change3_ma_comparison = close[lookback3_new - 1] >= ma(close[lookback3_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" volume_percent_change4 = lookback4_new > 0 ? 100 * (volume[lookback4_new - 1] - volume[lookback4_new])/volume[lookback4_new] : 0 price_percent_change4 = lookback4_new > 0 ? 100 * (close[lookback4_new - 1] - close[lookback4_new]) / close[lookback4_new] : 0 volume_percent4_above_ma = 100 * math.abs((volume[lookback4_new - 1] - ma(volume[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(volume[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) volume_percent_change4_ma_comparison = volume[lookback4_new - 1] >= ma(volume[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" price_percent4_above_ma = 100 * math.abs((close[lookback4_new - 1] - ma(close[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(close[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) price_percent_change4_ma_comparison = close[lookback4_new - 1] >= ma(close[lookback4_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" volume_percent_change5 = lookback5_new > 0 ? 100 * (volume[lookback5_new - 1] - volume[lookback5_new])/volume[lookback5_new] : 0 price_percent_change5 = lookback5_new > 0 ? 100 * (close[lookback5_new - 1] - close[lookback5_new]) / close[lookback5_new] : 0 volume_percent5_above_ma = 100 * math.abs((volume[lookback5_new - 1] - ma(volume[lookback5_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(volume[lookback5_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) volume_percent_change5_ma_comparison = volume[lookback5_new - 1] >= ma(volume[lookback5_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" price_percent5_above_ma = 100 * math.abs((close[lookback5_new - 1] - ma(close[lookback5_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type))/ma(close[lookback5_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type)) price_percent_change5_ma_comparison = close[lookback5_new - 1] >= ma(close[lookback5_new - 1], percent_change_show_ma_comparison_length, percent_change_show_ma_comparison_type) ? ", β‰₯" : ", <" percent_change1 = price_percent_change1 percent_change2 = price_percent_change2 percent_change3 = price_percent_change3 percent_change4 = price_percent_change4 percent_change5 = price_percent_change5 percent_change1_ma_comparison = price_percent_change1_ma_comparison percent_change2_ma_comparison = price_percent_change2_ma_comparison percent_change3_ma_comparison = price_percent_change3_ma_comparison percent_change4_ma_comparison = price_percent_change4_ma_comparison percent_change5_ma_comparison = price_percent_change5_ma_comparison table_text = " % βˆ†v" if (percent_change == "Volume") percent_change1 := volume_percent_change1 percent_change2 := volume_percent_change2 percent_change3 := volume_percent_change3 percent_change4 := volume_percent_change4 percent_change5 := volume_percent_change5 table_text := " % βˆ†v" percent_change1_ma_comparison := volume_percent_change1_ma_comparison percent_change2_ma_comparison := volume_percent_change2_ma_comparison percent_change3_ma_comparison := volume_percent_change3_ma_comparison percent_change4_ma_comparison := volume_percent_change4_ma_comparison percent_change5_ma_comparison := volume_percent_change5_ma_comparison else if (percent_change == "Price") percent_change1 := price_percent_change1 percent_change2 := price_percent_change2 percent_change3 := price_percent_change3 percent_change4 := price_percent_change4 percent_change5 := price_percent_change5 table_text := " % βˆ†p" percent_change1_ma_comparison := price_percent_change1_ma_comparison percent_change2_ma_comparison := price_percent_change2_ma_comparison percent_change3_ma_comparison := price_percent_change3_ma_comparison percent_change4_ma_comparison := price_percent_change4_ma_comparison percent_change5_ma_comparison := price_percent_change5_ma_comparison table_text1 = percent_change_show_ma_comparison ? " " + str.tostring(math.round(percent_change1, 2)) + table_text + str.tostring(math.round(lookback1_new,0)) + percent_change1_ma_comparison + str.tostring(percent_change_show_ma_comparison_length) + " ma" : " " + str.tostring(math.round(percent_change1, 2)) + table_text + str.tostring(lookback1_new) table_text2 = percent_change_show_ma_comparison ? " " + str.tostring(math.round(percent_change2, 2)) + table_text + str.tostring(math.round(lookback2_new,0)) + percent_change2_ma_comparison + str.tostring(percent_change_show_ma_comparison_length) + " ma" : " " + str.tostring(math.round(percent_change2, 2)) + table_text + str.tostring(lookback2_new) table_text3 = percent_change_show_ma_comparison ? " " + str.tostring(math.round(percent_change3, 2)) + table_text + str.tostring(math.round(lookback3_new,0)) + percent_change3_ma_comparison + str.tostring(percent_change_show_ma_comparison_length) + " ma" : " " + str.tostring(math.round(percent_change3, 2)) + table_text + str.tostring(lookback3_new) table_text4 = percent_change_show_ma_comparison ? " " + str.tostring(math.round(percent_change4, 2)) + table_text + str.tostring(math.round(lookback4_new,0)) + percent_change4_ma_comparison + str.tostring(percent_change_show_ma_comparison_length) + " ma" : " " + str.tostring(math.round(percent_change4, 2)) + table_text + str.tostring(lookback4_new) table_text5 = percent_change_show_ma_comparison ? " " + str.tostring(math.round(percent_change5, 2)) + table_text + str.tostring(math.round(lookback5_new,0)) + percent_change5_ma_comparison + str.tostring(percent_change_show_ma_comparison_length) + " ma" : " " + str.tostring(math.round(percent_change5, 2)) + table_text + str.tostring(lookback5_new) // Table Display - Exchange Upside/Downside Data display_exchange_data = input(defval = true, title = "Display exchage data", inline = "", group = group8_name) volume_source = input.string(defval = "NYSE", title = "Exchange", options = ["NYSE", "NASDAQ", "DJIA", "US"], inline = "Source", group = group8_name) volume_type = input.string(defval = "ADVN/DECL", title = "Variables", options = ["ADVN/DECL", "UPVOL/DNVOL", "ADV/DECL", "UVOL/DVOL"], tooltip = tooltip8_text, inline = "Type", group = group8_name) display_exchange_data_upside = input(defval = true, title = "% Upside", inline = "", group = group8_name) display_exchange_data_downside = input(defval = false, title = "% Downside", inline = "", group = group8_name) display_exchange_data_unchanged = input(defval = false, title = "% Unchanged", inline = "", group = group8_name) display_exchange_data_breadth = input(defval = true, title = "Breadth", inline = "Breadth", group = group8_name) display_exchange_data_breadth_type = input.string(defval = "Tick", title = "", options = ["Tick", "Trin"], inline = "Breadth", group = group8_name) // ADVN/DECL NUMBER OF NAMES // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:ADVN.NY USI:DECL.NY USI:UNCH.NY USI:ACTV.NY // NASDAQ USI:ADVN.NQ USI:DECL.NQ USI:UNCH.NQ USI:ACTV.NQ // DJIA USI:ADVN.DJ USI:DECL.DJ USI:UNCH.DJ USI:ACTV.DJ // US USI:ADVN.US USI:DECL.US USI:UNCH.US USI:ACTV.US // // UPVOL/DNVOL VOLUME OF SHARES IN THE GROUP "NUMBER OF NAMES" // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:UPVOL.NY USI:DNVOL.NY USI:UNCHVOL.NY USI:TVOL.NY // NASDAQ USI:UPVOL.NQ USI:DNVOL.NQ USI:UNCHVOL.NQ USI:TVOL.NQ // DJIA USI:UPVOL.DJ USI:DNVOL.DJ USI:UNCHVOL.DJ USI:TVOL.DJ // US USI:UPVOL.US USI:DNVOL.US USI:UNCHVOL.US USI:TVOL.US // // ADV/DECL NUMBER OF NAMES // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:ADV USI:DECL USI:UCHG USI:ADV+USI:DECL+USI:UCHG // NASDAQ USI:ADVQ USI:DECLQ USI:UCHGQ USI:ADVQ+USI:DECLQ+USI:UCHGQ // DJIA n.a. // US n.a. // // UVOL/DVOL VOLUME OF SHARES IN THE GROUP "NUMBER OF NAMES" // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:UVOL USI:DVOL USI:XVOL USI:TVOL // NASDAQ USI:UVOLQ USI:DVOLQ USI:XVOLQ USI:TVOLQ // DJIA n.a. // US n.a. up = "USI:ADVN.NY" down = "USI:DECL.NY" unchanged = "USI:UNCH.NY" total = "USI:ACTV.NY" tick = "USI:TICK" ticksource = " (nyse)" trin_namesup = "USI:ADV" trin_namesdown = "USI:DECL" trin_sharevolup = "USI:UVOL" trin_sharevoldown = "USI:DVOL" trinsource = " (nyse)" if (volume_source == "NYSE") up := volume_type == "ADVN/DECL" ? "USI:ADVN.NY" : volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.NY" : volume_type == "ADV/DECL" ? "USI:ADV" : volume_type == "UVOL/DVOL" ? "USI:UVOL" : "USI:ADVN.NY" down := volume_type == "ADVN/DECL" ? "USI:DECL.NY" : volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.NY" : volume_type == "ADV/DECL" ? "USI:DECL" : volume_type == "UVOL/DVOL" ? "USI:DVOL" : "USI:DECL.NY" unchanged := volume_type == "ADVN/DECL" ? "USI:UNCH.NY" : volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.NY" : volume_type == "ADV/DECL" ? "USI:UCHG" : volume_type == "UVOL/DVOL" ? "USI:XVOL" : "USI:UNCH.NY" total := volume_type == "ADVN/DECL" ? "USI:ACTV.NY" : volume_type == "UPVOL/DNVOL" ? "USI:TVOL.NY" : volume_type == "ADV/DECL" ? "USI:ADV + USI:DECL + USI:UCHG" : volume_type == "UVOL/DVOL" ? "USI:TVOL" : "USI:TVOL.NY" tick := "USI:TICK" ticksource := na trin_namesup := "USI:ADV" trin_namesdown := "USI:DECL" trin_sharevolup := "USI:UVOL" trin_sharevoldown := "USI:DVOL" trinsource := na else if (volume_source == "NASDAQ") up := volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:UVOLQ" : "USI:ADVN.NQ" down := volume_type == "UPVOL/DNVOL" ? "USI:DNVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:DVOLQ" : "USI:DECL.NQ" unchanged := volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:XVOLQ" : "USI:UNCH.NQ" total := volume_type == "UPVOL/DNVOL" ? "USI:TVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:TVOLQ" : "USI:ACTV.NQ" tick := "USI:TICKQ" ticksource := na trin_namesup := "USI:ADVQ" trin_namesdown := "USI:DECLQ" trin_sharevolup := "USI:UVOLQ" trin_sharevoldown := "USI:DVOLQ" trinsource := na else if (volume_source == "DJIA") up := volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:ADVN.DJ" down := volume_type == "UPVOL/DNVOL" ? "USI:DNVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:DECL.DJ" unchanged := volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:UNCH.DJ" total := volume_type == "UPVOL/DNVOL" ? "USI:TVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:ACTV.DJ" tick := "USI:TICKI" ticksource := na trin_namesup := "USI:ADV" trin_namesdown := "USI:DECL" trin_sharevolup := "USI:UVOL" trin_sharevoldown := "USI:DVOL" trinsource := " (nyse)" else if (volume_source == "US") up := volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:ADVN.US" down := volume_type == "UPVOL/DNVOL" ? "USI:DNVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:DECL.US" unchanged := volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:UNCH.US" total := volume_type == "UPVOL/DNVOL" ? "USI:TVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:ACTV.US" tick := "USI:TICK" ticksource := " (nyse)" trin_namesup := "USI:ADV" trin_namesdown := "USI:DECL" trin_sharevolup := "USI:UVOL" trin_sharevoldown := "USI:DVOL" trinsource := " (nyse)" // Calculations // request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency) // volume(up) / volume(total) returns a value is 0 to 1, 100 * volume(up) / volume(total) returns a percent 0 to 100% // Chart Time-Period Previous Period Close Up-volume Calculations volumeperiodclose(x) => request.security(x, timeframe.period, close) periodpercentup = 100 * volumeperiodclose(up) / volumeperiodclose(total) periodpercentdown = 100 * volumeperiodclose(down) / volumeperiodclose(total) periodpercentunchanged = 100 * volumeperiodclose(unchanged) / volumeperiodclose(total) tickindex(y) => request.security(y, "390", close) tickvalue = tickindex(tick) // TRIN = (Number of names advaincing / number of names declining) / (volume of shares advancing / volume of shares declining) // TRIN = (USI:ADV / USI:DECL) / ( USI:UVOL / USI:DVOL) trinindex(z) => request.security(z, timeframe.period, close) trinvalue = math.round((trinindex(trin_namesup)/trinindex(trin_namesdown)) / (trinindex(trin_sharevolup) / trinindex(trin_sharevoldown)), 3) breadthvalue = tickvalue tabletext_breadth = " tick" + ticksource if (display_exchange_data_breadth_type == "Tick") breadthvalue := tickvalue tabletext_breadth := " tick" + ticksource else if (display_exchange_data_breadth_type == "Trin") breadthvalue := trinvalue tabletext_breadth := " trin" + trinsource // Table Display - Exchange Data Column row_upside = display_exchange_data_upside == true ? 1 : display_exchange_data_upside == false ? 1 : 1 row_downside = display_exchange_data_downside == true and display_exchange_data_upside == true ? 2 : // display_exchange_data_downside == false and display_exchange_data_upside == true ? 2 : display_exchange_data_downside == true and display_exchange_data_upside == false ? 1 : display_exchange_data_downside == false and display_exchange_data_upside == false ? 2 : 2 row_unchanged = display_exchange_data_unchanged == true and display_exchange_data_downside == true and display_exchange_data_upside == true ? 3 : display_exchange_data_unchanged == false and display_exchange_data_downside == true and display_exchange_data_upside == true ? 3 : // display_exchange_data_unchanged == true and display_exchange_data_downside == false and display_exchange_data_upside == true ? 2 : display_exchange_data_unchanged == true and display_exchange_data_downside == true and display_exchange_data_upside == false ? 2 : display_exchange_data_unchanged == false and display_exchange_data_downside == false and display_exchange_data_upside == true ? 2 : display_exchange_data_unchanged == false and display_exchange_data_downside == true and display_exchange_data_upside == false ? 2 : display_exchange_data_unchanged == true and display_exchange_data_downside == false and display_exchange_data_upside == false ? 1 : display_exchange_data_unchanged == false and display_exchange_data_downside == false and display_exchange_data_upside == false ? 2 : 3 row_breadth = display_exchange_data_breadth == true and display_exchange_data_unchanged == true and display_exchange_data_downside == true and display_exchange_data_upside == true ? 4 : display_exchange_data_breadth == false and display_exchange_data_unchanged == true and display_exchange_data_downside == true and display_exchange_data_upside == true ? 4 : // display_exchange_data_breadth == true and display_exchange_data_unchanged == false and display_exchange_data_downside == true and display_exchange_data_upside == true ? 3 : display_exchange_data_breadth == true and display_exchange_data_unchanged == true and display_exchange_data_downside == false and display_exchange_data_upside == true ? 3 : display_exchange_data_breadth == true and display_exchange_data_unchanged == true and display_exchange_data_downside == true and display_exchange_data_upside == false ? 3 : display_exchange_data_breadth == false and display_exchange_data_unchanged == false and display_exchange_data_downside == true and display_exchange_data_upside == true ? 3 : // display_exchange_data_breadth == false and display_exchange_data_unchanged == true and display_exchange_data_downside == false and display_exchange_data_upside == true ? 3 : // display_exchange_data_breadth == false and display_exchange_data_unchanged == true and display_exchange_data_downside == true and display_exchange_data_upside == false ? 3 : // display_exchange_data_breadth == true and display_exchange_data_unchanged == false and display_exchange_data_downside == false and display_exchange_data_upside == true ? 2 : display_exchange_data_breadth == true and display_exchange_data_unchanged == false and display_exchange_data_downside == true and display_exchange_data_upside == false ? 2 : display_exchange_data_breadth == true and display_exchange_data_unchanged == true and display_exchange_data_downside == false and display_exchange_data_upside == false ? 2 : display_exchange_data_breadth == false and display_exchange_data_unchanged == false and display_exchange_data_downside == false and display_exchange_data_upside == true ? 2 : display_exchange_data_breadth == false and display_exchange_data_unchanged == false and display_exchange_data_downside == true and display_exchange_data_upside == false ? 2 : display_exchange_data_breadth == false and display_exchange_data_unchanged == true and display_exchange_data_downside == false and display_exchange_data_upside == false ? 2 : display_exchange_data_breadth == true and display_exchange_data_unchanged == false and display_exchange_data_downside == false and display_exchange_data_upside == false ? 1 : display_exchange_data_breadth == false and display_exchange_data_unchanged == false and display_exchange_data_downside == false and display_exchange_data_upside == false ? 2 : 4 // Table Display - Percent Change Column Text Content tabletext_2_1 = show_percent_change1_new ? table_text1 : show_percent_change2_new ? table_text2 : show_percent_change3_new ? table_text3 : show_percent_change4_new ? table_text4 : show_percent_change5_new ? table_text5 : na tabletext_2_2 = show_percent_change2_new and show_percent_change1_new ? table_text2 : (show_percent_change3_new and show_percent_change2_new) or (show_percent_change3_new and show_percent_change1_new) ? table_text3 : (show_percent_change4_new and show_percent_change3_new) or (show_percent_change4_new and show_percent_change2_new) or (show_percent_change4_new and show_percent_change1_new) ? table_text4 : (show_percent_change5_new and show_percent_change4_new) or (show_percent_change5_new and show_percent_change3_new) or (show_percent_change5_new and show_percent_change2_new) or (show_percent_change5_new and show_percent_change1_new) ? table_text5 : na tabletext_2_3 = show_percent_change3_new and show_percent_change2_new and show_percent_change1_new ? table_text3 : (show_percent_change4_new and show_percent_change3_new and show_percent_change2_new) or (show_percent_change4_new and show_percent_change3_new and show_percent_change1_new) or (show_percent_change4_new and show_percent_change2_new and show_percent_change1_new) ? table_text4 : (show_percent_change5_new and show_percent_change4_new and show_percent_change3_new) or (show_percent_change5_new and show_percent_change4_new and show_percent_change2_new) or (show_percent_change5_new and show_percent_change4_new and show_percent_change1_new) or (show_percent_change5_new and show_percent_change3_new and show_percent_change2_new) or (show_percent_change5_new and show_percent_change3_new and show_percent_change1_new) or (show_percent_change5_new and show_percent_change2_new and show_percent_change1_new) ? table_text5 : na tabletext_2_4 = show_percent_change4_new and show_percent_change3_new and show_percent_change2_new and show_percent_change1_new ? table_text4 : (show_percent_change5_new and show_percent_change4_new and show_percent_change3_new and show_percent_change2_new) or (show_percent_change5_new and show_percent_change4_new and show_percent_change3_new and show_percent_change1_new) or (show_percent_change5_new and show_percent_change4_new and show_percent_change2_new and show_percent_change1_new) or (show_percent_change5_new and show_percent_change3_new and show_percent_change2_new and show_percent_change1_new) ? table_text5 : na tabletext_2_5 = show_percent_change5_new and show_percent_change4_new and show_percent_change3_new and show_percent_change2_new and show_percent_change1_new ? table_text5 : na var table table_value = table.new(position.top_right, columns = 4, rows = 6) table_column_name = str.tostring(ticker.standard(syminfo.ticker)) background_transparency = 95 backgroundcolor0 = display_exchange_data == true ? color.rgb(220, 223, 228, background_transparency) : na backgroundcolor0a = display_exchange_data_upside == true ? display_exchange_data == true ? color.rgb(220, 223, 228, background_transparency) : na : na backgroundcolor0b = display_exchange_data_downside == true ? display_exchange_data == true ? color.rgb(220, 223, 228, background_transparency) : na : na backgroundcolor0c = display_exchange_data_unchanged == true ? display_exchange_data == true ? color.rgb(220, 223, 228, background_transparency) : na : na backgroundcolor0d = display_exchange_data_breadth == true ? display_exchange_data == true ? color.rgb(220, 223, 228, background_transparency) : na : na backgroundcolor1 = color.rgb(220, 223, 228, background_transparency) backgroundcolor2 = show_percent_change1_new or show_percent_change2_new or show_percent_change3_new or show_percent_change4_new or show_percent_change5_new ? color.rgb(220, 223, 228, background_transparency) : na backgroundcolor2a = str.tostring(tabletext_2_1) != "" ? color.rgb(220, 223, 228, background_transparency) : na backgroundcolor2b = str.tostring(tabletext_2_2) != "" ? color.rgb(220, 223, 228, background_transparency) : na backgroundcolor2c = str.tostring(tabletext_2_3) != "" ? color.rgb(220, 223, 228, background_transparency) : na backgroundcolor2d = str.tostring(tabletext_2_4) != "" ? color.rgb(220, 223, 228, background_transparency) : na backgroundcolor2e = str.tostring(tabletext_2_5) != "" ? color.rgb(220, 223, 228, background_transparency) : na textcolor1 = color.rgb(220, 223, 228, 0) if barstate.islast table.cell(table_value, column = 0, row = 0, text = (display_exchange_data_upside or display_exchange_data_downside or display_exchange_data_unchanged or display_exchange_data_breadth) ? display_exchange_data ? volume_source : na : na, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor0) table.cell(table_value, column = 0, row = row_upside, text = display_exchange_data and display_exchange_data_upside ? " " + str.tostring(math.round(periodpercentup, 2)) + " % up" : na, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor0a) table.cell(table_value, column = 0, row = row_downside, text = display_exchange_data and display_exchange_data_downside ? " " + str.tostring(math.round(periodpercentdown, 2)) + " % dn" : na, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor0b) table.cell(table_value, column = 0, row = row_unchanged, text = display_exchange_data and display_exchange_data_unchanged ? " " + str.tostring(math.round(periodpercentunchanged, 2)) + " % uc" : na, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor0c) table.cell(table_value, column = 0, row = row_breadth, text = display_exchange_data and display_exchange_data_breadth ? " " + str.tostring(breadthvalue) + tabletext_breadth : na, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor0d) table.cell(table_value, column = 1, row = 0, text = table_column_name, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor1) table.cell(table_value, column = 1, row = 1, text = " " + str.tostring(math.round(table_text_vol_percent_value, 3)) + table_text_vol_percent_lable, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor1) table.cell(table_value, column = 1, row = 2, text = " " + str.tostring(math.round(chart_float_to_outstanding, 3)) + " f/o", text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor1) table.cell(table_value, column = 2, row = 0, text = show_percent_change1_new or show_percent_change2_new or show_percent_change3_new or show_percent_change4_new or show_percent_change5_new ? table_column_name : na, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor2) table.cell(table_value, column = 2, row = 1, text = tabletext_2_1, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor2a) table.cell(table_value, column = 2, row = 2, text = tabletext_2_2, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor2b) table.cell(table_value, column = 2, row = 3, text = tabletext_2_3, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor2c) table.cell(table_value, column = 2, row = 4, text = tabletext_2_4, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor2d) table.cell(table_value, column = 2, row = 5, text = tabletext_2_5, text_color = textcolor1, text_halign = text.align_right, text_valign = text.align_center, text_size = size.small, bgcolor = backgroundcolor2e) // Display Horizontal Lines obPlot = hline(show_smoothed_chart_vol_percent ? .51 : 1.1, title="Upper Band", linestyle=hline.style_solid, color=color.rgb(220, 223, 228, 95), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="100% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="90% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 50), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="70% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="55% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 20), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? 0 : na, title="50% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="45% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 20), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="30% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : na, title="10% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 50), linewidth=1) // white 220, 223, 228 hline(show_smoothed_chart_vol_percent ? na : 0, title="0% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 osPlot = hline(show_smoothed_chart_vol_percent ? -.51 : -.1, title="Lower Band", linestyle=hline.style_solid, color=color.rgb(220, 223, 228, 95), linewidth=1) // white 220, 223, 228 fill(obPlot, osPlot, title="Background", color=color.rgb(220, 223, 228, 99)) // white 220, 223, 228 // NOTES // // EXCHANGE % UPSIDE/DOWNSIDE VARIABLES // // ADVN/DECL NUMBER OF NAMES // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:ADVN.NY USI:DECL.NY USI:UNCH.NY USI:ACTV.NY // NASDAQ USI:ADVN.NQ USI:DECL.NQ USI:UNCH.NQ USI:ACTV.NQ // DJIA USI:ADVN.DJ USI:DECL.DJ USI:UNCH.DJ USI:ACTV.DJ // US USI:ADVN.US USI:DECL.US USI:UNCH.US USI:ACTV.US // // UPVOL/DNVOL VOLUME OF SHARES IN THE GROUP "NUMBER OF NAMES" // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:UPVOL.NY USI:DNVOL.NY USI:UNCHVOL.NY USI:TVOL.NY // NASDAQ USI:UPVOL.NQ USI:DNVOL.NQ USI:UNCHVOL.NQ USI:TVOL.NQ // DJIA USI:UPVOL.DJ USI:DNVOL.DJ USI:UNCHVOL.DJ USI:TVOL.DJ // US USI:UPVOL.US USI:DNVOL.US USI:UNCHVOL.US USI:TVOL.US // // ADV/DECL NUMBER OF NAMES // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:ADV USI:DECL USI:UCHG USI:ADV+USI:DECL+USI:UCHG // NASDAQ USI:ADVQ USI:DECLQ USI:UCHGQ USI:ADVQ+USI:DECLQ+USI:UCHGQ // DJIA n.a. // US n.a. // // UVOL/DVOL VOLUME OF SHARES IN THE GROUP "NUMBER OF NAMES" // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:UVOL USI:DVOL USI:XVOL USI:TVOL // NASDAQ USI:UVOLQ USI:DVOLQ USI:XVOLQ USI:TVOLQ // DJIA n.a. // US n.a. // // Compare data https://www.wsj.com/market-data/stocks/marketsdiary // // COLOR SCHEMES // // ONE HALF DARK by Son A. Pham at github.com/sonph/onehalf // HEX RGB // black #282c34 40, 44, 52 // red #e06c75 224, 108, 117 // green #98c379 152, 195, 121 // yellow #e5c07b 229, 192, 123 // blue #61afef 97, 175, 239 // magenta #c678dd 198, 120, 221 // cyan #56b6c2 86, 182, 194 // white #dcdfe4 220, 223, 228 // foreground #dcdfe4 220, 223, 228 // background #282c34 40, 44, 52 // // // END
VWAP, AVWAP and MVWAP - Omkar Banne
https://www.tradingview.com/script/vfLqBSzY-VWAP-AVWAP-and-MVWAP-Omkar-Banne/
OmkarBanne
https://www.tradingview.com/u/OmkarBanne/
74
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© OmkarBanne //@version=5 indicator("VWAP, AVWAP and MVWAP - Omkar Banne", overlay = true) avwap_group ='-----------------AVWAP settings-----------------' avwap_on = input(true, "Plot AVWAP?", group=avwap_group, inline = '1') avwap_color = input(color.new(color.white,1), group = avwap_group, inline = "2") avwap_year = input(2023, title="Year", group = avwap_group, inline = "3") avwap_month = input(4, title="Month", group = avwap_group, inline = "3") avwap_day = input(28, title="Day", group = avwap_group, inline = "3") anchor_date = timestamp(avwap_year,avwap_month,avwap_day) anchor_range = time >= anchor_date and time[1] < anchor_date float sum_pricexvolume = na float sum_volume = na sum_pricexvolume := anchor_range ? hlc3 * volume : sum_volume[1] + (hlc3*volume) sum_volume := anchor_range ? volume : sum_volume[1] + volume avwap = sum_pricexvolume / sum_volume mvwap_group ='-----------------MVWAP settings-----------------' mvwap_on = input(true, "Plot MVWAP?", group=mvwap_group, inline = '1') mvwap_length = input(10, "Moving VWAP length", group = mvwap_group, inline = "2") mvwap_color = input(color.new(color.blue,1), group = mvwap_group, inline = "2") vwap_group ='-----------------VWAP settings-----------------' vwap_on = input(true, "Plot VWAP?", group=vwap_group, inline = '1') vwap_color = input(color.new(color.red,1), group = vwap_group, inline = "2") vwap_source = input(hlc3, 'VWAP Source', group = vwap_group, inline = "2") vwap = ta.vwap(vwap_source) mvwap = ta.ema(vwap,mvwap_length) //--------------PLOT-------------------- plot(avwap_on? avwap : na, linewidth = 2, color=avwap_color) plot(vwap_on? vwap : na, style = plot.style_line, linewidth = 1, color = vwap_color) plot(mvwap_on? mvwap : na, linewidth = 2, color= mvwap_color)
Swing Ranges [ChartPrime]
https://www.tradingview.com/script/x1uxHl67-Swing-Ranges-ChartPrime/
ChartPrime
https://www.tradingview.com/u/ChartPrime/
932
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Chartprime //@version=5 indicator("Swing Ranges [ChartPrime]",overlay = true,max_boxes_count = 500,max_bars_back = 300) color Offwhite = color.rgb(255, 255, 255, 71) color _offwhite = color.rgb(255, 255, 255, 50) color Red1 = color.rgb(255, 82, 82, 85) color Red2 = color.rgb(243, 6, 6, 50) color green = color.rgb(73, 241, 241, 85) color green2 = color.rgb(73, 241, 241, 50) color Black = color.rgb(7, 7, 7) color Yellow = color.rgb(254, 229, 4) int atrLen = 30 float mult = 0.3 float per = 5.0 var float prevHigh = na var float prevLow = na var int prevHighIndex = na var int prevLowIndex = na int sync = bar_index int swingbars = input.int(20, 'Swing Length', tooltip='Bar # for swings' ) int ATRPeriod = input.int(14, 'ATR Period' ) bool showHis = input.bool(true,"Show Historical Boxes") bool showPOC = input.bool(true,"Show VWAP POC",inline = "!") color POCcolor = input.color(#46ecf8,"",inline = "!") float pivHi = ta.pivothigh(high, swingbars, swingbars) float pivLo = ta.pivotlow(low, swingbars, swingbars) float atr = ta.atr(ATRPeriod) float atrPercent = (atr/close) * 100 // --- {Arrays var box [] LevelsBOX = array.new_box() var label [] Levelslabel = array.new_label() float [] Volume = array.new_float() float [] TotalVolume = array.new_float() float [] Greenvolume = array.new_float() float [] redvolume = array.new_float() float [] ATR = array.new_float() float [] VWAP = array.new_float() // -- } //Piv levels if not na(pivHi) prevHigh := pivHi prevHighIndex := sync - swingbars if not na(pivLo) prevLow := pivLo prevLowIndex := sync - swingbars DPlace(data,sign) => if sign == "+" data + (data * 0.0015) else if sign == "-" data - (data * 0.0015) dump = (pivLo - prevHigh) / prevHigh * 100 pump = (pivHi - prevLow) / prevLow * 100 perc = close * (per/100) srdatr = ta.atr (atrLen) * mult band = math.min (srdatr, perc) [swingbars] /2 HH = DPlace(prevHigh,"+") +band HL = DPlace(prevHigh,"+") -band LH = DPlace(prevLow,"-") +band LL = DPlace(prevLow,"-") -band Volume(GV,RV,TV,BC)=> GR = GV / TV RR = RV / TV GI = int(GR * BC) RI = int(RR * BC) [GI , RI , GR , RR] Message(dir)=> Message = "" Message+= dir == pump ? "Price pumped : " + str.tostring(math.round(pump,2),format.percent) + " %\n" : "Price dumped :" + str.tostring(math.round(dump,2),format.percent) + "\n" Message+= "ATR avarage : " + str.tostring(math.round(array.avg(ATR),4),format.percent) + "\n" Message+= "VWAP Mean : " + str.tostring(array.median(VWAP),format.mintick) + "\n" Message+= "Volume avarage : " + str.tostring(array.sum(Volume),format.volume) + "\n" Message+= "BAR count: " + str.tostring(array.size(Volume)) + "\n" if prevLow[1] != prevLow and showHis BIndex = int(((sync - swingbars) - prevHighIndex)) for i = 0 to BIndex array.push(Volume,math.round(volume[swingbars + i],2)) array.push(ATR,atrPercent[swingbars + i]) array.push(VWAP,ta.vwap[swingbars + i]) if array.size(Volume) > BIndex +1 array.shift(Volume) array.shift(ATR) box.new(prevHighIndex, prevHigh, sync - swingbars, pivLo, bgcolor = Red1, border_color =Red2, border_width = 1) label.new(prevHighIndex + int(((sync - swingbars) - prevHighIndex) / 2), prevHigh,text = "", tooltip = Message(dump), size = size.tiny, color = Red2) line.new(prevHighIndex, array.median(VWAP), sync - swingbars, array.median(VWAP), color = Yellow, width = 2) if prevHigh[1] != prevHigh and showHis BIndex = int(((sync - swingbars) - prevLowIndex)) for i = 0 to BIndex array.push(Volume,math.round(volume[swingbars + i],2)) array.push(ATR,atrPercent[swingbars + i]) array.push(VWAP,ta.vwap[swingbars + i]) if array.size(Volume) > BIndex +1 array.shift(Volume) array.shift(ATR) box.new(prevLowIndex, pivHi, sync - swingbars, prevLow, bgcolor =green, border_color = green2, border_width = 1) label.new(prevLowIndex + int(((sync - swingbars) - prevLowIndex) / 2) , prevLow, text = "", tooltip = Message(pump), size = size.tiny, color = green2, style = label.style_label_up) if prevHigh > array.median(VWAP) line.new(prevLowIndex, array.median(VWAP), sync - swingbars, array.median(VWAP), color = Yellow, width = 2) if barstate.islast BIndex = int(((sync - swingbars) - prevHighIndex)) for i = 0 to BIndex array.push(Volume,math.round(volume[swingbars + i],2)) array.push(ATR,atrPercent[swingbars + i]) array.push(VWAP,ta.vwap[swingbars + i]) if array.size(Volume) > BIndex +1 array.shift(Volume) array.shift(ATR) Bindex = sync - prevHighIndex IndexB = (sync + 50 )- prevHighIndex for i = 1 to Bindex if close[i] > open[i] array.push(Greenvolume,volume[i]) if close[i] < open[i] array.push(redvolume,volume[i]) array.push(TotalVolume,volume[i]) [GI , RI,GR,RR ] = Volume(array.sum(Greenvolume),array.sum(redvolume),array.sum(TotalVolume),IndexB) colorS = close > LH ? green : Red1 , ColorB = close > LH ? green2 : Red2 _colorS = close > HH ? green : Red1 , _ColorB = close > HH ? green2 : Red2 leftover = 100 - ((RR + GR) * 100 ) array.push(LevelsBOX, box.new(prevHighIndex, LH, sync + 50, LL, bgcolor = colorS, border_color =ColorB, border_width = 1)) array.push(LevelsBOX, box.new(prevHighIndex, HH, sync + 50, HL, bgcolor = _colorS, border_color =_ColorB, border_width = 1)) array.push(LevelsBOX, box.new(prevHighIndex, LH, prevHighIndex + GI, LL, bgcolor = Offwhite, border_color =_offwhite, border_width = 1, text = "Bull Volume", text_size = size.normal, text_color = Black)) array.push(LevelsBOX, box.new(prevHighIndex, HH, prevHighIndex + RI, HL, bgcolor = Offwhite, border_color =_offwhite, border_width = 1, text = "Bear Volume", text_size = size.normal, text_color = Black)) array.push(Levelslabel, label.new(prevHighIndex + ( GI + 9 ), (LL + LH) / 2, str.tostring(math.round(GR * 100,2)) + " %", xloc = xloc.bar_index, style = label.style_label_left, textcolor= color.white, color = color.new(color.black, 100))) array.push(Levelslabel, label.new(prevHighIndex + ( RI + 9 ), (HL + HH) / 2, str.tostring(math.round(RR * 100,2)) + " %", xloc = xloc.bar_index, style = label.style_label_left, textcolor= color.white, color = color.new(color.black, 100))) var line POC = na , line.delete(POC) if showPOC POC:=line.new(prevHighIndex, array.median(VWAP), sync + 50, array.median(VWAP), color = POCcolor, width = 2, style = line.style_dotted) var box left = na , box.delete(left) if leftover > 0 left:=box.new(prevHighIndex + ( RI + 20 ), HH, prevHighIndex + ( RI + 30 ), HL, bgcolor = color.rgb(255, 137, 68, 15), border_color =color.rgb(255, 137, 68, 8), border_width = 1, text = "NV " + str.tostring(math.round(leftover,2)) +" %", text_size = size.small, text_color = Black) if array.size(LevelsBOX) > 4 for i = 0 to 3 box.delete(array.shift(LevelsBOX)) if array.size(Levelslabel) > 2 for i = 0 to 1 label.delete(array.shift(Levelslabel))
Heikin Ashi MTF Trend [Pt]
https://www.tradingview.com/script/A32w8TZA-Heikin-Ashi-MTF-Trend-Pt/
PtGambler
https://www.tradingview.com/u/PtGambler/
301
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© PtGambler //@version=5 indicator("Heikin Ashi MTF Trend [Pt]", shorttitle = 'HA MTF Trend [Pt]', overlay = false) group_display = 'Display Options' tf1 = input.timeframe('15', 'Timeframe 1', inline = 'tf1') tf_weight1 = input.int(10, 'Weight', minval = 0, inline = 'tf1') tf2 = input.timeframe('30', 'Timeframe 2', inline = 'tf2') tf_weight2 = input.int(20, 'Weight', minval = 0, inline = 'tf2') tf3 = input.timeframe('60', 'Timeframe 3', inline = 'tf3') tf_weight3 = input.int(30, 'Weight', minval = 0, inline = 'tf3') tf4 = input.timeframe('240', 'Timeframe 4', inline = 'tf4') tf_weight4 = input.int(40, 'Weight', minval = 0, inline = 'tf4') show_bar_color = input.bool(true, 'Show Bar Color', inline = 'col') strong_bear_col = input.color(color.rgb(255, 74, 74), '', inline = 'col') weak_bear_col = input.color(color.rgb(223, 126, 61), '', inline = 'col') weak_bull_col = input.color(color.rgb(157, 159, 46), '', inline = 'col') strong_bull_col = input.color(color.rgb(0, 255, 8), '', inline = 'col') show_hist_lookahead = input.bool(true, 'Shows repainted historical HA bar colors') show_trend_signal = input.bool(false, 'Show Weighted Trend Signal') display_style = input.string('Squares', 'Style', options = ['Squares', 'Lines'], group = group_display) line_thickness = input.int(2, '    └ Line Thickness', group = group_display) bull_col = input.color(color.green, 'Bull', group = group_display, inline = 'col2') bear_col = input.color(color.red, 'Bear', group = group_display, inline = 'col2') lookahead_in = show_hist_lookahead ? barmerge.lookahead_on : barmerge.lookahead_off total_weight = tf_weight1 + tf_weight2 + tf_weight3 + tf_weight4 //Non repainting security f_security(_symbol, _res, _src, _repaint) => request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1] ha_o1 = f_security(ticker.heikinashi(syminfo.tickerid), tf1, open, show_hist_lookahead) ha_c1 = f_security(ticker.heikinashi(syminfo.tickerid), tf1, close, show_hist_lookahead) ha_o2 = f_security(ticker.heikinashi(syminfo.tickerid), tf2, open, show_hist_lookahead) ha_c2 = f_security(ticker.heikinashi(syminfo.tickerid), tf2, close, show_hist_lookahead) ha_o3 = f_security(ticker.heikinashi(syminfo.tickerid), tf3, open, show_hist_lookahead) ha_c3 = f_security(ticker.heikinashi(syminfo.tickerid), tf3, close, show_hist_lookahead) ha_o4 = f_security(ticker.heikinashi(syminfo.tickerid), tf4, open, show_hist_lookahead) ha_c4 = f_security(ticker.heikinashi(syminfo.tickerid), tf4, close, show_hist_lookahead) // [ha_o1, ha_c1] = request.security(ticker.heikinashi(syminfo.tickerid), tf1, [open, close], lookahead = lookahead_in) // [ha_o2, ha_c2] = request.security(ticker.heikinashi(syminfo.tickerid), tf2, [open, close], lookahead = lookahead_in) // [ha_o3, ha_c3] = request.security(ticker.heikinashi(syminfo.tickerid), tf3, [open, close], lookahead = lookahead_in) // [ha_o4, ha_c4] = request.security(ticker.heikinashi(syminfo.tickerid), tf4, [open, close], lookahead = lookahead_in) ha_trend1 = ha_c1 > ha_o1 ? 1 : ha_c1 < ha_o1 ? -1 : 0 ha_trend2 = ha_c2 > ha_o2 ? 1 : ha_c2 < ha_o2 ? -1 : 0 ha_trend3 = ha_c3 > ha_o3 ? 1 : ha_c3 < ha_o3 ? -1 : 0 ha_trend4 = ha_c4 > ha_o4 ? 1 : ha_c4 < ha_o4 ? -1 : 0 lvl1 = 3 lvl2 = 2 lvl3 = 1 lvl4 = 0 plotshape(lvl1, 'TF 1 Trend', shape.square, location.absolute, display_style == 'Squares' ? ha_trend1 == 1 ? bull_col : ha_trend1 == -1 ? bear_col : color.gray : na, size = size.small) plotshape(lvl2, 'TF 2 Trend', shape.square, location.absolute, display_style == 'Squares' ? ha_trend2 == 1 ? bull_col : ha_trend2 == -1 ? bear_col : color.gray : na, size = size.small) plotshape(lvl3, 'TF 3 Trend', shape.square, location.absolute, display_style == 'Squares' ? ha_trend3 == 1 ? bull_col : ha_trend3 == -1 ? bear_col : color.gray : na, size = size.small) plotshape(lvl4, 'TF 4 Trend', shape.square, location.absolute, display_style == 'Squares' ? ha_trend4 == 1 ? bull_col : ha_trend4 == -1 ? bear_col : color.gray : na, size = size.small) plot(lvl1, 'TF 1 Trend', display_style == 'Lines' ? ha_trend1 == 1 ? bull_col : ha_trend1 == -1 ? bear_col : color.gray : na, linewidth = line_thickness) plot(lvl2, 'TF 2 Trend', display_style == 'Lines' ? ha_trend2 == 1 ? bull_col : ha_trend2 == -1 ? bear_col : color.gray : na, linewidth = line_thickness) plot(lvl3, 'TF 3 Trend', display_style == 'Lines' ? ha_trend3 == 1 ? bull_col : ha_trend3 == -1 ? bear_col : color.gray : na, linewidth = line_thickness) plot(lvl4, 'TF 4 Trend', display_style == 'Lines' ? ha_trend4 == 1 ? bull_col : ha_trend4 == -1 ? bear_col : color.gray : na, linewidth = line_thickness) trend_score = tf_weight1 * ha_trend1 + tf_weight2 * ha_trend2 + tf_weight3 * ha_trend3 + tf_weight4 * ha_trend4 trend_color = trend_score > 0 ? color.from_gradient(trend_score, 0, total_weight, weak_bull_col, strong_bull_col) : trend_score < 0 ? color.from_gradient(trend_score, -total_weight, 0, strong_bear_col, weak_bear_col) : color.gray plotshape(show_trend_signal and trend_score > 0 and ta.change(math.sign(trend_score)), 'Bull Trend Signal', shape.triangleup, location.bottom, bull_col, size = size.small) plotshape(show_trend_signal and trend_score < 0 and ta.change(math.sign(trend_score)), 'Bear Trend Signal', shape.triangledown, location.top, bear_col, size = size.small) barcolor(show_bar_color ? trend_color : na) alertcondition(trend_score > 0 and trend_score[1] < 0, 'Bull Trend Signal Alert', 'MTF HA Bull Trend Signal') alertcondition(trend_score < 0 and trend_score[1] > 0, 'Bear Trend Signal Alert', 'MTF HA Bear Trend Signal') f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) => var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) label.set_xy(id, _x, _y) label.set_text(id, _text) label.set_tooltip(id, _tooltip) label.set_textcolor(id, _textcolor) id if barstate.islast f_drawLabelX(bar_index, lvl1, str.tostring(tf1), xloc.bar_index, yloc.price, chart.bg_color, label.style_label_left, chart.fg_color, size.small, text.align_left, '') f_drawLabelX(bar_index, lvl2, str.tostring(tf2), xloc.bar_index, yloc.price, chart.bg_color, label.style_label_left, chart.fg_color, size.small, text.align_left, '') f_drawLabelX(bar_index, lvl3, str.tostring(tf3), xloc.bar_index, yloc.price, chart.bg_color, label.style_label_left, chart.fg_color, size.small, text.align_left, '') f_drawLabelX(bar_index, lvl4, str.tostring(tf4), xloc.bar_index, yloc.price, chart.bg_color, label.style_label_left, chart.fg_color, size.small, text.align_left, '')
RenkoIndicator
https://www.tradingview.com/script/zb1k0oAU-RenkoIndicator/
jac001
https://www.tradingview.com/u/jac001/
124
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jac001 //@version=5 indicator("RenkoIndicator", overlay=true) bullish = ta.highest(high, 5) > ta.highest(high, 10) bearish = ta.lowest(low, 5) < ta.lowest(low, 10) marketSentiment = bullish and bearish ? "Neutral" : bullish ? "Bullish" : "Bearish" renkoStyle =input.string(defval="ATR", title="Box size assignment method", options=["ATR","Traditional"]) boxSize = input.float(defval =14, title="Box Size") renko_tickerid = ticker.renko(syminfo.tickerid, renkoStyle, boxSize) [renko_open, renko_high, renko_low, renko_close] = request.security(renko_tickerid, timeframe.period, [open, high, low, close]) //plotcandle(renko_open, renko_high, renko_low, renko_close, color = renko_close > renko_open ? color.green : color.red) plot((renko_close +renko_open)/2) plotshape( ta.crossover(renko_close,renko_open) and close>open, title = "Buy", text = 'Buy', style = shape.labelup, location = location.belowbar, color= color.green,textcolor = color.white, size = size.tiny) plotshape(ta.crossunder(renko_close,renko_open) and close<open , title = "Sell", text = 'Sell', style = shape.labeldown, location = location.abovebar, color= color.red,textcolor = color.white, size = size.tiny) alertcondition(ta.crossover(renko_close,renko_open) and close>open, title='Buy', message='Buy') alertcondition(ta.crossunder(renko_close,renko_open) and close<open, title='Sell', message='Sell')
Pivotal Moments
https://www.tradingview.com/script/qTTsZPpO-Pivotal-Moments/
allanster
https://www.tradingview.com/u/allanster/
396
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© allanster on TradingView //@version=5 indicator('Pivotal Moments', overlay = true, max_lines_count = 500, max_labels_count = 500) // Draws lines for each of up to 500 pivots that have never been revisited at the present moment in time. tooltipD = "Delays deletion by nBars or nTime of any Pivot lines that are touched or crossed by realtime bars formed after indicator has been loaded " + "on chart.\n\nWhen using nBars the bar duration is from next bar until close of Nth bar. This is the recommended delay method.\n\nWhen using nTime " + "units the time duration is the minimum time of delay desired, the actual time delay may exceed specified amount. Note that this delay method can be " + "computationally quite expensive and may cause erratic behavior when used with a large delay, large number of lines, or when the indicator has been " + "loaded for a long while.\n\nElapsed time is checked upon each price or volume update. Frequency of the updates is dependent upon liquidity. If time " + "delay is set to 3 seconds and the next bar update after touch does not occur until 5 seconds later then the delay would be 5 seconds since that is " + "when the next check for elapsed time occurs." tooltipQ = "Extend levels nBars to the right of current bar. Show number of newest Pivot levels to keep" inBarsL_ = input.int (defval = 2, title = 'Pivot Bars Left', minval = 0, maxval = 100, inline = '0') inBars_R = input.int (defval = 2, title = ' Right', minval = 0, maxval = 100, inline = '0') inStyles = input.string(defval = 'Dotted', title = 'Lines Show As', options = ['Dashed', 'Dotted', 'Solid'], inline = '1') inWidths = input.int (defval = 1, title = ' Wideβ€Š', inline = '1') inDelayN = input.int (defval = 0, title = 'Delay Removal', minval = 0, step = 1, inline = '2') inDelayT = input.string(defval = 'nBars', title = ' Units', options = ['nBars', 'nSecs', 'nMins', 'nHrs', 'nDays'], inline = '2', tooltip = tooltipD) inOffset = input.int (defval = 7, title = 'Extend Right    ', minval = 0, maxval = 100, step = 1, inline = '3') inQueueN = input.int (defval = 50, title = ' Showβ€Š', minval = 0, maxval = 500, step = 1, inline = '3', tooltip = tooltipQ) inColrHi = input.color (defval = color.new(#ff9800, 0), title = 'Colors Used   Hi', inline = '4') inColrLo = input.color (defval = color.new(#00e676, 0), title = 'Lo', inline = '4') inColrHL = input.color (defval = color.new(#9c27b0, 0), title = 'HL', inline = '4') inLabels = input (defval = true, title = 'Show Price Labels', inline = '5') inPlaced = input (defval = false, title = 'On Right', inline = '5') inColors = input (defval = false, title = 'Show Pivot Bars', inline = '6') drawLabl(_offset, _y, _colr, _styl)=> label.new(bar_index + _offset, _y, str.tostring(_y, format.mintick), xloc.bar_index, yloc.price, color(na), not _styl ? label.style_none : label.style_label_left, _colr, size.normal, text.align_left) drawLine(_inset, _offset, _y, _colr, _styl, _wide)=> line.new(bar_index - _inset, _y, bar_index + _offset, _y, xloc.bar_index, extend.none, _colr, _styl == 'Dashed' ? line.style_dashed : _styl == 'Dotted' ? line.style_dotted : line.style_solid, _wide) pivotsHi = ta.pivothigh(high, inBarsL_, inBars_R) // hi pivot occurs pivotsLo = ta.pivotlow( low, inBarsL_, inBars_R) // lo pivot occurs sourceHi = high[inBars_R] // price value of pivot when hi pivot is confirmed sourceLo = low[inBars_R] // price value of pivot when lo pivot is confirmed isColrHi = inLabels ? inColrHi : na // disable labels with na or use transparent color(na) isColrLo = inLabels ? inColrLo : na // disable labels with na or use transparent color(na) delayAmt = inDelayT == 'nBars' ? inDelayN + 1 : inDelayT == 'nSecs' ? inDelayN * 1e3 : inDelayT == 'nMins' ? inDelayN * 6e4 : inDelayT == 'nHrs' ? inDelayN * 3.6e6 : 2.52e7 // added + 1 to nBars to extend to the open of the Nth + 1 bar // when delay type is nTime convert nSecs to nMilliseconds type pivType // declare UD type string Type // declare field for string value of 'h' or 'l' float Valu // declare field for source value of pivot int BarI // declare field for bar_index when touched int Time // declare field for bar time when touched bool Mark // declare field for flagging touched lines label Labl // declare field for label of source value line Line // declare field for line of source value var pivArray = array.new<pivType>() // declare an array of UD type to hold UDT objects if pivotsHi // if condition occurs piv = pivType.new('h', sourceHi, na, na, false, drawLabl(inOffset, sourceHi, isColrHi, inPlaced), drawLine(inBars_R, inOffset, sourceHi, inColrHi, inStyles, inWidths)) // create an object of UDT type array.push(pivArray, piv) // populate array with element object if pivotsLo // if condition occurs piv = pivType.new('l', sourceLo, na, na, false, drawLabl(inOffset, sourceLo, isColrLo, inPlaced), drawLine(inBars_R, inOffset, sourceLo, inColrLo, inStyles, inWidths)) // create an object of UDT type array.push(pivArray, piv) // populate array with element object snapShot = timenow // create a single timestamp for loop, less accurate but more efficient for i = (array.size(pivArray) == 0 ? na : array.size(pivArray) - 1) to 0 by 1 // loop backwards through array of objects obj = array.get(pivArray, i) // assign the array's element i to arbitrarily named 'obj' breaksHi = obj.Type == 'h' and high >= obj.Valu // check if pivot hi and touched by high breaksLo = obj.Type == 'l' and low <= obj.Valu // check if pivot lo and touched by low if obj.Mark == false and (breaksHi or breaksLo) // check unflagged (untouched) element objects for source touches obj.BarI := bar_index // set element object's BarI field for later evaluating elapsed bars obj.Time := timenow // set element object's Time field for later evaluating elapsed time obj.Mark := true // set element object's flag field for later removal once delay has been met trgtValu = str.tostring(obj.Valu, '#.00') // format string of pivot level for alert srceValu = str.tostring(close, '#.00') // format string of current price for alert if breaksHi alert(syminfo.prefix + ' ' + syminfo.ticker + ' ' + timeframe.period + '\nPrice Touched Pivot Hi\nPrice: ' + srceValu + '\nPivot: ' + trgtValu, alert.freq_once_per_bar) // alert when pivot hi is touched or broken by high if breaksLo alert(syminfo.prefix + ' ' + syminfo.ticker + ' ' + timeframe.period + '\nPrice Touched Pivot Lo\nPivot: ' + trgtValu + '\nPrice: ' + srceValu, alert.freq_once_per_bar) // alert when pivot lo is touched or broken by low if obj.Mark == true and (barstate.ishistory or inDelayN == 0 or (inDelayT == 'nBars' and bar_index - obj.BarI >= delayAmt) or (inDelayT != 'nBars' and snapShot - obj.Time >= delayAmt)) // check if flagged touches have met required amount of delay label.delete(obj.Labl) // remove stored label drawing from chart line.delete(obj.Line) // remove stored line drawing from chart array.remove(pivArray, i) // remove touched element object label.set_x(obj.Labl, bar_index + inOffset) // offset remaining labels for current bar realignment line.set_x2(obj.Line, bar_index + inOffset) // offset remaining lines for current bar realignment trashBin = array.size(pivArray) - inQueueN // get current number of items exceeding queue if trashBin > 0 // if number of elements exceeds queue for elmnt = trashBin - 1 to 0 by 1 // loop backwards through elements to be trashed getEl = array.get(pivArray, elmnt) // get object element from array label.delete(getEl.Labl) // delete drawing before removal of object element line.delete(getEl.Line) // delete drawing before removal of object element array.remove(pivArray, elmnt) // remove object element from items array barColor = pivotsHi and pivotsLo ? inColrHL : pivotsHi ? inColrHi : pivotsLo ? inColrLo : na // assign appropriate color for type of fractal barcolor(inColors and pivotsHi ? barColor : na, -inBars_R) // colorize hi pivot bars barcolor(inColors and pivotsLo ? barColor : na, -inBars_R) // colorize lo pivot bars
Multi-Timeframe Trend Detector [Alifer]
https://www.tradingview.com/script/hccJ4040-Multi-Timeframe-Trend-Detector-Alifer/
alifer123
https://www.tradingview.com/u/alifer123/
148
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© alifer123 // Easy to use and customizable multi-timeframe visual trend indicator // The indicator uses EMAs, MACD, RSI and CCI to check whether the trend is Bullish or Bearish on 5M, 15M, 30M, 1H, 4H, 1D, 1W // Arrows will be printed in the Dashboard to represent Bullish (β–² Green) or Bearish (β–Ό Red) trends on each timeframe // For EMA trend: Fast EMA > Slow EMA = Bullish, Fast EMA < Slow EMA = Bearish // For MACD trend: MACD > MACD signal line = Bullish. MACD < MACD signal line = Bearish // For RSI trend: RSI > RSI Bullish Level = Bullish. RSI < RSI Bullish Level = Bearish. RSI in between = Neutral (No arrow) // The strategy will print an RSI warning sign (⚠) in green when RSI is above the RSI Overbought level you defined // The strategy will print an RSI warning sign (⚠) in red when RSI is below the RSI Oversold level you defined // For CCI trend: CCI > 0 = Bullish. CCI < 0 = Bearish // The strategy will print a CCI warning sign (⚠) in green when RSI is above the CCI Overbought level you defined // The strategy will print a CCI warning sign (⚠) in red when RSI is below the CCI Oversold level you defined // The indicator also calculates Volume and a Volume SMA for all timeframes // A blue square (β– ) will be printed if Volume > Volume SMA. A yellow square (β– ) will be printed if Volume < Volume SMA // Note: Because of the limitation of 40 security requests in Pine Script, Volume for 15M and 30M has to be calculated with an SMA of the 5M Volume //@version=5 indicator("Multi-Timeframe Trend Detector [Alifer]", shorttitle = "MTTD [Alifer]", overlay=true) // Inputs theme = input.string("Dark", "Theme", options=["Dark", "Light"]) emaFastPeriod = input(50, "Fast EMA Period", group = "EMA", tooltip = "Fast EMA > Slow EMA = Bullish. Fast EMA < Slow EMA = Bearish") emaSlowPeriod = input(200, "Slow EMA Period", group = "EMA") macdFastLength = input(12, "MACD Fast Length", group = "MACD", tooltip = "MACD > MACD signal line = Bullish. MACD < MACD signal line = Bearish") macdSlowLength = input(26, "MACD Slow Length", group = "MACD") macdSignalLength = input(9, "MACD Signal Length", group = "MACD") rsiPeriod = input(14, "RSI Period", group = "RSI", tooltip = "RSI > RSI Bullish Level = Bullish. RSI < RSI Bullish Level = Bearish. RSI in between = Neutral") rsiBullishLevel = input(50, "RSI Bullish Level", group = "RSI", tooltip = "MUST be >= RSI Bearish Level") rsiBearishLevel = input(50, "RSI Bearish Level", group = "RSI", tooltip = "MUST be <= RSI Bullish Level") rsiOverbought = input(70, "RSI Overbought", group = "RSI", tooltip = "Strategy will print a warning sign when RSI is above this value. Must be > RSI Bullish Level") rsiOversold = input(30, "RSI Oversold", group = "RSI", tooltip = "Strategy will print a warning sign when RSI is below this value. Must be < RSI Bearish Level") cciPeriod = input(14, "CCI Period", group = "CCI", tooltip = "CCI > 0 = Bullish. CCI < 0 = Bearish") cciOverbought = input.int(defval = 100, minval = 1, title = "CCI Overbought Level", group = "CCI", tooltip = "Strategy will print a warning sign when CCI is above this value") cciOversold = input.int(defval = -100, maxval = -1, title = "CCI Oversold Level", group = "CCI", tooltip = "Strategy will print a warning sign when CCI is below this value") volumePeriod = input.int(defval = 30, minval = 1, title = "Volume SMA Period", group = "Volume", tooltip = "If Volume > Volume SMA = Blue square. If Volume < Volume SMA = Yellow square") // Calculate EMAs on multiple timeframes emaFast_5min = request.security(syminfo.tickerid, "5", ta.ema(close, emaFastPeriod)) emaSlow_5min = request.security(syminfo.tickerid, "5", ta.ema(close, emaSlowPeriod)) emaFast_15min = request.security(syminfo.tickerid, "15", ta.ema(close, emaFastPeriod)) emaSlow_15min = request.security(syminfo.tickerid, "15", ta.ema(close, emaSlowPeriod)) emaFast_30min = request.security(syminfo.tickerid, "30", ta.ema(close, emaFastPeriod)) emaSlow_30min = request.security(syminfo.tickerid, "30", ta.ema(close, emaSlowPeriod)) emaFast_1hour = request.security(syminfo.tickerid, "60", ta.ema(close, emaFastPeriod)) emaSlow_1hour = request.security(syminfo.tickerid, "60", ta.ema(close, emaSlowPeriod)) emaFast_4hour = request.security(syminfo.tickerid, "240", ta.ema(close, emaFastPeriod)) emaSlow_4hour = request.security(syminfo.tickerid, "240", ta.ema(close, emaSlowPeriod)) emaFast_daily = request.security(syminfo.tickerid, "D", ta.ema(close, emaFastPeriod)) emaSlow_daily = request.security(syminfo.tickerid, "D", ta.ema(close, emaSlowPeriod)) emaFast_weekly = request.security(syminfo.tickerid, "W", ta.ema(close, emaFastPeriod)) emaSlow_weekly = request.security(syminfo.tickerid, "W", ta.ema(close, emaSlowPeriod)) // Calculate MACD on multiple timeframes [macdLine_5min, signalLine_5min, _] = request.security(syminfo.tickerid, "5", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) [macdLine_15min, signalLine_15min, _] = request.security(syminfo.tickerid, "15", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) [macdLine_30min, signalLine_30min, _] = request.security(syminfo.tickerid, "30", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) [macdLine_1hour, signalLine_1hour, _] = request.security(syminfo.tickerid, "60", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) [macdLine_4hour, signalLine_4hour, _] = request.security(syminfo.tickerid, "240", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) [macdLine_daily, signalLine_daily, _] = request.security(syminfo.tickerid, "D", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) [macdLine_weekly, signalLine_weekly, _] = request.security(syminfo.tickerid, "W", ta.macd(close, macdFastLength, macdSlowLength, macdSignalLength)) // Calculate RSI on multiple timeframes rsi_5min = request.security(syminfo.tickerid, "5", ta.rsi(close, rsiPeriod)) rsi_15min = request.security(syminfo.tickerid, "15", ta.rsi(close, rsiPeriod)) rsi_30min = request.security(syminfo.tickerid, "30", ta.rsi(close, rsiPeriod)) rsi_1hour = request.security(syminfo.tickerid, "60", ta.rsi(close, rsiPeriod)) rsi_4hour = request.security(syminfo.tickerid, "240", ta.rsi(close, rsiPeriod)) rsi_daily = request.security(syminfo.tickerid, "D", ta.rsi(close, rsiPeriod)) rsi_weekly = request.security(syminfo.tickerid, "W", ta.rsi(close, rsiPeriod)) // Calculate CCI on multiple timeframes cci_5min = request.security(syminfo.tickerid, "5", ta.cci(close, cciPeriod)) cci_15min = request.security(syminfo.tickerid, "15", ta.cci(close, cciPeriod)) cci_30min = request.security(syminfo.tickerid, "30", ta.cci(close, cciPeriod)) cci_1hour = request.security(syminfo.tickerid, "60", ta.cci(close, cciPeriod)) cci_4hour = request.security(syminfo.tickerid, "240", ta.cci(close, cciPeriod)) cci_daily = request.security(syminfo.tickerid, "D", ta.cci(close, cciPeriod)) cci_weekly = request.security(syminfo.tickerid, "W", ta.cci(close, cciPeriod)) // CAlculate Volume on multiple timeframes volume_5min = request.security(syminfo.tickerid, "5", volume) volume_15min = ta.sma(volume_5min, 3) volume_30min = ta.sma(volume_5min, 6) volume_1hour = request.security(syminfo.tickerid, "60", volume) volume_4hour = request.security(syminfo.tickerid, "240", volume) volume_daily = request.security(syminfo.tickerid, "D", volume) volume_weekly = request.security(syminfo.tickerid, "W", volume) // Calculate Volume Moving Average for different timeframes vma_5min = ta.sma(volume_5min, volumePeriod) vma_15min = ta.sma(volume_15min, volumePeriod) vma_30min = ta.sma(volume_30min, volumePeriod) vma_1hour = ta.sma(volume_1hour, volumePeriod) vma_4hour = ta.sma(volume_4hour, volumePeriod) vma_daily = ta.sma(volume_daily, volumePeriod) vma_weekly = ta.sma(volume_weekly, volumePeriod) // Determine EMA trends isBullish_5min = emaFast_5min > emaSlow_5min isBearish_5min = emaFast_5min < emaSlow_5min isBullish_15min = emaFast_15min > emaSlow_15min isBearish_15min = emaFast_15min < emaSlow_15min isBullish_30min = emaFast_30min > emaSlow_30min isBearish_30min = emaFast_30min < emaSlow_30min isBullish_1hour = emaFast_1hour > emaSlow_1hour isBearish_1hour = emaFast_1hour < emaSlow_1hour isBullish_4hour = emaFast_4hour > emaSlow_4hour isBearish_4hour = emaFast_4hour < emaSlow_4hour isBullish_daily = emaFast_daily > emaSlow_daily isBearish_daily = emaFast_daily < emaSlow_daily isBullish_weekly = emaFast_weekly > emaSlow_weekly isBearish_weekly = emaFast_weekly < emaSlow_weekly // Determine MACD trends isBullishMACD_5min = macdLine_5min > signalLine_5min isBearishMACD_5min = macdLine_5min < signalLine_5min isBullishMACD_15min = macdLine_15min > signalLine_15min isBearishMACD_15min = macdLine_15min < signalLine_15min isBullishMACD_30min = macdLine_30min > signalLine_30min isBearishMACD_30min = macdLine_30min < signalLine_30min isBullishMACD_1hour = macdLine_1hour > signalLine_1hour isBearishMACD_1hour = macdLine_1hour < signalLine_1hour isBullishMACD_4hour = macdLine_4hour > signalLine_4hour isBearishMACD_4hour = macdLine_4hour < signalLine_4hour isBullishMACD_daily = macdLine_daily > signalLine_daily isBearishMACD_daily = macdLine_daily < signalLine_daily isBullishMACD_weekly = macdLine_weekly > signalLine_weekly isBearishMACD_weekly = macdLine_weekly < signalLine_weekly // Determine RSI trends isBullishRSI_5min = rsi_5min > rsiBullishLevel isBearishRSI_5min = rsi_5min < rsiBearishLevel isRSIBullSign_5min = rsi_5min > rsiBullishLevel and rsi_5min < rsiOverbought isRSIBearSign_5min = rsi_5min < rsiBearishLevel and rsi_5min > rsiOversold isRSIWarning_5min = rsi_5min >= rsiOverbought or rsi_5min <= rsiOversold isBullishRSI_15min = rsi_15min > rsiBullishLevel isBearishRSI_15min = rsi_15min < rsiBearishLevel isRSIBullSign_15min = rsi_15min > rsiBullishLevel and rsi_15min < rsiOverbought isRSIBearSign_15min = rsi_15min < rsiBearishLevel and rsi_15min > rsiOversold isRSIWarning_15min = rsi_15min >= rsiOverbought or rsi_15min <= rsiOversold isBullishRSI_30min = rsi_30min > rsiBullishLevel isBearishRSI_30min = rsi_30min < rsiBearishLevel isRSIBullSign_30min = rsi_30min > rsiBullishLevel and rsi_30min < rsiOverbought isRSIBearSign_30min = rsi_30min < rsiBearishLevel and rsi_30min > rsiOversold isRSIWarning_30min = rsi_30min >= rsiOverbought or rsi_30min <= rsiOversold isBullishRSI_1hour = rsi_1hour > rsiBullishLevel isBearishRSI_1hour = rsi_1hour < rsiBearishLevel isRSIBullSign_1hour = rsi_1hour > rsiBullishLevel and rsi_1hour < rsiOverbought isRSIBearSign_1hour = rsi_1hour < rsiBearishLevel and rsi_1hour > rsiOversold isRSIWarning_1hour = rsi_1hour >= rsiOverbought or rsi_1hour <= rsiOversold isBullishRSI_4hour = rsi_4hour > rsiBullishLevel isBearishRSI_4hour = rsi_4hour < rsiBearishLevel isRSIBullSign_4hour = rsi_4hour > rsiBullishLevel and rsi_4hour < rsiOverbought isRSIBearSign_4hour = rsi_4hour < rsiBearishLevel and rsi_4hour > rsiOversold isRSIWarning_4hour = rsi_4hour >= rsiOverbought or rsi_4hour <= rsiOversold isBullishRSI_daily = rsi_daily > rsiBullishLevel isBearishRSI_daily = rsi_daily < rsiBearishLevel isRSIBullSign_daily = rsi_daily > rsiBullishLevel and rsi_daily < rsiOverbought isRSIBearSign_daily = rsi_daily < rsiBearishLevel and rsi_daily > rsiOversold isRSIWarning_daily = rsi_daily >= rsiOverbought or rsi_daily <= rsiOversold isBullishRSI_weekly = rsi_weekly > rsiBullishLevel isBearishRSI_weekly = rsi_weekly < rsiBearishLevel isRSIBullSign_weekly = rsi_weekly > rsiBullishLevel and rsi_weekly < rsiOverbought isRSIBearSign_weekly = rsi_weekly < rsiBearishLevel and rsi_weekly > rsiOversold isRSIWarning_weekly = rsi_weekly >= rsiOverbought or rsi_weekly <= rsiOversold // Determine CCI trends isBullishCCI_5min = cci_5min > 0 isBearishCCI_5min = cci_5min < 0 isCCIBullSign_5min = cci_5min > 0 and cci_5min < cciOverbought isCCIBearSign_5min = cci_5min < 0 and cci_5min > cciOversold isCCIWarning_5min = cci_5min >= cciOverbought or cci_5min <= cciOversold isBullishCCI_15min = cci_15min > 0 isBearishCCI_15min = cci_15min < 0 isCCIBullSign_15min = cci_15min > 0 and cci_15min < cciOverbought isCCIBearSign_15min = cci_15min < 0 and cci_15min > cciOversold isCCIWarning_15min = cci_15min >= cciOverbought or cci_15min <= cciOversold isBullishCCI_30min = cci_30min > 0 isBearishCCI_30min = cci_30min < 0 isCCIBullSign_30min = cci_30min > 0 and cci_30min < cciOverbought isCCIBearSign_30min = cci_30min < 0 and cci_30min > cciOversold isCCIWarning_30min = cci_30min >= cciOverbought or cci_30min <= cciOversold isBullishCCI_1hour = cci_1hour > 0 isBearishCCI_1hour = cci_1hour < 0 isCCIBullSign_1hour = cci_1hour > 0 and cci_1hour < cciOverbought isCCIBearSign_1hour = cci_1hour < 0 and cci_1hour > cciOversold isCCIWarning_1hour = cci_1hour >= cciOverbought or cci_1hour <= cciOversold isBullishCCI_4hour = cci_4hour > 0 isBearishCCI_4hour = cci_4hour < 0 isCCIBullSign_4hour = cci_4hour > 0 and cci_4hour < cciOverbought isCCIBearSign_4hour = cci_4hour < 0 and cci_4hour > cciOversold isCCIWarning_4hour = cci_4hour >= cciOverbought or cci_4hour <= cciOversold isBullishCCI_daily = cci_daily > 0 isBearishCCI_daily = cci_daily < 0 isCCIBullSign_daily = cci_daily > 0 and cci_daily < cciOverbought isCCIBearSign_daily = cci_daily < 0 and cci_daily > cciOversold isCCIWarning_daily = cci_daily >= cciOverbought or cci_daily <= cciOversold isBullishCCI_weekly = cci_weekly > 0 isBearishCCI_weekly = cci_weekly < 0 isCCIBullSign_weekly = cci_weekly > 0 and cci_weekly < cciOverbought isCCIBearSign_weekly = cci_weekly < 0 and cci_weekly > cciOversold isCCIWarning_weekly = cci_weekly >= cciOverbought or cci_weekly <= cciOversold // Determine if Volume > VMA isVolume5min = volume_5min > vma_5min isVolume15min = volume_15min > vma_15min isVolume30min = volume_30min > vma_30min isVolume1hour = volume_1hour > vma_1hour isVolume4hour = volume_4hour > vma_4hour isVolumeDaily = volume_daily > vma_daily isVolumeWeekly = volume_weekly > vma_weekly // EMA-based color color5m = emaFast_5min > emaSlow_5min ? color.green : color.red color15m = emaFast_15min > emaSlow_15min ? color.green : color.red color30m = emaFast_30min > emaSlow_30min ? color.green : color.red color1h = emaFast_1hour > emaSlow_1hour ? color.green : color.red color4h = emaFast_4hour > emaSlow_4hour ? color.green : color.red color1d = emaFast_daily > emaSlow_daily ? color.green : color.red color1w = emaFast_weekly > emaSlow_weekly ? color.green : color.red // MACD-based color colorMACD_5min = isBullishMACD_5min ? color.green : color.red colorMACD_15min = isBullishMACD_15min ? color.green : color.red colorMACD_30min = isBullishMACD_30min ? color.green : color.red colorMACD_1hour = isBullishMACD_1hour ? color.green : color.red colorMACD_4hour = isBullishMACD_4hour ? color.green : color.red colorMACD_daily = isBullishMACD_daily ? color.green : color.red colorMACD_weekly = isBullishMACD_weekly ? color.green : color.red // RSI-based color colorRSI_5min = isBullishRSI_5min ? color.green : color.red colorRSI_15min = isBullishRSI_15min ? color.green : color.red colorRSI_30min = isBullishRSI_30min ? color.green : color.red colorRSI_1hour = isBullishRSI_1hour ? color.green : color.red colorRSI_4hour = isBullishRSI_4hour ? color.green : color.red colorRSI_daily = isBullishRSI_daily ? color.green : color.red colorRSI_weekly = isBullishRSI_weekly ? color.green : color.red // CCI-based color colorCCI_5min = isBullishCCI_5min ? color.green : color.red colorCCI_15min = isBullishCCI_15min ? color.green : color.red colorCCI_30min = isBullishCCI_30min ? color.green : color.red colorCCI_1hour = isBullishCCI_1hour ? color.green : color.red colorCCI_4hour = isBullishCCI_4hour ? color.green : color.red colorCCI_daily = isBullishCCI_daily ? color.green : color.red colorCCI_weekly = isBullishCCI_weekly ? color.green : color.red // Volume-based color colorVolume_5min = isVolume5min ? color.blue : color.orange colorVolume_15min = isVolume15min ? color.blue : color.orange colorVolume_30min = isVolume30min ? color.blue : color.orange colorVolume_1hour = isVolume1hour ? color.blue : color.orange colorVolume_4hour = isVolume4hour ? color.blue : color.orange colorVolume_Daily = isVolumeDaily ? color.blue : color.orange colorVolume_Weekly = isVolumeWeekly ? color.blue : color.orange // Create dashboard var bgcolor = theme == "Light" ? color.new(#000000, 90) : color.new(#555555, 90) var frame_color = theme == "Light" ? color.new(#000000, 10) : color.new(#555555, 10) var border_color = theme == "Light" ? color.new(#000000, 10) : color.new(#555555, 10) var text_color = theme == "Light" ? color.new(#000000, 0) : color.new(#ffffff, 0) var table trendTable = table.new(position.top_right, 9, 7, bgcolor=bgcolor, frame_color = frame_color, frame_width = 1, border_color = border_color, border_width = 1) table.cell(trendTable, 1, 1, "", text_color=text_color) table.cell(trendTable, 1, 2, "EMA", text_color=text_color) table.cell(trendTable, 1, 3, "MACD", text_color=text_color) table.cell(trendTable, 1, 4, "RSI", text_color=text_color) table.cell(trendTable, 1, 5, "CCI", text_color=text_color) table.cell(trendTable, 1, 6, "VOL", text_color=text_color) table.cell(trendTable, 2, 1, "5M ", text_color=text_color) table.cell(trendTable, 2, 2, isBullish_5min ? "β–²" : isBearish_5min ? "β–Ό" : "", text_color=color5m) table.cell(trendTable, 2, 3, isBullishMACD_5min ? "β–²" : isBearishMACD_5min ? "β–Ό" : "", text_color=colorMACD_5min) table.cell(trendTable, 2, 4, isRSIWarning_5min ? "⚠" : isRSIBullSign_5min ? "β–²" : isRSIBearSign_5min ? "β–Ό" : "", text_color=colorRSI_5min) table.cell(trendTable, 2, 5, isCCIWarning_5min ? "⚠" : isCCIBullSign_5min ? "β–²" : isCCIBearSign_5min ? "β–Ό" : "", text_color=colorCCI_5min) table.cell(trendTable, 2, 6, "β– ", text_color=colorVolume_5min) table.cell(trendTable, 3, 1, "15M", text_color=text_color) table.cell(trendTable, 3, 2, isBullish_15min ? "β–²" : isBearish_15min ? "β–Ό" : "", text_color=color15m) table.cell(trendTable, 3, 3, isBullishMACD_15min ? "β–²" : isBearishMACD_15min ? "β–Ό" : "", text_color=colorMACD_15min) table.cell(trendTable, 3, 4, isRSIWarning_15min ? "⚠" : isRSIBullSign_15min ? "β–²" : isRSIBearSign_15min ? "β–Ό" : "", text_color=colorRSI_15min) table.cell(trendTable, 3, 5, isCCIWarning_15min ? "⚠" : isCCIBullSign_15min ? "β–²" : isCCIBearSign_15min ? "β–Ό" : "", text_color=colorCCI_15min) table.cell(trendTable, 3, 6, "β– ", text_color=colorVolume_15min) table.cell(trendTable, 4, 1, "30M", text_color=text_color) table.cell(trendTable, 4, 2, isBullish_30min ? "β–²" : isBearish_30min ? "β–Ό" : "", text_color=color30m) table.cell(trendTable, 4, 3, isBullishMACD_30min ? "β–²" : isBearishMACD_30min ? "β–Ό" : "", text_color=colorMACD_30min) table.cell(trendTable, 4, 4, isRSIWarning_30min ? "⚠" : isRSIBullSign_30min ? "β–²" : isRSIBearSign_30min ? "β–Ό" : "", text_color=colorRSI_30min) table.cell(trendTable, 4, 5, isCCIWarning_30min ? "⚠" : isCCIBullSign_30min ? "β–²" : isCCIBearSign_30min ? "β–Ό" : "", text_color=colorCCI_30min) table.cell(trendTable, 4, 6, "β– ", text_color=colorVolume_30min) table.cell(trendTable, 5, 1, "1H ", text_color=text_color) table.cell(trendTable, 5, 2, isBullish_1hour ? "β–²" : isBearish_1hour ? "β–Ό" : "", text_color=color1h) table.cell(trendTable, 5, 3, isBullishMACD_1hour ? "β–²" : isBearishMACD_1hour ? "β–Ό" : "", text_color=colorMACD_1hour) table.cell(trendTable, 5, 4, isRSIWarning_1hour ? "⚠" : isRSIBullSign_1hour ? "β–²" : isRSIBearSign_1hour ? "β–Ό" : "", text_color=colorRSI_1hour) table.cell(trendTable, 5, 5, isCCIWarning_1hour ? "⚠" : isCCIBullSign_1hour ? "β–²" : isCCIBearSign_1hour ? "β–Ό" : "", text_color=colorCCI_1hour) table.cell(trendTable, 5, 6, "β– ", text_color=colorVolume_1hour) table.cell(trendTable, 6, 1, "4H ", text_color=text_color) table.cell(trendTable, 6, 2, isBullish_4hour ? "β–²" : isBearish_4hour ? "β–Ό" : "", text_color=color4h) table.cell(trendTable, 6, 3, isBullishMACD_4hour ? "β–²" : isBearishMACD_4hour ? "β–Ό" : "", text_color=colorMACD_4hour) table.cell(trendTable, 6, 4, isRSIWarning_4hour ? "⚠" : isRSIBullSign_4hour ? "β–²" : isRSIBearSign_4hour ? "β–Ό" : "", text_color=colorRSI_4hour) table.cell(trendTable, 6, 5, isCCIWarning_4hour ? "⚠" : isCCIBullSign_4hour ? "β–²" : isCCIBearSign_4hour ? "β–Ό" : "", text_color=colorCCI_4hour) table.cell(trendTable, 6, 6, "β– ", text_color=colorVolume_4hour) table.cell(trendTable, 7, 1, "1D ", text_color=text_color) table.cell(trendTable, 7, 2, emaFast_daily > emaSlow_daily ? "β–²" : emaFast_daily < emaSlow_daily ? "β–Ό" : "", text_color=color1d) table.cell(trendTable, 7, 3, macdLine_daily > signalLine_daily ? "β–²" : macdLine_daily < signalLine_daily ? "β–Ό" : "", text_color=colorMACD_daily) table.cell(trendTable, 7, 4, isRSIWarning_daily ? "⚠" : isRSIBullSign_daily ? "β–²" : isRSIBearSign_daily ? "β–Ό" : "", text_color=colorRSI_daily) table.cell(trendTable, 7, 5, isCCIWarning_daily ? "⚠" : isCCIBullSign_daily ? "β–²" : isCCIBearSign_daily ? "β–Ό" : "", text_color=colorCCI_daily) table.cell(trendTable, 7, 6, "β– ", text_color=colorVolume_Daily) table.cell(trendTable, 8, 1, "1W ", text_color=text_color) table.cell(trendTable, 8, 2, emaFast_weekly > emaSlow_weekly ? "β–²" : emaFast_weekly < emaSlow_weekly ? "β–Ό" : "", text_color=color1w) table.cell(trendTable, 8, 3, macdLine_weekly > signalLine_weekly ? "β–²" : macdLine_weekly < signalLine_weekly ? "β–Ό" : "", text_color=colorMACD_weekly) table.cell(trendTable, 8, 4, isRSIWarning_weekly ? "⚠" : isRSIBullSign_weekly ? "β–²" : isRSIBearSign_weekly ? "β–Ό" : "", text_color=colorRSI_weekly) table.cell(trendTable, 8, 5, isCCIWarning_weekly ? "⚠" : isCCIBullSign_weekly ? "β–²" : isCCIBearSign_weekly ? "β–Ό" : "", text_color=colorCCI_weekly) table.cell(trendTable, 8, 6, "β– ", text_color=colorVolume_Weekly)
Historical Pattern Matcher [Trendoscope]
https://www.tradingview.com/script/YVWi3qqJ-Historical-Pattern-Matcher-Trendoscope/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
616
study
5
CC-BY-NC-SA-4.0
// 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/FibRatios/1 as fibs indicator("Historical Pattern Matcher [Trendoscope]", "HPM[Trendoscope]", overlay = true, max_lines_count=500, max_labels_count=500, max_bars_back = 1000) zigzagLength = input.int(13, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length', display = display.none) numberOfPivots = input.int(6, "Number of Pivots", group='Zigzag', minval = 5, tooltip = 'Number of pivots to match for pattern', display = display.none) projectionBullishColor = input.color(color.lime, 'Bullish Colors', inline='bullc', display = display.none, group='Display') labelBullishColor = input.color(color.green, '', inline='bullc', display = display.none, tooltip = 'Projection and label colors for bullish projections', group='Display') projectionBearishColor = input.color(color.orange, 'Bearish Colors', inline='bearc', display = display.none, group='Display') labelBearishColor = input.color(color.red, '', inline='bearc', display = display.none, tooltip = 'Projection and label colors for bearish projections', group='Display') type PatternData float[] ratios array<zg.Pivot> lastOccurence method tostring(PatternData this)=> strValue = "Last Occurence : "+str.format_time(this.lastOccurence.get(1).point.bartime) + "\nLast retracement :"+str.tostring(this.ratios.last()) + "\nMax retracement :"+str.tostring(this.ratios.max()) + "\nMin retracement :"+str.tostring(this.ratios.min()) + "\nMedian retracement :"+str.tostring(this.ratios.median()) + "\nNumber of Occurences :"+str.tostring(this.ratios.size()) strValue type PatternDrawing array<dr.Line> currentPattern array<dr.Line> lastOccurence dr.Box projectionRange dr.Label projectionDetails dr.Line medianProjection depth = numberOfPivots + 2 useRealTimeBars = true offset = useRealTimeBars? 0 : 1 indicators = matrix.new<float>() indicatorNames = array.new<string>() var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth, offset) zigzag.calculate(array.from(high, low), indicators, indicatorNames) dr.LineProperties bullishPatternProperties = dr.LineProperties.new(xloc.bar_time, color = labelBullishColor, width = 2) dr.LineProperties bearishPatternProperties = dr.LineProperties.new(xloc.bar_time, color = labelBearishColor, width = 2) dr.LineProperties bullishProjectionProperties = dr.LineProperties.new(color = labelBullishColor, style = line.style_arrow_right, width = 1) dr.LineProperties bearishProjectionProperties = dr.LineProperties.new(color = labelBearishColor, style = line.style_arrow_right, width = 1) dr.BoxProperties bullishBoxProperties = dr.BoxProperties.new(color.new(projectionBullishColor, 80), color.new(projectionBullishColor, 90)) dr.BoxProperties bearishBoxProperties = dr.BoxProperties.new(color.new(projectionBearishColor, 80), color.new(projectionBearishColor, 90)) dr.LabelProperties bullishlblProperties = dr.LabelProperties.new(textcolor = chart.fg_color, style = label.style_label_lower_left, color = color.new(labelBullishColor, 90)) dr.LabelProperties bearishLblProperties = dr.LabelProperties.new(textcolor = chart.fg_color, style = label.style_label_upper_left, color = color.new(labelBearishColor, 90)) method getMatchString(array<zg.Pivot> this, startIndex=1)=> matchstring = '' for i=startIndex to this.size()-2 for j=i+1 to this.size()-1 matchstring+= this.get(i).point.price > this.get(j).point.price ? '1' : '0' matchstring method ratios(array<zg.Pivot> this)=> ratios = array.new<float>() for pivot in this ratios.push(pivot.ratio) ratios method tostring(array<float> this)=> str.tostring(this) method tostring(array<int> this)=> str.tostring(this) method update(map<string, PatternData> this, array<zg.Pivot> pivots)=> matchstring = pivots.getMatchString() PatternData currentObj = na if(this.contains(matchstring)) currentObj := this.get(matchstring) else currentObj := PatternData.new(array.new<float>()) this.put(matchstring, currentObj) currentObj.ratios.push(pivots.get(0).ratio) currentObj.lastOccurence := pivots method draw(array<zg.Pivot> pivots, PatternData patternInfo, int startIndex=1)=> var drawing = PatternDrawing.new(array.new<dr.Line>(), array.new<dr.Line>(), dr.Box.new(), dr.Label.new(), dr.Line.new()) drawing.currentPattern.clear() drawing.lastOccurence.clear() drawing.medianProjection.delete() drawing.projectionDetails.delete() currentDir = pivots.get(startIndex).dir for i=startIndex to pivots.size()-2 drawing.currentPattern.push(pivots.get(i).point.createLine(pivots.get(i+1).point, currentDir < 0? bullishPatternProperties : bearishPatternProperties)) for i=1 to patternInfo.lastOccurence.size()-2 drawing.lastOccurence.push(patternInfo.lastOccurence.get(i).point.createLine(patternInfo.lastOccurence.get(i+1).point, currentDir < 0? bullishPatternProperties : bearishPatternProperties)) drawing.currentPattern.draw() drawing.lastOccurence.draw() ratioMin = patternInfo.ratios.min() ratioMax = patternInfo.ratios.max() lastPrice = pivots.get(startIndex+1).point.price currentPrice = pivots.get(startIndex).point.price lastBar = pivots.get(startIndex+1).point.bar currentBar = pivots.get(startIndex).point.bar priceMin = fibs.retracement(lastPrice, currentPrice, ratioMin) priceMax = fibs.retracement(lastPrice, currentPrice, ratioMax) barMin = int(currentBar + ratioMin*(currentBar-lastBar))+1 barMax = int(currentBar + ratioMax*(currentBar-lastBar))+1 drawing.projectionRange.p1 := dr.Point.new(priceMin, barMin) drawing.projectionRange.p2 := dr.Point.new(priceMax, barMax) drawing.projectionRange.properties := currentDir < 0? bullishBoxProperties : bearishBoxProperties drawing.projectionRange.draw() drawing.projectionDetails.lblText := patternInfo.tostring() drawing.projectionDetails.point := dr.Point.new(priceMax, barMax) drawing.projectionDetails.properties := currentDir < 0? bullishlblProperties : bearishLblProperties drawing.projectionDetails.draw() ratioMedium = patternInfo.ratios.median() priceMedian = fibs.retracement(lastPrice, currentPrice, ratioMedium) barMedian = int(currentBar + ratioMedium*(currentBar-lastBar))+1 drawing.medianProjection := pivots.get(startIndex).point.createLine(dr.Point.new(priceMedian, barMedian), currentDir < 0? bullishProjectionProperties : bearishProjectionProperties) drawing.medianProjection.draw() var patternMap = map.new<string, PatternData>() var lastPatternBar = 0 if zigzag.flags.newPivot and zigzag.zigzagPivots.size() == depth lastConfirmedPivot = zigzag.zigzagPivots.get(1) if(lastConfirmedPivot.point.bar > lastPatternBar) snapshot = zigzag.zigzagPivots.copy() snapshot.shift() patternMap.update(snapshot) lastPatternBar := lastConfirmedPivot.point.bar currentSnapshot = zigzag.zigzagPivots.copy() currentSnapshot.pop() matchstring = currentSnapshot.getMatchString() if(patternMap.contains(matchstring)) patternInfo = patternMap.get(matchstring) currentSnapshot.draw(patternInfo) latestSnapshot = zigzag.zigzagPivots.copy() latestSnapshot.pop() latestSnapshot.pop() latestMatch = latestSnapshot.getMatchString(0) if(patternMap.contains(latestMatch)) patternInfo = patternMap.get(latestMatch) latestSnapshot.draw(patternInfo, 0)
Realized price for BTC, ETH, LTC
https://www.tradingview.com/script/xDUE7niL-realized-price-for-btc-eth-ltc/
baal_hadad
https://www.tradingview.com/u/baal_hadad/
70
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© kard1nal001 //@version=5 indicator("Realized Price by Baal Hadad", overlay = true) emaLength = input.int(30, title="EMA Length") bandsOn = input.bool(true, title="Realized Price Bands", tooltip = "Band levels: -70%, -50%, -30%, 200%, 300%, 400%, 500% from Realized Price") signalsOn = input.bool(true, title="Signals") // regLength = input.int(30) // === INPUT BACKTEST RANGE === // startDate = input.time(defval = timestamp("05 Jan 15 00:00 +0000"), title = "From") startDate = timestamp("05 Jan 15 00:00 +0000") // === FUNCTION EXAMPLE === rightDate() => time >= startDate // create date function "within window of time" baseCurrency = syminfo.basecurrency request_supply_intotheblock = request.security('INTOTHEBLOCK:' + baseCurrency + '_CIRCULATINGSUPPLY',"D", close, ignore_invalid_symbol = true) request_supply_glassnode = request.security('GLASSNODE:' + baseCurrency + '_SUPPLY',"D", close, ignore_invalid_symbol = true) supply = na(request_supply_intotheblock)?request_supply_glassnode:request_supply_intotheblock qu_mvrv = 'INTOTHEBLOCK:' + baseCurrency + '_MVRV' float mvrv = request.security(qu_mvrv,"D", close) qu_marketCap = 'CRYPTOCAP:' + baseCurrency float marketCap = request.security(qu_marketCap,"D", close) float realizedCap = 1 / mvrv * marketCap realizedPrice = realizedCap / supply realizedPriceEMA = ta.ema(realizedCap / supply, emaLength) lb30 = realizedPriceEMA * 0.7 lb50 = realizedPriceEMA * 0.5 lb70 = realizedPriceEMA * 0.3 ub2 = realizedPriceEMA * 2 ub3 = realizedPriceEMA * 3 ub4 = realizedPriceEMA * 4 ub5 = realizedPriceEMA * 5 rightDate = rightDate() buySingal1 = ta.crossunder(lb30, close) buySingal2 = ta.crossunder(lb50, close) buySingal3 = ta.crossunder(lb70, close) sellSingal1 = ta.crossover(ub2, close) sellSingal2 = ta.crossover(ub3, close) sellSingal3 = ta.crossover(ub4, close) sellSingal4 = ta.crossover(ub5, close) bgcolor(buySingal3 and signalsOn?color.rgb(0, 255, 0, 50):buySingal2 and signalsOn?color.rgb(0, 255, 0, 70):buySingal1 and signalsOn?color.rgb(0, 100, 0, 70):na) bgcolor(sellSingal4 and signalsOn?color.rgb(255, 0, 0, 50):sellSingal3 and signalsOn?color.rgb(255, 0, 0, 50):sellSingal2 and signalsOn?color.rgb(255, 0, 0, 70):sellSingal1 and signalsOn?color.rgb(100, 0, 0, 70):na) plot(rightDate?realizedPriceEMA:na, color = color.orange, title = "RealizedPrice EMA 30", linewidth = 2) plot(rightDate and bandsOn?lb30:na, color = color.rgb(169, 255, 171, 50), title = "Falling 30%", linewidth = 2) plot(rightDate and bandsOn?lb50:na, color = color.rgb(169, 255, 171, 50), title = "Falling 50%", linewidth = 2) plot(rightDate and bandsOn?lb70:na, color = color.rgb(169, 255, 171, 50), title = "Falling 70%", linewidth = 2) plot(rightDate and bandsOn?ub2:na, color = color.rgb(255, 0, 0, 50), title = "Growth x2", linewidth = 2) plot(rightDate and bandsOn?ub3:na, color = color.rgb(255, 0, 0, 50), title = "Growth x3", linewidth = 2) plot(rightDate and bandsOn?ub4:na, color = color.rgb(255, 0, 0, 50), title = "Growth x4", linewidth = 2) plot(rightDate and bandsOn?ub5:na, color = color.rgb(255, 0, 0, 50), title = "Growth x5", linewidth = 2)
Volume Delta Compare [Ticks ~ LTF data]
https://www.tradingview.com/script/zn9dhLPS-Volume-Delta-Compare-Ticks-LTF-data/
fikira
https://www.tradingview.com/u/fikira/
334
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© fikira //@version=5 indicator("Volume Delta Compare [Ticks ~ LTF data]", max_labels_count=500, max_lines_count=500) _ =' ------------  –––––––––––––––––––––––––– SETTINGS –––––––––––––––––––––––––––  ------------ ' tick = input.string('Ticks', 'Data from: ', options=[ 'Ticks' , 'LTF' ]) res = input.string( '1' , 'LTF' , options=['1S', '5S', '10S', '15S', '30S', '1']) onlyN = input.bool ( true, 'Also start when bar already has data') iCumV = input.bool ( false, 'only show Cumulative Delta Volume' , group= 'CVD' ) cBull = input.color(color.rgb( 57, 196, 157, 25), 'Up' , inline='up', group='colour') cBull_ = input.color(color.rgb(105, 255, 60 ), '' , inline='up', group='colour') cBear = input.color(color.rgb(230, 92, 0, 25), 'Down' , inline='dn', group='colour') cBear_ = input.color(color.rgb(230, 0, 199 ), '' , inline='dn', group='colour') cNeut = input.color(color.rgb( 0, 207, 230, 0), 'Neutral' , inline='nt', group='colour') sDetail = input.bool ( true, 'Show details' , group='Label' ) sTotVol = input.bool ( true, 'Show Total Volume' , group='Label' ) sUpDnNt = input.bool ( true, 'Show Up/Dn/Nt Volume' , group='Label' ) sPriceDf = input.bool ( true, 'Show Price Delta' , group='Label' ) size = input.string(size.small, 'size labels' , options= [size.tiny, size.small, size.normal, size.large, size.auto] , group='Label' ) move = 10 / input.int ( 5 , 'move centerline', minval = 1, maxval = 20, group='0-line') isTick = tick == 'Ticks' Tdisplay1 = iCumV and isTick ? display.all : display.none Tdisplay2 = not iCumV and isTick ? display.all : display.none Ldisplay1 = iCumV and not isTick ? display.all : display.none Ldisplay2 = not iCumV and not isTick ? display.all : display.none _ =' -------------  –––––––––––––––––––––––––– VARIABLES ––––––––––––––––––––––––––  ------------- tick data ----------- ' varip float volBl = na varip float volBr = na varip float volNt = na varip float vl = na varip float cl = na varip float eq = na varip float dfP = na varip float dfV = na varip float TdfP = na varip float TdfV = na varip bool print = true varip string txt = '' var label lab = label.new(na, na) var label labTot = label.new(na, na) _ =' LTF data ----------- ' float upV = na float dnV = na float ntV = na float dV = na float ttV = na var float cumV = 0 _ =' ----------- ' onlyStartWhenCleanSlate = onlyN ? onlyN : barstate.isrealtime[1] _ =' --------------  –––––––––––––––––––––––– CALCULATIONS ––––––––––––––––––––––––––  -------------- tick data ----------- ' if isTick if barstate.isrealtime if not iCumV if onlyStartWhenCleanSlate if sDetail lab := label.new(bar_index, 0, color=color.new(chart.bg_color, 50), textcolor=chart.fg_color, size=size) if sTotVol or sUpDnNt or sPriceDf labTot := label.new(bar_index, 0, color=color.new(chart.bg_color, 50), textcolor=chart.fg_color, size=size , style= label.style_label_up ) else if not barstate.isrealtime[1] line.new(bar_index, 0, bar_index, syminfo.mintick, extend=extend.both) if barstate.isnew // ---------------------------------------------------------- cl := open , dfP := 0 , TdfP := 0 // "open" vl := volume, dfV := volume, TdfV := volume // "volume" at first tick if not iCumV and sDetail txt := 'Ξ” V [Ξ” P]\n\n' print := true switch dfP > 0 => volBl := dfV, volBr := 0 , volNt := 0 dfP < 0 => volBl := 0 , volBr := dfV, volNt := 0 => volBl := 0 , volBr := 0 , volNt := dfV // ---------------------------------------------------------- if not iCumV txt += (sDetail ? str.tostring( dfV ) // Ξ” volume - volume(previous tick) + ' [' + str.tostring( dfP ) + ']\n' : na) // Ξ” price - volume(previous tick) lab .set_text( txt ) labTot.set_text( (sTotVol ? 'Ξ£ V: ' + str.tostring( TdfV ) + '\n' : na) // Ξ£ volume + (sUpDnNt ? 'Ξ£ up: ' + str.tostring( volBl ) + '\n' : na) // Ξ£ up volume + (sUpDnNt ? 'Ξ£ dn: ' + str.tostring( volBr ) + '\n' : na) // Ξ£ down volume + (sUpDnNt ? 'Ξ£ nt: ' + str.tostring( volNt ) + '\n' + '\n' : na) // Ξ£ neutral volume + (sPriceDf? 'Ξ£ P: ' + str.tostring( TdfP ) : na)) // Ξ£ close - open else dfP := close - cl dfV := volume - vl switch dfP > 0 => volBl += dfV dfP < 0 => volBr += dfV => volNt += dfV TdfV += dfV TdfP += dfP if not iCumV if str.length(txt) < 4000 txt += (sDetail ? str.tostring( dfV ) // Ξ” volume - volume(previous tick) + ' [' + str.tostring( dfP ) + ']\n' : na) // Ξ” price - volume(previous tick) else if print txt += '\nToo much data\n-------------' print := false lab .set_text( txt ) labTot.set_text( (sTotVol ? 'Ξ£ V: ' + str.tostring( TdfV ) + '\n' : na) // Ξ£ volume + (sUpDnNt ? 'Ξ£ up: ' + str.tostring( volBl ) + '\n' : na) // Ξ£ up volume + (sUpDnNt ? 'Ξ£ dn: ' + str.tostring( volBr ) + '\n' : na) // Ξ£ down volume + (sUpDnNt ? 'Ξ£ nt: ' + str.tostring( volNt ) + '\n' + '\n' : na) // Ξ£ neutral volume + (sPriceDf? 'Ξ£ P: ' + str.tostring( TdfP ) : na)) // Ξ£ close - open eq := volBl - volBr cl := close vl := volume _ =' LTF data ---------- ' [bV, sV, nV, tV] = request.security_lower_tf( syminfo.tickerid, res , [ close > open ? volume : 0 , close < open ? volume : 0 , close == open ? volume : 0 , volume ] ) if not isTick if not iCumV and (sTotVol or sUpDnNt or sPriceDf) labTot := label.new(bar_index, 0, color=color.new(chart.bg_color, 50), textcolor=chart.fg_color, size=size , style= label.style_label_up ) upV := bV .sum() dnV := sV .sum() ntV := nV .sum() dV := upV - dnV ttV := upV + dnV + ntV if not iCumV labTot.set_text( (sTotVol ? 'Ξ£ V: ' + str.tostring( ttV ) + '\n' : na) // Ξ£ volume + (sUpDnNt ? 'Ξ£ up: ' + str.tostring( upV ) + '\n' : na) // Ξ£ up volume + (sUpDnNt ? 'Ξ£ dn: ' + str.tostring( dnV ) + '\n' : na) // Ξ£ down volume + (sUpDnNt ? 'Ξ£ nt: ' + str.tostring( ntV ) + '\n' + '\n' : na)) // Ξ£ neutral volume _ =' --------------  –––––––––––––––––––––––– DISPLAY ––––––––––––––––––––––––––  -------------- tick data ----------- ' cTick = eq > 0 ? close > open ? cBull : cBull_ : close < open ? cBear : cBear_ plot(barstate.isrealtime and onlyStartWhenCleanSlate and not iCumV ? volBl : na, 'Ξ£ Volume up' , color= color.new(cBull, 75), style=plot.style_columns , display= Tdisplay2) plot(barstate.isrealtime and onlyStartWhenCleanSlate and not iCumV ? -volBr : na, 'Ξ£ Volume down' , color= color.new(cBear, 75), style=plot.style_columns , display= Tdisplay2) plot(barstate.isrealtime and onlyStartWhenCleanSlate and not iCumV ? volNt : na, 'Ξ£ Volume neutral', color= color.new(cNeut, 50), style=plot.style_histogram , linewidth=5, display= Tdisplay2) plot(barstate.isrealtime and onlyStartWhenCleanSlate and not iCumV ? eq : na, 'Ξ£ Ξ” Volume' , color= cTick , style=plot.style_steplinebr, linewidth=3, display= Tdisplay2) hline(not iCumV ? 0 : na, color=color.silver) last20Vol = ta.highest(volume, 20) plot(not iCumV and isTick ? -(last20Vol / move) : na, 'move drawings (Tick data)', color=color(na), display= Tdisplay2) // creates an invisible line that pushes everything up/down (~ visibility labels) _ =' LTF data ----------- ' cLTF = dV > 0 ? close > open ? cBull : cBull_ : close < open ? cBear : cBear_ plot (not iCumV ? upV : na, 'Ξ£ Volume up' , color= color.new(cBull, 75) , style=plot.style_columns , display= Ldisplay2) plot (not iCumV ? -dnV : na, 'Ξ£ Volume down' , color= color.new(cBear, 75) , style=plot.style_columns , display= Ldisplay2) plot (not iCumV ? ntV : na, 'Ξ£ Volume neutral', color= color.new(cNeut, 50) , style=plot.style_histogram, linewidth=5, display= Ldisplay2) plot (not iCumV ? dV : na, 'Ξ£ Ξ” Volume' , color= cLTF , style=plot.style_stepline , linewidth=3, display= Ldisplay2) _ =' --------------  –––––––––––––––––––––––– Ξ£ Ξ” Volume ––––––––––––––––––––––––––  -------------- ' cumV += isTick ? nz(eq) : nz(dV) cCumV = cumV > nz( cumV[1]) ? cBull : cBear plot( iCumV ? isTick ? barstate.isrealtime ? cumV[1] : na : cumV[1] : na, 'cumulative Volume Delta', color=cCumV , style=plot.style_stepline, display= isTick ? Tdisplay1 : Ldisplay1) plot( iCumV ? isTick ? barstate.isrealtime ? cumV : na : cumV : na, 'cumulative Volume Delta', color=cCumV , style=plot.style_stepline, display= isTick ? Tdisplay1 : Ldisplay1) plot(not iCumV ? isTick ? TdfV : ttV : na, 'Total Volume' , color=color.gray, style=plot.style_stepline, display= isTick ? Tdisplay2 : Ldisplay2) if iCumV and (isTick ? barstate.isrealtime : true) line.new(bar_index, cumV, bar_index, cumV[1], color= cCumV, width=20) _ =' --------------  –––––––––––––––––––––––– Table ––––––––––––––––––––––––––  -------------- ' var table tab = table.new(position.top_right, 1, 2, chart.bg_color, chart.bg_color) if barstate.islast table.cell(tab, 0, 0, isTick ? 'Tick data' : 'LTF data' , text_color= chart.fg_color ) table.cell(tab, 0, 1, str.tostring(math.round_to_mintick(isTick ? eq : dV)), text_color=isTick ? cTick : cLTF) _ =' -------------------------------------------------------------------------------------------------------------------- '
Normalized Adaptive Trend Lines [MAMA and FAMA]
https://www.tradingview.com/script/fvTqPHL8-Normalized-Adaptive-Trend-Lines-MAMA-and-FAMA/
IkkeOmar
https://www.tradingview.com/u/IkkeOmar/
65
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© IkkeOmar //@version=5 indicator("Adaptive Trend Lines [MAMA and FAMA]", overlay = false, timeframe = "") fastLimit = input.float(title='Fast Limit', step=0.01, defval=0.01) slowLimit = input.float(title='Slow Limit', step=0.01, defval=0.08) norm_period = input.int(3, 'Normalization Period', 1) // Period for normalization src = input(title='Source', defval=close) // ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------} // CALCULATIONS ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ var float PI = math.pi // CREDIT TO everget and Chartprime for the following functions // Truncated Hilbert transform{ laplace(src) => (0.5) * math.exp(-math.abs(src)) _computeComponent(src, mesaPeriodMult) => out = laplace(src) * mesaPeriodMult out _smoothComponent(src) => out = 0.2 * src + 0.8 * nz(src[1]) out _computeAlpha(src, fastLimit, slowLimit) => mesaPeriod = 0.0 mesaPeriodMult = 0.075 * nz(mesaPeriod[1]) + 0.54 smooth = (4 * src + 3 * nz(src[1]) + 2 * nz(src[2]) + nz(src[3])) / 10 detrender = _computeComponent(smooth, mesaPeriodMult) // Compute InPhase and Quadrature components I1 = nz(detrender[3]) Q1 = _computeComponent(detrender, mesaPeriodMult) // Advance the phase of I1 and Q1 by 90 degrees jI = _computeComponent(I1, mesaPeriodMult) jQ = _computeComponent(Q1, mesaPeriodMult) // Phasor addition for 3 bar averaging I2 = I1 - jQ Q2 = Q1 + jI // Smooth the I and Q components before applying the discriminator I2 := _smoothComponent(I2) Q2 := _smoothComponent(Q2) // Homodyne Discriminator Re = I2 * nz(I2[1], I2) + Q2 * nz(Q2[1], Q2) Im = I2 * nz(Q2[1], Q2) - Q2 * nz(I2[1], I2) Re := _smoothComponent(Re) Im := _smoothComponent(Im) if Re != 0 and Im != 0 mesaPeriod := 2 * PI / math.atan(Im / Re) mesaPeriod mesaPeriod := math.min(mesaPeriod, 1.5 * nz(mesaPeriod[1], mesaPeriod)) mesaPeriod := math.max(mesaPeriod, 0.67 * nz(mesaPeriod[1], mesaPeriod)) mesaPeriod := math.min(math.max(mesaPeriod, 6), 50) mesaPeriod := _smoothComponent(mesaPeriod) phase = 0.0 if I1 != 0 phase := 180 / PI * math.atan(Q1 / I1) phase deltaPhase = nz(phase[1], phase) - phase deltaPhase := math.max(deltaPhase, 1) alpha = math.max(fastLimit / deltaPhase, slowLimit) out = alpha out alpha = _computeAlpha(src, fastLimit, slowLimit) alpha2 = alpha / 2 mama = 0.0 mama := alpha * src + (1 - alpha) * nz(mama[1]) fama = 0.0 fama := alpha2 * mama + (1 - alpha2) * nz(fama[1]) mama_fama_diff = mama - fama // Normalize the oscillator lowest = ta.lowest(mama_fama_diff, norm_period) highest = ta.highest(mama_fama_diff, norm_period) normalized = (mama_fama_diff - lowest) / (highest - lowest) - 0.5 // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------} // PLOTTING (I'm scared of aussies because they're usually tall) { ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ // Plot the difference as a histogram with green and red bars barcolor(normalized >= 0 ? color.green : color.red) plot(normalized, color = normalized > 0 ? color.green : color.red, style = plot.style_histogram, title = 'MAFA Oscillator', linewidth = 3) // Add a horizontal line at zero to indicate the neutral point hline(0, "Zero Line", color=color.gray)
Luffy Gear 5
https://www.tradingview.com/script/GckzHjVe-Luffy-Gear-5/
spacemanbtc
https://www.tradingview.com/u/spacemanbtc/
37
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© spacemanbtc //@version=5 indicator("Luffy Gear 5", overlay = true) i_location = input.string(defval = "Bottom Center",title = "Location",options = ["Bottom Right","Bottom Left", "Bottom Center", "Top Left", "Top Right", "Top Center"]) i_width = input.float(defval = 0.05,title ="Width") i_height = input.float(defval = 0.1,title = "Height") positionholder = i_location == "Bottom Right" ? position.bottom_right : i_location == "Top Left" ? position.top_left : i_location == "Top Right" ? position.top_right : i_location =="Bottom Center" ? position.bottom_center : i_location == "Top Center" ? position.top_center : position.bottom_left var displayGear5 = table.new(positionholder,50,50,bgcolor = color.rgb(0, 0, 0)) if barstate.islast for i = 0 to 49 for x = 0 to 49 table.cell(displayGear5,i,x,bgcolor = color.rgb(0, 0, 0),height = i_height,width= i_width) f_001()=> table.cell(displayGear5,1,8, bgcolor = color.rgb(96,136,153),height = i_height,width= i_width) table.cell(displayGear5,1,9, bgcolor = color.rgb(120,135,142),height = i_height,width= i_width) table.cell(displayGear5,1,13, bgcolor = color.rgb(170,170,166),height = i_height,width= i_width) table.cell(displayGear5,1,14, bgcolor = color.rgb(109,135,144),height = i_height,width= i_width) table.cell(displayGear5,1,17, bgcolor = color.rgb(90,130,148),height = i_height,width= i_width) table.cell(displayGear5,1,25, bgcolor = color.rgb(82,115,134),height = i_height,width= i_width) table.cell(displayGear5,2,8, bgcolor = color.rgb(89,129,142),height = i_height,width= i_width) table.cell(displayGear5,2,9, bgcolor = color.rgb(183,236,255),height = i_height,width= i_width) table.cell(displayGear5,2,10, bgcolor = color.rgb(106,128,140),height = i_height,width= i_width) table.cell(displayGear5,2,11, bgcolor = color.rgb(82,97,102),height = i_height,width= i_width) table.cell(displayGear5,2,12, bgcolor = color.rgb(218,223,225),height = i_height,width= i_width) table.cell(displayGear5,2,13, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,2,14, bgcolor = color.rgb(243,255,255),height = i_height,width= i_width) table.cell(displayGear5,2,15, bgcolor = color.rgb(129,171,190),height = i_height,width= i_width) table.cell(displayGear5,2,18, bgcolor = color.rgb(139,180,193),height = i_height,width= i_width) table.cell(displayGear5,2,26, bgcolor = color.rgb(78,119,136),height = i_height,width= i_width) table.cell(displayGear5,3,10, bgcolor = color.rgb(232,240,246),height = i_height,width= i_width) table.cell(displayGear5,3,11, bgcolor = color.rgb(222,251,255),height = i_height,width= i_width) table.cell(displayGear5,3,12, bgcolor = color.rgb(204,230,241),height = i_height,width= i_width) table.cell(displayGear5,3,13, bgcolor = color.rgb(160,194,202),height = i_height,width= i_width) table.cell(displayGear5,3,14, bgcolor = color.rgb(228,232,231),height = i_height,width= i_width) table.cell(displayGear5,3,15, bgcolor = color.rgb(224,252,255),height = i_height,width= i_width) table.cell(displayGear5,3,16, bgcolor = color.rgb(97,138,158),height = i_height,width= i_width) table.cell(displayGear5,3,17, bgcolor = color.rgb(158,160,164),height = i_height,width= i_width) table.cell(displayGear5,3,18, bgcolor = color.rgb(177,207,213),height = i_height,width= i_width) table.cell(displayGear5,3,26, bgcolor = color.rgb(124,167,184),height = i_height,width= i_width) table.cell(displayGear5,3,27, bgcolor = color.rgb(89,118,131),height = i_height,width= i_width) table.cell(displayGear5,4,5, bgcolor = color.rgb(104,117,120),height = i_height,width= i_width) table.cell(displayGear5,4,6, bgcolor = color.rgb(146,135,132),height = i_height,width= i_width) table.cell(displayGear5,4,7, bgcolor = color.rgb(125,125,123),height = i_height,width= i_width) table.cell(displayGear5,4,9, bgcolor = color.rgb(118,104,101),height = i_height,width= i_width) table.cell(displayGear5,4,10, bgcolor = color.rgb(220,221,225),height = i_height,width= i_width) table.cell(displayGear5,4,11, bgcolor = color.rgb(232,243,246),height = i_height,width= i_width) table.cell(displayGear5,4,12, bgcolor = color.rgb(215,226,231),height = i_height,width= i_width) table.cell(displayGear5,4,13, bgcolor = color.rgb(213,228,234),height = i_height,width= i_width) table.cell(displayGear5,4,14, bgcolor = color.rgb(241,247,248),height = i_height,width= i_width) table.cell(displayGear5,4,15, bgcolor = color.rgb(255,255,254),height = i_height,width= i_width) table.cell(displayGear5,4,16, bgcolor = color.rgb(214,237,243),height = i_height,width= i_width) table.cell(displayGear5,4,17, bgcolor = color.rgb(134,188,210),height = i_height,width= i_width) table.cell(displayGear5,4,18, bgcolor = color.rgb(132,188,214),height = i_height,width= i_width) table.cell(displayGear5,4,19, bgcolor = color.rgb(146,193,214),height = i_height,width= i_width) table.cell(displayGear5,4,26, bgcolor = color.rgb(197,213,222),height = i_height,width= i_width) table.cell(displayGear5,4,27, bgcolor = color.rgb(117,122,118),height = i_height,width= i_width) table.cell(displayGear5,5,2, bgcolor = color.rgb(93,131,155),height = i_height,width= i_width) table.cell(displayGear5,5,4, bgcolor = color.rgb(151,154,154),height = i_height,width= i_width) table.cell(displayGear5,5,5, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,6, bgcolor = color.rgb(252,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,7, bgcolor = color.rgb(252,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,8, bgcolor = color.rgb(240,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,9, bgcolor = color.rgb(251,254,254),height = i_height,width= i_width) table.cell(displayGear5,5,10, bgcolor = color.rgb(185,209,220),height = i_height,width= i_width) table.cell(displayGear5,5,11, bgcolor = color.rgb(224,233,235),height = i_height,width= i_width) table.cell(displayGear5,5,12, bgcolor = color.rgb(252,251,249),height = i_height,width= i_width) table.cell(displayGear5,5,13, bgcolor = color.rgb(232,242,243),height = i_height,width= i_width) table.cell(displayGear5,5,14, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,15, bgcolor = color.rgb(243,244,244),height = i_height,width= i_width) table.cell(displayGear5,5,16, bgcolor = color.rgb(144,183,200),height = i_height,width= i_width) table.cell(displayGear5,5,17, bgcolor = color.rgb(109,162,185),height = i_height,width= i_width) table.cell(displayGear5,5,18, bgcolor = color.rgb(182,204,216),height = i_height,width= i_width) table.cell(displayGear5,5,19, bgcolor = color.rgb(234,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,20, bgcolor = color.rgb(189,225,235),height = i_height,width= i_width) table.cell(displayGear5,5,24, bgcolor = color.rgb(195,221,235),height = i_height,width= i_width) table.cell(displayGear5,5,25, bgcolor = color.rgb(198,239,255),height = i_height,width= i_width) table.cell(displayGear5,5,26, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,5,27, bgcolor = color.rgb(117,109,106),height = i_height,width= i_width) table.cell(displayGear5,6,3, bgcolor = color.rgb(142,201,225),height = i_height,width= i_width) table.cell(displayGear5,6,4, bgcolor = color.rgb(231,255,255),height = i_height,width= i_width) table.cell(displayGear5,6,5, bgcolor = color.rgb(246,244,243),height = i_height,width= i_width) table.cell(displayGear5,6,6, bgcolor = color.rgb(199,219,225),height = i_height,width= i_width) table.cell(displayGear5,6,7, bgcolor = color.rgb(189,217,219),height = i_height,width= i_width) table.cell(displayGear5,6,8, bgcolor = color.rgb(251,253,251),height = i_height,width= i_width) table.cell(displayGear5,6,9, bgcolor = color.rgb(185,215,219),height = i_height,width= i_width) table.cell(displayGear5,6,10, bgcolor = color.rgb(153,190,205),height = i_height,width= i_width) table.cell(displayGear5,6,11, bgcolor = color.rgb(156,204,224),height = i_height,width= i_width) table.cell(displayGear5,6,12, bgcolor = color.rgb(155,208,230),height = i_height,width= i_width) table.cell(displayGear5,6,13, bgcolor = color.rgb(173,207,219),height = i_height,width= i_width) table.cell(displayGear5,6,14, bgcolor = color.rgb(194,211,222),height = i_height,width= i_width) table.cell(displayGear5,6,15, bgcolor = color.rgb(122,169,188),height = i_height,width= i_width) table.cell(displayGear5,6,16, bgcolor = color.rgb(134,177,200),height = i_height,width= i_width) table.cell(displayGear5,6,17, bgcolor = color.rgb(251,250,251),height = i_height,width= i_width) table.cell(displayGear5,6,18, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,6,19, bgcolor = color.rgb(237,242,242),height = i_height,width= i_width) table.cell(displayGear5,6,20, bgcolor = color.rgb(191,225,237),height = i_height,width= i_width) table.cell(displayGear5,6,21, bgcolor = color.rgb(175,203,214),height = i_height,width= i_width) table.cell(displayGear5,6,23, bgcolor = color.rgb(189,217,218),height = i_height,width= i_width) table.cell(displayGear5,6,24, bgcolor = color.rgb(233,252,254),height = i_height,width= i_width) table.cell(displayGear5,6,25, bgcolor = color.rgb(251,253,253),height = i_height,width= i_width) table.cell(displayGear5,6,26, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,6,27, bgcolor = color.rgb(100,106,109),height = i_height,width= i_width) table.cell(displayGear5,7,4, bgcolor = color.rgb(101,150,170),height = i_height,width= i_width) table.cell(displayGear5,7,5, bgcolor = color.rgb(181,208,221),height = i_height,width= i_width) table.cell(displayGear5,7,6, bgcolor = color.rgb(186,213,223),height = i_height,width= i_width) table.cell(displayGear5,7,7, bgcolor = color.rgb(164,199,208),height = i_height,width= i_width) table.cell(displayGear5,7,8, bgcolor = color.rgb(234,241,240),height = i_height,width= i_width) table.cell(displayGear5,7,9, bgcolor = color.rgb(164,199,212),height = i_height,width= i_width) table.cell(displayGear5,7,10, bgcolor = color.rgb(89,148,181),height = i_height,width= i_width) table.cell(displayGear5,7,13, bgcolor = color.rgb(127,165,184),height = i_height,width= i_width) table.cell(displayGear5,7,14, bgcolor = color.rgb(145,190,208),height = i_height,width= i_width) table.cell(displayGear5,7,15, bgcolor = color.rgb(177,206,220),height = i_height,width= i_width) f_100()=> table.cell(displayGear5,7,16, bgcolor = color.rgb(252,251,251),height = i_height,width= i_width) table.cell(displayGear5,7,17, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,7,18, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,7,19, bgcolor = color.rgb(240,243,244),height = i_height,width= i_width) table.cell(displayGear5,7,20, bgcolor = color.rgb(190,219,233),height = i_height,width= i_width) table.cell(displayGear5,7,21, bgcolor = color.rgb(154,178,189),height = i_height,width= i_width) table.cell(displayGear5,7,23, bgcolor = color.rgb(138,168,182),height = i_height,width= i_width) table.cell(displayGear5,7,24, bgcolor = color.rgb(93,160,196),height = i_height,width= i_width) table.cell(displayGear5,7,25, bgcolor = color.rgb(215,229,239),height = i_height,width= i_width) table.cell(displayGear5,7,26, bgcolor = color.rgb(195,210,215),height = i_height,width= i_width) table.cell(displayGear5,8,5, bgcolor = color.rgb(135,202,230),height = i_height,width= i_width) table.cell(displayGear5,8,6, bgcolor = color.rgb(120,173,197),height = i_height,width= i_width) table.cell(displayGear5,8,7, bgcolor = color.rgb(117,167,191),height = i_height,width= i_width) table.cell(displayGear5,8,8, bgcolor = color.rgb(127,173,195),height = i_height,width= i_width) table.cell(displayGear5,8,9, bgcolor = color.rgb(104,163,191),height = i_height,width= i_width) table.cell(displayGear5,8,10, bgcolor = color.rgb(158,195,209),height = i_height,width= i_width) table.cell(displayGear5,8,14, bgcolor = color.rgb(212,250,255),height = i_height,width= i_width) table.cell(displayGear5,8,15, bgcolor = color.rgb(249,255,255),height = i_height,width= i_width) table.cell(displayGear5,8,16, bgcolor = color.rgb(220,243,253),height = i_height,width= i_width) table.cell(displayGear5,8,17, bgcolor = color.rgb(240,250,255),height = i_height,width= i_width) table.cell(displayGear5,8,18, bgcolor = color.rgb(255,254,253),height = i_height,width= i_width) table.cell(displayGear5,8,19, bgcolor = color.rgb(213,228,232),height = i_height,width= i_width) table.cell(displayGear5,8,20, bgcolor = color.rgb(173,209,221),height = i_height,width= i_width) table.cell(displayGear5,8,21, bgcolor = color.rgb(165,191,197),height = i_height,width= i_width) table.cell(displayGear5,8,23, bgcolor = color.rgb(89,140,164),height = i_height,width= i_width) table.cell(displayGear5,8,24, bgcolor = color.rgb(151,195,214),height = i_height,width= i_width) table.cell(displayGear5,8,25, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,8,26, bgcolor = color.rgb(90,87,85),height = i_height,width= i_width) table.cell(displayGear5,8,29, bgcolor = color.rgb(176,204,207),height = i_height,width= i_width) table.cell(displayGear5,8,30, bgcolor = color.rgb(171,186,188),height = i_height,width= i_width) table.cell(displayGear5,9,5, bgcolor = color.rgb(114,162,182),height = i_height,width= i_width) table.cell(displayGear5,9,6, bgcolor = color.rgb(194,218,226),height = i_height,width= i_width) table.cell(displayGear5,9,7, bgcolor = color.rgb(211,224,228),height = i_height,width= i_width) table.cell(displayGear5,9,8, bgcolor = color.rgb(136,180,199),height = i_height,width= i_width) table.cell(displayGear5,9,9, bgcolor = color.rgb(120,170,191),height = i_height,width= i_width) table.cell(displayGear5,9,10, bgcolor = color.rgb(239,242,244),height = i_height,width= i_width) table.cell(displayGear5,9,11, bgcolor = color.rgb(190,222,239),height = i_height,width= i_width) table.cell(displayGear5,9,13, bgcolor = color.rgb(128,150,158),height = i_height,width= i_width) table.cell(displayGear5,9,14, bgcolor = color.rgb(205,217,219),height = i_height,width= i_width) table.cell(displayGear5,9,15, bgcolor = color.rgb(176,190,186),height = i_height,width= i_width) table.cell(displayGear5,9,16, bgcolor = color.rgb(171,189,186),height = i_height,width= i_width) table.cell(displayGear5,9,17, bgcolor = color.rgb(216,214,206),height = i_height,width= i_width) table.cell(displayGear5,9,18, bgcolor = color.rgb(234,245,243),height = i_height,width= i_width) table.cell(displayGear5,9,19, bgcolor = color.rgb(169,202,209),height = i_height,width= i_width) table.cell(displayGear5,9,20, bgcolor = color.rgb(192,214,222),height = i_height,width= i_width) table.cell(displayGear5,9,21, bgcolor = color.rgb(184,213,222),height = i_height,width= i_width) table.cell(displayGear5,9,22, bgcolor = color.rgb(188,221,233),height = i_height,width= i_width) table.cell(displayGear5,9,23, bgcolor = color.rgb(121,173,197),height = i_height,width= i_width) table.cell(displayGear5,9,24, bgcolor = color.rgb(232,243,248),height = i_height,width= i_width) table.cell(displayGear5,9,25, bgcolor = color.rgb(172,189,190),height = i_height,width= i_width) table.cell(displayGear5,9,28, bgcolor = color.rgb(146,172,181),height = i_height,width= i_width) table.cell(displayGear5,9,29, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,9,30, bgcolor = color.rgb(159,152,147),height = i_height,width= i_width) table.cell(displayGear5,10,6, bgcolor = color.rgb(138,187,211),height = i_height,width= i_width) table.cell(displayGear5,10,7, bgcolor = color.rgb(253,254,251),height = i_height,width= i_width) table.cell(displayGear5,10,8, bgcolor = color.rgb(240,244,241),height = i_height,width= i_width) table.cell(displayGear5,10,9, bgcolor = color.rgb(197,219,227),height = i_height,width= i_width) table.cell(displayGear5,10,10, bgcolor = color.rgb(180,206,218),height = i_height,width= i_width) table.cell(displayGear5,10,11, bgcolor = color.rgb(250,251,253),height = i_height,width= i_width) table.cell(displayGear5,10,12, bgcolor = color.rgb(168,205,224),height = i_height,width= i_width) table.cell(displayGear5,10,13, bgcolor = color.rgb(122,188,218),height = i_height,width= i_width) table.cell(displayGear5,10,14, bgcolor = color.rgb(183,160,139),height = i_height,width= i_width) table.cell(displayGear5,10,15, bgcolor = color.rgb(250,193,132),height = i_height,width= i_width) table.cell(displayGear5,10,16, bgcolor = color.rgb(234,180,126),height = i_height,width= i_width) table.cell(displayGear5,10,17, bgcolor = color.rgb(220,178,145),height = i_height,width= i_width) table.cell(displayGear5,10,18, bgcolor = color.rgb(218,244,248),height = i_height,width= i_width) table.cell(displayGear5,10,19, bgcolor = color.rgb(205,219,224),height = i_height,width= i_width) table.cell(displayGear5,10,20, bgcolor = color.rgb(250,249,249),height = i_height,width= i_width) table.cell(displayGear5,10,21, bgcolor = color.rgb(175,205,218),height = i_height,width= i_width) table.cell(displayGear5,10,22, bgcolor = color.rgb(171,204,218),height = i_height,width= i_width) table.cell(displayGear5,10,23, bgcolor = color.rgb(122,173,196),height = i_height,width= i_width) table.cell(displayGear5,10,24, bgcolor = color.rgb(169,205,224),height = i_height,width= i_width) table.cell(displayGear5,10,25, bgcolor = color.rgb(77,79,82),height = i_height,width= i_width) table.cell(displayGear5,10,27, bgcolor = color.rgb(151,172,181),height = i_height,width= i_width) table.cell(displayGear5,10,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,10,29, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,10,30, bgcolor = color.rgb(173,175,178),height = i_height,width= i_width) table.cell(displayGear5,11,6, bgcolor = color.rgb(135,188,214),height = i_height,width= i_width) table.cell(displayGear5,11,7, bgcolor = color.rgb(165,205,215),height = i_height,width= i_width) table.cell(displayGear5,11,8, bgcolor = color.rgb(211,224,228),height = i_height,width= i_width) table.cell(displayGear5,11,9, bgcolor = color.rgb(251,252,254),height = i_height,width= i_width) table.cell(displayGear5,11,10, bgcolor = color.rgb(186,212,220),height = i_height,width= i_width) table.cell(displayGear5,11,11, bgcolor = color.rgb(241,244,246),height = i_height,width= i_width) table.cell(displayGear5,11,12, bgcolor = color.rgb(213,237,253),height = i_height,width= i_width) table.cell(displayGear5,11,13, bgcolor = color.rgb(119,171,194),height = i_height,width= i_width) table.cell(displayGear5,11,14, bgcolor = color.rgb(191,194,176),height = i_height,width= i_width) table.cell(displayGear5,11,15, bgcolor = color.rgb(255,232,182),height = i_height,width= i_width) table.cell(displayGear5,11,16, bgcolor = color.rgb(226,161,109),height = i_height,width= i_width) table.cell(displayGear5,11,17, bgcolor = color.rgb(181,143,115),height = i_height,width= i_width) table.cell(displayGear5,11,18, bgcolor = color.rgb(136,196,219),height = i_height,width= i_width) table.cell(displayGear5,11,19, bgcolor = color.rgb(179,212,222),height = i_height,width= i_width) table.cell(displayGear5,11,20, bgcolor = color.rgb(247,247,248),height = i_height,width= i_width) table.cell(displayGear5,11,21, bgcolor = color.rgb(203,220,228),height = i_height,width= i_width) table.cell(displayGear5,11,22, bgcolor = color.rgb(182,209,217),height = i_height,width= i_width) table.cell(displayGear5,11,23, bgcolor = color.rgb(109,163,190),height = i_height,width= i_width) table.cell(displayGear5,11,24, bgcolor = color.rgb(79,143,176),height = i_height,width= i_width) table.cell(displayGear5,11,25, bgcolor = color.rgb(155,202,211),height = i_height,width= i_width) table.cell(displayGear5,11,26, bgcolor = color.rgb(208,235,243),height = i_height,width= i_width) table.cell(displayGear5,11,27, bgcolor = color.rgb(242,249,254),height = i_height,width= i_width) f_200()=> table.cell(displayGear5,11,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,11,29, bgcolor = color.rgb(255,255,254),height = i_height,width= i_width) table.cell(displayGear5,11,30, bgcolor = color.rgb(193,232,245),height = i_height,width= i_width) table.cell(displayGear5,12,4, bgcolor = color.rgb(203,229,241),height = i_height,width= i_width) table.cell(displayGear5,12,5, bgcolor = color.rgb(198,221,234),height = i_height,width= i_width) table.cell(displayGear5,12,6, bgcolor = color.rgb(180,205,213),height = i_height,width= i_width) table.cell(displayGear5,12,7, bgcolor = color.rgb(198,219,224),height = i_height,width= i_width) table.cell(displayGear5,12,8, bgcolor = color.rgb(237,246,246),height = i_height,width= i_width) table.cell(displayGear5,12,9, bgcolor = color.rgb(241,245,244),height = i_height,width= i_width) table.cell(displayGear5,12,10, bgcolor = color.rgb(186,210,221),height = i_height,width= i_width) table.cell(displayGear5,12,11, bgcolor = color.rgb(226,242,250),height = i_height,width= i_width) table.cell(displayGear5,12,12, bgcolor = color.rgb(184,207,213),height = i_height,width= i_width) table.cell(displayGear5,12,13, bgcolor = color.rgb(213,201,172),height = i_height,width= i_width) table.cell(displayGear5,12,14, bgcolor = color.rgb(255,223,181),height = i_height,width= i_width) table.cell(displayGear5,12,15, bgcolor = color.rgb(221,175,130),height = i_height,width= i_width) table.cell(displayGear5,12,17, bgcolor = color.rgb(141,112,91),height = i_height,width= i_width) table.cell(displayGear5,12,18, bgcolor = color.rgb(100,185,229),height = i_height,width= i_width) table.cell(displayGear5,12,19, bgcolor = color.rgb(118,169,189),height = i_height,width= i_width) table.cell(displayGear5,12,20, bgcolor = color.rgb(183,206,216),height = i_height,width= i_width) table.cell(displayGear5,12,21, bgcolor = color.rgb(236,242,243),height = i_height,width= i_width) table.cell(displayGear5,12,22, bgcolor = color.rgb(166,198,210),height = i_height,width= i_width) table.cell(displayGear5,12,23, bgcolor = color.rgb(120,169,193),height = i_height,width= i_width) table.cell(displayGear5,12,24, bgcolor = color.rgb(127,171,191),height = i_height,width= i_width) table.cell(displayGear5,12,25, bgcolor = color.rgb(184,215,223),height = i_height,width= i_width) table.cell(displayGear5,12,26, bgcolor = color.rgb(249,253,254),height = i_height,width= i_width) table.cell(displayGear5,12,27, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,12,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,12,29, bgcolor = color.rgb(226,238,240),height = i_height,width= i_width) table.cell(displayGear5,12,30, bgcolor = color.rgb(176,220,240),height = i_height,width= i_width) table.cell(displayGear5,12,31, bgcolor = color.rgb(93,128,139),height = i_height,width= i_width) table.cell(displayGear5,13,4, bgcolor = color.rgb(114,108,107),height = i_height,width= i_width) table.cell(displayGear5,13,5, bgcolor = color.rgb(252,255,255),height = i_height,width= i_width) table.cell(displayGear5,13,6, bgcolor = color.rgb(189,214,220),height = i_height,width= i_width) table.cell(displayGear5,13,7, bgcolor = color.rgb(237,242,243),height = i_height,width= i_width) table.cell(displayGear5,13,8, bgcolor = color.rgb(186,213,216),height = i_height,width= i_width) table.cell(displayGear5,13,9, bgcolor = color.rgb(175,203,215),height = i_height,width= i_width) table.cell(displayGear5,13,10, bgcolor = color.rgb(181,209,222),height = i_height,width= i_width) table.cell(displayGear5,13,11, bgcolor = color.rgb(176,199,208),height = i_height,width= i_width) table.cell(displayGear5,13,12, bgcolor = color.rgb(194,154,119),height = i_height,width= i_width) table.cell(displayGear5,13,13, bgcolor = color.rgb(249,205,155),height = i_height,width= i_width) table.cell(displayGear5,13,14, bgcolor = color.rgb(226,178,135),height = i_height,width= i_width) table.cell(displayGear5,13,17, bgcolor = color.rgb(164,122,92),height = i_height,width= i_width) table.cell(displayGear5,13,18, bgcolor = color.rgb(182,215,232),height = i_height,width= i_width) table.cell(displayGear5,13,19, bgcolor = color.rgb(155,201,227),height = i_height,width= i_width) table.cell(displayGear5,13,20, bgcolor = color.rgb(128,179,199),height = i_height,width= i_width) table.cell(displayGear5,13,21, bgcolor = color.rgb(181,211,222),height = i_height,width= i_width) table.cell(displayGear5,13,22, bgcolor = color.rgb(114,169,195),height = i_height,width= i_width) table.cell(displayGear5,13,23, bgcolor = color.rgb(169,203,215),height = i_height,width= i_width) table.cell(displayGear5,13,24, bgcolor = color.rgb(239,244,243),height = i_height,width= i_width) table.cell(displayGear5,13,25, bgcolor = color.rgb(248,246,248),height = i_height,width= i_width) table.cell(displayGear5,13,26, bgcolor = color.rgb(253,252,253),height = i_height,width= i_width) table.cell(displayGear5,13,27, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,13,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,13,29, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,13,30, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,13,31, bgcolor = color.rgb(173,179,180),height = i_height,width= i_width) table.cell(displayGear5,14,4, bgcolor = color.rgb(105,100,100),height = i_height,width= i_width) table.cell(displayGear5,14,5, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,6, bgcolor = color.rgb(181,211,220),height = i_height,width= i_width) table.cell(displayGear5,14,7, bgcolor = color.rgb(202,221,227),height = i_height,width= i_width) table.cell(displayGear5,14,8, bgcolor = color.rgb(249,251,250),height = i_height,width= i_width) table.cell(displayGear5,14,9, bgcolor = color.rgb(181,214,225),height = i_height,width= i_width) table.cell(displayGear5,14,10, bgcolor = color.rgb(161,201,221),height = i_height,width= i_width) table.cell(displayGear5,14,11, bgcolor = color.rgb(191,156,120),height = i_height,width= i_width) table.cell(displayGear5,14,12, bgcolor = color.rgb(242,189,139),height = i_height,width= i_width) table.cell(displayGear5,14,13, bgcolor = color.rgb(254,232,181),height = i_height,width= i_width) table.cell(displayGear5,14,14, bgcolor = color.rgb(188,135,107),height = i_height,width= i_width) table.cell(displayGear5,14,16, bgcolor = color.rgb(205,162,113),height = i_height,width= i_width) table.cell(displayGear5,14,18, bgcolor = color.rgb(174,120,81),height = i_height,width= i_width) table.cell(displayGear5,14,19, bgcolor = color.rgb(177,216,223),height = i_height,width= i_width) table.cell(displayGear5,14,20, bgcolor = color.rgb(186,211,218),height = i_height,width= i_width) table.cell(displayGear5,14,21, bgcolor = color.rgb(238,246,247),height = i_height,width= i_width) table.cell(displayGear5,14,22, bgcolor = color.rgb(196,221,232),height = i_height,width= i_width) table.cell(displayGear5,14,23, bgcolor = color.rgb(187,221,231),height = i_height,width= i_width) table.cell(displayGear5,14,24, bgcolor = color.rgb(195,227,235),height = i_height,width= i_width) table.cell(displayGear5,14,25, bgcolor = color.rgb(189,223,226),height = i_height,width= i_width) table.cell(displayGear5,14,26, bgcolor = color.rgb(237,243,242),height = i_height,width= i_width) table.cell(displayGear5,14,27, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,28, bgcolor = color.rgb(254,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,29, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,30, bgcolor = color.rgb(224,233,236),height = i_height,width= i_width) table.cell(displayGear5,14,31, bgcolor = color.rgb(144,171,194),height = i_height,width= i_width) table.cell(displayGear5,14,32, bgcolor = color.rgb(119,174,189),height = i_height,width= i_width) table.cell(displayGear5,14,33, bgcolor = color.rgb(204,224,235),height = i_height,width= i_width) table.cell(displayGear5,14,34, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,35, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,36, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,14,37, bgcolor = color.rgb(205,226,232),height = i_height,width= i_width) table.cell(displayGear5,14,38, bgcolor = color.rgb(138,189,214),height = i_height,width= i_width) table.cell(displayGear5,15,5, bgcolor = color.rgb(199,226,230),height = i_height,width= i_width) table.cell(displayGear5,15,6, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,15,7, bgcolor = color.rgb(252,252,252),height = i_height,width= i_width) table.cell(displayGear5,15,8, bgcolor = color.rgb(246,249,252),height = i_height,width= i_width) table.cell(displayGear5,15,9, bgcolor = color.rgb(168,201,213),height = i_height,width= i_width) table.cell(displayGear5,15,10, bgcolor = color.rgb(109,160,183),height = i_height,width= i_width) table.cell(displayGear5,15,11, bgcolor = color.rgb(214,195,161),height = i_height,width= i_width) table.cell(displayGear5,15,12, bgcolor = color.rgb(255,225,172),height = i_height,width= i_width) table.cell(displayGear5,15,13, bgcolor = color.rgb(223,165,115),height = i_height,width= i_width) table.cell(displayGear5,15,14, bgcolor = color.rgb(224,205,197),height = i_height,width= i_width) f_300()=> table.cell(displayGear5,15,17, bgcolor = color.rgb(255,210,164),height = i_height,width= i_width) table.cell(displayGear5,15,18, bgcolor = color.rgb(198,136,87),height = i_height,width= i_width) table.cell(displayGear5,15,19, bgcolor = color.rgb(203,142,95),height = i_height,width= i_width) table.cell(displayGear5,15,20, bgcolor = color.rgb(200,155,125),height = i_height,width= i_width) table.cell(displayGear5,15,21, bgcolor = color.rgb(192,211,223),height = i_height,width= i_width) table.cell(displayGear5,15,22, bgcolor = color.rgb(251,255,246),height = i_height,width= i_width) table.cell(displayGear5,15,23, bgcolor = color.rgb(255,255,250),height = i_height,width= i_width) table.cell(displayGear5,15,24, bgcolor = color.rgb(242,245,247),height = i_height,width= i_width) table.cell(displayGear5,15,25, bgcolor = color.rgb(240,248,252),height = i_height,width= i_width) table.cell(displayGear5,15,26, bgcolor = color.rgb(246,255,252),height = i_height,width= i_width) table.cell(displayGear5,15,27, bgcolor = color.rgb(249,255,255),height = i_height,width= i_width) table.cell(displayGear5,15,28, bgcolor = color.rgb(211,227,232),height = i_height,width= i_width) table.cell(displayGear5,15,29, bgcolor = color.rgb(139,189,198),height = i_height,width= i_width) table.cell(displayGear5,15,30, bgcolor = color.rgb(78,104,161),height = i_height,width= i_width) table.cell(displayGear5,15,31, bgcolor = color.rgb(142,124,172),height = i_height,width= i_width) table.cell(displayGear5,15,32, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,15,33, bgcolor = color.rgb(253,255,255),height = i_height,width= i_width) table.cell(displayGear5,15,34, bgcolor = color.rgb(255,255,249),height = i_height,width= i_width) table.cell(displayGear5,15,35, bgcolor = color.rgb(255,255,250),height = i_height,width= i_width) table.cell(displayGear5,15,36, bgcolor = color.rgb(254,255,255),height = i_height,width= i_width) table.cell(displayGear5,15,37, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,15,38, bgcolor = color.rgb(210,231,244),height = i_height,width= i_width) table.cell(displayGear5,15,39, bgcolor = color.rgb(140,191,220),height = i_height,width= i_width) table.cell(displayGear5,16,6, bgcolor = color.rgb(198,229,237),height = i_height,width= i_width) table.cell(displayGear5,16,7, bgcolor = color.rgb(192,217,225),height = i_height,width= i_width) table.cell(displayGear5,16,8, bgcolor = color.rgb(174,209,221),height = i_height,width= i_width) table.cell(displayGear5,16,9, bgcolor = color.rgb(117,171,194),height = i_height,width= i_width) table.cell(displayGear5,16,10, bgcolor = color.rgb(180,144,113),height = i_height,width= i_width) table.cell(displayGear5,16,11, bgcolor = color.rgb(241,206,158),height = i_height,width= i_width) table.cell(displayGear5,16,12, bgcolor = color.rgb(254,225,192),height = i_height,width= i_width) table.cell(displayGear5,16,13, bgcolor = color.rgb(208,149,97),height = i_height,width= i_width) table.cell(displayGear5,16,14, bgcolor = color.rgb(255,239,219),height = i_height,width= i_width) table.cell(displayGear5,16,15, bgcolor = color.rgb(84,112,117),height = i_height,width= i_width) table.cell(displayGear5,16,17, bgcolor = color.rgb(255,217,216),height = i_height,width= i_width) table.cell(displayGear5,16,18, bgcolor = color.rgb(221,179,130),height = i_height,width= i_width) table.cell(displayGear5,16,20, bgcolor = color.rgb(204,145,110),height = i_height,width= i_width) table.cell(displayGear5,16,21, bgcolor = color.rgb(223,166,182),height = i_height,width= i_width) table.cell(displayGear5,16,22, bgcolor = color.rgb(247,213,178),height = i_height,width= i_width) table.cell(displayGear5,16,23, bgcolor = color.rgb(251,217,179),height = i_height,width= i_width) table.cell(displayGear5,16,24, bgcolor = color.rgb(236,173,187),height = i_height,width= i_width) table.cell(displayGear5,16,25, bgcolor = color.rgb(197,196,210),height = i_height,width= i_width) table.cell(displayGear5,16,26, bgcolor = color.rgb(189,221,223),height = i_height,width= i_width) table.cell(displayGear5,16,27, bgcolor = color.rgb(151,196,212),height = i_height,width= i_width) table.cell(displayGear5,16,28, bgcolor = color.rgb(104,119,168),height = i_height,width= i_width) table.cell(displayGear5,16,30, bgcolor = color.rgb(117,115,170),height = i_height,width= i_width) table.cell(displayGear5,16,31, bgcolor = color.rgb(217,231,235),height = i_height,width= i_width) table.cell(displayGear5,16,32, bgcolor = color.rgb(244,255,255),height = i_height,width= i_width) table.cell(displayGear5,16,33, bgcolor = color.rgb(185,200,200),height = i_height,width= i_width) table.cell(displayGear5,16,34, bgcolor = color.rgb(211,151,100),height = i_height,width= i_width) table.cell(displayGear5,16,35, bgcolor = color.rgb(202,151,108),height = i_height,width= i_width) table.cell(displayGear5,16,36, bgcolor = color.rgb(127,168,191),height = i_height,width= i_width) table.cell(displayGear5,16,37, bgcolor = color.rgb(169,207,216),height = i_height,width= i_width) table.cell(displayGear5,16,38, bgcolor = color.rgb(186,211,217),height = i_height,width= i_width) table.cell(displayGear5,16,39, bgcolor = color.rgb(198,242,255),height = i_height,width= i_width) table.cell(displayGear5,17,4, bgcolor = color.rgb(218,228,233),height = i_height,width= i_width) table.cell(displayGear5,17,5, bgcolor = color.rgb(220,222,223),height = i_height,width= i_width) table.cell(displayGear5,17,6, bgcolor = color.rgb(163,199,210),height = i_height,width= i_width) table.cell(displayGear5,17,7, bgcolor = color.rgb(185,212,223),height = i_height,width= i_width) table.cell(displayGear5,17,8, bgcolor = color.rgb(236,244,246),height = i_height,width= i_width) table.cell(displayGear5,17,9, bgcolor = color.rgb(185,204,213),height = i_height,width= i_width) table.cell(displayGear5,17,10, bgcolor = color.rgb(235,197,159),height = i_height,width= i_width) table.cell(displayGear5,17,11, bgcolor = color.rgb(252,211,162),height = i_height,width= i_width) table.cell(displayGear5,17,12, bgcolor = color.rgb(250,225,182),height = i_height,width= i_width) table.cell(displayGear5,17,14, bgcolor = color.rgb(249,212,188),height = i_height,width= i_width) table.cell(displayGear5,17,15, bgcolor = color.rgb(99,125,124),height = i_height,width= i_width) table.cell(displayGear5,17,17, bgcolor = color.rgb(255,208,226),height = i_height,width= i_width) table.cell(displayGear5,17,18, bgcolor = color.rgb(222,182,131),height = i_height,width= i_width) table.cell(displayGear5,17,20, bgcolor = color.rgb(215,161,112),height = i_height,width= i_width) table.cell(displayGear5,17,21, bgcolor = color.rgb(246,201,177),height = i_height,width= i_width) table.cell(displayGear5,17,22, bgcolor = color.rgb(231,162,183),height = i_height,width= i_width) table.cell(displayGear5,17,23, bgcolor = color.rgb(228,156,175),height = i_height,width= i_width) table.cell(displayGear5,17,24, bgcolor = color.rgb(243,196,174),height = i_height,width= i_width) table.cell(displayGear5,17,25, bgcolor = color.rgb(209,163,124),height = i_height,width= i_width) table.cell(displayGear5,17,26, bgcolor = color.rgb(190,146,103),height = i_height,width= i_width) table.cell(displayGear5,17,27, bgcolor = color.rgb(204,151,93),height = i_height,width= i_width) table.cell(displayGear5,17,28, bgcolor = color.rgb(162,124,156),height = i_height,width= i_width) table.cell(displayGear5,17,30, bgcolor = color.rgb(158,139,177),height = i_height,width= i_width) table.cell(displayGear5,17,31, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,17,32, bgcolor = color.rgb(232,224,213),height = i_height,width= i_width) table.cell(displayGear5,17,33, bgcolor = color.rgb(200,146,97),height = i_height,width= i_width) table.cell(displayGear5,17,34, bgcolor = color.rgb(236,199,155),height = i_height,width= i_width) table.cell(displayGear5,17,35, bgcolor = color.rgb(230,203,159),height = i_height,width= i_width) table.cell(displayGear5,17,36, bgcolor = color.rgb(222,200,164),height = i_height,width= i_width) table.cell(displayGear5,17,37, bgcolor = color.rgb(203,153,115),height = i_height,width= i_width) table.cell(displayGear5,17,38, bgcolor = color.rgb(124,154,171),height = i_height,width= i_width) table.cell(displayGear5,17,39, bgcolor = color.rgb(161,211,228),height = i_height,width= i_width) table.cell(displayGear5,17,40, bgcolor = color.rgb(150,200,213),height = i_height,width= i_width) table.cell(displayGear5,18,4, bgcolor = color.rgb(106,126,132),height = i_height,width= i_width) table.cell(displayGear5,18,5, bgcolor = color.rgb(244,255,255),height = i_height,width= i_width) table.cell(displayGear5,18,6, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,18,7, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,18,8, bgcolor = color.rgb(249,243,237),height = i_height,width= i_width) table.cell(displayGear5,18,9, bgcolor = color.rgb(213,160,120),height = i_height,width= i_width) table.cell(displayGear5,18,10, bgcolor = color.rgb(238,208,157),height = i_height,width= i_width) table.cell(displayGear5,18,11, bgcolor = color.rgb(217,168,130),height = i_height,width= i_width) table.cell(displayGear5,18,12, bgcolor = color.rgb(244,207,166),height = i_height,width= i_width) table.cell(displayGear5,18,14, bgcolor = color.rgb(244,206,183),height = i_height,width= i_width) table.cell(displayGear5,18,15, bgcolor = color.rgb(103,131,134),height = i_height,width= i_width) table.cell(displayGear5,18,17, bgcolor = color.rgb(229,136,133),height = i_height,width= i_width) f_400()=> table.cell(displayGear5,18,18, bgcolor = color.rgb(202,180,140),height = i_height,width= i_width) table.cell(displayGear5,18,19, bgcolor = color.rgb(176,181,174),height = i_height,width= i_width) table.cell(displayGear5,18,20, bgcolor = color.rgb(213,156,104),height = i_height,width= i_width) table.cell(displayGear5,18,21, bgcolor = color.rgb(247,216,173),height = i_height,width= i_width) table.cell(displayGear5,18,22, bgcolor = color.rgb(229,152,189),height = i_height,width= i_width) table.cell(displayGear5,18,23, bgcolor = color.rgb(195,114,150),height = i_height,width= i_width) table.cell(displayGear5,18,24, bgcolor = color.rgb(239,206,171),height = i_height,width= i_width) table.cell(displayGear5,18,25, bgcolor = color.rgb(219,169,111),height = i_height,width= i_width) table.cell(displayGear5,18,26, bgcolor = color.rgb(206,139,88),height = i_height,width= i_width) table.cell(displayGear5,18,28, bgcolor = color.rgb(168,107,139),height = i_height,width= i_width) table.cell(displayGear5,18,30, bgcolor = color.rgb(155,139,181),height = i_height,width= i_width) table.cell(displayGear5,18,31, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,18,32, bgcolor = color.rgb(234,218,200),height = i_height,width= i_width) table.cell(displayGear5,18,33, bgcolor = color.rgb(207,142,89),height = i_height,width= i_width) table.cell(displayGear5,18,34, bgcolor = color.rgb(249,216,173),height = i_height,width= i_width) table.cell(displayGear5,18,35, bgcolor = color.rgb(250,219,179),height = i_height,width= i_width) table.cell(displayGear5,18,36, bgcolor = color.rgb(253,217,169),height = i_height,width= i_width) table.cell(displayGear5,18,37, bgcolor = color.rgb(245,204,153),height = i_height,width= i_width) table.cell(displayGear5,18,38, bgcolor = color.rgb(225,206,173),height = i_height,width= i_width) table.cell(displayGear5,18,39, bgcolor = color.rgb(208,171,139),height = i_height,width= i_width) table.cell(displayGear5,18,40, bgcolor = color.rgb(178,122,86),height = i_height,width= i_width) table.cell(displayGear5,19,5, bgcolor = color.rgb(88,103,107),height = i_height,width= i_width) table.cell(displayGear5,19,6, bgcolor = color.rgb(229,250,255),height = i_height,width= i_width) table.cell(displayGear5,19,7, bgcolor = color.rgb(204,228,236),height = i_height,width= i_width) table.cell(displayGear5,19,8, bgcolor = color.rgb(184,207,217),height = i_height,width= i_width) table.cell(displayGear5,19,9, bgcolor = color.rgb(181,192,193),height = i_height,width= i_width) table.cell(displayGear5,19,10, bgcolor = color.rgb(237,212,173),height = i_height,width= i_width) table.cell(displayGear5,19,11, bgcolor = color.rgb(219,148,102),height = i_height,width= i_width) table.cell(displayGear5,19,12, bgcolor = color.rgb(243,203,160),height = i_height,width= i_width) table.cell(displayGear5,19,14, bgcolor = color.rgb(214,185,172),height = i_height,width= i_width) table.cell(displayGear5,19,18, bgcolor = color.rgb(195,149,114),height = i_height,width= i_width) table.cell(displayGear5,19,19, bgcolor = color.rgb(229,219,218),height = i_height,width= i_width) table.cell(displayGear5,19,21, bgcolor = color.rgb(240,208,163),height = i_height,width= i_width) table.cell(displayGear5,19,22, bgcolor = color.rgb(196,120,146),height = i_height,width= i_width) table.cell(displayGear5,19,23, bgcolor = color.rgb(188,101,129),height = i_height,width= i_width) table.cell(displayGear5,19,24, bgcolor = color.rgb(241,204,172),height = i_height,width= i_width) table.cell(displayGear5,19,25, bgcolor = color.rgb(219,171,118),height = i_height,width= i_width) table.cell(displayGear5,19,26, bgcolor = color.rgb(209,143,83),height = i_height,width= i_width) table.cell(displayGear5,19,27, bgcolor = color.rgb(168,125,152),height = i_height,width= i_width) table.cell(displayGear5,19,28, bgcolor = color.rgb(118,77,174),height = i_height,width= i_width) table.cell(displayGear5,19,29, bgcolor = color.rgb(79,96,158),height = i_height,width= i_width) table.cell(displayGear5,19,30, bgcolor = color.rgb(165,196,210),height = i_height,width= i_width) table.cell(displayGear5,19,31, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,19,32, bgcolor = color.rgb(233,245,248),height = i_height,width= i_width) table.cell(displayGear5,19,33, bgcolor = color.rgb(176,177,171),height = i_height,width= i_width) table.cell(displayGear5,19,34, bgcolor = color.rgb(210,155,102),height = i_height,width= i_width) table.cell(displayGear5,19,35, bgcolor = color.rgb(241,208,163),height = i_height,width= i_width) table.cell(displayGear5,19,36, bgcolor = color.rgb(247,215,175),height = i_height,width= i_width) table.cell(displayGear5,19,37, bgcolor = color.rgb(248,219,177),height = i_height,width= i_width) table.cell(displayGear5,19,38, bgcolor = color.rgb(254,226,178),height = i_height,width= i_width) table.cell(displayGear5,19,39, bgcolor = color.rgb(250,212,166),height = i_height,width= i_width) table.cell(displayGear5,19,40, bgcolor = color.rgb(212,147,95),height = i_height,width= i_width) table.cell(displayGear5,19,42, bgcolor = color.rgb(221,172,132),height = i_height,width= i_width) table.cell(displayGear5,19,43, bgcolor = color.rgb(185,173,138),height = i_height,width= i_width) table.cell(displayGear5,19,44, bgcolor = color.rgb(159,158,105),height = i_height,width= i_width) table.cell(displayGear5,19,45, bgcolor = color.rgb(114,113,83),height = i_height,width= i_width) table.cell(displayGear5,20,8, bgcolor = color.rgb(177,215,220),height = i_height,width= i_width) table.cell(displayGear5,20,9, bgcolor = color.rgb(241,255,255),height = i_height,width= i_width) table.cell(displayGear5,20,10, bgcolor = color.rgb(224,170,126),height = i_height,width= i_width) table.cell(displayGear5,20,12, bgcolor = color.rgb(202,136,87),height = i_height,width= i_width) table.cell(displayGear5,20,13, bgcolor = color.rgb(216,153,95),height = i_height,width= i_width) table.cell(displayGear5,20,18, bgcolor = color.rgb(126,168,195),height = i_height,width= i_width) table.cell(displayGear5,20,19, bgcolor = color.rgb(224,236,237),height = i_height,width= i_width) table.cell(displayGear5,20,20, bgcolor = color.rgb(237,203,204),height = i_height,width= i_width) table.cell(displayGear5,20,21, bgcolor = color.rgb(206,126,132),height = i_height,width= i_width) table.cell(displayGear5,20,22, bgcolor = color.rgb(197,128,95),height = i_height,width= i_width) table.cell(displayGear5,20,23, bgcolor = color.rgb(191,105,125),height = i_height,width= i_width) table.cell(displayGear5,20,25, bgcolor = color.rgb(230,195,141),height = i_height,width= i_width) table.cell(displayGear5,20,27, bgcolor = color.rgb(146,94,160),height = i_height,width= i_width) table.cell(displayGear5,20,29, bgcolor = color.rgb(122,133,160),height = i_height,width= i_width) table.cell(displayGear5,20,30, bgcolor = color.rgb(176,225,228),height = i_height,width= i_width) table.cell(displayGear5,20,31, bgcolor = color.rgb(220,231,234),height = i_height,width= i_width) table.cell(displayGear5,20,32, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,20,33, bgcolor = color.rgb(222,239,242),height = i_height,width= i_width) table.cell(displayGear5,20,34, bgcolor = color.rgb(169,186,189),height = i_height,width= i_width) table.cell(displayGear5,20,35, bgcolor = color.rgb(182,200,196),height = i_height,width= i_width) table.cell(displayGear5,20,36, bgcolor = color.rgb(215,157,109),height = i_height,width= i_width) table.cell(displayGear5,20,37, bgcolor = color.rgb(215,147,98),height = i_height,width= i_width) table.cell(displayGear5,20,38, bgcolor = color.rgb(212,154,104),height = i_height,width= i_width) table.cell(displayGear5,20,39, bgcolor = color.rgb(247,219,177),height = i_height,width= i_width) table.cell(displayGear5,20,40, bgcolor = color.rgb(219,177,139),height = i_height,width= i_width) table.cell(displayGear5,20,41, bgcolor = color.rgb(220,172,128),height = i_height,width= i_width) table.cell(displayGear5,20,42, bgcolor = color.rgb(246,220,171),height = i_height,width= i_width) table.cell(displayGear5,20,43, bgcolor = color.rgb(187,182,127),height = i_height,width= i_width) table.cell(displayGear5,20,44, bgcolor = color.rgb(130,128,77),height = i_height,width= i_width) table.cell(displayGear5,20,45, bgcolor = color.rgb(130,127,80),height = i_height,width= i_width) table.cell(displayGear5,20,46, bgcolor = color.rgb(151,146,102),height = i_height,width= i_width) table.cell(displayGear5,21,7, bgcolor = color.rgb(162,185,188),height = i_height,width= i_width) table.cell(displayGear5,21,8, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,21,9, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,21,10, bgcolor = color.rgb(194,196,192),height = i_height,width= i_width) table.cell(displayGear5,21,11, bgcolor = color.rgb(167,174,170),height = i_height,width= i_width) table.cell(displayGear5,21,12, bgcolor = color.rgb(176,183,181),height = i_height,width= i_width) table.cell(displayGear5,21,13, bgcolor = color.rgb(201,212,204),height = i_height,width= i_width) table.cell(displayGear5,21,14, bgcolor = color.rgb(135,153,156),height = i_height,width= i_width) table.cell(displayGear5,21,15, bgcolor = color.rgb(137,143,147),height = i_height,width= i_width) table.cell(displayGear5,21,16, bgcolor = color.rgb(236,208,189),height = i_height,width= i_width) table.cell(displayGear5,21,17, bgcolor = color.rgb(219,214,210),height = i_height,width= i_width) table.cell(displayGear5,21,18, bgcolor = color.rgb(127,191,215),height = i_height,width= i_width) f_500()=> table.cell(displayGear5,21,19, bgcolor = color.rgb(120,175,200),height = i_height,width= i_width) table.cell(displayGear5,21,20, bgcolor = color.rgb(147,191,217),height = i_height,width= i_width) table.cell(displayGear5,21,21, bgcolor = color.rgb(193,186,202),height = i_height,width= i_width) table.cell(displayGear5,21,22, bgcolor = color.rgb(250,231,216),height = i_height,width= i_width) table.cell(displayGear5,21,23, bgcolor = color.rgb(188,190,202),height = i_height,width= i_width) table.cell(displayGear5,21,24, bgcolor = color.rgb(206,176,141),height = i_height,width= i_width) table.cell(displayGear5,21,25, bgcolor = color.rgb(218,161,115),height = i_height,width= i_width) table.cell(displayGear5,21,26, bgcolor = color.rgb(231,191,131),height = i_height,width= i_width) table.cell(displayGear5,21,27, bgcolor = color.rgb(146,119,155),height = i_height,width= i_width) table.cell(displayGear5,21,29, bgcolor = color.rgb(153,147,184),height = i_height,width= i_width) table.cell(displayGear5,21,30, bgcolor = color.rgb(151,202,216),height = i_height,width= i_width) table.cell(displayGear5,21,31, bgcolor = color.rgb(122,170,192),height = i_height,width= i_width) table.cell(displayGear5,21,32, bgcolor = color.rgb(228,235,235),height = i_height,width= i_width) table.cell(displayGear5,21,33, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,21,34, bgcolor = color.rgb(239,254,255),height = i_height,width= i_width) table.cell(displayGear5,21,35, bgcolor = color.rgb(231,239,243),height = i_height,width= i_width) table.cell(displayGear5,21,36, bgcolor = color.rgb(185,191,191),height = i_height,width= i_width) table.cell(displayGear5,21,37, bgcolor = color.rgb(175,186,187),height = i_height,width= i_width) table.cell(displayGear5,21,39, bgcolor = color.rgb(205,132,78),height = i_height,width= i_width) table.cell(displayGear5,21,40, bgcolor = color.rgb(241,203,162),height = i_height,width= i_width) table.cell(displayGear5,21,41, bgcolor = color.rgb(227,205,160),height = i_height,width= i_width) table.cell(displayGear5,21,42, bgcolor = color.rgb(165,161,113),height = i_height,width= i_width) table.cell(displayGear5,21,46, bgcolor = color.rgb(137,133,80),height = i_height,width= i_width) table.cell(displayGear5,21,47, bgcolor = color.rgb(140,136,84),height = i_height,width= i_width) table.cell(displayGear5,22,7, bgcolor = color.rgb(91,100,102),height = i_height,width= i_width) table.cell(displayGear5,22,8, bgcolor = color.rgb(84,79,78),height = i_height,width= i_width) table.cell(displayGear5,22,10, bgcolor = color.rgb(114,165,191),height = i_height,width= i_width) table.cell(displayGear5,22,11, bgcolor = color.rgb(195,246,255),height = i_height,width= i_width) table.cell(displayGear5,22,12, bgcolor = color.rgb(214,249,255),height = i_height,width= i_width) table.cell(displayGear5,22,13, bgcolor = color.rgb(132,192,220),height = i_height,width= i_width) table.cell(displayGear5,22,14, bgcolor = color.rgb(115,182,212),height = i_height,width= i_width) table.cell(displayGear5,22,15, bgcolor = color.rgb(224,246,255),height = i_height,width= i_width) table.cell(displayGear5,22,16, bgcolor = color.rgb(204,231,237),height = i_height,width= i_width) table.cell(displayGear5,22,17, bgcolor = color.rgb(197,222,238),height = i_height,width= i_width) table.cell(displayGear5,22,18, bgcolor = color.rgb(216,234,235),height = i_height,width= i_width) table.cell(displayGear5,22,19, bgcolor = color.rgb(110,173,205),height = i_height,width= i_width) table.cell(displayGear5,22,20, bgcolor = color.rgb(145,190,209),height = i_height,width= i_width) table.cell(displayGear5,22,21, bgcolor = color.rgb(118,181,202),height = i_height,width= i_width) table.cell(displayGear5,22,22, bgcolor = color.rgb(149,198,224),height = i_height,width= i_width) table.cell(displayGear5,22,23, bgcolor = color.rgb(230,251,253),height = i_height,width= i_width) table.cell(displayGear5,22,24, bgcolor = color.rgb(228,197,152),height = i_height,width= i_width) table.cell(displayGear5,22,25, bgcolor = color.rgb(225,178,129),height = i_height,width= i_width) table.cell(displayGear5,22,26, bgcolor = color.rgb(224,176,130),height = i_height,width= i_width) table.cell(displayGear5,22,27, bgcolor = color.rgb(226,195,153),height = i_height,width= i_width) table.cell(displayGear5,22,28, bgcolor = color.rgb(119,90,142),height = i_height,width= i_width) table.cell(displayGear5,22,29, bgcolor = color.rgb(158,141,197),height = i_height,width= i_width) table.cell(displayGear5,22,30, bgcolor = color.rgb(232,252,243),height = i_height,width= i_width) table.cell(displayGear5,22,31, bgcolor = color.rgb(109,162,184),height = i_height,width= i_width) table.cell(displayGear5,22,32, bgcolor = color.rgb(114,167,191),height = i_height,width= i_width) table.cell(displayGear5,22,33, bgcolor = color.rgb(216,228,232),height = i_height,width= i_width) table.cell(displayGear5,22,34, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,22,35, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,22,36, bgcolor = color.rgb(192,226,241),height = i_height,width= i_width) table.cell(displayGear5,22,37, bgcolor = color.rgb(183,224,243),height = i_height,width= i_width) table.cell(displayGear5,22,38, bgcolor = color.rgb(136,175,191),height = i_height,width= i_width) table.cell(displayGear5,22,40, bgcolor = color.rgb(209,159,101),height = i_height,width= i_width) table.cell(displayGear5,22,41, bgcolor = color.rgb(167,174,126),height = i_height,width= i_width) table.cell(displayGear5,22,48, bgcolor = color.rgb(135,129,84),height = i_height,width= i_width) table.cell(displayGear5,23,10, bgcolor = color.rgb(169,220,239),height = i_height,width= i_width) table.cell(displayGear5,23,11, bgcolor = color.rgb(93,109,112),height = i_height,width= i_width) table.cell(displayGear5,23,13, bgcolor = color.rgb(126,138,155),height = i_height,width= i_width) table.cell(displayGear5,23,14, bgcolor = color.rgb(213,242,255),height = i_height,width= i_width) table.cell(displayGear5,23,15, bgcolor = color.rgb(205,236,244),height = i_height,width= i_width) table.cell(displayGear5,23,16, bgcolor = color.rgb(164,206,224),height = i_height,width= i_width) table.cell(displayGear5,23,17, bgcolor = color.rgb(179,233,254),height = i_height,width= i_width) table.cell(displayGear5,23,18, bgcolor = color.rgb(127,155,171),height = i_height,width= i_width) table.cell(displayGear5,23,20, bgcolor = color.rgb(169,215,235),height = i_height,width= i_width) table.cell(displayGear5,23,21, bgcolor = color.rgb(166,212,234),height = i_height,width= i_width) table.cell(displayGear5,23,22, bgcolor = color.rgb(134,180,201),height = i_height,width= i_width) table.cell(displayGear5,23,23, bgcolor = color.rgb(198,219,223),height = i_height,width= i_width) table.cell(displayGear5,23,24, bgcolor = color.rgb(204,147,106),height = i_height,width= i_width) table.cell(displayGear5,23,25, bgcolor = color.rgb(237,196,148),height = i_height,width= i_width) table.cell(displayGear5,23,26, bgcolor = color.rgb(240,209,171),height = i_height,width= i_width) table.cell(displayGear5,23,27, bgcolor = color.rgb(255,193,111),height = i_height,width= i_width) table.cell(displayGear5,23,28, bgcolor = color.rgb(186,169,148),height = i_height,width= i_width) table.cell(displayGear5,23,29, bgcolor = color.rgb(152,182,220),height = i_height,width= i_width) table.cell(displayGear5,23,30, bgcolor = color.rgb(239,248,245),height = i_height,width= i_width) table.cell(displayGear5,23,31, bgcolor = color.rgb(242,248,249),height = i_height,width= i_width) table.cell(displayGear5,23,32, bgcolor = color.rgb(196,215,224),height = i_height,width= i_width) table.cell(displayGear5,23,33, bgcolor = color.rgb(162,193,206),height = i_height,width= i_width) table.cell(displayGear5,23,34, bgcolor = color.rgb(147,182,204),height = i_height,width= i_width) table.cell(displayGear5,23,35, bgcolor = color.rgb(142,183,205),height = i_height,width= i_width) table.cell(displayGear5,23,36, bgcolor = color.rgb(139,182,198),height = i_height,width= i_width) table.cell(displayGear5,23,37, bgcolor = color.rgb(151,203,228),height = i_height,width= i_width) table.cell(displayGear5,23,40, bgcolor = color.rgb(156,134,81),height = i_height,width= i_width) table.cell(displayGear5,23,41, bgcolor = color.rgb(162,161,100),height = i_height,width= i_width) table.cell(displayGear5,23,46, bgcolor = color.rgb(121,119,76),height = i_height,width= i_width) table.cell(displayGear5,24,10, bgcolor = color.rgb(85,94,101),height = i_height,width= i_width) table.cell(displayGear5,24,13, bgcolor = color.rgb(158,209,229),height = i_height,width= i_width) table.cell(displayGear5,24,14, bgcolor = color.rgb(130,149,163),height = i_height,width= i_width) table.cell(displayGear5,24,17, bgcolor = color.rgb(79,90,99),height = i_height,width= i_width) table.cell(displayGear5,24,21, bgcolor = color.rgb(105,108,112),height = i_height,width= i_width) table.cell(displayGear5,24,22, bgcolor = color.rgb(240,246,244),height = i_height,width= i_width) table.cell(displayGear5,24,23, bgcolor = color.rgb(182,212,229),height = i_height,width= i_width) table.cell(displayGear5,24,24, bgcolor = color.rgb(191,147,113),height = i_height,width= i_width) table.cell(displayGear5,24,25, bgcolor = color.rgb(242,195,146),height = i_height,width= i_width) table.cell(displayGear5,24,26, bgcolor = color.rgb(247,209,155),height = i_height,width= i_width) table.cell(displayGear5,24,27, bgcolor = color.rgb(146,96,102),height = i_height,width= i_width) table.cell(displayGear5,24,28, bgcolor = color.rgb(196,178,195),height = i_height,width= i_width) f_600()=> table.cell(displayGear5,24,29, bgcolor = color.rgb(210,249,246),height = i_height,width= i_width) table.cell(displayGear5,24,30, bgcolor = color.rgb(158,192,204),height = i_height,width= i_width) table.cell(displayGear5,24,31, bgcolor = color.rgb(219,233,237),height = i_height,width= i_width) table.cell(displayGear5,24,32, bgcolor = color.rgb(220,233,239),height = i_height,width= i_width) table.cell(displayGear5,24,33, bgcolor = color.rgb(169,200,210),height = i_height,width= i_width) table.cell(displayGear5,24,34, bgcolor = color.rgb(136,175,196),height = i_height,width= i_width) table.cell(displayGear5,24,35, bgcolor = color.rgb(135,184,208),height = i_height,width= i_width) table.cell(displayGear5,24,36, bgcolor = color.rgb(122,184,214),height = i_height,width= i_width) table.cell(displayGear5,25,22, bgcolor = color.rgb(208,227,235),height = i_height,width= i_width) table.cell(displayGear5,25,23, bgcolor = color.rgb(186,218,233),height = i_height,width= i_width) table.cell(displayGear5,25,24, bgcolor = color.rgb(201,145,101),height = i_height,width= i_width) table.cell(displayGear5,25,25, bgcolor = color.rgb(249,200,146),height = i_height,width= i_width) table.cell(displayGear5,25,26, bgcolor = color.rgb(233,178,114),height = i_height,width= i_width) table.cell(displayGear5,25,28, bgcolor = color.rgb(124,131,202),height = i_height,width= i_width) table.cell(displayGear5,25,29, bgcolor = color.rgb(239,255,246),height = i_height,width= i_width) table.cell(displayGear5,25,30, bgcolor = color.rgb(239,246,245),height = i_height,width= i_width) table.cell(displayGear5,25,31, bgcolor = color.rgb(206,220,228),height = i_height,width= i_width) table.cell(displayGear5,25,32, bgcolor = color.rgb(162,193,209),height = i_height,width= i_width) table.cell(displayGear5,25,33, bgcolor = color.rgb(175,211,218),height = i_height,width= i_width) table.cell(displayGear5,25,34, bgcolor = color.rgb(202,225,229),height = i_height,width= i_width) table.cell(displayGear5,25,35, bgcolor = color.rgb(199,217,226),height = i_height,width= i_width) table.cell(displayGear5,26,22, bgcolor = color.rgb(141,184,203),height = i_height,width= i_width) table.cell(displayGear5,26,23, bgcolor = color.rgb(216,231,239),height = i_height,width= i_width) table.cell(displayGear5,26,24, bgcolor = color.rgb(162,164,158),height = i_height,width= i_width) table.cell(displayGear5,26,25, bgcolor = color.rgb(221,205,174),height = i_height,width= i_width) table.cell(displayGear5,26,26, bgcolor = color.rgb(242,185,120),height = i_height,width= i_width) table.cell(displayGear5,26,27, bgcolor = color.rgb(147,126,137),height = i_height,width= i_width) table.cell(displayGear5,26,28, bgcolor = color.rgb(168,187,222),height = i_height,width= i_width) table.cell(displayGear5,26,29, bgcolor = color.rgb(217,238,236),height = i_height,width= i_width) table.cell(displayGear5,26,30, bgcolor = color.rgb(219,233,236),height = i_height,width= i_width) table.cell(displayGear5,26,31, bgcolor = color.rgb(206,228,231),height = i_height,width= i_width) table.cell(displayGear5,26,32, bgcolor = color.rgb(170,204,213),height = i_height,width= i_width) table.cell(displayGear5,26,33, bgcolor = color.rgb(184,207,218),height = i_height,width= i_width) table.cell(displayGear5,26,34, bgcolor = color.rgb(193,227,239),height = i_height,width= i_width) table.cell(displayGear5,26,35, bgcolor = color.rgb(152,194,216),height = i_height,width= i_width) table.cell(displayGear5,27,20, bgcolor = color.rgb(126,144,152),height = i_height,width= i_width) table.cell(displayGear5,27,21, bgcolor = color.rgb(170,216,237),height = i_height,width= i_width) table.cell(displayGear5,27,22, bgcolor = color.rgb(134,174,194),height = i_height,width= i_width) table.cell(displayGear5,27,23, bgcolor = color.rgb(249,250,251),height = i_height,width= i_width) table.cell(displayGear5,27,24, bgcolor = color.rgb(152,209,239),height = i_height,width= i_width) table.cell(displayGear5,27,25, bgcolor = color.rgb(184,164,130),height = i_height,width= i_width) table.cell(displayGear5,27,27, bgcolor = color.rgb(202,186,167),height = i_height,width= i_width) table.cell(displayGear5,27,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,27,29, bgcolor = color.rgb(243,246,246),height = i_height,width= i_width) table.cell(displayGear5,27,30, bgcolor = color.rgb(173,205,213),height = i_height,width= i_width) table.cell(displayGear5,27,31, bgcolor = color.rgb(154,190,207),height = i_height,width= i_width) table.cell(displayGear5,27,32, bgcolor = color.rgb(185,210,225),height = i_height,width= i_width) table.cell(displayGear5,27,33, bgcolor = color.rgb(184,211,221),height = i_height,width= i_width) table.cell(displayGear5,27,34, bgcolor = color.rgb(134,178,195),height = i_height,width= i_width) table.cell(displayGear5,28,20, bgcolor = color.rgb(237,255,255),height = i_height,width= i_width) table.cell(displayGear5,28,21, bgcolor = color.rgb(151,204,217),height = i_height,width= i_width) table.cell(displayGear5,28,22, bgcolor = color.rgb(134,185,209),height = i_height,width= i_width) table.cell(displayGear5,28,23, bgcolor = color.rgb(138,141,143),height = i_height,width= i_width) table.cell(displayGear5,28,24, bgcolor = color.rgb(230,236,230),height = i_height,width= i_width) table.cell(displayGear5,28,25, bgcolor = color.rgb(253,226,199),height = i_height,width= i_width) table.cell(displayGear5,28,26, bgcolor = color.rgb(161,125,113),height = i_height,width= i_width) table.cell(displayGear5,28,27, bgcolor = color.rgb(207,199,198),height = i_height,width= i_width) table.cell(displayGear5,28,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,28,29, bgcolor = color.rgb(255,255,254),height = i_height,width= i_width) table.cell(displayGear5,28,30, bgcolor = color.rgb(251,252,253),height = i_height,width= i_width) table.cell(displayGear5,28,31, bgcolor = color.rgb(204,222,230),height = i_height,width= i_width) table.cell(displayGear5,28,32, bgcolor = color.rgb(185,205,216),height = i_height,width= i_width) table.cell(displayGear5,28,33, bgcolor = color.rgb(183,226,240),height = i_height,width= i_width) table.cell(displayGear5,28,34, bgcolor = color.rgb(103,162,186),height = i_height,width= i_width) table.cell(displayGear5,29,20, bgcolor = color.rgb(123,145,156),height = i_height,width= i_width) table.cell(displayGear5,29,21, bgcolor = color.rgb(141,186,206),height = i_height,width= i_width) table.cell(displayGear5,29,24, bgcolor = color.rgb(161,139,162),height = i_height,width= i_width) table.cell(displayGear5,29,25, bgcolor = color.rgb(229,245,255),height = i_height,width= i_width) table.cell(displayGear5,29,26, bgcolor = color.rgb(207,248,255),height = i_height,width= i_width) table.cell(displayGear5,29,27, bgcolor = color.rgb(237,250,254),height = i_height,width= i_width) table.cell(displayGear5,29,28, bgcolor = color.rgb(255,254,251),height = i_height,width= i_width) table.cell(displayGear5,29,29, bgcolor = color.rgb(254,255,255),height = i_height,width= i_width) table.cell(displayGear5,29,30, bgcolor = color.rgb(254,251,250),height = i_height,width= i_width) table.cell(displayGear5,29,31, bgcolor = color.rgb(216,230,232),height = i_height,width= i_width) table.cell(displayGear5,29,32, bgcolor = color.rgb(171,209,217),height = i_height,width= i_width) table.cell(displayGear5,29,33, bgcolor = color.rgb(137,178,199),height = i_height,width= i_width) table.cell(displayGear5,30,21, bgcolor = color.rgb(182,210,204),height = i_height,width= i_width) table.cell(displayGear5,30,25, bgcolor = color.rgb(176,179,205),height = i_height,width= i_width) table.cell(displayGear5,30,26, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,30,27, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,30,28, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,30,29, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,30,30, bgcolor = color.rgb(219,229,233),height = i_height,width= i_width) table.cell(displayGear5,30,31, bgcolor = color.rgb(170,198,206),height = i_height,width= i_width) table.cell(displayGear5,30,32, bgcolor = color.rgb(182,226,242),height = i_height,width= i_width) table.cell(displayGear5,30,33, bgcolor = color.rgb(95,149,174),height = i_height,width= i_width) table.cell(displayGear5,31,20, bgcolor = color.rgb(80,106,105),height = i_height,width= i_width) table.cell(displayGear5,31,21, bgcolor = color.rgb(138,152,175),height = i_height,width= i_width) table.cell(displayGear5,31,23, bgcolor = color.rgb(127,83,187),height = i_height,width= i_width) table.cell(displayGear5,31,24, bgcolor = color.rgb(88,92,165),height = i_height,width= i_width) table.cell(displayGear5,31,25, bgcolor = color.rgb(189,206,211),height = i_height,width= i_width) table.cell(displayGear5,31,26, bgcolor = color.rgb(208,232,233),height = i_height,width= i_width) table.cell(displayGear5,31,27, bgcolor = color.rgb(171,202,217),height = i_height,width= i_width) table.cell(displayGear5,31,28, bgcolor = color.rgb(207,225,233),height = i_height,width= i_width) table.cell(displayGear5,31,29, bgcolor = color.rgb(247,248,245),height = i_height,width= i_width) table.cell(displayGear5,31,30, bgcolor = color.rgb(217,227,229),height = i_height,width= i_width) table.cell(displayGear5,31,31, bgcolor = color.rgb(176,216,230),height = i_height,width= i_width) table.cell(displayGear5,31,32, bgcolor = color.rgb(155,202,225),height = i_height,width= i_width) table.cell(displayGear5,32,19, bgcolor = color.rgb(88,86,125),height = i_height,width= i_width) f_700()=> table.cell(displayGear5,32,20, bgcolor = color.rgb(150,172,224),height = i_height,width= i_width) table.cell(displayGear5,32,21, bgcolor = color.rgb(131,92,199),height = i_height,width= i_width) table.cell(displayGear5,32,22, bgcolor = color.rgb(158,116,229),height = i_height,width= i_width) table.cell(displayGear5,32,23, bgcolor = color.rgb(117,111,174),height = i_height,width= i_width) table.cell(displayGear5,32,24, bgcolor = color.rgb(147,187,199),height = i_height,width= i_width) table.cell(displayGear5,32,25, bgcolor = color.rgb(198,224,228),height = i_height,width= i_width) table.cell(displayGear5,32,26, bgcolor = color.rgb(160,196,211),height = i_height,width= i_width) table.cell(displayGear5,32,27, bgcolor = color.rgb(99,156,181),height = i_height,width= i_width) table.cell(displayGear5,32,28, bgcolor = color.rgb(137,181,197),height = i_height,width= i_width) table.cell(displayGear5,32,29, bgcolor = color.rgb(152,191,207),height = i_height,width= i_width) table.cell(displayGear5,32,30, bgcolor = color.rgb(171,203,217),height = i_height,width= i_width) table.cell(displayGear5,32,31, bgcolor = color.rgb(170,203,213),height = i_height,width= i_width) table.cell(displayGear5,33,18, bgcolor = color.rgb(124,99,177),height = i_height,width= i_width) table.cell(displayGear5,33,19, bgcolor = color.rgb(172,129,249),height = i_height,width= i_width) table.cell(displayGear5,33,20, bgcolor = color.rgb(144,109,213),height = i_height,width= i_width) table.cell(displayGear5,33,23, bgcolor = color.rgb(191,213,213),height = i_height,width= i_width) table.cell(displayGear5,33,24, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,33,25, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,33,26, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,33,27, bgcolor = color.rgb(247,247,247),height = i_height,width= i_width) table.cell(displayGear5,33,28, bgcolor = color.rgb(201,218,228),height = i_height,width= i_width) table.cell(displayGear5,33,29, bgcolor = color.rgb(138,180,204),height = i_height,width= i_width) table.cell(displayGear5,33,30, bgcolor = color.rgb(144,200,226),height = i_height,width= i_width) table.cell(displayGear5,33,31, bgcolor = color.rgb(113,134,142),height = i_height,width= i_width) table.cell(displayGear5,34,19, bgcolor = color.rgb(96,77,141),height = i_height,width= i_width) table.cell(displayGear5,34,23, bgcolor = color.rgb(237,241,240),height = i_height,width= i_width) table.cell(displayGear5,34,24, bgcolor = color.rgb(253,255,255),height = i_height,width= i_width) table.cell(displayGear5,34,25, bgcolor = color.rgb(234,223,218),height = i_height,width= i_width) table.cell(displayGear5,34,26, bgcolor = color.rgb(241,212,189),height = i_height,width= i_width) table.cell(displayGear5,34,27, bgcolor = color.rgb(221,239,243),height = i_height,width= i_width) table.cell(displayGear5,34,28, bgcolor = color.rgb(196,229,241),height = i_height,width= i_width) table.cell(displayGear5,34,29, bgcolor = color.rgb(191,212,213),height = i_height,width= i_width) table.cell(displayGear5,34,30, bgcolor = color.rgb(172,218,239),height = i_height,width= i_width) table.cell(displayGear5,34,31, bgcolor = color.rgb(80,115,134),height = i_height,width= i_width) table.cell(displayGear5,35,22, bgcolor = color.rgb(207,230,239),height = i_height,width= i_width) table.cell(displayGear5,35,23, bgcolor = color.rgb(255,255,255),height = i_height,width= i_width) table.cell(displayGear5,35,24, bgcolor = color.rgb(183,198,203),height = i_height,width= i_width) table.cell(displayGear5,35,25, bgcolor = color.rgb(192,152,113),height = i_height,width= i_width) table.cell(displayGear5,35,26, bgcolor = color.rgb(222,149,83),height = i_height,width= i_width) table.cell(displayGear5,35,27, bgcolor = color.rgb(134,132,125),height = i_height,width= i_width) table.cell(displayGear5,35,28, bgcolor = color.rgb(125,167,187),height = i_height,width= i_width) table.cell(displayGear5,35,29, bgcolor = color.rgb(178,211,221),height = i_height,width= i_width) table.cell(displayGear5,35,30, bgcolor = color.rgb(210,239,249),height = i_height,width= i_width) table.cell(displayGear5,35,31, bgcolor = color.rgb(129,150,162),height = i_height,width= i_width) table.cell(displayGear5,36,22, bgcolor = color.rgb(250,252,254),height = i_height,width= i_width) table.cell(displayGear5,36,23, bgcolor = color.rgb(249,255,255),height = i_height,width= i_width) table.cell(displayGear5,36,24, bgcolor = color.rgb(210,165,124),height = i_height,width= i_width) table.cell(displayGear5,36,25, bgcolor = color.rgb(238,193,143),height = i_height,width= i_width) table.cell(displayGear5,36,26, bgcolor = color.rgb(255,236,202),height = i_height,width= i_width) table.cell(displayGear5,36,28, bgcolor = color.rgb(116,101,89),height = i_height,width= i_width) table.cell(displayGear5,36,29, bgcolor = color.rgb(129,192,225),height = i_height,width= i_width) table.cell(displayGear5,36,30, bgcolor = color.rgb(220,245,248),height = i_height,width= i_width) table.cell(displayGear5,36,31, bgcolor = color.rgb(136,151,158),height = i_height,width= i_width) table.cell(displayGear5,37,22, bgcolor = color.rgb(239,244,244),height = i_height,width= i_width) table.cell(displayGear5,37,23, bgcolor = color.rgb(193,222,237),height = i_height,width= i_width) table.cell(displayGear5,37,24, bgcolor = color.rgb(230,201,167),height = i_height,width= i_width) table.cell(displayGear5,37,25, bgcolor = color.rgb(252,219,173),height = i_height,width= i_width) table.cell(displayGear5,37,26, bgcolor = color.rgb(252,225,182),height = i_height,width= i_width) table.cell(displayGear5,37,27, bgcolor = color.rgb(237,176,117),height = i_height,width= i_width) table.cell(displayGear5,37,28, bgcolor = color.rgb(136,141,137),height = i_height,width= i_width) table.cell(displayGear5,37,29, bgcolor = color.rgb(128,181,208),height = i_height,width= i_width) table.cell(displayGear5,37,30, bgcolor = color.rgb(214,250,255),height = i_height,width= i_width) table.cell(displayGear5,37,31, bgcolor = color.rgb(125,156,167),height = i_height,width= i_width) table.cell(displayGear5,38,22, bgcolor = color.rgb(171,210,227),height = i_height,width= i_width) table.cell(displayGear5,38,23, bgcolor = color.rgb(188,220,236),height = i_height,width= i_width) table.cell(displayGear5,38,24, bgcolor = color.rgb(200,143,98),height = i_height,width= i_width) table.cell(displayGear5,38,25, bgcolor = color.rgb(233,183,131),height = i_height,width= i_width) table.cell(displayGear5,38,26, bgcolor = color.rgb(243,220,180),height = i_height,width= i_width) table.cell(displayGear5,38,27, bgcolor = color.rgb(255,220,169),height = i_height,width= i_width) table.cell(displayGear5,38,28, bgcolor = color.rgb(165,185,183),height = i_height,width= i_width) table.cell(displayGear5,38,29, bgcolor = color.rgb(136,197,228),height = i_height,width= i_width) table.cell(displayGear5,38,30, bgcolor = color.rgb(173,214,233),height = i_height,width= i_width) table.cell(displayGear5,39,22, bgcolor = color.rgb(102,155,180),height = i_height,width= i_width) table.cell(displayGear5,39,23, bgcolor = color.rgb(177,217,239),height = i_height,width= i_width) table.cell(displayGear5,39,24, bgcolor = color.rgb(173,122,84),height = i_height,width= i_width) table.cell(displayGear5,39,26, bgcolor = color.rgb(238,197,154),height = i_height,width= i_width) table.cell(displayGear5,39,27, bgcolor = color.rgb(255,223,178),height = i_height,width= i_width) table.cell(displayGear5,39,28, bgcolor = color.rgb(219,215,197),height = i_height,width= i_width) table.cell(displayGear5,39,29, bgcolor = color.rgb(151,202,224),height = i_height,width= i_width) table.cell(displayGear5,40,23, bgcolor = color.rgb(99,152,174),height = i_height,width= i_width) table.cell(displayGear5,40,24, bgcolor = color.rgb(115,166,197),height = i_height,width= i_width) table.cell(displayGear5,40,26, bgcolor = color.rgb(221,169,119),height = i_height,width= i_width) table.cell(displayGear5,40,27, bgcolor = color.rgb(255,239,202),height = i_height,width= i_width) table.cell(displayGear5,40,28, bgcolor = color.rgb(253,196,142),height = i_height,width= i_width) table.cell(displayGear5,41,26, bgcolor = color.rgb(175,153,124),height = i_height,width= i_width) table.cell(displayGear5,41,27, bgcolor = color.rgb(255,249,201),height = i_height,width= i_width) table.cell(displayGear5,41,28, bgcolor = color.rgb(255,196,144),height = i_height,width= i_width) table.cell(displayGear5,42,27, bgcolor = color.rgb(255,209,159),height = i_height,width= i_width) table.cell(displayGear5,42,28, bgcolor = color.rgb(255,248,199),height = i_height,width= i_width) table.cell(displayGear5,42,29, bgcolor = color.rgb(134,113,89),height = i_height,width= i_width) table.cell(displayGear5,43,27, bgcolor = color.rgb(255,203,156),height = i_height,width= i_width) table.cell(displayGear5,43,28, bgcolor = color.rgb(255,240,197),height = i_height,width= i_width) table.cell(displayGear5,43,29, bgcolor = color.rgb(242,196,147),height = i_height,width= i_width) table.cell(displayGear5,44,26, bgcolor = color.rgb(241,196,152),height = i_height,width= i_width) table.cell(displayGear5,44,27, bgcolor = color.rgb(254,223,181),height = i_height,width= i_width) table.cell(displayGear5,44,28, bgcolor = color.rgb(247,216,176),height = i_height,width= i_width) table.cell(displayGear5,44,29, bgcolor = color.rgb(255,229,185),height = i_height,width= i_width) table.cell(displayGear5,44,30, bgcolor = color.rgb(232,210,157),height = i_height,width= i_width) table.cell(displayGear5,45,24, bgcolor = color.rgb(209,177,139),height = i_height,width= i_width) f_800()=> table.cell(displayGear5,45,25, bgcolor = color.rgb(252,219,176),height = i_height,width= i_width) table.cell(displayGear5,45,26, bgcolor = color.rgb(242,193,144),height = i_height,width= i_width) table.cell(displayGear5,45,27, bgcolor = color.rgb(196,169,121),height = i_height,width= i_width) table.cell(displayGear5,45,28, bgcolor = color.rgb(185,178,130),height = i_height,width= i_width) table.cell(displayGear5,45,29, bgcolor = color.rgb(195,181,135),height = i_height,width= i_width) table.cell(displayGear5,45,30, bgcolor = color.rgb(205,192,134),height = i_height,width= i_width) table.cell(displayGear5,45,31, bgcolor = color.rgb(199,189,130),height = i_height,width= i_width) table.cell(displayGear5,46,22, bgcolor = color.rgb(134,127,87),height = i_height,width= i_width) table.cell(displayGear5,46,23, bgcolor = color.rgb(209,182,125),height = i_height,width= i_width) table.cell(displayGear5,46,24, bgcolor = color.rgb(230,212,149),height = i_height,width= i_width) table.cell(displayGear5,46,25, bgcolor = color.rgb(214,205,155),height = i_height,width= i_width) table.cell(displayGear5,46,26, bgcolor = color.rgb(135,116,76),height = i_height,width= i_width) table.cell(displayGear5,46,30, bgcolor = color.rgb(121,116,76),height = i_height,width= i_width) table.cell(displayGear5,46,31, bgcolor = color.rgb(147,139,90),height = i_height,width= i_width) table.cell(displayGear5,46,32, bgcolor = color.rgb(141,134,91),height = i_height,width= i_width) table.cell(displayGear5,47,22, bgcolor = color.rgb(206,197,137),height = i_height,width= i_width) table.cell(displayGear5,47,23, bgcolor = color.rgb(153,151,98),height = i_height,width= i_width) table.cell(displayGear5,47,25, bgcolor = color.rgb(131,129,81),height = i_height,width= i_width) table.cell(displayGear5,48,23, bgcolor = color.rgb(130,128,83),height = i_height,width= i_width) if barstate.islast f_001() f_100() f_200() f_300() f_400() f_500() f_600() f_700() f_800()
KF Percentage Change
https://www.tradingview.com/script/IpevlhoY-KF-Percentage-Change/
Koalafied_3
https://www.tradingview.com/u/Koalafied_3/
17
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© TJ_667 //@version=5 indicator('KF Percentage Change') // ---------- INPUTS ---------- // src = input(close, "Source") period_selection = input.string(title = "Period Option", defval="D", options = ["D", "W", "M", "Q", "Y"]) plot_start = input(true, title = 'Show Period Start') //-------------------- CALCS --------------------// _period = period_selection == "D" ? "D" : period_selection == "W" ? "W" : period_selection == "M" ? "M" : period_selection == "Q" ? "3M" : period_selection == "Y" ? "12M" : na newSession = ta.change(time(_period)) // Bars back since period start var int count = na count := newSession ? 0 : count + 1 len = count perc_change(_current, _start) => overall_change = (_current - _start) / _start * 100 var float _startvalue = na _startvalue := newSession ? open : _startvalue[1] percentage_change = perc_change(src, _startvalue) var float p_pc = na p_pc := newSession ? percentage_change[1] : p_pc // ---------- PLOTS ---------- // hline(0, 'Center Line', color=color.gray, linestyle=hline.style_dotted) plot(percentage_change, title = "Percentage Change", style = plot.style_histogram, color = percentage_change > 0 ? color.white : percentage_change < 0 ? color.red : color.black) if plot_start and newSession p_start = line.new(bar_index, 0, bar_index, 0.1, color = color.gray, style = line.style_dashed, extend = extend.both, width = 1) var table PC_Display = table.new(position.bottom_right, 2, 2, bgcolor = color.new(color.teal, 90),frame_color=color.new(color.white, 80), frame_width=1, border_width=2,border_color=color.new(color.white, 80)) if barstate.islast table.cell(PC_Display, 0, 0, "PC", text_color = color.gray, text_size = size.small) table.cell(PC_Display, 1, 0, str.tostring(math.round(percentage_change, 2)) + '%', text_color = color.gray, text_size = size.small) table.cell(PC_Display, 0, 1, "Prev PC", text_color = color.gray, text_size = size.small) table.cell(PC_Display, 1, 1, str.tostring(math.round(p_pc, 2)) + '%', text_color = color.gray, text_size = size.small)
SMC Structures and FVG
https://www.tradingview.com/script/uJDx1aKO/
LudoGH68
https://www.tradingview.com/u/LudoGH68/
702
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© LudoGH68 //@version=5 indicator("SMC Structures and FVG", overlay = true) import LudoGH68/Drawings_public/1 as d getLineStyle(lineOption) => lineOption == "β”ˆ" ? line.style_dotted : lineOption == "β•Œ" ? line.style_dashed : line.style_solid get_structure_highest_bar(lookback) => var int idx = 0 maxBar = bar_index > lookback ? ta.highestbars(high, lookback) : ta.highestbars(high, bar_index + 1) for i = 0 to lookback - 1 by 1 if high[i+1] > high[i+2] and high[i] <= high[i+1] and ((i+1) * -1) >= maxBar idx := (i+1) * -1 //break idx := idx == 0 ? maxBar : idx get_structure_lowest_bar(lookback) => var int idx = 0 minBar = bar_index > lookback ? ta.lowestbars(low, lookback) : ta.lowestbars(low, bar_index + 1) for i = 0 to lookback - 1 by 1 if low[i+1] < low[i+2] and low[i] >= low[i+1] and ((i+1) * -1) >= minBar idx := (i+1) * -1 //break idx := idx == 0 ? minBar : idx is_structure_high_broken(_highStructBreakPrice, _structureHigh, _structureHighStartIndex, _structureDirection) => var bool res = false if (_highStructBreakPrice > _structureHigh and bar_index[1] > _structureHighStartIndex) or (_structureDirection == 1 and _highStructBreakPrice > _structureHigh) res := true else res := false res // Fear Value Gap isFvgToShow = input(true, title='Display FVG', group="Fear Value Gap") bullishFvgColor = input(color.new(color.green, 50), 'Bullish FVG Color', group="Fear Value Gap") bearishFvgColor = input(color.new(color.red, 50), 'Bearish FVG Color', group="Fear Value Gap") mitigatedFvgColor = input(color.new(color.gray, 50), 'Mitigated FVG Color', group="Fear Value Gap") fvgHistoryNbr = input.int(5, 'Number of FVG to show', minval=1, maxval=50) isMitigatedFvgToReduce = input(false, title='Reduce mitigated FVG', group="Fear Value Gap") // Structures isStructBodyCandleBreak = input(true, title='Break with candle\'s body', group="Structures") isCurrentStructToShow = input(true, title='Display current structure', group="Structures") bullishBosColor = input(color.silver, 'Bullish BOS Color', group="Structures") bearishBosColor = input(color.silver, 'Bearish BOS Color', group="Structures") bosLineStyleOption = input.string("─", title="BOS Style", group="Structures", options=["─", "β”ˆ", "β•Œ"]) bosLineStyle = getLineStyle(bosLineStyleOption) bosLineWidth = input.int(1, title="BOS Width", group="Structures", minval=1, maxval=5) bullishChochColor = input(color.yellow, 'Bullish CHoCH Color', group="Structures") bearishChochColor = input(color.yellow, 'Bearish CHoCH Color', group="Structures") chochLineStyleOption = input.string("─", title="CHoCH Style", group="Structures", options=["─", "β”ˆ", "β•Œ"]) chochLineStyle = getLineStyle(chochLineStyleOption) chochLineWidth = input.int(1, title="MSB Width", group="Structures", minval=1, maxval=5) currentStructColor = input(color.blue, 'Current structure Color', group="Structures") currentStructLineStyleOption = input.string("─", title="Current structure Style", group="Structures", options=["─", "β”ˆ", "β•Œ"]) currentStructLineStyle = getLineStyle(currentStructLineStyleOption) currentStructLineWidth = input.int(1, title="Current structure Width", group="Structures", minval=1, maxval=5) structHistoryNbr = input.int(10, 'Number of break to show', minval=1, maxval=50) // Fibonacci 1 isFibo1ToShow = input(true, title = "", group="Structure Fibonacci", inline = "Fibo1") fibo1Value = input.float(0.786, title = "", group="Structure Fibonacci", inline = "Fibo1") fibo1Color = input(#64b5f6, title = "", group="Structure Fibonacci", inline = "Fibo1") fibo1StyleOption = input.string("─", title = "", group="Structure Fibonacci", options=["─", "β”ˆ", "β•Œ"], inline = "Fibo1") fibo1Style = getLineStyle(fibo1StyleOption) fibo1LineWidth = input.int(1, title = "", group="Structure Fibonacci", minval=1, maxval=5, inline = "Fibo1") // Fibonacci 2 isFibo2ToShow = input(true, title = "", group="Structure Fibonacci", inline = "Fibo2") fibo2Value = input.float(0.705, title = "", group="Structure Fibonacci", inline = "Fibo2") fibo2Color = input(#f23645, title = "", group="Structure Fibonacci", inline = "Fibo2") fibo2StyleOption = input.string("─", title = "", group="Structure Fibonacci", options=["─", "β”ˆ", "β•Œ"], inline = "Fibo2") fibo2Style = getLineStyle(fibo2StyleOption) fibo2LineWidth = input.int(1, title = "", group="Structure Fibonacci", minval=1, maxval=5, inline = "Fibo2") // Fibonacci 3 isFibo3ToShow = input(true, title = "", group="Structure Fibonacci", inline = "Fibo3") fibo3Value = input.float(0.618, title = "", group="Structure Fibonacci", inline = "Fibo3") fibo3Color = input(#089981, title = "", group="Structure Fibonacci", inline = "Fibo3") fibo3StyleOption = input.string("─", title = "", group="Structure Fibonacci", options=["─", "β”ˆ", "β•Œ"], inline = "Fibo3") fibo3Style = getLineStyle(fibo3StyleOption) fibo3LineWidth = input.int(1, title = "", group="Structure Fibonacci", minval=1, maxval=5, inline = "Fibo3") // Fibonacci 3 isFibo4ToShow = input(true, title = "", group="Structure Fibonacci", inline = "Fibo4") fibo4Value = input.float(0.5, title = "", group="Structure Fibonacci", inline = "Fibo4") fibo4Color = input(#4caf50, title = "", group="Structure Fibonacci", inline = "Fibo4") fibo4StyleOption = input.string("─", title = "", group="Structure Fibonacci", options=["─", "β”ˆ", "β•Œ"], inline = "Fibo4") fibo4Style = getLineStyle(fibo4StyleOption) fibo4LineWidth = input.int(1, title = "", group="Structure Fibonacci", minval=1, maxval=5, inline = "Fibo4") // Fibonacci 5 isFibo5ToShow = input(true, title = "", group="Structure Fibonacci", inline = "Fibo5") fibo5Value = input.float(0.382, title = "", group="Structure Fibonacci", inline = "Fibo5") fibo5Color = input(#81c784, title = "", group="Structure Fibonacci", inline = "Fibo5") fibo5StyleOption = input.string("─", title = "", group="Structure Fibonacci", options=["─", "β”ˆ", "β•Œ"], inline = "Fibo5") fibo5Style = getLineStyle(fibo5StyleOption) fibo5LineWidth = input.int(1, title = "", group="Structure Fibonacci", minval=1, maxval=5, inline = "Fibo5") // Draw FVG into graph FVGDraw(_boxes, _fvgTypes, _isFvgMitigated) => // Loop into all values of the array for [index, value] in _boxes // Processing bullish FVG if(array.get(_fvgTypes, index)) // Check if FVG has been totally mitigated if(low <= box.get_bottom(value)) array.remove(_boxes, index) array.remove(_fvgTypes, index) array.remove(_isFvgMitigated, index) box.delete(value) else if(low < box.get_top((value))) box.set_bgcolor(value, mitigatedFvgColor) // Mitigated FVG Alert if(not(array.get(_isFvgMitigated, index))) alert("FVG has been mitigated", alert.freq_once_per_bar) array.set(_isFvgMitigated, index, true) // Reduce FVG if needed if(isMitigatedFvgToReduce) box.set_top(value, low) box.set_right(value, bar_index) // Processing bearish FVG else // Check if FVG has been mitigated if(high >= box.get_top(value)) array.remove(_boxes, index) array.remove(_fvgTypes, index) array.remove(_isFvgMitigated, index) box.delete(value) else if(high > box.get_bottom((value))) box.set_bgcolor(value, mitigatedFvgColor) // Mitigated FVG Alert if(not(array.get(_isFvgMitigated, index))) alert("FVG has been mitigated", alert.freq_once_per_bar) array.set(_isFvgMitigated, index, true) // Reduce FVG if needed if(isMitigatedFvgToReduce) box.set_bottom(value, high) box.set_right(value, bar_index) // Arrays variable var array<line> structureLines = array.new_line(0) var array<label> structureLabels = array.new_label(0) var array<box> fvgBoxes = array.new_box(0) var array<bool> fvgTypes = array.new_bool(0) var array<bool> isFvgMitigated = array.new_bool(0) // Price variables var float structureHigh = 0.0 var float structureLow = 0.0 var float fibo1Price = 0.0 var float fibo2Price = 0.0 var float fibo3Price = 0.0 var float fibo4Price = 0.0 var float fibo5Price = 0.0 // Index variable var int structureHighStartIndex = 0 var int structureLowStartIndex = 0 var int structureDirection = 0 var int fibo1StartIndex = 0 var int fibo2StartIndex = 0 var int fibo3StartIndex = 0 var int fibo4StartIndex = 0 var int fibo5StartIndex = 0 // Line variable var line structureHighLine = na var line structureLowLine = na var line fibo1Line = na var line fibo2Line = na var line fibo3Line = na var line fibo4Line = na var line fibo5Line = na // Label variable var label fibo1Label = na var label fibo2Label = na var label fibo3Label = na var label fibo4Label = na var label fibo5Label = na // // // ========================================================================================== // FAIR VALUE GAP FINDER PROCESSING // ========================================================================================== // // // Define FVG type isBullishFVG = high[3] < low[1] isBearishFVG = low[3] > high[1] // Bullish FVG process if(isBullishFVG and isFvgToShow) // Add FVG into FVG's array box _box = box.new(left=bar_index - 2, top=low[1], right=bar_index[1], bottom=high[3], border_style=line.style_solid, border_width=1, bgcolor=bullishFvgColor, border_color=color.new(color.green, 100)) array.push(fvgBoxes, _box) array.push(fvgTypes, true) array.push(isFvgMitigated, false) // Check if FVG to show is upper than user parameter if(array.size(fvgBoxes) > fvgHistoryNbr + 1) // Delete the FVG and its index from arrays box.delete(array.get(fvgBoxes, 0)) array.remove(fvgBoxes, 0) array.remove(fvgTypes, 0) array.remove(isFvgMitigated, 0) // Bearish FVG process if(isBearishFVG and isFvgToShow) // Add FVG into FVG's array box _box = box.new(left=bar_index - 2, top=low[3], right=bar_index[1], bottom=high[1], border_style=line.style_solid, border_width=1, bgcolor=bearishFvgColor, border_color=color.new(color.red, 100)) array.push(fvgBoxes, _box) array.push(fvgTypes, false) array.push(isFvgMitigated, false) // Check if FVG to show is upper than user parameter if(array.size(fvgBoxes) > fvgHistoryNbr + 1) // Delete the FVG and its index from arrays box.delete(array.get(fvgBoxes, 0)) array.remove(fvgBoxes, 0) array.remove(fvgTypes, 0) array.remove(isFvgMitigated, 0) // Draw FVG FVGDraw(fvgBoxes, fvgTypes, isFvgMitigated) // // // ========================================================================================== // STRUCTURES PROCESSING // ========================================================================================== // // // Initialize value for bar 0 if(bar_index == 0) structureHighStartIndex := bar_index structureLowStartIndex := bar_index structureHigh := high structureLow := low highest = bar_index > 10 ? ta.highest(10) : ta.highest(bar_index + 1) highestBar = bar_index > 10 ? ta.highestbars(high, 10) : ta.highestbars(high, bar_index + 1) lowest = bar_index > 10 ? ta.lowest(10) : ta.lowest(bar_index + 1) lowestBar = bar_index > 10 ? ta.lowestbars(low, 10) : ta.lowestbars(low, bar_index + 1) structureMaxBar = bar_index + get_structure_highest_bar(10) structureMinBar = bar_index + get_structure_lowest_bar(10) lowStructBreakPrice = isStructBodyCandleBreak ? close : low highStructBreakPrice = isStructBodyCandleBreak ? close : high isStuctureLowBroken = (lowStructBreakPrice < structureLow and lowStructBreakPrice[1] >= structureLow and lowStructBreakPrice[2] >= structureLow and lowStructBreakPrice[3] >= structureLow and bar_index[1] > structureLowStartIndex and bar_index[2] > structureLowStartIndex and bar_index[3] > structureLowStartIndex) or (structureDirection == 2 and lowStructBreakPrice < structureLow) isStructureHighBroken = (highStructBreakPrice > structureHigh and highStructBreakPrice[1] <= structureHigh and highStructBreakPrice[2] <= structureHigh and highStructBreakPrice[3] <= structureHigh and bar_index[1] > structureHighStartIndex and bar_index[2] > structureHighStartIndex and bar_index[3] > structureHighStartIndex) or (structureDirection == 1 and highStructBreakPrice > structureHigh) //if((low < structureLow and low[1] >= structureLow and low[2] >= structureLow and low[3] >= structureLow and bar_index[1] > structureLowStartIndex and bar_index[2] > structureLowStartIndex and bar_index[3] > structureLowStartIndex) or (structureDirection == 2 and low < structureLow)) if(isStuctureLowBroken) // Check if structures to show is upper than user parameter if(array.size(structureLines) >= structHistoryNbr) // Delete the line and its index from arrays d.delete_line(array.get(structureLines, 0), array.get(structureLabels, 0)) array.remove(structureLabels, 0) array.remove(structureLines, 0) // Create BOS line if(structureDirection == 1) array.push(structureLines, line.new(structureLowStartIndex, structureLow, bar_index, structureLow, xloc=xloc.bar_index, extend=extend.none, color=bearishBosColor, style=bosLineStyle, width=bosLineWidth)) array.push(structureLabels, label.new((bar_index + structureLowStartIndex) / 2, structureLow, text="BOS", style=label.style_none, textcolor=bearishBosColor)) // Create CHoCH line else array.push(structureLines, line.new(structureLowStartIndex, structureLow, bar_index, structureLow, xloc=xloc.bar_index, extend=extend.none, color=bearishChochColor, style=chochLineStyle, width=chochLineWidth)) array.push(structureLabels, label.new((bar_index + structureLowStartIndex) / 2, structureLow, text="CHoCH", style=label.style_none, textcolor=bearishChochColor)) // Update values for new structure structureDirection := 1 structureHighStartIndex := structureMaxBar structureLowStartIndex := bar_index structureHigh := high[bar_index - structureHighStartIndex] //highest structureLow := low // Check for breakout else if(isStructureHighBroken) // Check if structures to show is upper than user parameter if(array.size(structureLines) >= structHistoryNbr) // Delete the line and its index from arrays d.delete_line(array.get(structureLines, 0), array.get(structureLabels, 0)) array.remove(structureLabels, 0) array.remove(structureLines, 0) // Create BOS line if(structureDirection == 2) array.push(structureLines, line.new(structureHighStartIndex, structureHigh, bar_index, structureHigh, xloc=xloc.bar_index, extend=extend.none, color=bullishBosColor, style=bosLineStyle, width=bosLineWidth)) array.push(structureLabels, label.new((bar_index + structureHighStartIndex) / 2, structureHigh, text="BOS", style=label.style_none, textcolor=bullishBosColor)) // Create CHoCH line else array.push(structureLines, line.new(structureHighStartIndex, structureHigh, bar_index, structureHigh, xloc=xloc.bar_index, extend=extend.none, color=bullishChochColor, style=chochLineStyle, width=chochLineWidth)) array.push(structureLabels, label.new((bar_index + structureHighStartIndex) / 2, structureHigh, text="CHoCH", style=label.style_none, textcolor=bullishChochColor)) // Update values for new structure structureDirection := 2 structureHighStartIndex := bar_index structureLowStartIndex := structureMinBar structureHigh := high structureLow := low[bar_index - structureLowStartIndex] //lowest else if(high > structureHigh and (structureDirection == 0 or structureDirection == 2)) if(not(isStructBodyCandleBreak) or not(isStructBodyCandleBreak and bar_index[1] > structureHighStartIndex and bar_index[2] > structureHighStartIndex and bar_index[3] > structureHighStartIndex)) structureHigh := high structureHighStartIndex := bar_index else if(low < structureLow and (structureDirection == 0 or structureDirection == 1)) if(not(isStructBodyCandleBreak) or not(isStructBodyCandleBreak and bar_index[1] > structureLowStartIndex and bar_index[2] > structureLowStartIndex and bar_index[3] > structureLowStartIndex)) structureLow := low structureLowStartIndex := bar_index structureRange = math.abs(structureHigh - structureLow) // Affichage de la structure actuelle if(isCurrentStructToShow) d.delete_line(structureHighLine, na) d.delete_line(structureLowLine, na) structureHighLine := line.new(structureHighStartIndex, structureHigh, bar_index, structureHigh, xloc.bar_index, color=currentStructColor, style = currentStructLineStyle, width = currentStructLineWidth) structureLowLine := line.new(structureLowStartIndex, structureLow, bar_index, structureLow, xloc.bar_index, color=currentStructColor, style = currentStructLineStyle, width = currentStructLineWidth) // Affichage du Fibonnacci 1 de la structure actuelle if(isFibo1ToShow) d.delete_line(fibo1Line, fibo1Label) fibo1Price := structureDirection == 1 ? structureHigh - (structureRange - structureRange * fibo1Value) : structureLow + (structureRange - structureRange * fibo1Value) fibo1StartIndex := structureDirection == 1 ? structureHighStartIndex : structureLowStartIndex fibo1Line := line.new(fibo1StartIndex, fibo1Price, bar_index, fibo1Price, xloc.bar_index, color = fibo1Color, style = fibo1Style, width = fibo1LineWidth) fibo1Label := label.new(bar_index + 20, fibo1Price, text = str.tostring(fibo1Value) + "(" + str.tostring(fibo1Price) + ")", style = label.style_none, textcolor = fibo1Color) // Affichage du Fibonnacci 2 de la structure actuelle if(isFibo2ToShow) d.delete_line(fibo2Line, fibo2Label) fibo2Price := structureDirection == 1 ? structureHigh - (structureRange - structureRange * fibo2Value) : structureLow + (structureRange - structureRange * fibo2Value) fibo2StartIndex := structureDirection == 1 ? structureHighStartIndex : structureLowStartIndex fibo2Line := line.new(fibo2StartIndex, fibo2Price, bar_index, fibo2Price, xloc.bar_index, color = fibo2Color, style = fibo2Style, width = fibo2LineWidth) fibo2Label := label.new(bar_index + 20, fibo2Price, text = str.tostring(fibo2Value) + "(" + str.tostring(fibo2Price) + ")", style = label.style_none, textcolor = fibo2Color) // Affichage du Fibonnacci 3 de la structure actuelle if(isFibo3ToShow) d.delete_line(fibo3Line, fibo3Label) fibo3Price := structureDirection == 1 ? structureHigh - (structureRange - structureRange * fibo3Value) : structureLow + (structureRange - structureRange * fibo3Value) fibo3StartIndex := structureDirection == 1 ? structureHighStartIndex : structureLowStartIndex fibo3Line := line.new(fibo3StartIndex, fibo3Price, bar_index, fibo3Price, xloc.bar_index, color = fibo3Color, style = fibo3Style, width = fibo3LineWidth) fibo3Label := label.new(bar_index + 20, fibo3Price, text = str.tostring(fibo3Value) + "(" + str.tostring(fibo3Price) + ")", style = label.style_none, textcolor = fibo3Color) // Affichage du Fibonnacci 1 de la structure actuelle if(isFibo4ToShow) d.delete_line(fibo4Line, fibo4Label) fibo4Price := structureDirection == 1 ? structureHigh - (structureRange - structureRange * fibo4Value) : structureLow + (structureRange - structureRange * fibo4Value) fibo4StartIndex := structureDirection == 1 ? structureHighStartIndex : structureLowStartIndex fibo4Line := line.new(fibo4StartIndex, fibo4Price, bar_index, fibo4Price, xloc.bar_index, color = fibo4Color, style = fibo4Style, width = fibo4LineWidth) fibo4Label := label.new(bar_index + 20, fibo4Price, text = str.tostring(fibo4Value) + "(" + str.tostring(fibo4Price) + ")", style = label.style_none, textcolor = fibo4Color) // Affichage du Fibonnacci 1 de la structure actuelle if(isFibo5ToShow) d.delete_line(fibo5Line, fibo5Label) fibo5Price := structureDirection == 1 ? structureHigh - (structureRange - structureRange * fibo5Value) : structureLow + (structureRange - structureRange * fibo5Value) fibo5StartIndex := structureDirection == 1 ? structureHighStartIndex : structureLowStartIndex fibo5Line := line.new(fibo5StartIndex, fibo5Price, bar_index, fibo5Price, xloc.bar_index, color = fibo5Color, style = fibo5Style, width = fibo5LineWidth) fibo5Label := label.new(bar_index + 20, fibo5Price, text = str.tostring(fibo5Value) + "(" + str.tostring(fibo5Price) + ")", style = label.style_none, textcolor = fibo5Color) plot(na)
Offset Project
https://www.tradingview.com/script/wxri5rM7-Offset-Project/
dharmatech
https://www.tradingview.com/u/dharmatech/
19
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© dharmatech //@version=5 indicator("Offset Project", overlay = true) offset = input.int(12) plot(series=close, title = 'Offset Project', color = color.blue, style = plot.style_columns, offset = offset) max_ir = input.float(4.6, "Max Inflation Rate") proj = max_ir / 100 * close + close plot(series=proj, title = 'MAX ALLOWED', color = color.red, style = plot.style_line, offset = offset)
Buy/Sell EMA Candle
https://www.tradingview.com/script/BLV8p5zw-Buy-Sell-EMA-Candle/
AleSaira
https://www.tradingview.com/u/AleSaira/
328
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© AleSaira //@version=5 indicator(title="Buy/Sell EMA Candle", shorttitle="Buy/SellEMA211", overlay=true) ema1 = ta.ema(close, length=13) ema2 = ta.ema(close, length=21) ema3 = ta.ema(close, length=55) ema4 = ta.ema(close, length=90) ema5 = ta.ema(close, length=200) //out = 3 * (ema1 - ema2) + ema3 nooo plot(ema3, "EMA 55", color=#ff9e03) plot(ema4, "EMA 90", color=#f910ed) plot(ema5, "EMA 200", color=#2b00ff) // Calculate the body of the candle bodySize = close > open ? close - open : open - close // Calculate the body of the previous and next candles using a loop bodySizeSurrounding = 0.0 for i = 1 to 4 bodySizeSurrounding := bodySizeSurrounding + (close[i] > open[i] ? close[i] - open[i] : open[i] - close[i]) // Check if the current candle encompasses the previous and next four candles engulfing = (close > open[3] and open < close[3]) and (bodySize > bodySizeSurrounding) // Highlight the area of the engulfing candle engulfingB = (close < open[4] and open > close[4]) and (bodySize > bodySizeSurrounding) //plotshape(engulfing, style=shape.triangleup, location=location.belowbar, color=color.rgb(1, 1, 1), size=size.small, text = "Sell") plotshape(engulfingB, style=shape.triangledown, location=location.abovebar, color=color.rgb(4, 4, 4), size=size.small, text = "Sell") engulfingC = (close > open[2] and open < close[2]) and (bodySize > bodySizeSurrounding) engulfingD = (close > open[1] and open < close[1]) and (bodySize > bodySizeSurrounding) // Highlight the area of the engulfing candle bearish //bgcolor(engulfingC ? color.rgb(77, 77, 77) : na, title="Engulfing Candles", transp=100) //bgcolor(engulfingD ? color.rgb(77, 77, 77) : na, title="Engulfing Candles", transp=100) // Highlight the zone where ema1 crosses ema2 //bgcolor((ema1 > ema2) and (ema1[1] < ema2[1]) ? color.green : na, title="EMA1 crosses above EMA2", transp=80) //bgcolor((ema1 < ema2) and (ema1[1] > ema2[1]) ? color.red : na, title="EMA1 crosses below EMA2", transp=80) // Place markers at engulfing candle bar indices plotshape(engulfingC, style=shape.triangleup, location=location.belowbar, color=color.rgb(1, 1, 1), size=size.small, text = "Buy") plotshape(engulfingD, style=shape.triangledown, location=location.abovebar, color=color.rgb(4, 4, 4), size=size.small, text = "Sell") plot(ema1, "EMA 13", color=#f3f4f7, linewidth=2) plot(ema2, "EMA 21", color=#00aa06, linewidth=2) emaCrossUp = (ema1 > ema2) and (ema1[1] < ema2[1]) emaCrossDown = (ema1 < ema2) and (ema1[1] > ema2[1]) // plot function to set a circle that highlights the intersections between ema1 and ema2 plot(emaCrossUp ? ema1 : na, style=plot.style_circles, color=color.green, linewidth=14, transp=50) plot(emaCrossDown ? ema1 : na, style=plot.style_circles, color=color.red, linewidth=14, transp=50) plotshape(emaCrossDown ? ema1 : false, title = "short", text = 'short', style = shape.labelup, location = location.abovebar, color= color.rgb(19, 19, 19),textcolor = color.white, transp = 0, size = size.tiny) plotshape(emaCrossUp ? ema1 : false, title = "long", text = 'long', style = shape.labelup, location = location.belowbar, color= color.rgb(0, 0, 0),textcolor = color.white, transp = 0, size = size.tiny) // Determine the trend direction for the last candle lastCandleL = close > ta.ema(open,21) lastCandleS = close < ta.ema(open,21) last2L = close > open last2S = close < open currentCandleDirection = close[1] > open[1] ? "L" : (close[1] < open[1] ? "S" : "N/A") // Calculate RSI // Calculate RSI rsiLength = input(14, title="RSI Length") rsiThreshold = input(70, title="RSI Threshold (%)") rsiValue = ta.rsi(close, rsiLength) // Determine RSI trend direction rsiTrendDirection = rsiValue > rsiThreshold ? "OB" : (rsiValue < (100 - rsiThreshold) ? "OS" : "NT") last3L = close < ta.rsi(close,20) last3S = close > ta.rsi(close,80) tabfancy = input.string(defval="bottomR", title = "Position", options = ["bottomR","bottomC","bottomL","topR","topC","topL"]) // Define trend labels for each time frame monthlyTrend = lastCandleL ? "L" : (lastCandleS ? "S" : "N/A") weeklyTrend = request.security(syminfo.tickerid, "W", lastCandleL ? "L" : (lastCandleS ? "S" : "N/A")) dailyTrend = request.security(syminfo.tickerid, "D", lastCandleL ? "L" : (lastCandleS ? "S" : "N/A")) fourHourTrend = request.security(syminfo.tickerid, "240", lastCandleL ? "L" : (lastCandleS ? "S" : "N/A")) oneHourTrend = request.security(syminfo.tickerid, "60", lastCandleL ? "L" : (lastCandleS ? "S" : "N/A")) monthlyTrend1 = currentCandleDirection weeklyTrend1 = request.security(syminfo.tickerid, "W", currentCandleDirection) dailyTrend1 = request.security(syminfo.tickerid, "D", currentCandleDirection) fourHourTrend1 = request.security(syminfo.tickerid, "240", currentCandleDirection) oneHourTrend1 = request.security(syminfo.tickerid, "60", currentCandleDirection) monthlyTrend2 = rsiTrendDirection weeklyTrend2 = request.security(syminfo.tickerid, "W", rsiTrendDirection) dailyTrend2 = request.security(syminfo.tickerid, "D", rsiTrendDirection) fourHourTrend2 = request.security(syminfo.tickerid, "240", rsiTrendDirection) oneHourTrend2 = request.security(syminfo.tickerid, "60", rsiTrendDirection) // Display the table tblpos(add) => switch add "bottomR"=> position.bottom_right "bottomC" => position.bottom_center "bottomL" => position.bottom_left "topR" => position.top_right "topC" => position.top_center "topL" => position.top_left =>position.middle_center tableData = table.new(position = tblpos(tabfancy), columns = 4, rows = 7, bgcolor = color.white) table.cell(tableData, 0, 0, "", bgcolor=color.yellow) table.cell(tableData, 1, 0, "T", bgcolor=color.yellow) table.cell(tableData, 2, 0, "C", bgcolor=color.yellow) table.cell(tableData, 3, 0, "R", bgcolor=color.yellow) table.cell(tableData, 0, 1, "M", bgcolor=color.blue, text_color = color.white) table.cell(tableData, 0, 2, "W", bgcolor=color.blue,text_color = color.white) table.cell(tableData, 0, 3, "D", bgcolor=color.blue, text_color = color.white) table.cell(tableData, 0, 4, "4h", bgcolor=color.blue, text_color = color.white) table.cell(tableData, 0, 5, "1h", bgcolor=color.blue, text_color = color.white) table.cell(tableData, 1, 1, monthlyTrend) table.cell(tableData, 1, 2, weeklyTrend) table.cell(tableData, 1, 3, dailyTrend) table.cell(tableData, 1, 4, fourHourTrend) table.cell(tableData, 1, 5, oneHourTrend) table.cell(tableData, 2, 1, monthlyTrend1) table.cell(tableData, 2, 2, weeklyTrend1) table.cell(tableData, 2, 3, dailyTrend1) table.cell(tableData, 2, 4, fourHourTrend1) table.cell(tableData, 2, 5, oneHourTrend1) table.cell(tableData, 3, 1, monthlyTrend2) table.cell(tableData, 3, 2, weeklyTrend2) table.cell(tableData, 3, 3, dailyTrend2) table.cell(tableData, 3, 4, fourHourTrend2) table.cell(tableData, 3, 5, oneHourTrend2) hvbBullColor = input.color(defval=color.green, title='Bullish HVB Color', inline='Set Custom Color', group='High Volume Bar') hvbBearColor = input.color(defval=color.red, title='Bearish HVB Color', inline='Set Custom Color', group='High Volume Bar') hvbEMAPeriod = input.int(defval=50, minval=1, title='Volume EMA Period', group='High Volume Bar') hvbMultiplier = input.float(defval=1.5, title='Volume Multiplier', minval=1, maxval=100, group='High Volume Bar') //Functions isUp(index) => close[index] > open[index] isDown(index) => close[index] < open[index] volEma = ta.ema(volume, hvbEMAPeriod) isHighVolume = volume > (hvbMultiplier * volEma) barcolor(isUp(0) and isHighVolume ? hvbBullColor : na, title="Bullish HVB") barcolor(isDown(0) and isHighVolume ? hvbBearColor : na, title="Bearish HVB") attention = input.float(0.15, minval=0.010, title='Doji') release = input(false, title='Above') barcolor(math.abs(open - close) <= (high - low) * attention ? color.rgb(58, 214, 249) : na) doji = math.abs(open - close) <= (high - low) * attention ? 1 : 0 plotshape(release ? doji :na, style=shape.labeldown, color=color.new(#ffffff, 0), location=location.top, size=size.huge, title='Doji') plot(release ? doji :na, style=plot.style_stepline, color=color.rgb(0, 206, 196), linewidth=2, transp=20) plotshape(doji, title = "Doji", text = '', style = shape.cross, location = location.belowbar, color= color.rgb(249, 249, 249),textcolor = color.white, transp = 90, size = size.tiny) // parameters definition rsiLength1 = input(14, "Periodi RSI") overboughtThreshold1 = input(80, "Soglia overbought") oversoldThreshold1 = input(20, "Soglia oversold") // Calculate ofRSI rsiValue1 = ta.rsi(open, rsiLength1) // candle color calculation based on RSI candleColor1 = rsiValue1 >= overboughtThreshold1 or rsiValue1 <= oversoldThreshold1 ? color.yellow : na barcolor(candleColor1)
Price Range Volume Profile [Pt]
https://www.tradingview.com/script/gSWit7xP-Price-Range-Volume-Profile-Pt/
PtGambler
https://www.tradingview.com/u/PtGambler/
202
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© PtGambler //@version=5 indicator("Price Range Volume Profile [Pt]", "PRVP [Pt]", true, max_bars_back = 5000, max_lines_count = 500, max_boxes_count = 500,max_labels_count = 500, explicit_plot_zorder = true) group_volume_profile = 'Volume Profile ---------------------------------------------------------' group_extra = 'Extra ------------------------------------------------------------------' priceRange = input.float(2, 'Price Range, % distance', minval = 0.5, step = 0.5, group = group_volume_profile, confirm = true, inline = 'pr') /100 ps = input.float(0, 'Profile Step size (tick)', inline = 'mintick', step = 0.1, group = group_volume_profile, confirm = true, tooltip = 'Choose 0 for auto step size') var initial_open_price = 0. if bar_index == 0 initial_open_price := open if ps == 0 ps := math.round_to_mintick(initial_open_price / 2000) else ps := math.round_to_mintick(ps) lookbackLength = input.int(3000, 'Historical bars Lookback', minval = 100, maxval = 20000, step = 100 , group = group_volume_profile, confirm = true, inline = 'lb', tooltip = 'Do not exceed 10000 if you are not subscribed to Premium TradingView account') fullRangeLB = input.bool(true, 'β”” Full Historical Lookback', group = group_volume_profile, confirm = true) if lookbackLength > last_bar_index and last_bar_index > 10000 runtime.error('Historical bars Lookback period exceeds your TradingView subscription limit. Please reduce.') volumeProfile = input.bool(true, 'Volume Profile', inline='ZZ', group = group_volume_profile) nonVaColor = input.color(color.new(#3fdcff, 30), '', inline='ZZ', group = group_volume_profile) show_poc = input.bool(true, 'Point of Control (POC)', inline = 'poc', group = group_volume_profile) poc_color = input.color(color.orange, '', inline = 'poc', group = group_volume_profile) profileWidth = input.int(300, 'Profile Width', minval = 25, maxval = 300 , group = group_volume_profile, inline = 'pw') horizontalOffset = input.int(40, 'Horizontal Offset', minval = 0 , maxval = 200 , group = group_volume_profile, inline = 'ho') applyBackColor = input.bool(false, 'Background Fill of Profile Range' , inline = 'BG', group = group_volume_profile) backgroundColor = input.color(color.new(#2962ff, 90), '' , inline = 'BG', group = group_volume_profile) timeWeighted = input.bool(false, 'Time Weighted Profile', group = group_volume_profile, inline = 'tw') timeWeight_pow = input.int(2, '| Power', group = group_volume_profile, inline = 'tw') smoothing = input.bool(false, 'Smooth filter', group = group_volume_profile, inline = 'sm') sm_len = input.int(3, '| Length', group = group_volume_profile, inline = 'sm') show_table = input.bool(true,"Show Settings", group= group_extra, inline="Table") tableLocation = input.string(defval='Bottom right', options=['Top left', 'Top center', 'Top right', 'Bottom left', 'Bottom center', 'Bottom right'], title='| Location', group=group_extra, inline="Table") tablePosition = tableLocation == 'Top left' ? position.top_left : tableLocation == 'Top center' ? position.top_center : tableLocation == 'Top right' ? position.top_right : tableLocation == 'Bottom left' ? position.bottom_left : tableLocation == 'Bottom center' ? position.bottom_center : position.bottom_right font_size = input.string('Normal', "    └ Font Size", options = ['Auto', 'Tiny', 'Small', 'Normal', 'Large'], group= group_extra, inline = 'font') stbar = fullRangeLB ? 0 : last_bar_index - lookbackLength bs_lastSession = nz(ta.barssince(session.isfirstbar)) var a_pv = array.new_box() var m_pvol = matrix.new<float>(1,2) var m_pvol_sm = matrix.new<float>(1,2) var poclvl = 0. noError = true b_lvlblw = false lvlblw = 0 bpl = low bph = high nzVol = nz(volume) var ath = 0.0 var atl = 0.0 var pb = low var stpb = low if bar_index > stbar ath := high > nz(ath[1]) or ath <= 0 ? high : nz(ath[1]) atl := low < nz(atl[1]) or atl <= 0 ? low : nz(atl[1]) atl := atl - ((atl - pb) % ps) prh = math.min(math.round_to_mintick(close + (close*priceRange)), ath) prl = math.max(math.round_to_mintick(close - (close*priceRange)), atl) prl := prl - ((prl - pb) % ps) // Functions ----------------------------------------------------------------------------------- f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) => var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size, _textalign, _tooltip) label.set_xy(id, _x, _y) label.set_text(id, _text) label.set_tooltip(id, _tooltip) label.set_textcolor(id, _textcolor) id f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) => var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) line.set_xy1(id, _x1, _y1) line.set_xy2(id, _x2, _y2) line.set_color(id, _color) id f_drawBoxX(_left, _top, _right, _bottom, _border_color, _border_width, _border_style, _bgcolor) => var id = box.new(_left, _top, _right, _bottom, _border_color, _border_width, _border_style, bgcolor = _bgcolor) box.set_left(id, _left) box.set_top(id, _top) box.set_right(id, _right) box.set_bottom(id, _bottom) id f_tfIsIntraday(_res) => [intraday, daily, weekly, monthly] = request.security(syminfo.tickerid, _res, [timeframe.isintraday, timeframe.isdaily, timeframe.isweekly, timeframe.ismonthly]) check = intraday ? "Intraday" : daily ? "Daily" : weekly ? "Weekly" : monthly ? "Monthly" : "Error" check // Main Calculations and data collection ---------------------------------------------------- stpb := bpl > bph[1] ? bph[1] : bpl if bpl > atl[1] stpb := stpb - ((stpb - pb) % ps) else if bpl < atl[1] b_lvlblw := true lvlblw := math.ceil((atl[1] - stpb) / ps) stpb := atl stlvl = math.floor((stpb - atl) / ps) endlvl = math.ceil((bph - atl) / ps) blvl = endlvl - stlvl + 1 tlvl = nz(matrix.rows(m_pvol)) tw_factor = timeWeighted ? math.pow(math.max((bar_index - stbar), 0) / (last_bar_index - stbar),timeWeight_pow) : 1 if bar_index >= stbar and bar_index < stbar + 2 for lvl = 0 to blvl - 1 pl = pb + ps * lvl matrix.add_row(m_pvol) matrix.set(m_pvol, lvl, 0, pl) matrix.set(m_pvol, lvl, 1, volume[1] / blvl * tw_factor) if barstate.isconfirmed and bar_index > stbar + 1 and nzVol if b_lvlblw for lvl = 1 to lvlblw pl = atl[1] - ps * lvl matrix.add_row(m_pvol, 0) matrix.set(m_pvol, 0, 0, pl) for lvl = stlvl to endlvl if lvl >= 0 if lvl < tlvl matrix.set(m_pvol, lvl, 1, nz(matrix.get(m_pvol, lvl, 1)) + nzVol / blvl * tw_factor) else if lvl >= tlvl pl = atl[1] + ps * lvl matrix.add_row(m_pvol) matrix.set(m_pvol, lvl, 0, pl) matrix.set(m_pvol, lvl, 1, nz(matrix.get(m_pvol, lvl, 1)) + nzVol / blvl * tw_factor) if smoothing m_pvol_sm := matrix.copy(m_pvol) for i = 0 to matrix.rows(m_pvol_sm)-1 sum_vol = 0.0 count = 0 for j = -sm_len/2 to sm_len/2 if i+j >= 0 and i+j < matrix.rows(m_pvol_sm) sum_vol := sum_vol + nz(matrix.get(m_pvol, i+j, 1)) count := count + 1 matrix.set(m_pvol_sm, i, 1, sum_vol / count) vpl = math.max(math.floor((prl - atl) / ps), 0) vph = math.min(math.floor((prh - atl) / ps), matrix.rows(m_pvol)-1) vplvl = vph - vpl // Error handling ---------------------------------------------------------- option1 = '- Increase Profile Step size (tick)\n' option2 = '- Reduce Price Range, % distance\n' error_text = '' total_boxes = vplvl if total_boxes > 500 noError := false if barstate.islast and not noError error_text := 'There are too many levels (' + str.tostring(vplvl) + ') shown on the volume profile. \nIt must be <500. Considering the following options: \n' + option1 + option2 f_drawLabelX(last_bar_index, close, error_text, xloc.bar_index, yloc.price, color.new(color.red,90), label.style_label_left, chart.fg_color, size.large, text.align_left, '') // Plotting Profile ------------------------------------------------------- if barstate.islast and nzVol and noError if array.size(a_pv) > 0 for i = 0 to array.size(a_pv) - 1 box.delete(array.shift(a_pv)) maxVol = 0. for lvl = vpl to vph - 1 maxVol := math.max(maxVol, smoothing ? nz(matrix.get(m_pvol_sm, lvl, 1)) : nz(matrix.get(m_pvol, lvl, 1))) for lvl = vpl to vph - 1 lvlvol = smoothing ? nz(matrix.get(m_pvol_sm, lvl, 1)) : nz(matrix.get(m_pvol, lvl, 1)) if volumeProfile lvlCol = nonVaColor stind = bar_index + profileWidth + horizontalOffset - math.ceil(profileWidth * (lvlvol / maxVol)) endind = bar_index + profileWidth + horizontalOffset array.push(a_pv, box.new(stind, atl + (lvl + 0.9) * ps, endind, atl + (lvl + 0.1) * ps, lvlCol, bgcolor = lvlCol)) if lvlvol == maxVol poclvl := atl + (lvl + 0.5) * ps if show_poc f_drawLineX(bar_index, poclvl, bar_index + profileWidth + horizontalOffset, poclvl, xloc.bar_index, extend.left, poc_color, line.style_solid, 2) if applyBackColor f_drawBoxX(math.max(stbar, bar_index-5000), prh, bar_index, prl, backgroundColor, 1, line.style_dotted, backgroundColor) // Table -------------------------------------------------------------------------------------------------------------- var displayTable = table.new(tablePosition, 1, 9, border_width=1) f_fillCell(_row, _column,series string _cellText) => switch font_size "Auto" => table.cell(displayTable, _column, _row, _cellText, bgcolor=color.new(chart.bg_color,90), text_color=color.white, text_halign = text.align_left, text_valign = text.align_center, text_size = size.auto) "Tiny" => table.cell(displayTable, _column, _row, _cellText, bgcolor=color.new(chart.bg_color,90), text_color=color.white, text_halign = text.align_left, text_valign = text.align_center, text_size = size.tiny) "Small" => table.cell(displayTable, _column, _row, _cellText, bgcolor=color.new(chart.bg_color,90), text_color=color.white, text_halign = text.align_left, text_valign = text.align_center, text_size = size.small) "Normal" => table.cell(displayTable, _column, _row, _cellText, bgcolor=color.new(chart.bg_color,90), text_color=color.white, text_halign = text.align_left, text_valign = text.align_center, text_size = size.normal) "Large" => table.cell(displayTable, _column, _row, _cellText, bgcolor=color.new(chart.bg_color,90), text_color=color.white, text_halign = text.align_left, text_valign = text.align_center, text_size = size.large) if barstate.islast and show_table f_fillCell(0, 0, '% range: ' + str.tostring(priceRange*100) + "%") f_fillCell(1, 0, 'Tick size: ' + str.tostring(ps)) f_fillCell(2, 0, 'VP levels: ' + str.tostring(vplvl) + ' (500 Max)') f_fillCell(3, 0, 'Lookback length: ' + (fullRangeLB ? 'Full History' : str.tostring(lookbackLength) + ' Bars')) f_fillCell(4, 0, 'Time Weighted: ' + (timeWeighted ? 'ON' : 'OFF'))
Pivot Point Trend Line
https://www.tradingview.com/script/NIuGTgAO-Pivot-Point-Trend-Line/
jadeja_rajdeep
https://www.tradingview.com/u/jadeja_rajdeep/
135
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jadeja_rajdeep //@version=5 indicator("Pivot Point Trend Line",overlay = true) high_1=input.int(20,'Pivot High - 1') high_2=input.int(15,'Pivot High - 2') low_1=input.int(15,'Pivot Low - 1') low_2=input.int(10,'Pivot Low - 2') pph=ta.pivothigh(high,high_1,high_2) ppl=ta.pivotlow(low,low_1,low_2) var high1=0.0 var low1=0.0 var int barindexh1=na var int barindexl1=na var high2=0.0 var low2=0.0 var int barindexh2=na var int barindexl2=na var high3=0.0 var low3=0.0 var int barindexh3=na var int barindexl3=na var high4=0.0 var low4=0.0 var int barindexh4=na var int barindexl4=na var high5=0.0 var low5=0.0 var int barindexh5=na var int barindexl5=na var line lineh1 = na var line lineh2 = na var line lineh3 = na var line lineh4 = na var line linel1 = na var line linel2 = na var line linel3 = na var line linel4 = na if(pph) high5:=high4 barindexh5:=barindexh4 high4:=high3 barindexh4:=barindexh3 high3:=high2 barindexh3:=barindexh2 high2:=high1 barindexh2:=barindexh1 high1:=high[high_2] barindexh1:=bar_index - high_2 if(ppl) low5:=low4 barindexl5:=barindexl4 low4:=low3 barindexl4:=barindexl3 low3:=low2 barindexl3:=barindexl2 low2:=low1 barindexl2:=barindexl1 low1:=low[low_2] barindexl1:=bar_index - low_2 if(bar_index==last_bar_index) if(high2 > 0) line.delete(lineh1) lineh1:=line.new(x1=barindexh2,y1=high2,x2=barindexh1,y2=high1,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.red) if(high3 > 0) line.delete(lineh2) lineh2:=line.new(x1=barindexh3,y1=high3,x2=barindexh2,y2=high2,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.red) if(high4 > 0) line.delete(lineh3) lineh3:=line.new(x1=barindexh4,y1=high4,x2=barindexh3,y2=high3,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.red) if(high5 > 0) line.delete(lineh4) lineh4:=line.new(x1=barindexh5,y1=high5,x2=barindexh4,y2=high4,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.red) if(low2 > 0) line.delete(linel1) linel1:=line.new(x1=barindexl2,y1=low2,x2=barindexl1,y2=low1,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.green) if(low3 > 0) line.delete(linel2) linel2:=line.new(x1=barindexl3,y1=low3,x2=barindexl2,y2=low2,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.green) if(low4 > 0) line.delete(linel3) linel3:=line.new(x1=barindexl4,y1=low4,x2=barindexl3,y2=low3,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.green) if(low5 > 0) line.delete(linel4) linel4:=line.new(x1=barindexl5,y1=low5,x2=barindexl4,y2=low4,xloc=xloc.bar_index,extend=extend.right,style=line.style_solid,color=color.green)
Average Range Lines
https://www.tradingview.com/script/z6wDA6zP-Average-Range-Lines/
BigGuavaTrading
https://www.tradingview.com/u/BigGuavaTrading/
55
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© BigGuavaTrading //@version=5 indicator("Average Range Lines", "Average Range Lines", true) //Average Daily Range Lines length = input(14, "Lookback Period", group = "Average Range") timeframe = input.timeframe(defval = "W", title = "Input Timeframe") timehigh = request.security(syminfo.tickerid, timeframe, high) timelow = request.security(syminfo.tickerid, timeframe, low) avgrange = ta.sma(timehigh,length)-ta.sma(timelow,length) //Define Range Lines openup2_0 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*2.0)), barmerge.gaps_off, barmerge.lookahead_on) openup1_75 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*1.75)), barmerge.gaps_off, barmerge.lookahead_on) openup1_5 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*1.5)), barmerge.gaps_off, barmerge.lookahead_on) openup1_25 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*1.25)), barmerge.gaps_off, barmerge.lookahead_on) openup1_0 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*1)), barmerge.gaps_off, barmerge.lookahead_on) openup0_75 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*.75)), barmerge.gaps_off, barmerge.lookahead_on) openup0_5 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*.5)), barmerge.gaps_off, barmerge.lookahead_on) openup0_25 = request.security(syminfo.tickerid, timeframe, (open + (avgrange*.25)), barmerge.gaps_off, barmerge.lookahead_on) open0_0 = request.security(syminfo.tickerid, timeframe, open, barmerge.gaps_off, barmerge.lookahead_on) opendown0_25 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*.25)), barmerge.gaps_off, barmerge.lookahead_on) opendown0_5 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*.5)), barmerge.gaps_off, barmerge.lookahead_on) opendown0_75 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*.75)), barmerge.gaps_off, barmerge.lookahead_on) opendown1_0 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*1)), barmerge.gaps_off, barmerge.lookahead_on) opendown1_25 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*1.25)), barmerge.gaps_off, barmerge.lookahead_on) opendown1_5 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*1.5)), barmerge.gaps_off, barmerge.lookahead_on) opendown1_75 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*1.75)), barmerge.gaps_off, barmerge.lookahead_on) opendown2_0 = request.security(syminfo.tickerid, timeframe, (open - (avgrange*2.0)), barmerge.gaps_off, barmerge.lookahead_on) //Plot Range Lines color = input(color.purple, "Apply same color to all lines") plot(openup2_0, "+2.0 Range", color, 2, plot.style_cross) plot(openup1_75, "+1.75 Range", color, 2, plot.style_circles) plot(openup1_5, "+1.5 Range", color, 2, plot.style_cross) plot(openup1_25, "+1.25 Range", color, 2, plot.style_circles) plot(openup1_0, "+1.0 Range", color, 2, plot.style_cross) plot(openup0_75, "+0.75 Range", color, 2, plot.style_circles) plot(openup0_5, "+0.5 Range", color, 2, plot.style_cross) plot(openup0_25, "+0.25 Range", color, 2, plot.style_circles) plot(open0_0, "Timeframe Open", color, 2, plot.style_cross) plot(opendown0_25, "-0.25 Range", color, 2, plot.style_circles) plot(opendown0_5, "-0.5 Range", color, 2, plot.style_cross) plot(opendown0_75, "-0.75 Range", color, 2, plot.style_circles) plot(opendown1_0, "-1.0 Range", color, 2, plot.style_cross) plot(opendown1_25, "-1.25 Range", color, 2, plot.style_circles) plot(opendown1_5, "-1.5 Range", color, 2, plot.style_cross) plot(opendown1_75, "-1.75 Range", color, 2, plot.style_circles) plot(opendown2_0, "-2.0 Range", color, 2, plot.style_cross) //Labelling var label label_openup2_0 = na label.delete(label_openup2_0) label_openup2_0 := label.new (barstate.islast ? bar_index : na, openup2_0, text=" +2.0", style= label.style_none, textcolor = color, size = size.normal) var label label_openup1_75 = na label.delete(label_openup1_75) label_openup1_75 := label.new (barstate.islast ? bar_index : na, openup1_75, text=" +1.75", style= label.style_none, textcolor = color, size = size.normal) var label label_openup1_5 = na label.delete(label_openup1_5) label_openup1_5 := label.new (barstate.islast ? bar_index : na, openup1_5, text=" +1.5", style= label.style_none, textcolor = color, size = size.normal) var label label_openup1_25 = na label.delete(label_openup1_25) label_openup1_25 := label.new (barstate.islast ? bar_index : na, openup1_25, text=" +1.25", style= label.style_none, textcolor = color, size = size.normal) var label label_openup1_0 = na label.delete(label_openup1_0) label_openup1_0 := label.new (barstate.islast ? bar_index : na, openup1_0, text=" +1.0", style= label.style_none, textcolor = color, size = size.normal) var label label_openup0_75 = na label.delete(label_openup0_75) label_openup0_75 := label.new (barstate.islast ? bar_index : na, openup0_75, text=" +0.75", style= label.style_none, textcolor = color, size = size.normal) var label label_openup0_5 = na label.delete(label_openup0_5) label_openup0_5 := label.new (barstate.islast ? bar_index : na, openup0_5, text=" +0.5", style= label.style_none, textcolor = color, size = size.normal) var label label_openup0_25 = na label.delete(label_openup0_25) label_openup0_25 := label.new (barstate.islast ? bar_index : na, openup0_25, text=" +0.25", style= label.style_none, textcolor = color, size = size.normal) var label label_open0_0 = na label.delete(label_open0_0) label_open0_0 := label.new (barstate.islast ? bar_index : na, open0_0, text=" Open", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown0_25 = na label.delete(label_opendown0_25) label_opendown0_25 := label.new (barstate.islast ? bar_index : na, opendown0_25, text=" -0.25", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown0_5 = na label.delete(label_opendown0_5) label_opendown0_5 := label.new (barstate.islast ? bar_index : na, opendown0_5, text=" -0.5", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown0_75 = na label.delete(label_opendown0_75) label_opendown0_75 := label.new (barstate.islast ? bar_index : na, opendown0_75, text=" -0.75", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown1_0 = na label.delete(label_opendown1_0) label_opendown1_0 := label.new (barstate.islast ? bar_index : na, opendown1_0, text=" -1.0", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown1_25 = na label.delete(label_opendown1_25) label_opendown1_25 := label.new (barstate.islast ? bar_index : na, opendown1_25, text=" -1.25", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown1_5 = na label.delete(label_opendown1_5) label_opendown1_5 := label.new (barstate.islast ? bar_index : na, opendown1_5, text=" -1.5", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown1_75 = na label.delete(label_opendown1_75) label_opendown1_75 := label.new (barstate.islast ? bar_index : na, opendown1_75, text=" -1.75", style= label.style_none, textcolor = color, size = size.normal) var label label_opendown2_0 = na label.delete(label_opendown2_0) label_opendown2_0 := label.new (barstate.islast ? bar_index : na, opendown2_0, text=" -2.0", style= label.style_none, textcolor = color, size = size.normal)
High/Low of week: Stats & Day of Week tendencies
https://www.tradingview.com/script/xiOTzyRM-High-Low-of-week-Stats-Day-of-Week-tendencies/
twingall
https://www.tradingview.com/u/twingall/
73
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // High of week day and low of week day statistics // 'meta averages' showing HoW/LoW day averages across set of all possible custom week start/end days to filter out 'continuation bias' in seeking statistical evidence of day of week tendencies // August 3rd 2023 // Β© twingall //@version=5 indicator("High/Low of week: DAY of week; STATS", overlay=true, max_lines_count =500) useCustomStart =input.bool(false, "Use custom week start day:", group = "Week Start", inline = '1') _inputWkStrtDay = input.string("MON", "", group = "Week Start", options = ["MON","TUES","WEDS","THURS","FRI", "SAT", "SUN"], inline = '1', tooltip = "Choose arbitrary start day of week.\n\nUseful for teasing out the week-start/ week-end bias in the stats.\n\nAlso use this setting to skip over bank holiday weeks: if your input day was a bank holiday, its week is discounted from the stats ") showMetaAverages = input.bool(true, "Show Meta Averages", group = "Week Start", inline ='2', tooltip = "Shows the average frequencies/percentages across the set of all possible custom defined week start days.\n\nThis is an experimental attempt to negate the 'continuation bias' effect that comes from having a hard-defined week start/end time. Make of the results what you will.") showVerTable = input.bool(true, "Verification Table", group ="~~~ Verification ~~~",inline = '0') showNewWeekLines = input.bool(true, "Show New Week Lines:", group = "~~~ Verification ~~~", inline ='0') lineCount = input.int(10, "",group = "~~~ Verification ~~~", inline ='0') tablePosVer=input.string(position.top_right, "Table position:", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group="~~~ Verification ~~~", inline = '1') textSizeVer = input.string(size.normal, "Size:", options = [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], group="~~~ Verification ~~~", inline = '1') textColVer = input.color(color.blue, "Text color", group="~~~ Verification ~~~", inline = '2') borderColVer = input.color(color.blue, "Border color", group="~~~ Verification ~~~", inline = '2') _userTimezone = input.string("America/New_York", "(tweak timezone in case of misaligned days)", group ="~~~ Verification ~~~", inline ='3', options =["America/New_York", "syminfo.timezone", "UTC-10", "UTC-9", "UTC-8", "UTC-7", "UTC-6", "UTC-5", "UTC-4", "UTC-3", "UTC-2", "UTC-1","UTC", "UTC+1", "UTC+2", "UTC+3", "UTC+4","UTC+5","UTC+6","UTC+7","UTC+8","UTC+9","UTC+10","UTC+11","UTC+12","UTC+13"], tooltip = "Recommend leaving this as 'America/New_York' regardless of your timezone or your asset\n\nHowever, if you do encounter misaligned day values in the verification table, adjust this to fix..") showStatsTable = input.bool(true, "show |", group="~~~~ Statistics Table ~~~~", inline = '1') tablePos = input.string(position.bottom_right, "Table position:", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group="~~~~ Statistics Table ~~~~", inline = '1') textSize = input.string(size.large, "Size:", options = [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], group="~~~~ Statistics Table ~~~~", inline = '1') textCol = input.color(color.blue, "Text color:", group="~~~~ Statistics Table ~~~~", inline = '2') borderCol = input.color(color.blue, "Border color:", group="~~~~ Statistics Table ~~~~", inline = '2') useStartDate = input.bool(false, "use start date | ", inline = "1", group = "~~ Manual Backtesting Period ~~") startLineCol = input.color(color.red, "start line color", inline = "1", group = "~~ Manual Backtesting Period ~~", tooltip = "this line can be set manually here, or dragged across the chart to change") startLineWidth = input.int(2, "width", options= [1,2,3,4,5], inline = "1", group = "~~ Manual Backtesting Period ~~") startDate= input.time(timestamp("20 May 2023 00:00 +0300"), "Start Date", inline = "2", confirm = false, group = "~~ Manual Backtesting Period ~~") useEndDate = input.bool(false, "use end date | ", inline = "3", group = "~~ Manual Backtesting Period ~~") endLineCol = input.color(color.blue, "end line color", inline = "3", group = "~~ Manual Backtesting Period ~~", tooltip = "this line can be set manually here, or dragged across the chart to change") endLineWidth = input.int(2, "width", options= [1,2,3,4,5], inline = "3", group = "~~ Manual Backtesting Period ~~") endDate= input.time(timestamp("20 Jul 2023 00:00 +0300"), "End Date", inline = "4", confirm = false, group = "~~ Manual Backtesting Period ~~") /// Declaring Variables: var line lnStrt = na var line lnEnd = na var int lastWeekLength =na var float HoWval = na var float LoWval = na var int HoWdayInt = na var int LoWdayInt = na var array<int> HoWArr = array.new<int>(8,0) // need to be size 8 because i don't want to use the '0' element (dayofweek numbers are 1 >> 7) var array<int> LoWArr = array.new<int>(8,0) var int H_intLst=na var int L_intLst=na var int cusStTime = na var int cusEndTime = na var line vLine = na var array<line> vLineArr = array.new<line>(na) // for meta averages: var array<int> HoWArrMon = array.new<int>(8,0) , var array<int> LoWArrMon = array.new<int>(8,0) var int HoWdayIntMon = na, var int LoWdayIntMon = na, var int H_intLstMon=na, var int L_intLstMon=na, var int lastWeekLengthMon =na var array<int> HoWArrTue = array.new<int>(8,0), var array<int> LoWArrTue = array.new<int>(8,0) var int HoWdayIntTue = na, var int LoWdayIntTue = na, var int H_intLstTue=na, var int L_intLstTue=na, var int lastWeekLengthTue =na var array<int> HoWArrWed = array.new<int>(8,0), var array<int> LoWArrWed = array.new<int>(8,0) var int HoWdayIntWed = na, var int LoWdayIntWed = na, var int H_intLstWed=na, var int L_intLstWed=na, var int lastWeekLengthWed =na var array<int> HoWArrThu = array.new<int>(8,0), var array<int> LoWArrThu = array.new<int>(8,0) var int HoWdayIntThu = na, var int LoWdayIntThu = na, var int H_intLstThu=na, var int L_intLstThu=na, var int lastWeekLengthThu =na var array<int> HoWArrFri = array.new<int>(8,0), var array<int> LoWArrFri = array.new<int>(8,0) var int HoWdayIntFri = na, var int LoWdayIntFri = na, var int H_intLstFri=na, var int L_intLstFri=na, var int lastWeekLengthFri =na var array<int> HoWArrSat = array.new<int>(8,0), var array<int> LoWArrSat = array.new<int>(8,0) var int HoWdayIntSat = na, var int LoWdayIntSat = na, var int H_intLstSat=na, var int L_intLstSat=na, var int lastWeekLengthSat =na var array<int> HoWArrSun = array.new<int>(8,0), var array<int> LoWArrSun = array.new<int>(8,0) var int HoWdayIntSun = na, var int LoWdayIntSun = na, var int H_intLstSun=na, var int L_intLstSun=na, var int lastWeekLengthSun =na var VerTable = table.new(tablePosVer, columns = 26, rows = 12, border_width = 1,border_color= borderColVer) var Table = table.new(tablePos, columns = 9, rows = 16, border_width = 1,border_color= borderCol) //''''''''''''''''''''''''''''''''''''''''''''''''''''''''''| //''''''''''''''''''''''''''''''''''''''''''''''''''''''''''| // ~~~~~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~~~~~ wkStartAndEnd(int _lastWeekLength)=> int wkStartTime = na int wkEndTime = na if _lastWeekLength<8 wkStartTime:=time[_lastWeekLength] wkEndTime := time_close[1] if useCustomStart and _lastWeekLength==9 wkStartTime:=time[9] wkEndTime := time_close[5] if useCustomStart and _lastWeekLength==13 wkStartTime:=time[13] wkEndTime := time_close[9] [wkStartTime, wkEndTime] HiLoValAndDoW(bool isHigh, int _lastWeekLength, bool metAvgs)=> _hilo = isHigh?high:low array<float> HiLoArr = array.new<float>(7) array<int> HiLoTimeArr = array.new<int>(7) /// these should NOT be var, want them to reset on each bar if _lastWeekLength<8 for i = 1 to _lastWeekLength array.set(HiLoArr, i-1, _hilo[i]) array.set(HiLoTimeArr, i-1, time_close[i]) if (useCustomStart or metAvgs) and _lastWeekLength==9 // if custom day is missing (bank holiday), count only the prior 'full custom week' for i = 1 to 5 array.set(HiLoArr, i-1, _hilo[i+4]) array.set(HiLoTimeArr, i-1, time_close[i+4]) if (useCustomStart or metAvgs) and _lastWeekLength==13 // for custom day is missing (bank holiday), twice consecutively, count only prior 'full custom week' for i = 1 to 5 array.set(HiLoArr, i-1, _hilo[i+8]) array.set(HiLoTimeArr, i-1, time_close[i+8]) hiloVal = isHigh?array.max(HiLoArr):array.min(HiLoArr) hiloInd = array.indexof(HiLoArr,hiloVal) whenHiLo = hiloInd!=-1?array.get(HiLoTimeArr, hiloInd):na DoWHiLo = dayofweek(whenHiLo, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) [hiloVal, DoWHiLo] pctFxn(array<int> _arr, int _ind)=> float result = (array.get(_arr, _ind)/array.sum(_arr))*100 DayCellsFill(int col, int _day)=> table.cell(Table, col, 3, array.get(HoWArr, _day)!=0?str.tostring(array.get(HoWArr, _day)):" -- ", bgcolor =color.new(color.green, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) table.cell(Table, col, 4, array.get(HoWArr, _day)!=0?(str.tostring(pctFxn(HoWArr, _day), '0.0')+"%"):" -- ", bgcolor =color.new(color.green, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) table.cell(Table, col, 5, array.get(LoWArr, _day)!=0?str.tostring(array.get(LoWArr, _day)):" -- ", bgcolor =color.new(color.red, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) table.cell(Table, col, 6, array.get(LoWArr, _day)!=0?(str.tostring(pctFxn(LoWArr, _day), '0.0')+"%"):" -- ", bgcolor =color.new(color.red, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) DoW(int num)=> dayofweek(time_close, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) == num DoWstring(int _DoW)=> string dayString = switch _DoW 1 => "Sunday" 2 => "Monday" 3 => "Tuesday" 4 => "Wednesday" 5 => "Thursday" 6 => "Friday" 7 => "Saturday" => na incremMetaAvgs(int H, int L, array<int> arrH, array<int> arrL)=> H_intLast = array.get(arrH, H) array.set(arrH, H, H_intLast+1) L_intLast = array.get(arrL, L) array.set(arrL, L, L_intLast+1) metaAverage(int _day)=> if array.get(HoWArr, 1) ==0 and array.get(HoWArr, 7)==0 MetaAvgHoW= math.round( math.avg( array.get(HoWArrMon, _day), array.get(HoWArrTue, _day), array.get(HoWArrWed, _day), array.get(HoWArrThu, _day), array.get(HoWArrFri, _day))) MetaAvgLoW= math.round( math.avg( array.get(LoWArrMon, _day), array.get(LoWArrTue, _day), array.get(LoWArrWed, _day), array.get(LoWArrThu, _day), array.get(LoWArrFri, _day))) MetaAvgHoWpct = math.round(math.avg(pctFxn(HoWArrMon, _day), pctFxn(HoWArrTue, _day), pctFxn(HoWArrWed, _day), pctFxn(HoWArrThu, _day), pctFxn(HoWArrFri, _day)),2) MetaAvgLoWpct = math.round(math.avg(pctFxn(LoWArrMon, _day), pctFxn(LoWArrTue, _day), pctFxn(LoWArrWed, _day), pctFxn(LoWArrThu, _day), pctFxn(LoWArrFri, _day)),2) [MetaAvgHoW, MetaAvgLoW, MetaAvgHoWpct, MetaAvgLoWpct] else MetaAvgHoW= math.round( math.avg( array.get(HoWArrMon, _day), array.get(HoWArrTue, _day), array.get(HoWArrWed, _day), array.get(HoWArrThu, _day), array.get(HoWArrFri, _day), array.get(HoWArrSat, _day), array.get(HoWArrSun, _day))) MetaAvgLoW= math.round( math.avg( array.get(LoWArrMon, _day), array.get(LoWArrTue, _day), array.get(LoWArrWed, _day), array.get(LoWArrThu, _day), array.get(LoWArrFri, _day), array.get(LoWArrSat, _day), array.get(LoWArrSun, _day))) MetaAvgHoWpct = math.round(math.avg(pctFxn(HoWArrMon, _day), pctFxn(HoWArrTue, _day), pctFxn(HoWArrWed, _day), pctFxn(HoWArrThu, _day), pctFxn(HoWArrFri, _day), pctFxn(HoWArrSat, _day), pctFxn(HoWArrSun, _day)),2) MetaAvgLoWpct = math.round(math.avg(pctFxn(LoWArrMon, _day), pctFxn(LoWArrTue, _day), pctFxn(LoWArrWed, _day), pctFxn(LoWArrThu, _day), pctFxn(LoWArrFri, _day), pctFxn(LoWArrSat, _day), pctFxn(LoWArrSun, _day)),2) [MetaAvgHoW, MetaAvgLoW, MetaAvgHoWpct, MetaAvgLoWpct] metaAvgCellFill(int col, int superDayHoW, int superDayLoW, float superDayHoWpct, float superDayLoWpct)=> table.cell(Table, col, 8, superDayHoW!=0?str.tostring(superDayHoW):" -- ", bgcolor =color.new(color.green, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) table.cell(Table, col, 9, superDayHoWpct!=0?(str.tostring(superDayHoWpct, '0.0')+"%"):" -- ", bgcolor =color.new(color.green, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) table.cell(Table, col, 10, superDayLoW!=0?str.tostring(superDayLoW):" -- ", bgcolor =color.new(color.red, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) table.cell(Table, col, 11, superDayLoWpct!=0?(str.tostring(superDayLoWpct, '0.0')+"%"):" -- ", bgcolor =color.new(color.red, 80), text_size = textSize, text_color=textCol, text_halign =text.align_center) //..........................................................|| //..........................................................|| if barstate.islastconfirmedhistory and useStartDate and timeframe.isdaily lnStrt:=line.new(startDate, high, startDate, high+1, xloc = xloc.bar_time, color= startLineCol, extend = extend.both, width = startLineWidth) line.delete(lnStrt[1]) if barstate.islastconfirmedhistory and useEndDate and timeframe.isdaily lnEnd:=line.new(endDate, high, endDate, high+1, xloc = xloc.bar_time, color= endLineCol, extend = extend.both, width = endLineWidth) line.delete(lnEnd[1]) int inputWkStrtDay = switch _inputWkStrtDay "SUN" => 1 "MON" => 2 "TUES" => 3 "WEDS" => 4 "THURS" => 5 "FRI" => 6 "SAT" => 7 =>na tradNewWeek = timeframe.change('W') customNewWeek = dayofweek(time_close, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) == inputWkStrtDay // Sun = 1 new_week = useCustomStart?customNewWeek:tradNewWeek timeCond = useStartDate and useEndDate? time>startDate and time<endDate: useStartDate and not useEndDate? time>startDate: not useStartDate and useEndDate? time<endDate:true WeeklengthBarInd = ta.valuewhen(new_week, bar_index, 1) if new_week and bar_index >10 and timeCond and timeframe.isdaily lastWeekLength:= bar_index- WeeklengthBarInd [_HoWval, _DoWhi] = HiLoValAndDoW(true, lastWeekLength, false) [_LoWval, _DoWlo] = HiLoValAndDoW(false, lastWeekLength, false) [weekStTime, weekEndTime] = wkStartAndEnd(lastWeekLength) if new_week and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLength <8 or lastWeekLength==9 or lastWeekLength==13) HoWval:= _HoWval LoWval:= _LoWval HoWdayInt := _DoWhi LoWdayInt := _DoWlo H_intLst := array.get(HoWArr, HoWdayInt) // get last value for that day of week cumulative frequency array.set(HoWArr,HoWdayInt, H_intLst+1) // increment by 1 L_intLst := array.get(LoWArr, LoWdayInt) array.set(LoWArr,LoWdayInt, L_intLst+1) cusStTime:= weekStTime cusEndTime:=weekEndTime sumHoWs = array.sum(HoWArr) sumLoWs = array.sum(LoWArr) //''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|| //''''''''''''''''''''''''''''''''''''''''''''''''''''''''''|| // ~~~~~~~~~~~~~~~~ META AVERAGES ~~~~~~~~~~~~~~~~ monStart = DoW(2) tueStart = DoW(3) wedStart = DoW(4) thuStart = DoW(5) friStart = DoW(6) satStart = DoW(7) sunStart = DoW(1) WeeklengthBarIndMon = ta.valuewhen(monStart, bar_index, 1) WeeklengthBarIndTue = ta.valuewhen(tueStart, bar_index, 1) WeeklengthBarIndWed = ta.valuewhen(wedStart, bar_index, 1) WeeklengthBarIndThu = ta.valuewhen(thuStart, bar_index, 1) WeeklengthBarIndFri = ta.valuewhen(friStart, bar_index, 1) WeeklengthBarIndSat = ta.valuewhen(satStart, bar_index, 1) WeeklengthBarIndSun = ta.valuewhen(sunStart, bar_index, 1) if monStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthMon:= bar_index- WeeklengthBarIndMon [_HoWvalMon, _DoWhiMon] = HiLoValAndDoW(true, lastWeekLengthMon, true) [_LoWvalMon, _DoWloMon] = HiLoValAndDoW(false, lastWeekLengthMon, true) if monStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthMon <8 or lastWeekLengthMon==9 or lastWeekLengthMon==13) and showMetaAverages incremMetaAvgs(_DoWhiMon, _DoWloMon, HoWArrMon, LoWArrMon) if tueStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthTue:= bar_index- WeeklengthBarIndTue [_HoWvalTue, _DoWhiTue] = HiLoValAndDoW(true, lastWeekLengthTue, true) [_LoWvalTue, _DoWloTue] = HiLoValAndDoW(false, lastWeekLengthTue, true) if tueStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthTue <8 or lastWeekLengthTue==9 or lastWeekLengthTue==13) and showMetaAverages incremMetaAvgs(_DoWhiTue, _DoWloTue, HoWArrTue, LoWArrTue) if wedStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthWed:= bar_index- WeeklengthBarIndWed [_HoWvalWed, _DoWhiWed] = HiLoValAndDoW(true, lastWeekLengthWed, true) [_LoWvalWed, _DoWloWed] = HiLoValAndDoW(false, lastWeekLengthWed, true) if wedStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthWed <8 or lastWeekLengthWed==9 or lastWeekLengthWed==13) and showMetaAverages incremMetaAvgs(_DoWhiWed, _DoWloWed, HoWArrWed, LoWArrWed) if thuStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthThu:= bar_index- WeeklengthBarIndThu [_HoWvalThu, _DoWhiThu] = HiLoValAndDoW(true, lastWeekLengthThu, true) [_LoWvalThu, _DoWloThu] = HiLoValAndDoW(false, lastWeekLengthThu, true) if thuStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthThu <8 or lastWeekLengthThu==9 or lastWeekLengthThu==13) and showMetaAverages incremMetaAvgs(_DoWhiThu, _DoWloThu, HoWArrThu, LoWArrThu) if friStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthFri:= bar_index- WeeklengthBarIndFri [_HoWvalFri, _DoWhiFri] = HiLoValAndDoW(true, lastWeekLengthFri, true) [_LoWvalFri, _DoWloFri] = HiLoValAndDoW(false, lastWeekLengthFri, true) if friStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthFri <8 or lastWeekLengthFri==9 or lastWeekLengthFri==13) and showMetaAverages incremMetaAvgs(_DoWhiFri, _DoWloFri, HoWArrFri, LoWArrFri) if satStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthSat:= bar_index- WeeklengthBarIndSat [_HoWvalSat, _DoWhiSat] = HiLoValAndDoW(true, lastWeekLengthSat, true) [_LoWvalSat, _DoWloSat] = HiLoValAndDoW(false, lastWeekLengthSat, true) if satStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthSat <8 or lastWeekLengthSat==9 or lastWeekLengthSat==13) and showMetaAverages incremMetaAvgs(_DoWhiSat, _DoWloSat, HoWArrSat, LoWArrSat) if sunStart and bar_index >10 and timeCond and timeframe.isdaily and showMetaAverages lastWeekLengthSun:= bar_index- WeeklengthBarIndSun [_HoWvalSun, _DoWhiSun] = HiLoValAndDoW(true, lastWeekLengthSun, true) [_LoWvalSun, _DoWloSun] = HiLoValAndDoW(false, lastWeekLengthSun, true) if sunStart and bar_index >10 and timeCond and timeframe.isdaily and (lastWeekLengthSun <8 or lastWeekLengthSun==9 or lastWeekLengthSun==13) and showMetaAverages incremMetaAvgs(_DoWhiSun, _DoWloSun, HoWArrSun, LoWArrSun) [monMetaAvgHoW, monMetaAvgLoW, monMetaAvgHoWpct, monMetaAvgLoWpct] = metaAverage(2) [tueMetaAvgHoW, tueMetaAvgLoW, tueMetaAvgHoWpct, tueMetaAvgLoWpct] = metaAverage(3) [wedMetaAvgHoW, wedMetaAvgLoW, wedMetaAvgHoWpct, wedMetaAvgLoWpct] = metaAverage(4) [thuMetaAvgHoW, thuMetaAvgLoW, thuMetaAvgHoWpct, thuMetaAvgLoWpct] = metaAverage(5) [friMetaAvgHoW, friMetaAvgLoW, friMetaAvgHoWpct, friMetaAvgLoWpct] = metaAverage(6) [satMetaAvgHoW, satMetaAvgLoW, satMetaAvgHoWpct, satMetaAvgLoWpct] = metaAverage(7) [sunMetaAvgHoW, sunMetaAvgLoW, sunMetaAvgHoWpct, sunMetaAvgLoWpct] = metaAverage(1) //..........................................................|| //..........................................................|| // for displaying the start of traditional week & end of traditional week [_prevWkOpTime, _prevWkClTime] = request.security(syminfo.tickerid, "W", [time[1], time_close[1]]) PrevWkOpTime = str.format_time(_prevWkOpTime, "HH:mm", _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) PrevWkClTime = str.format_time(_prevWkClTime, "HH:mm", _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) _PrevWkOpDay = dayofweek(_prevWkOpTime, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) _PrevWkClDay = dayofweek(_prevWkClTime, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) PrevWkOpDay = DoWstring(_PrevWkOpDay) PrevWkClDay = DoWstring(_PrevWkClDay) // for displaying start start of custom week & end of custom week customPrevWkStTime = str.format_time(cusStTime, "HH:mm", _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) customPrevWkEndTime = str.format_time(cusEndTime, "HH:mm", _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) _customWkStartDay= dayofweek(cusStTime, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) _customWkEndDay = dayofweek(cusEndTime, _userTimezone=="syminfo.timezone"? syminfo.timezone:_userTimezone) customWkStartDay = DoWstring(_customWkStartDay) customWkEndDay = DoWstring(_customWkEndDay) HoWday = DoWstring(HoWdayInt) LoWday = DoWstring(LoWdayInt) if barstate.islast and timeframe.isdaily and showVerTable table.cell(VerTable, 0, 0, "~~ VERIFICATION ~~ (Last Week)",bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.merge_cells(VerTable, 0, 0, 2, 0) table.cell(VerTable,0, 1, "High of week: ", bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 1, 1, HoWday, bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable,2, 1, str.tostring(math.round_to_mintick(HoWval)), bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textCol, text_halign =text.align_center) table.cell(VerTable, 0, 2, "Low of week: ", bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 1, 2, LoWday, bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 2, 2, str.tostring(math.round_to_mintick(LoWval)), bgcolor =color.new(color.red, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 0, 3, "last week length (bars): ", bgcolor =color.new(color.gray, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.merge_cells(VerTable, 0, 3, 1, 3) table.cell(VerTable, 2, 3, str.tostring(lastWeekLength), bgcolor =color.new(color.gray, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 0, 4, text = useCustomStart? "~~ Custom Week ~~":"~~ Traditional Week ~~", bgcolor =color.new(color.orange, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.merge_cells(VerTable, 0, 4, 2, 4) table.cell(VerTable, 0, 5, "Week Start:", bgcolor =color.new(color.orange, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 1, 5, text = useCustomStart?(customWkStartDay+" "+customPrevWkStTime):(PrevWkOpDay+ " "+PrevWkOpTime), bgcolor =color.new(color.orange, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.merge_cells(VerTable, 1, 5, 2, 5) table.cell(VerTable, 0, 6, "Week End:", bgcolor =color.new(color.orange, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.cell(VerTable, 1, 6, text = useCustomStart?(customWkEndDay+" "+customPrevWkEndTime):(PrevWkClDay+ " "+PrevWkClTime), bgcolor =color.new(color.orange, 50), text_size = textSizeVer, text_color =textColVer, text_halign =text.align_center) table.merge_cells(VerTable, 1, 6, 2, 6) if barstate.islast and timeframe.isdaily and showStatsTable if useCustomStart table.cell(Table, 1, 0, "(Custom week start day = "+_inputWkStrtDay+")", bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.merge_cells(Table, 1, 0, 7, 0) table.cell(Table, 1, 1, "~~ STATISTICS ~~ || Asset = "+str.tostring(syminfo.ticker), bgcolor =color.new(color.blue, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.merge_cells(Table, 1, 1, 7, 1) table.cell(Table, 0, 1, str.tostring(sumHoWs)+ " = Weeks History\n(" +str.tostring(sumHoWs/52, '#.#')+" yrs)", bgcolor =color.new(color.red, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) //array.size to be inserted here table.cell(Table, 0, 2, "Day of week:" , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 3, "High of week (freq):" , bgcolor =color.new(color.green, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 4, "High of week (%):" , bgcolor =color.new(color.green, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 5, "Low of week (freq):" , bgcolor =color.new(color.red, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 6, "Low of week (%):" , bgcolor =color.new(color.red, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 1, 2, " MON " , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 2, 2, "TUES " , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 3, 2, "WEDS " , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 4, 2, "THURS" , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 5, 2, " FRI " , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 6, 2, " SAT " , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 7, 2, " SUN " , bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) DayCellsFill(1,2) DayCellsFill(2,3) DayCellsFill(3,4) DayCellsFill(4,5) DayCellsFill(5,6) DayCellsFill(6,7) DayCellsFill(7,1) if showMetaAverages table.cell(Table, 0,7, "~~ META AVERAGES: averages from set of all possible custom weeks ~~", bgcolor =color.new(color.yellow, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.merge_cells(Table, 0,7,7,7) table.cell(Table, 0, 8, "High of week (freq):" , bgcolor =color.new(color.green, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 9, "High of week (%):" , bgcolor =color.new(color.green, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 10, "Low of week (freq):" , bgcolor =color.new(color.red, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) table.cell(Table, 0, 11, "Low of week (%):" , bgcolor =color.new(color.red, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center) metaAvgCellFill(1, monMetaAvgHoW, monMetaAvgLoW, monMetaAvgHoWpct, monMetaAvgLoWpct) metaAvgCellFill(2, tueMetaAvgHoW, tueMetaAvgLoW, tueMetaAvgHoWpct, tueMetaAvgLoWpct) metaAvgCellFill(3, wedMetaAvgHoW, wedMetaAvgLoW, wedMetaAvgHoWpct, wedMetaAvgLoWpct) metaAvgCellFill(4, thuMetaAvgHoW, thuMetaAvgLoW, thuMetaAvgHoWpct, thuMetaAvgLoWpct) metaAvgCellFill(5, friMetaAvgHoW, friMetaAvgLoW, friMetaAvgHoWpct, friMetaAvgLoWpct) metaAvgCellFill(6, satMetaAvgHoW, satMetaAvgLoW, satMetaAvgHoWpct, satMetaAvgLoWpct) metaAvgCellFill(7, sunMetaAvgHoW, sunMetaAvgLoW, sunMetaAvgHoWpct, sunMetaAvgLoWpct) // wrong timeframe warning message if barstate.islast and not timeframe.isdaily table.cell(Table, 1, 0, "!! This indicator only works on Daily timeframe !!" , bgcolor =color.new(color.blue, 50), text_size = size.large, text_color =color.red, text_halign =text.align_center) // vertical new week lines if new_week and showNewWeekLines and timeframe.isdaily vLine:= line.new(bar_index, high, bar_index, high+1, extend=extend.both, style = line.style_dashed) array.push(vLineArr, vLine) if array.size(vLineArr)>lineCount line.delete(array.shift(vLineArr))
Volume Delta Methods (Chart) [LuxAlgo]
https://www.tradingview.com/script/OhLE0vnH-Volume-Delta-Methods-Chart-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
1,374
study
5
CC-BY-NC-SA-4.0
// 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("Volume Delta Methods (Chart) [LuxAlgo]", "LuxAlgo - Volume Delta Methods (Chart)", true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 5000) //------------------------------------------------------------------------------ // Settings //-----------------------------------------------------------------------------{ clGR = 'Calculation Settings' vdCT = 'This indicator uses two different intrabar analysis methods for the ​volume delta calculation:\n' + ' - buying/selling pressure of the intrabar (default), or\n - polarity of the intrabar\n\n' + 'Note : The most precise calculation method uses tick data but requires huge amounts of data on historical bars, ' + 'which usually limits the historical depth of charts' vdT1 = 'Intrabar Buying/Selling Pressure' vdT2 = 'Intrabar Polarity' vdCM = input.string(vdT1, 'Calculation Method', options = [vdT1, vdT2], group = clGR, tooltip = vdCT) tfTP = 'The indicator Precision is set by the input of the Lower Timeframe Precision. ' + 'If the Lower Timeframe Precision is set to AUTO, then the Lower Timeframe is determined by the following algorithm:\n\n' + ' - Chart Timeframe, Lower Timeframe\n' + ' <= 1 min 1 Sec\n' + ' <= 2 min 5 Sec\n' + ' <= 3 min 10 Sec\n' + ' <= 5 min 15 Sec\n' + ' <= 15 min 30 Sec\n' + ' <= 1 hour 1 min\n' + ' <= 2 hour 3 min\n' + ' <= 4 hour 5 min\n' + ' <= 1 day 15 min\n' + ' <= 1 week 1 hour\n' + ' > 1 week 1 day' vdLT = input.string('Auto', 'Lower Timeframe Precision', options=['Auto', '1 Sec', '5 Sec', '10 Sec', '15 Sec', '30 Sec', '1 Min', '3 Min', '5 Min', '15 Min', '30 Min', '1 Hour', '4 Hour', '1 Day'], group = clGR, tooltip = tfTP) prGR = 'Presentation Settings' vdTT = 'Volume Delta is the difference between buying and selling pressure. ' + 'Theoretically, Volume Delta is calculated by taking the difference of the volume that traded at the ask price and the volume that traded at the bid price.\n' + 'This indicator uses intrabar analysis to achieve the most approximate calculation of the ​volume delta' vlT1 = 'Volume Delta (Unipolarity)' vlT2 = 'Volume Delta (Buy/Sell Polarity)' vlT3 = 'Volume Delta + Regular Volume (Overlapping)' vlT4 = 'Volume Delta + Regular Volume (Non-Overlapping)' vdHG = input.string(vlT3, 'Volume Delta', options = [vlT1, vlT2, vlT3, vlT4, 'None'], group = prGR, tooltip = vdTT) cvdTT = 'Cumulative Volume Delta (CVD) takes the delta values for every bar and adds them together' cvdT1 = 'Line (Overlapping Price Bars)' cvdT2 = 'Line (Above Price Bars)' cvdT3 = 'Area (Above Price Bars)' cvdT4 = 'Baseline (Above Price Bars)' cvdT5 = 'Candles (Overlapping Price Bars)' cvdSH = input.string(cvdT4, 'Cumulative Volume Delta', options = [cvdT1, cvdT5, cvdT2, cvdT3, cvdT4, 'None'], group = prGR, tooltip = cvdTT) dvTT = 'Divergences occur when the polarity of ​volume delta does not match the polarity of the chart bar' vdDV = input.bool(false, 'Volume Delta/Price Bar Divergences', inline='V7', group = prGR, tooltip = dvTT) vdCL = input.color(color.new(#ff9800, 3), '', inline='V7', group = prGR) nvTT = 'Displays numerical values of the Volume Delta\n\n' + ' - green above the bar for positive delta\n' + ' - red below the bar for negative delta\n' + ' - orange when the polarity of the volume delete does not match the polarity of the bar' vdNV = input.bool(false, 'Volume Delta Numerical Values', inline='V73', group = prGR, tooltip = nvTT) vdLS = input.string('Tiny', "", options=['Auto', 'Tiny', 'Small', 'Normal'], inline = 'V73', group = prGR) otGR = 'Other Features' vlTT = 'Toggles the visibility of the average volume over a selected period of time\n\nNote: Applicable when Regular Volume Histogram display is enabled' vlMA = input.bool(true, 'Volume MA', inline='V3', group = otGR, tooltip = vlTT) vlLN = input.int(13, '', inline='V3', minval = 1, group = otGR) vlMC = input.color(color.new(#ff9800, 43), '', inline='V3', group = otGR) sigTT = 'Toggles the visibility of the Smoothing Line, calculated by applying an exponentially weighted moving average over the Cumulative Volume Delta\n\n' + 'Note: Applicable when Cumulative Volume Delta display is enabled' sigSH = input.bool(true, 'CVD Smoothing', inline='SMT1', group = otGR, tooltip = sigTT) sigML = input.int(7 , "", minval = 1, inline='SMT1', group = otGR) sigC = input.color(color.new(#FF6D00, 33), '', inline='SMT1', group = otGR) vdGR = 'Volume Delta, Others' vdUC = input.color(color.new(#26a69a, 33), 'Volume Delta : Positive' , inline='V1', group = vdGR, tooltip = 'Volume Delta color customization options') vdDC = input.color(color.new(#ef5350, 33), 'Negative', inline='V1', group = vdGR) vlUC = input.color(color.new(#9598a1, 53), 'Volume Histogram : Growing', inline='V2', group = vdGR, tooltip = 'Volume Histogram color customization options') vlDC = input.color(color.new(#9598a1, 83), 'Falling', inline='V2', group = vdGR) lnTT = 'Display Length is the length of the visual objects presented with this indicator. Possible values [5-500], where max of 500 length will be visualized ' + 'only if a single line and/or a single histogram enabled, second line or histogram will reduce lenght by half\n\n' + 'Note: When an indicator\'s output is in a different scale from the price scale then the general approach is to present them in a separate pane. ' + 'Unlike the general approach, this script presents the visuals on top of the price chart, which requires additional calculations ' + 'to re-scale the indicator\'s output to fit on top of the price chart. Besides re-scale calculations, the methods used to plot them ' + 'also differ which brings us to the limitation of PineScript (number of line, box, label limits) and hence the need to limit the Display Length of the visuals' vdLN = input.int(100, 'Display Length', minval = 5, step = 5, maxval = 500, group = vdGR, tooltip = lnTT) vdLN := last_bar_index < vdLN ? last_bar_index : vdLN vdPL = input.string('Bottom', 'Placement', options = ['Top', 'Bottom'], group = vdGR, tooltip = 'Volume Delta placment on the ptice chart.\n\nNote: if Volume Delta input option is selected as \'Volume Delta + Regular Volume (Non-Overlapping)\', then Regular Volume will be ploted in the opposite direction') vdHT = input.float(.7, 'Volume Delta Height' , minval = .1, maxval = 7, step = .1, group = vdGR, tooltip = 'Volume Delta Height - Possible values [0.1-7]') vlHT = input.float(.7, 'Volume Histogram Height' , minval = .1, maxval = 7, step = .1, group = vdGR, tooltip = 'Volume Histogram Height - Possible values [0.1-7]') vvVO = input.float(.07, 'Vertical Offset' , minval = -.7, maxval = .7, step = .01, group = vdGR, tooltip = 'Volume Delta and Volume Histogram Vertical Offset - Possible values [-0.7-0.7]') cvdGR = "Cumulative Volume Delta, Others" cvdW = input.int(2 , "CVD Line, Width", minval = 1, maxval = 5, inline='CVD', group = cvdGR, tooltip = 'Cumulative Volume Delta Line Width and Color') cvdC = input.color(color.new(#2962FF, 33), 'Color', inline='CVD', group = cvdGR) cvdBU = input.color(color.new(#2962FF, 89), 'CVD Area/Baseline, Gradient Coloring', inline='CVD1', group = cvdGR, tooltip = 'Cumulative Volume Delta Area and Baseline Gradient Coloring') cvdBD = input.color(color.new(#FF6D00, 89), '', inline='CVD1', group = cvdGR) cvdCU = input.color(color.new(#26a69a, 13), 'CVD Candles Color, Positive' , inline='CV1', group = cvdGR, tooltip = 'Cumulative Volume Delta Candles Coloring') cvdCD = input.color(color.new(#ef5350, 13), 'Negative', inline='CV1', group = cvdGR) sigBG = input.bool(true, "CVD/Smoothing Background", inline = 'BG', group = cvdGR, tooltip = 'Highlights and adjusts the transparency of the area between the Cumulative Volume Delta Line and it\'s Smoothing Line') sigBT = input.int(89 , "", inline = 'BG', minval = 0, maxval = 100, group = cvdGR) //-----------------------------------------------------------------------------} // User Defined Types //-----------------------------------------------------------------------------{ // @type bar properties with their values // // @field o (float) open price of the bar // @field h (float) high price of the bar // @field l (float) low price of the bar // @field c (float) close price of the bar // @field v (float) volume of the bar // @field i (int) index of the bar type bar float o = open float h = high float l = low float c = close float v = volume int i = bar_index //-----------------------------------------------------------------------------} // Variables //-----------------------------------------------------------------------------{ bar b = bar.new() nzV = nz(b.v) var aCVD = array.new_line() var aVD = array.new_box() var aBG = array.new_linefill() var aDV = array.new_label() mInMS = 60 * 1000 //-----------------------------------------------------------------------------} // Functions/Methods //-----------------------------------------------------------------------------{ // @function Calculates the volume of up and down bars // // @returns [float, float] the volume of up bars, and the volume of down bars f_calcV() => uV = 0., dV = 0. switch vdCM == vdT1 and (b.c - b.l) > (b.h - b.c) => uV += nzV vdCM == vdT1 and (b.c - b.l) < (b.h - b.c) => dV -= nzV vdCM == vdT2 and b.c > b.o => uV += nzV vdCM == vdT2 and b.c < b.o => dV -= nzV b.c > nz(b.c[1]) => uV += nzV b.c < nz(b.c[1]) => dV -= nzV nz(uV[1]) > 0 => uV += nzV nz(dV[1]) < 0 => dV -= nzV [uV, dV] // @function Calculates the Lower Timeframe based on the Input or Chart Resolution // // @returns [string] Lower Timeframe string f_calcLTF(_tf) => int tfInMs = timeframe.in_seconds() * 1000 switch _tf 'Auto' => tfInMs <= 1 * mInMS ? '1S' : tfInMs <= 2 * mInMS ? '5S' : tfInMs <= 3 * mInMS ? '10S' : tfInMs <= 5 * mInMS ? '15S' : tfInMs <= 15 * mInMS ? '30S' : tfInMs <= 60 * mInMS ? '1' : tfInMs <= 120 * mInMS ? '3' : tfInMs <= 240 * mInMS ? '5' : tfInMs <= 1440 * mInMS ? '15' : tfInMs <= 7 * 1440 * mInMS ? '60' : 'D' '1 Sec' => '1S' '5 Sec' => '5S' '10 Sec' => '10S' '15 Sec' => '15S' '30 Sec' => '30S' '1 Min' => '1' '3 Min' => '3' '5 Min' => '5' '15 Min' => '15' '30 Min' => '30' '1 Hour' => '60' '4 Hour' => '240' '1 Day' => '1D' //-----------------------------------------------------------------------------} // Calculations //-----------------------------------------------------------------------------{ [uV, dV] = request.security_lower_tf(syminfo.tickerid, f_calcLTF(vdLT), f_calcV()) tuV = uV.sum() tdV = dV.sum() vd = tuV + tdV cvd = ta.cum(vd) sig = sigSH ? ta.rma(cvd, sigML) : na pHST = ta.highest(b.h, vdLN) pLST = ta.lowest (b.l, vdLN) pCHG = (pHST - pLST) / pHST oHST = ta.highest(cvd, vdLN) oLST = ta.lowest (cvd, vdLN) vdHS = ta.highest(vd, vdLN) vHST = ta.highest(nzV, vdLN) vCHG = nzV/ta.sma(nzV, vlLN) bull = b.c > b.o vlPL = vdHG == vlT3 ? vdPL : vdPL == 'Top' ? 'Bottom' : 'Top' vdHT := vdHG == vlT3 or vdHG == vlT4 ? vdHT + 1.5 : vdHT nvS = switch vdLS 'Auto' => size.auto 'Tiny' => size.tiny 'Small' => size.small 'Normal' => size.normal if barstate.islast and nzV if aCVD.size() > 0 for i = 1 to aCVD.size() line.delete(aCVD.shift()) if aVD.size() > 0 for i = 1 to aVD.size() box.delete(aVD.shift()) if aBG.size() > 0 for i = 1 to aBG.size() linefill.delete(aBG.shift()) if aDV.size() > 0 for i = 1 to aDV.size() label.delete(aDV.shift()) for bI = 0 to vdLN - 1 if array.size(aCVD) < 500 if cvdSH != 'None' and cvdSH != cvdT5 aCVD.push(line.new(b.i[bI] , (cvdSH == cvdT1 ? pLST : cvdSH == cvdT3 ? pHST * (1 + pCHG * .1) : pHST) + (cvd[bI] - oLST) * (pHST - pLST) / (oHST - oLST), b.i[bI + 1], (cvdSH == cvdT1 ? pLST : cvdSH == cvdT3 ? pHST * (1 + pCHG * .1) : pHST) + (cvd[bI + 1] - oLST) * (pHST - pLST) / (oHST - oLST), xloc.bar_index, extend.none, cvdSH == cvdT4 ? color.from_gradient(pHST + (cvd[bI] - oLST) * (pHST - pLST) / (oHST - oLST), pHST, pHST + (pHST - pLST), sigC, cvdC) : cvdC, line.style_solid, cvdW)) if cvdSH == cvdT3 or cvdSH == cvdT4 aCVD.push(line.new(b.i[bI], pHST * (1 + pCHG * (cvdSH == cvdT4 ? .5 : .1)), b.i[bI + 1], pHST * (1 + pCHG * (cvdSH == cvdT4 ? .5 : .1)), xloc.bar_index, extend.none, color(na), line.style_solid, cvdW)) aBG.push(linefill.new(aCVD.get(vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 and sigSH ? 4 * bI : vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 or sigSH ? 3 * bI : 2 * bI), aCVD.get((vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 and sigSH ? 4 * bI : vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 or sigSH ? 3 * bI : 2 * bI) + 1), color.from_gradient(pHST + (cvd[bI] - oLST) * (pHST - pLST) / (oHST - oLST), pHST, pHST + (pHST - pLST), cvdBD, cvdBU) )) if sigSH and cvdSH != 'None' aCVD.push(line.new(b.i[bI] , (cvdSH == cvdT1 or cvdSH == cvdT5 ? pLST : cvdSH == cvdT3 ? pHST * (1 + pCHG * .1) : pHST) + (sig[bI] - oLST) * (pHST - pLST) / (oHST - oLST), b.i[bI + 1], (cvdSH == cvdT1 or cvdSH == cvdT5 ? pLST : cvdSH == cvdT3 ? pHST * (1 + pCHG * .1) : pHST) + (sig[bI + 1] - oLST) * (pHST - pLST) / (oHST - oLST), xloc.bar_index, extend.none, sigC, line.style_solid, 1)) if sigBG and cvdSH != 'None' and sigSH and cvdSH != cvdT3 and cvdSH != cvdT4 and cvdSH != cvdT5 aBG.push(linefill.new(aCVD.get(vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 ? 3 * bI : 2 * bI), aCVD.get((vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 ? 3 * bI : 2 * bI) + 1), cvd[bI] > sig[bI] ? color.new(cvdC, sigBT) : color.new(sigC, sigBT))) if vlMA and vdHG == vlT3 or vlMA and vdHG == vlT4 aCVD.push(line.new(b.i[bI] , (vlPL == 'Top' ? pHST * (1 + pCHG * vvVO) : pLST * (1 - pCHG * vvVO)) * (1 + (vlPL == 'Top' ? 1 : -1) * nzV[bI] / vHST * pCHG * vlHT / vCHG[bI]), b.i[bI + 1], (vlPL == 'Top' ? pHST * (1 + pCHG * vvVO) : pLST * (1 - pCHG * vvVO)) * (1 + (vlPL == 'Top' ? 1 : -1) * nzV[bI + 1] / vHST * pCHG * vlHT / vCHG[bI + 1]), xloc.bar_index, extend.none, vlMC, line.style_solid, 1)) if array.size(aVD) < 500 if vdHG == vlT3 or vdHG == vlT4 aVD.push(box.new (b.i[bI], vlPL == 'Top' ? pHST * (1 + pCHG * vvVO) : pLST * (1 - pCHG * vvVO), b.i[bI], (vlPL == 'Top' ? pHST * (1 + pCHG * vvVO) : pLST * (1 - pCHG * vvVO)) * (1 + (vlPL == 'Top' ? 1 : -1) * nzV[bI] / vHST * pCHG * vlHT), bull[bI] ? vlUC : vlDC, 2, bgcolor = color(na))) if vdHG != vlT2 and vdHG != 'None' aVD.push(box.new (b.i[bI], vdPL == 'Top' ? pHST * (1 + pCHG * vvVO) : pLST * (1 - pCHG * vvVO), b.i[bI], (vdPL == 'Top' ? pHST * (1 + pCHG * vvVO) : pLST * (1 - pCHG * vvVO)) * (1 + (vdPL == 'Top' ? 1 : -1) * math.abs(vd[bI]) / (vdHG == vlT3 ? vHST : vdHS) * pCHG / 2 * vdHT), vd[bI] > 0 ? vdUC : vdDC, 2, bgcolor = color(na))) if vdHG == vlT2 aVD.push(box.new (b.i[bI], vdPL == 'Top' ? pHST * (1 + pCHG * vvVO) + ((oHST - oLST) / 2) * (pHST - pLST) / (oHST - oLST) : pLST * (1 - pCHG * vvVO) - ((oHST - oLST) / 2) * (pHST - pLST) / (oHST - oLST), b.i[bI], (vdPL == 'Top' ? pHST * (1 + pCHG * vvVO) + ((oHST - oLST) / 2) * (pHST - pLST) / (oHST - oLST) : pLST * (1 - pCHG * vvVO) - ((oHST - oLST) / 2) * (pHST - pLST) / (oHST - oLST)) * (1 + vd[bI] / (vdHG == vlT3 ? vHST : vdHS) * pCHG / 2 * vdHT), vd[bI] > 0 ? vdUC : vdDC, 2, bgcolor = color(na))) if cvdSH == cvdT5 aVD.push(box.new (b.i[bI], pLST + (cvd[bI] - oLST) * (pHST - pLST) / (oHST - oLST), b.i[bI], pLST + (cvd[bI + 1] - oLST) * (pHST - pLST) / (oHST - oLST), vd[bI] > 0 ? cvdCU : cvdCD, 2, bgcolor = color(na))) vdS = 'Total Volume : ' + str.tostring(nzV[bI] , format.volume) + '\nBuy Volume : ' + str.tostring(tuV[bI] , format.volume) + '\nSell Volume : ' + str.tostring(-tdV[bI], format.volume) + '\nVolume Delta : ' + str.tostring(vd[bI] , format.volume) if vdNV if math.sign(b.c[bI] - b.o[bI]) != math.sign(vd[bI]) aDV.push(label.new(b.i[bI], bull[bI] ? b.h[bI] : b.l[bI], str.tostring(vd[bI], format.volume), color = color(na), style = bull[bI] ? label.style_label_down : label.style_label_up, size = nvS, textcolor = color.orange, tooltip = 'Divergence\n the polarity of ​volume delta does not match the polarity of the chart bar\n\n' + vdS)) else aDV.push(label.new(b.i[bI], bull[bI] ? b.h[bI] : b.l[bI], str.tostring(vd[bI], format.volume), color = color(na), style = bull[bI] ? label.style_label_down : label.style_label_up, size = nvS, textcolor = bull[bI] ? color.green : color.red, tooltip = vdS)) if vdDV and math.sign(b.c[bI] - b.o[bI]) != math.sign(vd[bI]) aDV.push(label.new(b.i[bI], b.h[bI] * (1 + pCHG * .04), '', color = vdCL, style = label.style_label_down, size = size.auto, tooltip = 'Divergence\n the polarity of ​volume delta does not match the polarity of the chart bar\n\n' + vdS)) //-----------------------------------------------------------------------------}
SPDR Tracker
https://www.tradingview.com/script/BjU7TOJH-SPDR-Tracker/
syntaxgeek
https://www.tradingview.com/u/syntaxgeek/
12
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© syntaxgeek //@version=5 indicator("SPDR Tracker", "SpdrT") import TradingView/ta/5 // { consts c_tableStyle_vertical = "Vertical" c_tableStyle_horizontal = "Horizontal" c_sym1 = "XLF" c_sym2 = "XLK" c_sym3 = "XLV" c_sym4 = "XLY" c_sym5 = "XLP" c_sym6 = "XLI" c_sym7 = "XLU" c_sym8 = "XLC" c_sym9 = "XLB" c_sym10 = "XLRE" c_sym11 = "XLE" c_mode_sma = "SMA" c_mode_ema = "EMA" c_mode_hma = "HMA" c_mode_vwma = "VWMA" c_mode_swma = "SWMA" c_mode_alma = "ALMA" c_mode_median = "Median" c_mode_bbw = "BBW" c_mode_kcw = "KCW" c_mode_rsi = "RSI" c_mode_atr = "ATR" c_mode_cci = "CCI" c_mode_mfi = "MFI" c_mode_change = "Change" c_mode_linreg = "LinReg" c_mode_vwap = "VWAP" c_mode_wpr = "WPR" c_mode_roc = "ROC" c_mode_adr = "ADR" c_mode_cog = "COG" c_mode_cmo = "CMO" c_mode_dev = "DEV" // } consts // { inputs i_symColor = input.color(color.white, "Symbol", inline="sym", group="Symbols") i_symEnabled = input.bool(true, "", inline="sym", group="Symbols") i_sym1Color = input.color(color.gray, "Financial (XLF)", inline="sym1", group="Symbols") i_sym1Enabled = input.bool(true, "", inline="sym1", group="Symbols") i_sym2Color = input.color(color.aqua, "Technology (XLK)", inline="sym2", group="Symbols") i_sym2Enabled = input.bool(true, "", inline="sym2", group="Symbols") i_sym3Color = input.color(color.blue, "Health Care (XLV)", inline="sym3", group="Symbols") i_sym3Enabled = input.bool(true, "", inline="sym3", group="Symbols") i_sym4Color = input.color(color.navy, "Consumer Discretionary (XLY)", inline="sym4", group="Symbols") i_sym4Enabled = input.bool(true, "", inline="sym4", group="Symbols") i_sym5Color = input.color(color.purple, "Consumer Staples (XLP)", inline="sym5", group="Symbols") i_sym5Enabled = input.bool(true, "", inline="sym5", group="Symbols") i_sym6Color = input.color(color.maroon, "Industrial (XLI)", inline="sym6", group="Symbols") i_sym6Enabled = input.bool(true, "", inline="sym6", group="Symbols") i_sym7Color = input.color(color.fuchsia, "Utilities (XLU)", inline="sym7", group="Symbols") i_sym7Enabled = input.bool(true, "", inline="sym7", group="Symbols") i_sym8Color = input.color(color.red, "Communication Services (XLC)", inline="sym8", group="Symbols") i_sym8Enabled = input.bool(true, "", inline="sym8", group="Symbols") i_sym9Color = input.color(color.yellow, "Materials (XLB)", inline="sym9", group="Symbols") i_sym9Enabled = input.bool(true, "", inline="sym9", group="Symbols") i_sym10Color = input.color(color.orange, "Real-Estate (XLRE)", inline="sym10", group="Symbols") i_sym10Enabled = input.bool(true, "", inline="sym10", group="Symbols") i_sym11Color = input.color(color.green, "Energy (XLE)", inline="sym11", group="Symbols") i_sym11Enabled = input.bool(true, "", inline="sym11", group="Symbols") i_mode = input.string("SMA", "Mode", options=[c_mode_sma, c_mode_ema, c_mode_hma, c_mode_vwma, c_mode_swma, c_mode_alma, c_mode_median, c_mode_bbw, c_mode_kcw, c_mode_rsi, c_mode_atr, c_mode_cci, c_mode_mfi, c_mode_change, c_mode_linreg, c_mode_vwap, c_mode_wpr, c_mode_roc, c_mode_adr, c_mode_cog, c_mode_cmo, c_mode_dev], inline="Mode", group="Presentation") i_modeLength = input.int(20, "Length", minval=1, step=1, inline="Mode", group="Presentation", tooltip="Only applies to certain modes, VWAP not included.") i_modeSource = input.source(close, "Source", inline="Mode", group="Presentation", tooltip="Will be the source for the mode if applicable, not all modes use source (such as " + c_mode_atr + ")") i_modeVWAPAnchor = input.string("Month", "Anchor", options=["Session", "Week", "Month", "Quarter", "Year", "Decade", "Century", "Earnings", "Dividends", "Splits"], tooltip="Only applies to VWAP") i_tableStyle = input.string(c_tableStyle_horizontal, "Style", options=[c_tableStyle_vertical, c_tableStyle_horizontal], group="Info Table") v_modeVWAPAnchor = switch i_modeVWAPAnchor "Session" => timeframe.change("D") "Week" => timeframe.change("W") "Month" => timeframe.change("M") "Quarter" => timeframe.change("3M") "Year" => timeframe.change("12M") "Decade" => timeframe.change("12M") and year % 10 == 0 "Century" => timeframe.change("12M") and year % 100 == 0 => false // } inputs // { funcs f_symDataMode() => switch(i_mode) c_mode_sma => ta.sma(i_modeSource, i_modeLength) c_mode_ema => ta.ema(i_modeSource, i_modeLength) c_mode_hma => ta.hma(i_modeSource, i_modeLength) c_mode_vwma => ta.vwma(i_modeSource, i_modeLength) c_mode_swma => ta.swma(i_modeSource) c_mode_median => ta.median(i_modeSource, i_modeLength) c_mode_bbw => ta.bbw(i_modeSource, i_modeLength, 2) c_mode_kcw => ta.kcw(i_modeSource, i_modeLength, 2, true) c_mode_rsi => ta.rsi(i_modeSource, i_modeLength) c_mode_atr => ta.atr(i_modeLength) c_mode_cci => ta.cci(i_modeSource, i_modeLength) c_mode_mfi => ta.mfi(i_modeSource, i_modeLength) c_mode_change => ta.change(i_modeSource, i_modeLength) c_mode_linreg => ta.linreg(i_modeSource, i_modeLength, 0) c_mode_vwap => ta.vwap(i_modeSource, v_modeVWAPAnchor) c_mode_wpr => ta.wpr(i_modeLength) c_mode_roc => ta.roc(i_modeSource, i_modeLength) c_mode_adr => ta.sma(high, i_modeLength) - ta.sma(low, i_modeLength) c_mode_cog => ta.cog(i_modeSource, i_modeLength) c_mode_cmo => ta.cmo(i_modeSource, i_modeLength) c_mode_dev => ta.dev(i_modeSource, i_modeLength) c_mode_alma => ta.alma(i_modeSource, i_modeLength, 0.85, 6) f_getSymData(_sym) => request.security(ticker.modify(_sym, session=session.extended), timeframe.period, [f_symDataMode(), volume, ta.change(close, 1)]) f_addTableSymbolStat(_table, _sym, _symColor, _symModeValue, _symChange, _symVolume, _symTooltip, _positionX, _positionY) => v_symTooltip = _symTooltip + " (" + i_mode + ", Price Change, Volume)" v_symStat = _sym + " (" + str.tostring(_symModeValue, format.mintick) + ", " + str.tostring(_symChange, format.mintick) + ", " + str.tostring(_symVolume, format.volume) + ")" table.cell(_table, _positionX, _positionY, v_symStat, bgcolor=color.white, tooltip=v_symTooltip, text_halign=text.align_left, text_size=size.small) table.cell(_table, _positionX + 1, _positionY, bgcolor=_symColor, width=0.5, tooltip=v_symTooltip) table.cell(_table, _positionX + 2, _positionY) f_createStatsTable() => if i_tableStyle == c_tableStyle_horizontal table.new(position.bottom_center, 37, 2) else table.new(position.top_left, 4, 13) // } funcs // { vars [_sym1ModeValue, _sym1Volume, _sym1Change] = f_getSymData(c_sym1) [_sym2ModeValue, _sym2Volume, _sym2Change] = f_getSymData(c_sym2) [_sym3ModeValue, _sym3Volume, _sym3Change] = f_getSymData(c_sym3) [_sym4ModeValue, _sym4Volume, _sym4Change] = f_getSymData(c_sym4) [_sym5ModeValue, _sym5Volume, _sym5Change] = f_getSymData(c_sym5) [_sym6ModeValue, _sym6Volume, _sym6Change] = f_getSymData(c_sym6) [_sym7ModeValue, _sym7Volume, _sym7Change] = f_getSymData(c_sym7) [_sym8ModeValue, _sym8Volume, _sym8Change] = f_getSymData(c_sym8) [_sym9ModeValue, _sym9Volume, _sym9Change] = f_getSymData(c_sym9) [_sym10ModeValue, _sym10Volume, _sym10Change] = f_getSymData(c_sym10) [_sym11ModeValue, _sym11Volume, _sym11Change] = f_getSymData(c_sym11) [_symModeValue, _symVolume, _symChange] = f_getSymData(syminfo.tickerid) var v_statsTable = f_createStatsTable() f_addTableSymbolStat(v_statsTable, c_sym1, i_sym1Color, _sym1ModeValue, _sym1Change, _sym1Volume, "Financial", i_tableStyle == c_tableStyle_vertical ? 1 : 1, i_tableStyle == c_tableStyle_vertical ? 1 : 1) f_addTableSymbolStat(v_statsTable, c_sym2, i_sym2Color, _sym2ModeValue, _sym2Change, _sym2Volume, "Technology", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 3, i_tableStyle == c_tableStyle_vertical ? 2 : 1) f_addTableSymbolStat(v_statsTable, c_sym3, i_sym3Color, _sym3ModeValue, _sym3Change, _sym3Volume, "Health Care", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 6, i_tableStyle == c_tableStyle_vertical ? 3 : 1) f_addTableSymbolStat(v_statsTable, c_sym4, i_sym4Color, _sym4ModeValue, _sym4Change, _sym4Volume, "Consumer Discretionary", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 9, i_tableStyle == c_tableStyle_vertical ? 4 : 1) f_addTableSymbolStat(v_statsTable, c_sym5, i_sym5Color, _sym5ModeValue, _sym5Change, _sym5Volume, "Consumer Staples", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 12, i_tableStyle == c_tableStyle_vertical ? 5 : 1) f_addTableSymbolStat(v_statsTable, c_sym6, i_sym6Color, _sym6ModeValue, _sym6Change, _sym6Volume, "Industrial", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 15, i_tableStyle == c_tableStyle_vertical ? 6 : 1) f_addTableSymbolStat(v_statsTable, c_sym7, i_sym7Color, _sym7ModeValue, _sym7Change, _sym7Volume, "Utilities", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 18, i_tableStyle == c_tableStyle_vertical ? 7 : 1) f_addTableSymbolStat(v_statsTable, c_sym8, i_sym8Color, _sym8ModeValue, _sym8Change, _sym8Volume, "Communication Services", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 21, i_tableStyle == c_tableStyle_vertical ? 8 : 1) f_addTableSymbolStat(v_statsTable, c_sym9, i_sym9Color, _sym9ModeValue, _sym9Change, _sym9Volume, "Materials", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 24, i_tableStyle == c_tableStyle_vertical ? 9 : 1) f_addTableSymbolStat(v_statsTable, c_sym10, i_sym10Color, _sym10ModeValue, _sym10Change, _sym10Volume, "Real-Estate", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 27, i_tableStyle == c_tableStyle_vertical ? 10 : 1) f_addTableSymbolStat(v_statsTable, c_sym11, i_sym11Color, _sym11ModeValue, _sym11Change, _sym11Volume, "Energy", i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 30, i_tableStyle == c_tableStyle_vertical ? 11 : 1) f_addTableSymbolStat(v_statsTable, syminfo.ticker, i_symColor, _symModeValue, _symChange, _symVolume, syminfo.description, i_tableStyle == c_tableStyle_vertical ? 1 : 1 + 33, i_tableStyle == c_tableStyle_vertical ? 12 : 1) v_style = plot.style_line // } vars // { plots plot(i_sym1Enabled ? _sym1ModeValue : na, c_sym1, color=i_sym1Color, style=v_style) plot(i_sym2Enabled ? _sym2ModeValue : na, c_sym2, color=i_sym2Color, style=v_style) plot(i_sym3Enabled ? _sym3ModeValue : na, c_sym3, color=i_sym3Color, style=v_style) plot(i_sym4Enabled ? _sym4ModeValue : na, c_sym4, color=i_sym4Color, style=v_style) plot(i_sym5Enabled ? _sym5ModeValue : na, c_sym5, color=i_sym5Color, style=v_style) plot(i_sym6Enabled ? _sym6ModeValue : na, c_sym6, color=i_sym6Color, style=v_style) plot(i_sym7Enabled ? _sym7ModeValue : na, c_sym7, color=i_sym7Color, style=v_style) plot(i_sym8Enabled ? _sym8ModeValue : na, c_sym8, color=i_sym8Color, style=v_style) plot(i_sym9Enabled ? _sym9ModeValue : na, c_sym9, color=i_sym9Color, style=v_style) plot(i_sym10Enabled ? _sym10ModeValue : na, c_sym10, color=i_sym10Color, style=v_style) plot(i_sym11Enabled ? _sym11ModeValue : na, c_sym11, color=i_sym11Color, style=v_style) plot(i_symEnabled ? _symModeValue : na, "Sym", color=i_symColor, style=v_style, linewidth=2) // rsi plots p_upperRSIBand = hline(70, 'Upper Band', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_rsi ? display.all : display.none) hline(50, 'Middle Band', color.new(color.gray, 50), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_rsi ? display.all : display.none) p_lowerRSIBand = hline(30, 'Lower Band', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_rsi ? display.all : display.none) fill(p_upperRSIBand, p_lowerRSIBand, color=color.new(color.gray, 90), editable=false, display=i_mode == c_mode_rsi ? display.all : display.none) // cci plots p_upperCCIBand = hline(100, 'Upper Band', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_cci ? display.all : display.none) hline(0, 'Middle Band', color.new(color.gray, 50), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_cci ? display.all : display.none) p_lowerCCIBand = hline(-100, 'Lower Band', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_cci ? display.all : display.none) fill(p_upperCCIBand, p_lowerCCIBand, color=color.new(color.gray, 90), editable=false, display=i_mode == c_mode_cci ? display.all : display.none) // mfi plots p_upperMFIBand = hline(80, 'Overbought', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_mfi ? display.all : display.none) hline(50, 'Middle Band', color.new(color.gray, 50), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_mfi ? display.all : display.none) p_lowerMFIBand = hline(20, 'Oversold', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_mfi ? display.all : display.none) fill(p_upperMFIBand, p_lowerMFIBand, color=color.new(color.gray, 90), editable=false, display=i_mode == c_mode_mfi ? display.all : display.none) // wpr plots p_upperWPRBand = hline(-20, 'Upper Band', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_wpr ? display.all : display.none) hline(-50, 'Middle Band', color.new(color.gray, 50), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_wpr ? display.all : display.none) p_lowerWPRBand = hline(-80, 'Lower Band', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_wpr ? display.all : display.none) fill(p_upperWPRBand, p_lowerWPRBand, color=color.new(color.gray, 90), editable=false, display=i_mode == c_mode_wpr ? display.all : display.none) // roc plot hline(0, 'Zero Line', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_roc ? display.all : display.none) // cmo plot hline(0, 'Zero Line', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_cmo ? display.all : display.none) // change plot hline(0, 'Zero Line', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_change ? display.all : display.none) // bbw plot hline(0, 'Zero Line', color.new(color.gray, 0), hline.style_dashed, 1, editable=false, display=i_mode == c_mode_bbw ? display.all : display.none) // } plots
nVPSA - Normalized Volume-Price Spread Analysis
https://www.tradingview.com/script/tPlnLNR5/
TradingCat79
https://www.tradingview.com/u/TradingCat79/
33
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© TradingCat79 //@version=5 indicator("nVPSA") import TradingView/ta/5 //input intradaybars = input(1440, "Bars number for intraday analysis","Below one day, all interval have same number") hourbarsno = input(60, "Bars number for higher interval analysis","Above one day, all interval have same number") vreglenght = input(14, "Linear regression length","Linear regression calculated from normalized volume") sreglenght = input(14, "Linear regression length", "Linear regression calculated from normalized spread") //variables int barrange0 = na spread = high - low voldown = volume[2] > volume[1] and volume[1] > volume[0] sprdown = spread[2] > spread[1] and spread[1] > spread[0] //timeframe test if timeframe.isintraday barrange0 := intradaybars else barrange0 := 60 //calcs volnorm = (volume/ta.highest(volume, barrange0)) sprnorm = (spread/ta.highest(spread, barrange0)) volstd = ta.stdev(volume, barrange0) normvolstd = ta.stdev(volnorm, barrange0) sprstd = ta.stdev(spread, barrange0) normsprstd = ta.stdev(sprnorm, barrange0) gbv = volnorm == 1 gbs = sprnorm == 1 regv = ta.linreg(volnorm, vreglenght, 0) regs = ta.linreg(sprnorm, sreglenght, 0) //plots plot(volnorm, title='Normalized volume', color = (gbv) ? color.yellow: (volnorm > 4*normvolstd) ? color.fuchsia: (volnorm < 4*normvolstd) and (volnorm > 2*normvolstd) ? color.red : (volnorm < 2*normvolstd) and (volnorm > normvolstd) ? color.green : (volnorm < normvolstd) ? color.blue : color.rgb(59, 255, 222, 50), style = plot.style_columns) plotcandle(0,0,0, sprnorm, "Normalized price spread", color = (gbs) ? color.yellow: (sprnorm > 4*normsprstd) ? color.rgb(223, 64, 251, 50): (sprnorm < 4*normsprstd) and (sprnorm > 2*normsprstd) ? color.rgb(255, 82, 82, 50) : (sprnorm < 2*normsprstd) and (sprnorm > normsprstd) ? color.rgb(76, 175, 79, 50) : (sprnorm < normsprstd) ? color.rgb(33, 149, 243, 50) : color.rgb(59, 255, 222, 50)) plot(regv, color= voldown ? color.black: (volume[1]<volume[0]) ? color.green: color.red, linewidth = 2, style = plot.style_cross) plot(regs, color= sprdown ? color.black: (spread[1]<spread[0]) ? color.green: color.red, linewidth = 2, style = plot.style_circles) //alerts alertcondition(gbv or gbs, "VPSA Golden Bar", "Golden Bar now on chart!") alertcondition(volnorm > 4*normvolstd, "Volume > 4Vstd", "Volume > 4Vstd") alertcondition((volnorm < 4*normvolstd) and (volnorm > 2*normvolstd), "Volume > 2Vstd", "Volume > 2Vstd") alertcondition((volnorm < 2*normvolstd) and (volnorm > normvolstd), "Volume > Vstd", "Volume > Vstd!") alertcondition((volnorm < normvolstd), "Volume < Vstd", "Volume < Vstd") alertcondition((sprnorm > 4*normsprstd),"Spread > 4Sstd", "Spread > 4Sst") alertcondition((sprnorm < 4*normsprstd) and (sprnorm > 2*normsprstd), "Spread > 2Sstd", "Spread > 2Sstd") alertcondition((sprnorm < 2*normsprstd) and (sprnorm > normsprstd), "Spread > Sstd", "Spread > Sstd") alertcondition((sprnorm < normsprstd), "Spread < Sstd", "Spread < Sstd")
Price on chart Binance spot USDT and Bybit perpetual USDT.P.
https://www.tradingview.com/script/2PrHPY8E/
charthussars
https://www.tradingview.com/u/charthussars/
10
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© hussarya //@version=5 indicator(title="Price Binance spot USDT and Bybit perpetual USDT.P.", overlay=true) // dane aktywa nazwa = syminfo.basecurrency gielda = syminfo.prefix waluta = syminfo.currency ticker0 = syminfo.tickerid ticker1 = "BINANCE:" + nazwa + "USDT" ticker2 = "BYBIT:" + nazwa + "USDT.P" timeframe = timeframe.period kolor0 = color.black kolor1 = color.rgb(197, 246, 198) kolor2 = color.rgb(208, 230, 249) kolor3 = color.rgb(247, 230, 205) //spot = input.symbol( "BINANCE:AAVEUSDT" , "Symbol" ) //bybit = input.symbol("Bybit:AAVEUSDT.P", "Symbol" ) spot_close = request.security(ticker1, timeframe , close) spot_open = request.security(ticker1, timeframe , open) spot_high = request.security(ticker1, timeframe , high) spot_low = request.security(ticker1, timeframe , low) spot_volume = request.security(ticker1, timeframe , volume) bybit_close = request.security(ticker2, timeframe , close) bybit_open = request.security(ticker2, timeframe , open) bybit_high = request.security(ticker2, timeframe , high) bybit_low = request.security(ticker2, timeframe , low) bybit_volume = request.security(ticker2, timeframe , volume) plotcandle(spot_open, spot_high, spot_low, spot_close, title = "Binance SPOT", color = color.blue, wickcolor = color.blue, bordercolor = color.blue) plotcandle(bybit_open, bybit_high, bybit_low, bybit_close, title = "BYBIT Perpetual", color = color.orange, wickcolor = color.orange, bordercolor = color.orange) var mytable = table.new(position = position.top_right, columns = 3, rows = 3, bgcolor = kolor1, border_width = 1 , frame_color = kolor0, frame_width = 1, border_color = kolor0) //pierwsza kolumna table.cell(table_id = mytable,column =0, row=0, text = "Base chart currency ticker ID", text_color = kolor0,bgcolor = kolor1) table.cell(table_id = mytable,column =0, row=1, text = "Binance SPOT ticker ID", text_color = kolor0,bgcolor = kolor2) table.cell(table_id = mytable,column =0, row=2, text = "BYBIT ticker ID", text_color = kolor0 ,bgcolor = kolor3) //2 kolumna table.cell(table_id = mytable,column =1, row=0, text = str.tostring(ticker0), text_color = kolor0,bgcolor = kolor1) table.cell(table_id = mytable,column =1, row=1, text = str.tostring(ticker1), text_color = kolor0,bgcolor = kolor2) table.cell(table_id = mytable,column =1, row=2, text = str.tostring(ticker2), text_color = kolor0,bgcolor = kolor3) //3 kolumna table.cell(table_id = mytable,column =2, row=0, text ="volume: " + str.tostring( volume), text_color = kolor0,bgcolor = kolor1) table.cell(table_id = mytable,column =2, row=1, text ="volume: " + str.tostring(spot_volume), text_color = kolor0,bgcolor = kolor2) table.cell(table_id = mytable,column =2, row=2, text ="volume: " + str.tostring(bybit_volume), text_color = kolor0,bgcolor = kolor3)
Higher Time Frame {HTF} Candles [QuantVue]
https://www.tradingview.com/script/gOzy5IQF-Higher-Time-Frame-HTF-Candles-QuantVue/
QuantVue
https://www.tradingview.com/u/QuantVue/
252
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© QuantVue //@version=5 indicator("Higher Time Frame {HTF} Candles [QuantVue]", overlay = true) htf = input.timeframe('D', 'Higher Time Frame', tooltip = 'Must be greater than timeframe of current chart.') showPrev = input.bool(true, 'Show Previous 5 Higher Time Frame Bars') showWarn = input.bool(true, 'Display Warning Label if Current TF >= HTF') var box body = na var box upperWick = na var box lowerWick = na var startIndex = 0 var prevStarts = array.new<int>(6) newTime = ta.change(time(htf)) [ohtf, hhtf, lhtf, chtf] = request.security(syminfo.tickerid, htf, [open, high, low, close]) bullish = chtf > ohtf if newTime startIndex := bar_index if prevStarts.size() > 6 prevStarts.pop() prevStarts.unshift(startIndex) else prevStarts.unshift(startIndex) if newTime or barstate.islast (body[1]).delete(), (upperWick[1]).delete(), (lowerWick[1]).delete() boxColor = bullish ? color.green : color.red body := box.new(startIndex, bullish ? chtf : ohtf, bar_index, bullish ? ohtf : chtf, color.new(boxColor,50), bgcolor = color.new(boxColor,50)) upperWick := box.new(startIndex, hhtf, bar_index, bullish ? chtf : ohtf, color.new(boxColor,90), bgcolor = color.new(boxColor,90)) lowerWick := box.new(startIndex, bullish ? ohtf : chtf, bar_index, lhtf, color.new(boxColor,90), bgcolor = color.new(boxColor,90)) [ohtf1, hhtf1, lhtf1, chtf1] = request.security(syminfo.tickerid, htf, [open[1], high[1], low[1], close[1]]) [ohtf2, hhtf2, lhtf2, chtf2] = request.security(syminfo.tickerid, htf, [open[2], high[2], low[2], close[2]]) [ohtf3, hhtf3, lhtf3, chtf3] = request.security(syminfo.tickerid, htf, [open[3], high[3], low[3], close[3]]) [ohtf4, hhtf4, lhtf4, chtf4] = request.security(syminfo.tickerid, htf, [open[4], high[4], low[4], close[4]]) [ohtf5, hhtf5, lhtf5, chtf5] = request.security(syminfo.tickerid, htf, [open[5], high[5], low[5], close[5]]) prevOpens = array.from(ohtf1, ohtf2, ohtf3, ohtf4, ohtf5) prevHighs = array.from(hhtf1, hhtf2, hhtf3, hhtf4, hhtf5) prevLows = array.from(lhtf1, lhtf2, lhtf3, lhtf4, lhtf5) prevCloses = array.from(chtf1, chtf2, chtf3, chtf4, chtf5) oldStart = ta.valuewhen(newTime, bar_index, 0) if barstate.islast and showPrev for i = 0 to 4 bullBar = prevOpens.get(i) < prevCloses.get(i) box.new(prevStarts.get(i+1), bullBar? prevCloses.get(i) : prevOpens.get(i), prevStarts.get(i) - 1, bullBar ? prevOpens.get(i) : prevCloses.get(i), bullBar ? color.new(color.green,50) : color.new(color.red,50), bgcolor = bullBar ? color.new(color.green,50) : color.new(color.red,50)) box.new(prevStarts.get(i+1), prevHighs.get(i), prevStarts.get(i) - 1, bullBar ? prevCloses.get(i) : prevOpens.get(i), bullBar ? color.new(color.green,90) : color.new(color.red,90), bgcolor = bullBar ? color.new(color.green,90) : color.new(color.red,90)) box.new(prevStarts.get(i+1), prevLows.get(i), prevStarts.get(i) - 1, bullBar ? prevOpens.get(i) : prevCloses.get(i), bullBar ? color.new(color.green,90) : color.new(color.red,90), bgcolor = bullBar ? color.new(color.green,90) : color.new(color.red,90)) if barstate.islast and timeframe.in_seconds() >= timeframe.in_seconds(htf) and showWarn label.new(bar_index, high, 'Please select a higher time frame from the indicator settings\nor change current the chart to lower time frame to display\nhigher time frame candles.', color=color.aqua, textcolor = color.white, textalign = text.align_left)
MTF FVG
https://www.tradingview.com/script/kG5p9bl4-MTF-FVG/
pmk07
https://www.tradingview.com/u/pmk07/
209
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© pmk07 //@version=5 indicator("MTF FVG", overlay=true, max_boxes_count = 500) changelvl = input.bool(true, "Move box levels with price touch", group='General') changecolor = input.bool(true, "Change box color with price touch", group='General') extend_r = input.bool(true, "Extend boxes to the right", group='General') plotLabel = input.bool(defval=false, title='Plot OB Label', inline='FVG label', group='Style') LabelColor = input.color(defval=color.gray, title='Color', inline='FVG label', group='Style') LabelSize = input.string(defval=size.tiny, title="Size", options=[size.huge, size.large, size.small, size.tiny, size.auto, size.normal], inline='FVG label', group='Style') BullColor = input.color(defval=color.new(color.green, 90), title='Bullish FVG Color', inline='Set Custom Color', group='Style') BearColor = input.color(defval=color.new(color.red, 90), title='Bearish FVG Color', inline='Set Custom Color', group='Style') BullColorTested = input.color(defval=color.new(color.gray, 90), title='Tested Bullish FVG Color', inline='Set Custom Color', group='Style') BearColorTested = input.color(defval=color.new(color.gray, 90), title='Tested Bearish FVG Color', inline='Set Custom Color', group='Style') var box[] bull_box = array.new_box() var box[] bear_box = array.new_box() tf1 = input.bool(false, "1", group='Timeframe') tf2 = input.bool(false, "3", group='Timeframe') tf3 = input.bool(false, "5", group='Timeframe') tf4 = input.bool(true, "15", group='Timeframe') tf5 = input.bool(false, "30", group='Timeframe') tf6 = input.bool(false, "45", group='Timeframe') tf7 = input.bool(true, "60", group='Timeframe') tf8 = input.bool(false, "120", group='Timeframe') tf9 = input.bool(false, "180", group='Timeframe') tf10 = input.bool(true, "240", group='Timeframe') tf11 = input.bool(true, "D", group='Timeframe') tf12 = input.bool(true, "W", group='Timeframe') find_box(t) => var int x = na var float _top = na var float _bottom = na var int _time = na if barstate.isconfirmed x := low[2] >= high ? -1 : low >= high[2] ? 1 : 0 _top := x > 0 ? low : x < 0 ? low[2] : 0 _bottom := x > 0 ? high[2] : x < 0 ? high : 0 _time := time - t * 60000 * 2 [_time, _top, _bottom, x] create_box(_time, _top, _bottom, x, TF) => _col = x > 0 ? BullColor : BearColor _extend = extend_r ? extend.right : extend.none _text = plotLabel ? TF : na box boxOB = na if x != 0 boxOB := box.new(left=_time, top=_top, right=time, extend=_extend , bottom=_bottom, bgcolor=_col, border_color = na, text=_text, text_halign=text.align_right, text_size=LabelSize, text_color=LabelColor, xloc = xloc.bar_time) if x > 0 array.push(bull_box, boxOB) if x < 0 array.push(bear_box, boxOB) control_box(_boxes, bearbull) => if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) if (bearbull > 0 and low < _boxLow) or (bearbull < 0 and high > _boxHigh) box.delete(_box) array.set(_boxes, i, na) else if bearbull > 0 and low < _boxHigh if changelvl box.set_top(_box, low) if changecolor box.set_bgcolor(_box, BullColorTested) if bearbull < 0 and high > _boxLow if changelvl box.set_bottom(_box, high) if changecolor box.set_bgcolor(_box, BullColorTested) box.set_right(_box, time) if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 if na(array.get(_boxes, i)) array.remove(_boxes, i) [_time1, _top1, _bottom1, xtf1] = request.security(syminfo.tickerid, "1", find_box(1)) [_time2, _top2, _bottom2, xtf2] = request.security(syminfo.tickerid, "3", find_box(3)) [_time3, _top3, _bottom3, xtf3] = request.security(syminfo.tickerid, "5", find_box(5)) [_time4, _top4, _bottom4, xtf4] = request.security(syminfo.tickerid, "15", find_box(15)) [_time5, _top5, _bottom5, xtf5] = request.security(syminfo.tickerid, "30", find_box(30)) [_time6, _top6, _bottom6, xtf6] = request.security(syminfo.tickerid, "45", find_box(45)) [_time7, _top7, _bottom7, xtf7] = request.security(syminfo.tickerid, "60", find_box(60)) [_time8, _top8, _bottom8, xtf8] = request.security(syminfo.tickerid, "120", find_box(120)) [_time9, _top9, _bottom9, xtf9] = request.security(syminfo.tickerid, "180", find_box(180)) [_time10, _top10, _bottom10, xtf10] = request.security(syminfo.tickerid, "240", find_box(240)) [_time11, _top11, _bottom11, xtf11] = request.security(syminfo.tickerid, "D", find_box(1440)) [_time12, _top12, _bottom12, xtf12] = request.security(syminfo.tickerid, "W", find_box(10080)) if tf1 and timeframe.change("1") create_box(_time1, _top1, _bottom1, xtf1, "1") if tf2 and timeframe.change("3") create_box(_time2, _top2, _bottom2, xtf2, "3") if tf3 and timeframe.change("5") create_box(_time3, _top3, _bottom3, xtf3, "5") if tf4 and timeframe.change("15") create_box(_time4, _top4, _bottom4, xtf4, "15") if tf5 and timeframe.change("30") create_box(_time5, _top5, _bottom5, xtf5, "30") if tf6 and timeframe.change("45") create_box(_time6, _top6, _bottom6, xtf6, "45") if tf7 and timeframe.change("60") create_box(_time7, _top7, _bottom7, xtf7, "60") if tf8 and timeframe.change("120") create_box(_time8, _top8, _bottom8, xtf8, "120") if tf9 and timeframe.change("180") create_box(_time9, _top9, _bottom9, xtf9, "180") if tf10 and timeframe.change("240") create_box(_time10, _top10, _bottom10, xtf10, "240") if tf11 and timeframe.change("D") create_box(_time11, _top11, _bottom11, xtf11, "D") if tf12 and timeframe.change("W") create_box(_time12, _top12, _bottom12, xtf12, "W") control_box(bull_box, 1) control_box(bear_box, -1)
Profit Estimate
https://www.tradingview.com/script/PBMDsDB7-Profit-Estimate/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
6
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© kaigouthro //@version=5 // @description Simple profit Estimatr. Engages when Position != 0 // and holds until posittion is na/0... // if position changes sizes, it will update automatically and adjust. // it has an input for comission to estmate exit fees library("profitestimate",true) // @function Get a new Average position Price // @param _sizewas (float) the position prior // @param _delta (float) the order amount // @param _pricewas (float) the prior price // @param _newprice (float) the price of order // @returns New Avg Price export update_avgprice(float _sizewas, float _delta, float _pricewas, float _newprice) => (_sizewas * _pricewas + _delta * _newprice) / (_sizewas + _delta) // @function Position Net Profit Net Commission, automatic on/off if position != 0 // @param _position (float) position size (total or margin size) // @param _commission (float) % where (0.1 = 0.1%) // @param _leverage (float) optional if leveraged, default 1x // @param _fullqty (bool) if position entered is tottal trade size default is margin qty (1/lev) // @returns quote value of profit export amount(float _position, float _close, float _commission, float _leverage = 1, bool _fullqty = false) => var _price = float(na) var _size = float(na) var _new = true _price := nz(_price) _size := nz(_size) _new := _position != _size switch _new => _price := update_avgprice(_size,_position-_size,_price,_close) _size := _position _new := false _size := nz(_position) _value = _price * ( _fullqty ? _size : _size * _leverage ) _fee = math.abs ( _value ) / 100* _commission (_price * _size * ( _close / _price - 1 ) ) - _fee // @function Position Net Profit, automatic on/off if position != 0 // @param _position (float) position size (total or margin size) // @param _commission (float) % where (0.1 = 0.1%) // @param _leverage (float) optional if leveraged, default 1x // @param _fullqty (bool) if position entered is tottal trade size, default is margin qty (1/lev) // @returns percentage profit (1% = 1) export percent(float _position, float _close, float _commission, float _leverage = 1, bool _fullqty = false) => amount (_position, _close, _commission, _leverage , _fullqty ) / (math.abs(_position) * _close)
racille_arrayutils
https://www.tradingview.com/script/HJKqdUkw-racille-arrayutils/
pro1007ka
https://www.tradingview.com/u/pro1007ka/
3
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© pro1007ka //@version=5 // @description The most used array utility functions library("racille_arrayutils") // Notes // A -> set of arrays // R -> set of real numbers // 0 -> null set // a -> argument set // ------------------------------------------------------------------------------------------------- // { f : 0 -> a // ------------------------------------------------------------------------------------------------- // @function returns sin function as a parameter to calculate the function_array() export func_sin() => "sin" // @function returns cos function as a parameter to calculate the function_array() export func_cos() => "cos" // @function returns tan function as a parameter to calculate the function_array() export func_tan() => "tan" // @function returns cot function as a parameter to calculate the function_array() export func_cot() => "cot" // @function returns asin function as a parameter to calculate the function_array() export func_asin() => "asin" // @function returns acos function as a parameter to calculate the function_array() export func_acos() => "acos" // @function returns atan function as a parameter to calculate the function_array() export func_atan() => "atan" // @function returns acot function as a parameter to calculate the function_array() export func_acot() => "acot" // @function returns sqrt function as a parameter to calculate the function_array() export func_sqrt() => "pow|0.5" // @function returns pow function as a parameter to calculate the function_array() // @param x - power export func_pow(float x) => "pow|" + str.tostring(x) // ------------------------------------------------------------------------------------------------- // } f : 0 -> a // ------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------- // { f : R -> a // ------------------------------------------------------------------------------------------------- // @function returns exp function as a parameter to calculate the function_array() // @param x - base export func_exp(float x = math.e) => "exp|" + str.tostring(x) // @function returns log function as a parameter to calculate the function_array() // @param x - base export func_log(float x = math.e) => "log|" + str.tostring(x) // ------------------------------------------------------------------------------------------------- // } f : R -> a // ------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------- // { f : A, a -> A // ------------------------------------------------------------------------------------------------- // validate that string is numeric __number_validator(string s) => ret = true for i = 0 to str.length(s) - 1 by 1 if not str.contains("0123456789.", str.substring(s, i, i)) ret := false ret // validate that input string is an appropriate function parameter func_* __func_validator(string func) => if func == "sin" or func == "cos" or func == "tan" or func == "cot" or func == "asin" or func == "acos" or func == "atan" or func == "acot" true else if str.contains(func, '|') t_key = array.get(str.split(func, '|'), 0) t_val = array.get(str.split(func, '|'), 1) (t_key == "log" or t_key == "pow" or t_key == "exp") and __number_validator(t_val) else false // utility that classificates func as simple (without additional parameter) or complex __func_clasificator(string func) => func == "sin" or func == "cos" or func == "tan" or func == "cot" or func == "asin" or func == "acos" or func == "atan" or func == "acot" ? "simple" : "complex" __simple_func_replace(float arg, string func) => switch func "sin" => math.sin(arg) "cos" => math.cos(arg) "tan" => math.tan(arg) "cot" => 1/math.tan(arg) "asin" => math.asin(arg) "acos" => math.acos(arg) "atan" => math.atan(arg) "acot" => math.pi/2 - math.atan(arg) __complex_func_replace(float arg, string func, float parameter) => switch func "exp" => math.pow(parameter, arg) "pow" => math.pow(arg, parameter) "log" => math.log(arg) / math.log(parameter) // utility for func_replace_array __func_replace_util(float arg, string func) => switch __func_clasificator(func) "simple" => __simple_func_replace(arg, func) "complex" => __complex_func_replace(arg, array.get(str.split(func, '|'), 0), str.tonumber(array.get(str.split(func, '|'), 1))) // @function replace each element of array with func(element) and returns a new array // @param arr - array // @param func - function to replace. Must be one of func_*() // @returns new array, where each element is func(element) export apply_func(float[] arr, string func) => if not __func_validator(func) runtime.error("Invalid function parameter passed as an func_replace_array argument") res = array.new_float() if array.size(arr) for i = 0 to array.size(arr) - 1 by 1 array.push(res, __func_replace_util(array.get(arr, i), func)) res // ------------------------------------------------------------------------------------------------- // { f : A, R -> A // ------------------------------------------------------------------------------------------------- // @function multiplies each element of array by multiplier and returns a new array // @param arr - array // @param x - multiplier // @returns new array, where each element is multiplied on x export multiply_array(float[] arr, float x) => res = array.new_float() if array.size(arr) for i = 0 to array.size(arr) - 1 by 1 array.push(res, array.get(arr, i) * x) res // @function multiplies each element of array by multiplier and returns a new array // @param arr - array // @param n - multiplier // @returns new array, where each element is multiplied on n export multiply_array(float[] arr, int n) => multiply_array(arr, float(n)) // @function multiplies each element of array by multiplier and returns a new array // @param arr - array // @param n - multiplier // @returns new array, where each element is multiplied on n export multiply_array(int[] arr, int n) => res = array.new_int() if array.size(arr) for i = 0 to array.size(arr) - 1 by 1 array.push(res, array.get(arr, i) * n) res // @function divides each element of array by divider and returns a new array // @param arr - array // @param x - divider // @returns new array, where each element is divided by x export divide_array(float[] arr, float x) => res = array.new_float() if array.size(arr) and x != 0 for i = 0 to array.size(arr) - 1 by 1 array.push(res, array.get(arr, i) / x) res // @function divides each element of array by divider and returns a new array // @param arr - array // @param n - divider // @returns new array, where each element is divided by n export divide_array(float[] arr, int n) => multiply_array(arr, float(n)) // @function adds increment to each element of array and returns a new array // @param arr - array // @param x - increment // @returns new array, where each element is increased by x export increase_array(float[] arr, float x) => res = array.new_float() if array.size(arr) for i = 0 to array.size(arr) - 1 by 1 array.push(res, array.get(arr, i) + x) res // @function adds increment to each element of array and returns a new array // @param arr - array // @param n - increment // @returns new array, where each element is increased by n export increase_array(float[] arr, int n) => increase_array(arr, float(n)) // @function adds increment to each element of array and returns a new array // @param arr - array // @param n - increment // @returns new array, where each element is multiplied on x export increase_array(int[] arr, int n) => res = array.new_int() if array.size(arr) for i = 0 to array.size(arr) - 1 array.push(res, array.get(arr, i) + n) res // @function substracts decrement to each element of array and returns a new array // @param arr - array // @param x - decrement // @returns new array, where each element is decreased by x export decrease_array(float[] arr, float x) => increase_array(arr, -x) // @function substracts decrement to each element of array and returns a new array // @param arr - array // @param n - decrement // @returns new array, where each element is decreased by n export decrease_array(float[] arr, int n) => increase_array(arr, -n) // @function substracts decrement to each element of array and returns a new array // @param arr - array // @param n - decrement // @returns new array, where each element is decreased by x export decrease_array(int[] arr, int n) => increase_array(arr, -n) // @function changes each elements sign of array and returns a new array // @param arr - array // @returns new array, where each element is of different sign export negate_array(float[] arr) => multiply_array(arr, -1) // ------------------------------------------------------------------------------------------------- // } f : A, R -> A // ------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------- // { f : A, A -> A // ------------------------------------------------------------------------------------------------- // @function calculates elementwise sum of two arrays export array_sum(float[] arr1, float[] arr2) => res = array.new_float() if array.size(arr1) and array.size(arr2) for i = 0 to math.min(array.size(arr1), array.size(arr2)) - 1 array.push(res, array.get(arr1, i) + array.get(arr2, i)) res // @function calculates elementwise difference of two arrays export array_diff(float[] arr1, float[] arr2) => array_sum(arr1, negate_array(arr2)) // @function calculates elementwise product of two arrays export array_product(float[] arr1, float[] arr2) => res = array.new_float() if array.size(arr1) and array.size(arr2) for i = 0 to math.min(array.size(arr1), array.size(arr2)) - 1 array.push(res, array.get(arr1, i) * array.get(arr2, i)) res // @function calculates elementwise division of two arrays export array_division(float[] arr1, float[] arr2) => array_product(arr1, apply_func(arr2, func_pow(-1))) // ------------------------------------------------------------------------------------------------- // } f : A, A -> A // ------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------- // { f : A -> R // ------------------------------------------------------------------------------------------------- // @function calculates the product of array elements export array_element_prod(float[] arr) => ret = 0.0 if array.size(arr) ret := 1 for i = 0 to array.size(arr) - 1 ret := ret * array.get(arr, i) ret __naive_geomean(float[] arr) => if array.size(arr) math.pow(array_element_prod(arr), 1/array.size(arr)) else 0.0 __log_geomean(float[] arr) => if array.size(arr) math.exp(array.avg(apply_func(arr, func_log()))) else 0.0 // @function calculates the geometric mean of array elements // @param arr - array // @param method - calculation method. Can be chosen from ["auto", "naive", "log"] // @returns geometric mean of array elements. 0 if array is empty export array_geomean(float[] arr, string method = "auto") => if method != "auto" and method != "naive" and method != "log" runtime.error("Invalid usage of array_geomean(). Unexpected calculation method") sz_ = array.size(arr) if sz_ < 10 or method == "naive" __naive_geomean(arr) else __log_geomean(arr) // ------------------------------------------------------------------------------------------------- // } f : A -> R // ------------------------------------------------------------------------------------------------- // Testing PASSED = "βœ…" FAILED = "❌" test_result_tostr(string name, bool pass) => name + " " + (pass ? PASSED : FAILED) + "\n" test_AR_to_A() => string result = "f: A, R -> A suite:\n" float[] i_float = array.from(4.0, 5.5, 2.9) float[] o_float_plus2p5 = increase_array(i_float, 2.5) float[] o_float_minus3 = decrease_array(i_float, 3) float[] o_float_mult2 = multiply_array(i_float, 2) float[] o_float_div2p2 = divide_array(i_float, 2.2) bool validate_plus = true bool validate_minus = true bool validate_mult = true bool validate_div = true for i = 0 to array.size(i_float) - 1 validate_plus := validate_plus and (array.get(i_float, i) + 2.5 == array.get(o_float_plus2p5, i)) validate_minus := validate_minus and (array.get(i_float, i) - 3 == array.get(o_float_minus3, i)) validate_mult := validate_mult and (array.get(i_float, i) * 2 == array.get(o_float_mult2, i)) validate_div := validate_div and (array.get(i_float, i) / 2.2 == array.get(o_float_div2p2, i)) result := result + test_result_tostr("Addition", validate_plus) result := result + test_result_tostr("Subtraction", validate_minus) result := result + test_result_tostr("Multiplication", validate_mult) result := result + test_result_tostr("Division", validate_div) result test_AA_to_A() => string result = "f: A, A -> A suite:\n" float[] i1 = array.from(2.5, 3.5, 5.5) float[] i2 = array.from(0.5, 1.75, 11.0) float[] o_plus = array_sum(i1, i2) float[] o_minus = array_diff(i1, i2) float[] o_mult = array_product(i1, i2) float[] o_div = array_division(i1, i2) bool validate_plus = true bool validate_minus = true bool validate_mult = true bool validate_div = true for i = 0 to array.size(i1) - 1 validate_plus := validate_plus and (array.get(i1, i) + array.get(i2, i) == array.get(o_plus, i)) validate_minus := validate_minus and (array.get(i1, i) - array.get(i2, i) == array.get(o_minus, i)) validate_mult := validate_mult and (array.get(i1, i) * array.get(i2, i) == array.get(o_mult, i)) validate_div := validate_div and (array.get(i1, i) / array.get(i2, i) == array.get(o_div, i)) result := result + test_result_tostr("Addition", validate_plus) result := result + test_result_tostr("Subtraction", validate_minus) result := result + test_result_tostr("Multiplication", validate_mult) result := result + test_result_tostr("Division", validate_div) result test_A_to_R() => string result = "f: A -> R suite:\n" float[] i_pos = array.from(2.5, 4.0, 3.3) float[] i_neg = array.from(2.5, -4.0, 3.3) float expected_prod = 2.5 * 4.0 * 3.3 float expected_geomean = math.pow(expected_prod, 1./3) result := result + test_result_tostr("Product", expected_prod == array_element_prod(i_pos)) result := result + test_result_tostr("Naive Geomean, pos x", expected_geomean == array_geomean(i_pos, "naive")) result := result + test_result_tostr("Log Geomean, pos x", expected_geomean == array_geomean(i_pos, "log")) result := result + test_result_tostr("Naive Geomean, neg x", -expected_geomean == array_geomean(i_neg, "naive")) result := result + test_result_tostr("Log Geomean, neg x", -expected_geomean == array_geomean(i_neg, "log")) result test_Aa_to_A_common() => string result = "f: A, a -> A, common suite:\n" float[] i_pos = array.from(0.25, 0.81, 1.3) float[] i_neg = array.from(0.25, -0.81, 1.3) float[] o_sqrt_pos = apply_func(i_pos, func_sqrt()) float[] o_pow3_neg = apply_func(i_neg, func_pow(3)) float[] o_pow2p81_pos = apply_func(i_pos, func_pow(2.81)) float[] o_exp_pos = apply_func(i_pos, func_exp()) float[] o_exp2_neg = apply_func(i_neg, func_pow(2)) float[] o_ln_pos = apply_func(i_pos, func_log()) float[] o_log4_pos = apply_func(i_pos, func_log(4)) validate_sqrt = true validate_powneg = true validate_powpos = true validate_exppos = true validate_expneg = true validate_ln = true validate_log4 = true for i = 0 to array.size(i_pos) - 1 validate_sqrt := validate_sqrt and (math.sqrt(array.get(i_pos, i)) == array.get(o_sqrt_pos, i)) validate_powneg := validate_powneg and (math.pow(array.get(i_neg, i), 3) == array.get(o_pow3_neg, i)) validate_powpos := validate_powpos and (math.pow(array.get(i_pos, i), 2.81) == array.get(o_pow2p81_pos, i)) validate_exppos := validate_exppos and (math.exp(array.get(i_pos, i)) == array.get(o_exp_pos, i)) validate_expneg := validate_expneg and (math.pow(2, array.get(i_neg, i)) == array.get(o_exp2_neg, i)) validate_ln := validate_ln and (math.log(array.get(i_pos, i)) == array.get(o_ln_pos, i)) validate_log4 := validate_log4 and (math.log(array.get(i_pos, i))/math.log(4) == array.get(o_log4_pos, i)) result := result + test_result_tostr("Sqrt", validate_sqrt) result := result + test_result_tostr("x^2, any x", validate_powneg) result := result + test_result_tostr("x^2.81, pos x", validate_powpos) result := result + test_result_tostr("Exp, pos x", validate_exppos) result := result + test_result_tostr("Exp, neg x", validate_expneg) result := result + test_result_tostr("Ln", validate_ln) result := result + test_result_tostr("Log 4", validate_log4) result test_Aa_to_A_trig() => string result = "f: A, a -> A, trigonometric suite:\n" float[] i_pos = array.from(0.25, 0.81, math.pi/4) float[] o_sin = apply_func(i_pos, func_sin()) float[] o_cos = apply_func(i_pos, func_cos()) float[] o_tan = apply_func(i_pos, func_tan()) float[] o_cot = apply_func(i_pos, func_cot()) float[] o_asin = apply_func(i_pos, func_asin()) float[] o_acos = apply_func(i_pos, func_acos()) float[] o_atan = apply_func(i_pos, func_atan()) float[] o_acot = apply_func(i_pos, func_acot()) validate_sin = true validate_cos = true validate_tan = true validate_cot = true validate_asin = true validate_acos = true validate_atan = true validate_acot = true for i = 0 to array.size(i_pos) - 1 validate_sin := validate_sin and (math.sin(array.get(i_pos, i)) == array.get(o_sin, i)) validate_cos := validate_cos and (math.cos(array.get(i_pos, i)) == array.get(o_cos, i)) validate_tan := validate_tan and (math.tan(array.get(i_pos, i)) == array.get(o_tan, i)) validate_cot := validate_cot and (1/math.tan(array.get(i_pos, i)) == array.get(o_cot, i)) validate_asin := validate_asin and (math.asin(array.get(i_pos, i)) == array.get(o_asin, i)) validate_acos := validate_acos and (math.acos(array.get(i_pos, i)) == array.get(o_acos, i)) validate_atan := validate_atan and (math.atan(array.get(i_pos, i)) == array.get(o_atan, i)) validate_acot := validate_acot and (math.pi/2 - math.atan(array.get(i_pos, i)) == array.get(o_acot, i)) result := result + test_result_tostr("Sin", validate_sin) result := result + test_result_tostr("Cos", validate_cos) result := result + test_result_tostr("Tan", validate_tan) result := result + test_result_tostr("Cot", validate_cot) result := result + test_result_tostr("Asin", validate_asin) result := result + test_result_tostr("Acos", validate_acos) result := result + test_result_tostr("Atan", validate_atan) result := result + test_result_tostr("Acot", validate_acot) result run_all_tests() => result = "Racille array utils unit tests:\n\n" result := result + test_A_to_R() + "\n" result := result + test_AA_to_A() + "\n" result := result + test_AR_to_A() + "\n" result := result + test_Aa_to_A_common() + "\n" result := result + test_Aa_to_A_trig() result if barstate.islast label.new(bar_index, close, run_all_tests(), textalign = text.align_left)
libcompress
https://www.tradingview.com/script/iJBJw9S2-libcompress/
pro1007ka
https://www.tradingview.com/u/pro1007ka/
0
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© pro1007ka //@version=5 // @description numbers compressor for large output data compression library("libcompress") __int2bin(int n) => ret = "" if n == 0 ret := "0" else nc = n while nc > 0 ret := str.tostring(nc % 2) + ret nc := int(nc/2) ret __int2bin(int n, int padding) => ret = __int2bin(n) while str.length(ret) < padding ret := '0' + ret ret __first_nonzero_pos(string s) => ret = -1 if(str.length(s)) for i = 0 to str.length(s) - 1 by 1 if str.substring(s, i, i+1) != '0' ret := i break ret __calc_exponent(float x) => s = str.tostring(x) if str.contains(s, '.') vals = str.split(s, '.') lval = array.get(vals, 0) rval = array.get(vals, 1) if lval == "0" - 1 - __first_nonzero_pos(rval) else str.length(array.get(str.split(s, '.'), 0)) - 1 else str.length(s) - 1 var string base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" __int2base64digit(int n) => str.substring("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", n, n+1) __baset64digit2int(string d) => str.pos("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", d) __float_erase_point(float x) => str.replace_all(str.tostring(x), '.', '') __calc_mantissa(int arg, int size) => argcpy = arg //while str.length(__int2bin(argcpy)) > size argmax = math.pow(2, size) while argcpy > argmax argcpy := int(argcpy / 10) ret = __int2bin(argcpy) while str.length(ret) < size ret := '0' + ret ret __6bits2int(string bits) => ret = 0 __exp = 32 for i = 0 to 5 ret := ret + __exp * int(str.tonumber(str.substring(bits, i, i + 1))) __exp := int(__exp/2) ret __bin2base64(string bin) => bin_raw = bin while str.length(bin_raw) % 6 != 0 bin_raw := "0" + bin_raw string ret = "" for i = 0 to str.length(bin_raw) -1 by 6 ret := ret + __int2base64digit(__6bits2int(str.substring(bin_raw, i, i + 6))) ret // @function converts float to base64 (4 chars) | 24 bits: 1 sign + 5 exponent + 18 mantissa // @returns 4-character base64_1/5/18 representation of x export compress_fp24(float x) => sign_val = x > 0 ? 32 : 0 exponent = __calc_exponent(x) + 15 firstdigit = __int2base64digit(sign_val + exponent) mantissa = __calc_mantissa(int(str.tonumber(__float_erase_point(math.abs(x)))), 18) firstdigit + __bin2base64(mantissa) // @function converts unsigned float to base64 (3 chars) | 18 bits: 5 exponent + 13 mantissa // @returns 3-character base64_0/5/13 representation of x export compress_ufp18(float x) => exponent = __calc_exponent(x) + 15 mantissa = __calc_mantissa(int(str.tonumber(__float_erase_point(math.abs(x)))), 13) ret_bin = __int2bin(exponent, 5) + mantissa __bin2base64(ret_bin) // @function converts int to base64 export compress_int(int n) => __bin2base64(__int2bin(n)) // @function converts base64 to int string export base64_tointstr(string b64, int fsize) => ret = 0 for _i = 0 to str.length(b64) - 1 i = str.length(b64) - 1 - _i ret := ret + int(math.pow(64, i)) * __baset64digit2int(str.substring(b64, i, i + 1)) retstr = str.tostring(ret) while str.length(retstr) < fsize retstr := "0" + retstr retstr
Stringify - Timeframe Enumeration --> String
https://www.tradingview.com/script/fHiIULvD-Stringify-Timeframe-Enumeration-String/
DasanC
https://www.tradingview.com/u/DasanC/
9
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© DasanC //@version=5 // @description Cast variable types and enumerations to human-readable Strings library("Stringify") // @function Cast a timeframe enumeration to readable string. // @param string `x` is a timeframe enumeration ('3D', '120', '15', '5s' ...) // @returns A string representation of the timeframe or 'NA' if `x` is `na` export timeframe(string T) => x = T if x == '' x := timeframe.period if na(x) 'NA' else string period = switch str.upper(str.substring(x,str.length(x)-1)) 'S' => str.lower(x) //Seconds Timeframe 'D' => str.upper(x) //Daily Timeframe 'W' => str.upper(x) //Weekly Timeframe 'M' => str.upper(x) //Monthly Timeframe //Default Case (Hour and/or Minutes) => str.tonumber(x) < 60 ? x + 'm' : str.tonumber(x)%60 == 0 ? str.tostring(str.tonumber(x)/60) + 'H' : str.format("{0,number,integer}H {1,number,integer}m",math.floor(str.tonumber(str.replace(x,'S',''))/60),str.tonumber(str.replace(x,'S',''))%60) Sample_Timeframe = input.timeframe('61',"Sample Timeframe Input") if barstate.islast label.new(bar_index,close,timeframe(Sample_Timeframe),color=chart.fg_color,textcolor = chart.bg_color)
PlurexSignalCore
https://www.tradingview.com/script/6Du1dnBD-PlurexSignalCore/
plurex
https://www.tradingview.com/u/plurex/
7
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© plurex //@version=5 // @description General purpose functions and helpers for use in more specific Plurex Signal alerting scripts and libraries library("PlurexSignalCore") // @function Build a Plurex market string from a base and quote asset symbol. // @returns A market string that can be used in Plurex Signal messages. export plurexMarket(string base, string quote) => base + "-" + quote // @function Builds Plurex market string from the syminfo // @returns A market string that can be used in Plurex Signal messages. export tickerToPlurexMarket() => plurexMarket(syminfo.basecurrency, syminfo.currency) // @function Builds Plurex Signal Message json to be sent to a Signal webhook // @param secret The secret for your Signal on plurex // @param action The action of the message. One of [LONG, SHORT, CLOSE_LONGS, CLOSE_SHORTS, CLOSE_ALL, CLOSE_LAST_LONG, CLOSE_LAST_SHORT, CLOSE_FIRST_LONG, CLOSE_FIRST_SHORT]. // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export simpleMessage(string secret, string action, string marketOverride = na) => market = na(marketOverride) ? tickerToPlurexMarket() : marketOverride "{\"secret\": \""+secret+"\", \"action\": \""+action+"\", \"market\": \""+market+"\"}" // @function Builds Plurex Signal Entry Message json to be sent to a Signal webhook with optional parameters for budget and price limits. // @param secret The secret for your Signal on plurex // @param isLong The action of the message. true for LONG, false for SHORT. // @param budgetPercentage Optional, The percentage of budget to use in the entry. // @param priceLimit Optional, The worst price to accept for the entry. // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export entryMessage(string secret, bool isLong, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) => market = na(marketOverride) ? tickerToPlurexMarket() : marketOverride action = isLong ? "LONG" : "SHORT" baseMessage = "{\"secret\": \""+secret+"\", \"action\": \""+action+"\", \"market\": \""+market+"\"" if not na(budgetPercentage) baseMessage := baseMessage+", \"budgetPercentage\": "+str.tostring(budgetPercentage) if not na(priceLimit) baseMessage := baseMessage+", \"priceLimit\": "+str.tostring(priceLimit) baseMessage+"}" // @function Builds Plurex Signal LONG Message json to be sent to a Signal webhook with optional parameters for budget and price limits. // @param secret The secret for your Signal on plurex // @param budgetPercentage Optional, The percentage of budget to use in the entry. // @param priceLimit Optional, The worst price to accept for the entry. // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export long(string secret, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) => entryMessage(secret = secret, isLong = true, budgetPercentage = budgetPercentage, priceLimit = priceLimit, marketOverride = marketOverride) // @function Builds Plurex Signal SHORT Message json to be sent to a Signal webhook with optional parameters for budget and price limits. // @param secret The secret for your Signal on plurex // @param budgetPercentage Optional, The percentage of budget to use in the entry. // @param priceLimit Optional, The worst price to accept for the entry. // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export short(string secret, float budgetPercentage = na, float priceLimit = na, string marketOverride = na) => entryMessage(secret = secret, isLong = false, budgetPercentage = budgetPercentage, priceLimit = priceLimit, marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_ALL Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeAll(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_ALL", marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_SHORTS Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeShorts(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_SHORTS", marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_LONGS Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeLongs(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_LONGS", marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_FIRST_LONG Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeFirstLong(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_FIRST_LONG", marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_LAST_LONG Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeLastLong(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_LAST_LONG", marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_FIRST_SHORT Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeFirstShort(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_FIRST_SHORT", marketOverride = marketOverride) // @function Builds Plurex Signal CLOSE_LAST_SHORT Message json to be sent to a Signal webhook. // @param secret The secret for your Signal on plurex // @param marketOverride Optional, defaults to the syminfo for the ticker. Use the `plurexMarket` function to build your own. // @returns A json string message that can be used in alerts to send messages to Plurex. export closeLastShort(string secret, string marketOverride = na) => simpleMessage(secret = secret, action="CLOSE_LAST_SHORT", marketOverride = marketOverride)
ta
https://www.tradingview.com/script/Hl3qMUJN-ta/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
73
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // //@version=5 // @description Collection of all custom and enhanced TA indicators library("ta", overlay=true) import HeWhoMustNotBeNamed/arrays/1 as pa bandwidth(float middle, float upper, float lower)=> 100*(upper-lower)/middle percentb(float source, float upper, float lower)=> 100*(source-lower)/(upper-lower) customseries(float source=close, simple string type="sma", simple int length) => switch type "ema" => ta.ema(source, length) "sma" => ta.sma(source, length) "rma" => ta.rma(source, length) "hma" => ta.hma(source, length) "wma" => ta.wma(source, length) "vwma" => ta.vwma(source, length) "swma" => ta.swma(source) "linreg" => ta.linreg(source, length, 0) "median" => ta.median(source, length) "mom" => ta.mom(source, length) "high" => ta.highest(source, length) "low" => ta.lowest(source, length) "medianHigh" => ta.median(ta.highest(source, length), length) "medianLow" => ta.median(ta.lowest(source, length), length) "percentrank" => ta.percentrank(source, length) => (ta.highest(length) + ta.lowest(length))/2 getStickyRange(float highsource, float lowsource, float upper, float lower, simple bool sticky=false)=> newUpper = upper newLower = lower highBreakout = highsource[1] >= newUpper[1] lowBreakout = lowsource[1] <= newLower[1] newUpper := (highBreakout or lowBreakout or not sticky)? newUpper : nz(newUpper[1], newUpper) newLower := (highBreakout or lowBreakout or not sticky)? newLower : nz(newLower[1], newLower) [newUpper, newLower] // @function returns custom moving averages // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @returns moving average for the given type and length export ma(float source=close, simple string maType="sma", simple int length) => customseries(source, maType, length) // @function returns ATR with custom moving average // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @returns ATR for the given moving average type and length export atr(simple string maType="sma", simple int length) => customseries(ta.tr, maType, length) // @function returns ATR as percentage of close price // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @returns ATR as percentage of close price for the given moving average type and length export atrpercent(simple string maType="sma", simple int length) => 100*atr(maType, length)/close // @function returns Bollinger band for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Bollinger band with custom moving average for given source, length and multiplier export bb(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) => float middle = ma(source, maType, length) float upper = middle + ta.stdev(source, length)*multiplier float lower = middle - ta.stdev(source, length)*multiplier [newUpper, newLower] = getStickyRange(high, low, upper, lower, sticky) upper := newUpper lower := newLower [middle, upper, lower] // @function returns Bollinger bandwidth for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Bollinger Bandwidth for custom moving average for given source, length and multiplier export bbw(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) => [middle, upper, lower] = bb(source, maType, length, multiplier, sticky) bandwidth(middle, upper, lower) // @function returns Bollinger Percent B for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Bollinger Percent B for custom moving average for given source, length and multiplier export bpercentb(float source=close, simple string maType="sma", simple int length=20, float multiplier=2.0, simple bool sticky=false) => [middle, upper, lower] = bb(source, maType, length, multiplier, sticky) percentb(source, upper, lower) // @function returns Keltner Channel for custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param useTrueRange - if set to false, uses high-low. // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Keltner Channel for custom moving average for given souce, length and multiplier export kc(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) => float middle = ma(source, maType, length) float span = (useTrueRange) ? ta.tr : (high - low) float rangeMa = ma(span, maType, length) float upper = middle + rangeMa*multiplier float lower = middle - rangeMa*multiplier [newUpper, newLower] = getStickyRange(high, low, upper, lower, sticky) upper := newUpper lower := newLower [middle, upper, lower] // @function returns Keltner Channel Width with custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param useTrueRange - if set to false, uses high-low. // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Keltner Channel Width for custom moving average export kcw(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) => [middle, upper, lower] = kc(source, maType, length, multiplier, useTrueRange, sticky) bandwidth(middle, upper, lower) // @function returns Keltner Channel Percent K Width with custom moving average // @param source Moving Average Source // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length Moving Average Length // @param multiplier Standard Deviation multiplier // @param useTrueRange - if set to false, uses high-low. // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Keltner Percent K for given moving average, source, length and multiplier export kpercentk(float source=close, simple string maType="ema", simple int length=20, float multiplier=2, simple bool useTrueRange=true, simple bool sticky=false) => [middle, upper, lower] = kc(source, maType, length, multiplier, useTrueRange, sticky) percentb(source, upper, lower) // @function returns Custom Donchian Channel // @param length - donchian channel length // @param useAlternateSource - Custom source is used only if useAlternateSource is set to true // @param alternateSource - Custom source // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Donchian channel export dc(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) => highSource = useAlternateSource? alternateSource : high lowSource = useAlternateSource? alternateSource : low [upper, lower] = getStickyRange(highSource, lowSource, ta.highest(highSource, length), ta.lowest(lowSource, length), sticky) middle = (upper+lower)/2 [middle, upper, lower] // @function returns Donchian Channel Width // @param length - donchian channel length // @param useAlternateSource - Custom source is used only if useAlternateSource is set to true // @param alternateSource - Custom source // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Donchian channel width export dcw(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) => [middle, upper, lower] = dc(length, useAlternateSource, alternateSource, sticky) bandwidth(middle, upper, lower) // @function returns Donchian Channel Percent of price // @param useAlternateSource - Custom source is used only if useAlternateSource is set to true // @param alternateSource - Custom source // @param length - donchian channel length // @param sticky - sticky boundaries which will only change when value is outside boundary. // @returns Donchian channel Percent D export dpercentd(simple int length=20, simple bool useAlternateSource = false, float alternateSource = close, simple bool sticky=false) => [middle, upper, lower] = dc(length, useAlternateSource, alternateSource, sticky) percentb(useAlternateSource? alternateSource : hl2, upper, lower) // @function oscillatorRange - returns Custom overbought/oversold areas for an oscillator input // @param source - Osillator source such as RSI, COG etc. // @param method - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param highlowLength - length on which highlow of the oscillator is calculated // @param rangeLength - length used for calculating oversold/overbought range - usually same as oscillator length // @param sticky - overbought, oversold levels won't change unless crossed // @returns Dynamic overbought and oversold range for oscillator input export oscillatorRange(float source, simple string method="highlow", simple int highlowLength=50, simple int rangeLength=14, simple bool sticky=false) => oscillatorHighest = customseries(source, "high", highlowLength) oscillatorLowest = customseries(source, "low", highlowLength) oscOverbought = customseries(oscillatorHighest, method == "highlow"? "low" : method, rangeLength) oscOversold = customseries(oscillatorLowest, method == "highlow"? "high" : method, rangeLength) getStickyRange(source, source, oscOverbought, oscOversold, sticky) // @function oscillator - returns Choice of oscillator with custom overbought/oversold range // @param type - oscillator type. Valid values : cci, cmo, cog, mfi, roc, rsi, stoch, tsi, wpr // @param length - Oscillator length - not used for TSI // @param shortLength - shortLength only used for TSI // @param longLength - longLength only used for TSI // @param source - custom source if required // @param highSource - custom high source for stochastic oscillator // @param lowSource - custom low source for stochastic oscillator // @param method - Valid values for method are : sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param highlowLength - length on which highlow of the oscillator is calculated // @param sticky - overbought, oversold levels won't change unless crossed // @returns Oscillator value along with dynamic overbought and oversold range for oscillator input export oscillator(simple string type="rsi", simple int length=14, simple int shortLength = 13, simple int longLength = 25, float source = close, float highSource = high, float lowSource = low, simple string method="highlow", simple int highlowLength=50, simple bool sticky=false)=> oscillator = switch type "cci" => ta.cci(source, length) "cmo" => ta.cmo(source, length) "cog" => ta.cog(source, length) "mfi" => ta.mfi(source, length) "roc" => ta.roc(source, length) "rsi" => ta.rsi(source, length) "stoch" => ta.stoch(source, highSource, lowSource, length) "tsi" => ta.tsi(source, shortLength, longLength) "wpr" => ta.wpr(length) => ta.rsi(source, length) [overbought, oversold] = oscillatorRange(oscillator, method, highlowLength, length, sticky) [oscillator, overbought, oversold] // @function multibands - returns Choice of oscillator with custom overbought/oversold range // @param bandType - Band type - can be either bb or kc // @param source - custom source if required // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length - Oscillator length - not used for TSI // @param useTrueRange - if set to false, uses high-low. // @param sticky - for sticky borders which only change upon source crossover/crossunder // @param numberOfBands - Number of bands to generate // @param multiplierStart - Starting ATR or Standard deviation multiplier for first band // @param multiplierStep - Incremental value for multiplier for each band // @returns array of band values sorted in ascending order export multibands(simple string bandType="bb", float source=close, simple string maType = "sma", simple int length = 60, simple bool useTrueRange=true, simple bool sticky=false, simple int numberOfBands=7, simple float multiplierStart = 0.5, simple float multiplierStep = 0.5)=> bands = array.new_float() for i=0 to numberOfBands-1 multiplier = multiplierStart + i*multiplierStep middle = 0.0 upper = 0.0 lower = 0.0 if(bandType == "bb") [bbmiddle, bbupper, bblower] = bb(source, maType, length, multiplier, sticky) middle := bbmiddle upper := bbupper lower := bblower else [kcmiddle, kcupper, kclower] = kc(source, maType, length, multiplier, useTrueRange, sticky) middle := kcmiddle upper := kcupper lower := kclower array.unshift(bands, lower) array.unshift(bands, upper) if(i == 0) array.unshift(bands, middle) array.sort(bands) bands // @function mbandoscillator - Multiband oscillator created on the basis of bands // @param bandType - Band type - can be either bb or kc // @param source - custom source if required // @param maType Moving Average Type : Can be sma, ema, hma, rma, wma, vwma, swma, highlow, linreg, median // @param length - Oscillator length - not used for TSI // @param useTrueRange - if set to false, uses high-low. // @param stickyBands - for sticky borders which only change upon source crossover/crossunder for band detection // @param numberOfBands - Number of bands to generate // @param multiplierStart - Starting ATR or Standard deviation multiplier for first band // @param multiplierStep - Incremental value for multiplier for each band // @returns oscillator currentStates - Array containing states for last n bars export mbandoscillator(simple string bandType="kc", float source=close, simple string maType = "sma", simple int length = 60, simple bool useTrueRange=false, simple bool stickyBands=false, simple int numberOfBands=100, simple float multiplierStart = 0.5, simple float multiplierStep = 0.5 )=> states = multibands(bandType, source, maType, length, useTrueRange, stickyBands, numberOfBands, multiplierStart, multiplierStep) currentState = array.size(states) for i = 0 to array.size(states) - 1 by 1 if source < array.get(states, i) currentState := i break currentState
SignalBuilder
https://www.tradingview.com/script/Ei9A76RS-SignalBuilder/
Electrified
https://www.tradingview.com/u/Electrified/
46
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Electrified // @version=5 // @description Utility for building a collection of signal values and displaying them. library("SignalBuilder", true) import Electrified/TableBuilder/13 as TB import Electrified/Color/8 //////////////////////////////////////////////////////////////// // @type An object for holding signal details. // @field value Represents the signal value. // @field description Describes the signal. // @field group The group this signal belongs to. export type Signal float value string description string group //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @type An object for holding a group of signal details. // @field group The signal group value/name. // @field signals The grouped signals. // @field color A color related to this group. // @field symbol An optional symbol related to this group. export type Group string group Signal[] signals color color string symbol //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates an empty array of Signal objects. // @returns The new array. export newArray() => array.new<Signal>() //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates a new Group object with a given name and an empty array of Signal objects. // @param name The group value/name. // @param color The color for the group. // @param symbol The symbol for the group. // @returns The new Group object. export newGroup(string name, color color, string symbol) => Group.new(name, newArray(), color, symbol) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates a new Group object with a given name and an empty array of Signal objects. // @param name The group value/name. // @param color The color for the group. // @returns The new Group object. export newGroup(string name, color color) => Group.new(name, newArray(), color, na) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates a new Group object with a given name and an empty array of Signal objects. // @param name The group value/name. // @param symbol The symbol for the group. // @returns The new Group object. export newGroup(string name, string symbol) => Group.new(name, newArray(), na, symbol) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates a new Group object with a given name and an empty array of Signal objects. // @param name The group value/name. // @returns The new Group object. export newGroup(string name) => Group.new(name, newArray(), na, na) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Searches through an array of Group objects and returns the index of the first group whose group value matches the provided group value. // @param signals The array of Group objects to search through. // @param group The group value to search for. // @returns The index of the matching group, or -1 if no matching group is found. export indexOfGroup( Group[] signals, string group) => size = array.size(signals) index = -1 i = 0 while i < size and index == -1 s = array.get(signals, i) g = s.group if g == group or na(group) and na(g) index := i i += 1 index //////////////////////////////////////////////////////////////// // @function Ensures that a Group with a given group value exists in an array of Group objects, and returns it. If a group with the given value does not exist, a new Group is created and added to the array. // @param signals The array of Group objects to search through. // @param group The group value to search for or create. // @returns The matching or newly-created Group object. export registerGroup( Group[] signals, string group) => i = indexOfGroup(signals, group) // Ensure the group. if i == -1 g = newGroup(group) array.push(signals, g) g else array.get(signals, i) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Groups an array of Signal objects by their group value. // @param signals The array of Signal objects to group. // @returns An array of Group objects, grouping the signals by their group value. export group(Signal[] signals) => // Initialize the grouping. result = array.new<Group>() // Loop through all the signals. for signal in signals group = registerGroup(result, signal.group) array.push(group.signals, signal) result //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates a new Signal object with a given value, description, and group value. // @param value The value of the signal. // @param description The description of the signal. // @param group A value representing what group the signal belongs to. // @returns The constructed Signal object. export create( float value, string description, string group = na) => Signal.new(value, description, group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given Signal array, with a given value, description, and group value. // @param collection The Signal array to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param condition An optional boolean value that will decide if the signal is added or not. // @param group A value representing what group the signal belongs to. // @returns true if the condition was true; otherwise false. export add( Signal[] collection, string description, float value = na, bool condition = true, string group = na) => if condition array.push(collection, Signal.new(value, description, group)) condition //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a Group. // @param group The Group object to add the Signal object to. // @param description The description of the signal. // @param value The value of the signal. If not provided, the value will be set to `na`. // @param condition A boolean condition that determines whether the signal will be added to the group. If not provided, the default value is `true`. // @returns The constructed Signal object. export add( Group group, string description, float value = na, bool condition = true) => add(group.signals, description, value, condition, group.group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a Group. // @param posGroup The Group object to add the Signal object to if the value is positive. // @param negGroup The Group object to add the Signal object to if the value is negative. // @param description The description of the signal. // @param value The value of the signal. If not provided, the value will be set to `na`. // @param condition A boolean condition that determines whether the signal will be added to the group. If not provided, the default value is `true`. // @returns The constructed Signal object. export add( Group posGroup, Group negGroup, string description, float value = na, bool condition = true) => if value > 0 add(posGroup, description, value, condition) else if value < 0 add(negGroup, description, value, condition) else false //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given array of Group objects, with a given value, description, and group value. // @param collection The array of Group objects to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param condition An optional boolean value that will decide if the signal is added or not. // @param group A value representing what group the signal belongs to. // @returns true if the condition was true; otherwise false. export add( Group[] collection, string description, float value = na, bool condition = true, string group = na) => if condition g = registerGroup(collection, group) array.push(g.signals, Signal.new(value, description, group)) condition //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Group object to an array of Group objects. // @param collection The array of Group objects to add the new Group object to. // @param group The group value/name of the Group object. // @param color An optional color for the group. // @param symbol An optional symbol for the group. // @returns The constructed Group object. export addGroup( Group[] collection, string group, color color = na, string symbol = na) => g = Group.new(group, array.new<Signal>(), color, symbol) array.push(collection, g) g //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given Signal array under the "Warning" group, with a given value and description. // @param collection The Signal array to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param condition An optional boolean value that will decide if the signal is added or not. // @returns true if the condition was true; otherwise false. export addWarning( Signal[] collection, string description, float value, bool condition = true) => add(collection, description, value, condition, "Warning") //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given array of Group objects under the "Warning" group, with a given value and description. // @param collection The array of Group objects to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param condition An optional boolean value that will decide if the signal is added or not. // @returns true if the condition was true; otherwise false. export addWarning( Group[] collection, string description, float value, bool condition = true) => add(collection, description, value, condition, "Warning") //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given Signal array, with a given value, description, and group value, but only if the value is positive. // @param collection The Signal array to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param group A value representing what group the signal belongs to. // @returns true if the value was positive and the signal was added; otherwise false. export addPosOnly( Signal[] collection, string description, float value, string group = na) => add(collection, description, value, value > 0, group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given Signal array, with a given value, description, and group value, but only if the value is negative. // @param collection The Signal array to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param group A value representing what group the signal belongs to. // @returns true if the value was negative and the signal was added; otherwise false. export addNegOnly( Signal[] collection, string description, float value, string group = na) => add(collection, description, value, value < 0, group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given Signal array, with a given value, description, and group value, but only if the value is positive. // @param group The group of signals to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param group A value representing what group the signal belongs to. // @returns true if the value was positive and the signal was added; otherwise false. export addPosOnly( Group group, string description, float value) => add(group, description, value, value > 0) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given Signal array, with a given value, description, and group value, but only if the value is negative. // @param group The group of signals to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param group A value representing what group the signal belongs to. // @returns true if the value was negative and the signal was added; otherwise false. export addNegOnly( Group group, string description, float value) => add(group, description, value, value < 0) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given array of Group objects, with a given value, description, and group value, but only if the value is positive. // @param collection The array of Group objects to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param group A value representing what group the signal belongs to. // @returns true if the value was positive and the signal was added; otherwise false. export addPosOnly( Group[] collection, string description, float value, string group = na) => add(collection, description, value, value > 0, group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Adds a new Signal object to a given array of Group objects, with a given value, description, and group value, but only if the value is negative. // @param collection The array of Group objects to add the new Signal object to. // @param description The description of the signal. // @param value The value of the signal. // @param group A value representing what group the signal belongs to. // @returns true if the value was negative and the signal was added; otherwise false. export addNegOnly( Group[] collection, string description, float value, string group = na) => add(collection, description, value, value < 0, group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function A utility for standardizing the string format of numeric values. export digits(float value, bool addSign = false) => if na(value) "" else sign = value > 0 ? "+" : value < 0 ? "-" : "" a = math.abs(value) v = a < 1 ? 4 : a < 10 ? 3 : 2 d = math.pow(10, v) s = str.tostring(math.floor(a * d) / d) addSign ? (sign + s) : s //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function A utility for splitting the integer value from its decimal portion. export splitDecimal(float value) => if na(value) [na, na] else int sign = value > 0 ? 1 : value < 0 ? -1 : 0 a = math.abs(value) int whole = math.floor(a) float remain = a - whole [sign * whole, remain] //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Gets the values of the signal objects in the and returns the sum. // @param signals The array of Signal objects to sum the values. export sumValues(Signal[] signals) => if na(signals) 0.0 else s = 0.0 for signal in signals s += nz(signal.value) s //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Gets the values of the signal objects in the and returns the sum. // @param signals The array of Signal objects to sum the values. export sumValues(Group group) => na(group) ? 0.0 : sumValues(group.signals) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Gets the sum of the all the signal objects in each group. // @param signals The array of Signal objects to sum the values. export sumValues(Group[] groups) => if na(groups) 0.0 else s = 0.0 for group in groups s += sumValues(group.signals) s //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Combines an array of Signal objects into a single Signal object, with the descriptions concatenated and the value being the sum of all values of the Signal objects that have a value. The value of each signal is appended to the end of its description in parenthesis. // @param signals The array of Signal objects to combine. // @param group An optional group value to set for the combined Signal object. // @param prefix An optional prefix to use as a prefix for each line in the resultant description. // @returns The combined Signal object. export combine(Signal[] signals, string group = na, string prefix = "") => float value = 0 description = "" for signal in signals value += nz(signal.value) if description != "" description += "\n" description += prefix + signal.description if not na(signal.value) description += " (" + digits(signal.value) + ")" Signal.new(value, description, group) //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Combines a Group object into a single Signal object, with the descriptions concatenated and the value being the sum of all values for the group. // @param group The Group object to combine. // @returns The combined Signal object. export combine(Group group, bool prefixWithSymbol = false) => combine(group.signals, group.group, prefixWithSymbol ? group.symbol + " " : "") //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Combines an array of Group objects into an array of Signal objects, with the descriptions concatenated and the value being the sum of all values for each group. // @param groups The array of Group objects to combine. // @returns The array of combined Signal objects. export combine(Group[] groups, bool prefixWithSymbol = false) => result = array.new<Signal>() for group in groups // Combine the signals within the group. combined = combine(group, prefixWithSymbol) // Add the combined Signal object to the result array. array.push(result, combined) result //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Counts the number of signals in an array of Group objects. // @param groups The array of Group objects to count signals from. // @returns The number of signals in the array of Group objects. export countSignals(Group[] groups) => count = 0 for group in groups for signal in group.signals count += 1 count //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Utility for adding rows to a Row array and color array. export addRow(TB.Row[] rows, color[] rowColors, string desc, float value, color color, string tooltip = na) => row = TB.addRow(rows, tooltip = tooltip) TB.addCell(row, desc) [whole, decimal] = splitDecimal(value) sign = value > 0 ? "+" : value < 0 ? "-" : "" TB.addCell(row, sign + digits(whole)) if nz(decimal) != 0 TB.addCell(row, math.round(decimal, 4)) array.push(rowColors, color) row //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function A simple table display for showing signal values. // @param groups All the signal groups in order. // @param headGroup Optional group to combine in the header. // @param footGroup Optional group to combine in the footer. // @param position The position of the display. Default is position.middle_right. // @returns A TableBuilder.Table object containing the resultant configuration and visible PineScript table. export display(Group[] groups, Group headGroup = na, Group footGroup = na, string position = position.middle_right) => rows = array.new<TB.Row>() rowColors = array.new_color() sumUp = sumValues(headGroup) sumDn = sumValues(footGroup) // Header if sumUp != 0 addRow(rows, rowColors, headGroup.symbol, sumUp, Color.darken(headGroup.color, 50), na(headGroup.group) or headGroup.group == headGroup.symbol ? na : headGroup.group) // Body for group in groups for signal in group.signals addRow(rows, rowColors, signal.description, signal.value, group.color) // Footer if sumDn != 0 addRow(rows, rowColors, footGroup.symbol, sumDn, Color.darken(footGroup.color, 50), na(footGroup.group) or footGroup.group == footGroup.symbol ? na : footGroup.group) tbl = TB.initialize(rows, position)//, frame = TB.LineStyle.new(color.white, 1)) TB.style(tbl, align = TB.CellAlign.new(text.align_left)) TB.styleColumn(tbl, 1, align = TB.CellAlign.new(text.align_right)) TB.styleRows(tbl, rowColors) tbl //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // @function Creates a default set of groups to use with the display function. export defaultGroups() => groups = array.new<Group>() posGroup = addGroup(groups, "β–²", color.rgb(54, 122, 56), "β–²") warnGroup = addGroup(groups, "-", color.orange,'-') negGroup = addGroup(groups, "β–Ό", #a92323, "β–Ό") [groups, posGroup, warnGroup, negGroup] //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //// DEMO ////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// if barstate.islast // First setup the signal groups to accept values. [groups, posGroup, warnGroup, negGroup] = defaultGroups() // Add any signals desired. add(posGroup, "Momentum", +1.1) add(posGroup, "Oversold", +1) add(warnGroup, "Unconfirmed") add(negGroup, "Downtrend", -2) add(negGroup, "Below VWAP", -1) // Show the values (last bar only). display(groups, posGroup, negGroup)
Expansion Contraction Library
https://www.tradingview.com/script/dv7lgp2K-Expansion-Contraction-Library/
viewer405
https://www.tradingview.com/u/viewer405/
42
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© viewer405 //@version=5 // @description Library for Expansion Contraction Indicator, a zero-lag dual perspective indicator created by Brian Latta based on Jake Bernstein’s principles of Moving Average Channel system. library("ExpansionContraction") // @function Calculates Expansion Contraction values. // @param shortLookback Integer for the short lookback calculation, defaults to 8 // @param longLookback Integer for the long lookback calculation, defaults to 32 // @return Returns array of Expansion Contraction values export calc(int shortLookback = 8, int longLookback = 32) => avgHighShort = ta.sma(high, shortLookback) avgHighLong = ta.sma(high, longLookback) xcPositiveShort = (high - avgHighShort) + (low - avgHighShort) xcPositiveLong = (high - avgHighLong) + (low - avgHighLong) avgLowShort = ta.sma(low, shortLookback) avgLowLong = ta.sma(low, longLookback) xcNegativeShort = (avgLowShort - low) + (avgLowShort - high) xcNegativeLong = (avgLowLong - low) + (avgLowLong - high) mediumShort = (xcPositiveShort + xcNegativeShort) / 2 mediumLong = (xcPositiveLong + xcNegativeLong) / 2 positiveShort = xcPositiveShort - mediumShort positiveLong = xcPositiveLong - mediumLong negativeShort = xcNegativeShort - mediumShort negativeLong = xcNegativeLong - mediumLong [positiveShort, negativeShort, positiveLong, negativeLong] // @function Calculates standard deviation lines based on Expansion Contraction Long and Short values. // @param positiveShort Float for the positive short XC value from calculation // @param negativeShort Float for the negative short XC value from calculation // @param positiveLong Float for the positive long XC value from calculation // @param negativeLong Float for the negative long XC value from calculation // @param stdevLookback Integer for the standard deviation lookback, defaults to 500 // @return Returns array of standard deviation values export stdevCalc(float positiveShort, float negativeShort, float positiveLong, float negativeLong, int stdevLookback = 500) => avgShort = ta.sma(math.max(positiveShort, negativeShort), stdevLookback) stdevShort = ta.stdev(avgShort, stdevLookback) avgLong = ta.sma(math.max(positiveLong, negativeLong), stdevLookback) stdevLong = ta.stdev(avgLong, stdevLookback) upperShort = avgShort + stdevShort lowerShort = -upperShort upperLong = avgLong + stdevLong lowerLong = -upperLong upperLong2 = upperLong * 2 lowerLong2 = -upperLong2 [upperShort, lowerShort, upperLong, lowerLong, upperLong2, lowerLong2] // @function Determines if trend is strong or weak based on Expansion Contraction values. // @param positiveShort Float for the positive short XC value from calculation // @param negativeShort Float for the negative short XC value from calculation // @param positiveLong Float for the positive long XC value from calculation // @param negativeLong Float for the negative long XC value from calculation // @return Returns array of boolean values indicating strength or weakness of trend export trend(float positiveShort, float negativeShort, float positiveLong, float negativeLong) => bool weakBull = positiveLong > negativeLong and positiveShort < negativeShort bool weakBear = negativeLong > positiveLong and negativeShort < positiveShort bool strongBull = positiveLong > negativeLong and positiveShort > negativeShort bool strongBear = negativeLong > positiveLong and negativeShort > positiveShort [weakBull, strongBull, weakBear, strongBear] [positiveShort, negativeShort, positiveLong, negativeLong] = calc() [upperShort, lowerShort, upperLong, lowerLong, upperLong2, lowerLong2] = stdevCalc(positiveShort, negativeShort, positiveLong, negativeLong) [weakBull, strongBull, weakBear, strongBear] = trend(positiveShort, negativeShort, positiveLong, negativeLong) shortLookback=input(defval=8, title="Short-Term Length") longLookback=input(defval=32, title="Long-Term Length") stdevLookback=input(defval=500, title="Standard Deviation Length") bullColor = #26a69a bearColor = #ef5350 enableBarColor=input(defval=true, title="Enable Trend Bar Colors", group="Candlestick Colors") weakBullColor=input(color.new(bullColor, 50), "Weak Bull Bar", group="Candlestick Colors") weakBearColor=input(color.new(bearColor, 50), "Weak Bear Bar", group="Candlestick Colors") strongBullColor=input(color.new(bullColor, 0), "Strong Bull Bar", group="Candlestick Colors") strongBearColor=input(color.new(bearColor, 0), "Strong Bear Bar", group="Candlestick Colors") positiveShortColor=input(color.new(color.green, 0), "+ Short Exp/Con Line", group="Expansion/Contraction Color Settings") negativeShortColor=input(color.new(color.red, 0), "- Short Exp/Con Line", group="Expansion/Contraction Color Settings") mediumColor=input(color.new(color.gray, 0), "Medium Line", group="Expansion/Contraction Color Settings") positiveLongColor=input(color.new(color.green, 80), "+ Long Exp/Con Line", group="Expansion/Contraction Color Settings") negativeLongColor=input(color.new(color.red, 80), "- Long Exp/Con Line", group="Expansion/Contraction Color Settings") cloudColor=(positiveLong > negativeLong) ? positiveLongColor : negativeLongColor plot(positiveShort, color=positiveShortColor, linewidth=2, title="+ Short Exp/Con Line") plot(negativeShort, color=negativeShortColor, linewidth=2, title="- Short Exp/Con Line") hline(0, color=mediumColor, title="Medium") u = plot(positiveLong, color=cloudColor, title="+ Long Exp/Con Line") l = plot(negativeLong, color=cloudColor, title="- Long Exp/Con Line") fill(u, l, color=cloudColor, title="Long Exp/Con Cloud") plot(upperShort, color=color.new(color.gray, 50), linewidth=1, title="+ 1 Standard Deviation - Short") plot(lowerShort, color=color.new(color.gray, 50), linewidth=1, title="- 1 Standard Deviation - Short") plot(upperLong, color=color.new(color.gray, 25), linewidth=1, title="+ 1 Standard Deviation - Long") plot(lowerLong, color=color.new(color.gray, 25), linewidth=1, title="- 1 Standard Deviation - Long") plot(upperLong2, color=color.new(color.gray, 20), linewidth=1, title="+ 2 Standard Deviation - Long") plot(lowerLong2, color=color.new(color.gray, 20), linewidth=1, title="- 2 Standard Deviation - Long") candleColor = open > close ? bullColor : bearColor if weakBull == true candleColor:=weakBullColor else if strongBull == true candleColor:=strongBullColor else if weakBear == true candleColor:=weakBearColor else if strongBear == true candleColor:=strongBearColor candleColor:=enableBarColor == true ? candleColor : na barcolor(candleColor)
CSMlibrary
https://www.tradingview.com/script/NwNvbp49-CSMlibrary/
ckppmarathe
https://www.tradingview.com/u/ckppmarathe/
4
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© ckppmarathe //@version=5 // @description TODO: add library description here library("CSMlibrary", overlay = true) // @function TODO: add function description here // @param x TODO: add parameter x description here // @returns TODO: add what function returns //export fun(float x) => //TODO : add function body and return value here // x // --------------------------- // @function CSMplot: This function plots a seris with its title at right end // The plot will be drawn for last 400 bars. // @param myseries: seris to be plotted // @param mytitle: plot title for the seris // @param mycolor: plot color for the seris // @param mywidth: plot line width. // @param myoffset: offset at right end for the plot label // @param l_size: string describing the size of the plot label // @returns TODO: add what function returns export CSMplot(float myseries, string mytitle, color mycolor, int mywidth, int myoffset, string l_size) => ll_offset = timenow + math.round(ta.change(time)*myoffset) // draw last 4000 bars var a = array.new_line() array.push(a, line.new(bar_index - 1, myseries[1], bar_index, myseries, color = mycolor, width = mywidth, style = line.style_solid)) if array.size(a) > 4000 ln = array.shift(a) line.delete(ln) myplot_line = line.new(x1=timenow, x2=ll_offset, y1=myseries, y2=myseries, xloc=xloc.bar_time, extend=extend.right, color=mycolor, width=mywidth, style=line.style_dotted) line.delete(myplot_line[1]) myplot_label = label.new(x=ll_offset, y=myseries, xloc=xloc.bar_time, yloc=yloc.price, text=mytitle + " β•‘ " + str.tostring(myseries), style=label.style_none, textcolor=mycolor, size=l_size) label.delete(myplot_label[1]) //CSMplot(close, "CLOSE", color.lime, 1, 5, size.normal) //CSMplot(open, "OPEN", color.maroon, 1, 5, size.normal) // --------------------------- /// --------------------------- /// --------------------------- // --------------------------- // --------------------------- // --------------------------- // --------------------------- // --------------------------- // --------------------------- // --------------------------- // --------------------------- //
EMAFlow
https://www.tradingview.com/script/shTcQ2rJ-EMAFlow/
SimpleCryptoLife
https://www.tradingview.com/u/SimpleCryptoLife/
16
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© SimpleCryptoLife //@version=5 // @description Library of functions that manipulate a set of 5 MAs created within user-supplied maximum and minimum lengths. // The MAs are spaced out (within the range) in a way that approximates how Fibonnaci numbers are spaced. // Using MA flow, as opposed to simple crosses of the minimum and maximum lengths, gives more detail, and can result in faster changes and more resistance to chop, depending how you use it. library("EMAFlow", overlay=true) in_maMinLength = input.int(defval=8, minval=4, maxval=50, title='Shortest MA Length', tooltip='The length of the shortest MA in the set. The middle three MAs are generated automatically. Must be 15 less than the maximum in order to generate a meaningful spread. If too close, the background is coloured red and a label indicates the error.') in_maMaxLength = input.int(defval=34, minval=20, maxval=250, title='Longest MA Length', tooltip='The length of the longest MA in the set. The middle three MAs are generated automatically. Must be 15 more than the minimum in order to generate a meaningful spread. If too close, the background is coloured red and a label indicates the error.') var string errorTextLibraryName = "EMAFlow" // === Helper functions === f_ema(_source,_length) => _alpha = (2 / (_length + 1)), var float _ema = 0.0, _ema := na(_ema[1]) ? _source : _alpha * _source + (1 - _alpha) * nz(_ema[1]) f_source(_source) => _output = switch _source "ohlc4" => ohlc4 "open" => open "high" => high "low" => low "close" => close "hl2" => hl2 "hlc3" => hlc3 => na // === Exported functions === // @function f_emaFlowBias: Gives a bullish or bearish bias reading based on the EMA flow from the user-supplied range. // @param int _min: The minimum length of the EMA set. // @param int _max: The maximum length of the EMA set. // @param: float _source: The source for the EMA set. Supply the actual floating-point number. // @returns: An integer, representing the bias: 1 is bearish, 2 is slightly bearish, 3 is neutral, 4 is slightly bullish, 5 is bullish. export f_emaFlowBias(int _min=8, int _max=34, float _source=ohlc4) => // Error-checking var string errorTextFunctionName = "f_emaFlowBias" if (_max - _min) < 15 runtime.error("Max MA length must be at least 15 greater than min length [Error 001:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _min < 4 runtime.error("Min MA length cannot be less than 4. [Error 002:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _min > 50 runtime.error("Min MA length cannot be more than 50. [Error 003:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _max > 200 runtime.error("Max MA length cannot be more than 200. [Error 004:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") float _emaAdjustedRange = (_max - _min) / 55 // Because 8+13+21+34+55 = 5 Fib MAs float _ema1 = f_ema(_source, _min) float _ema2 = f_ema(_source, _min + int(9 * _emaAdjustedRange)) float _ema3 = f_ema(_source, _min + int(21 * _emaAdjustedRange)) float _ema4 = f_ema(_source, _min + int(34 * _emaAdjustedRange)) float _ema5 = f_ema(_source, _max) float _rma = ta.rma(_source,2) if barstate.isfirst // A way of ignoring the first bar (which can be useful to exclude strangeness on some charts) that doesn't give compilation warnings _ema1 := na, _ema2 := na, _ema3 := na, _ema4 := na, _ema5 := na, _rma := na bool _allEmasBearish = _ema1 < math.min(_ema2, _ema3, _ema4, _ema5) and _ema2 < math.min(_ema3, _ema4, _ema5) and _ema3 < math.min(_ema4, _ema5) and _ema4 < _ema5 bool _allEmasBullish = _ema1 > math.max(_ema2, _ema3, _ema4, _ema5) and _ema2 > math.max(_ema3, _ema4, _ema5) and _ema3 > math.max(_ema4, _ema5) and _ema4 > _ema5 _emasHowManyBearish = 0 _emasHowManyBearish := _ema1 < math.min(_ema2, _ema3, _ema4, _ema5) ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBearish := _ema2 < math.min(_ema3, _ema4, _ema5) ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBearish := _ema3 < math.min(_ema4, _ema5) ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBearish := _ema4 < _ema5 ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBullish = 0 _emasHowManyBullish := _ema1 > math.max(_ema2, _ema3, _ema4, _ema5) ? _emasHowManyBullish + 1 : _emasHowManyBullish _emasHowManyBullish := _ema2 > math.max(_ema3, _ema4, _ema5) ? _emasHowManyBullish + 1 : _emasHowManyBullish _emasHowManyBullish := _ema3 > math.max(_ema4, _ema5) ? _emasHowManyBullish + 1 : _emasHowManyBullish _emasHowManyBullish := _ema4 > _ema5 ? _emasHowManyBullish + 1 : _emasHowManyBullish bool _moreEmasBearish = _emasHowManyBearish > _emasHowManyBullish bool _moreEmasBullish = _emasHowManyBullish > _emasHowManyBearish int _bias = _allEmasBearish ? 1 : _allEmasBullish ? 5 : _moreEmasBearish and (_rma < _ema5) ? 2 : _moreEmasBullish and (_rma > _ema5) ? 4 : 3 // @function f_emaFlowBiasSource: Same as f_emaFlowBias except you can supply the source as a string. // @param int _min: The minimum length of the EMA set. // @param int _max: The maximum length of the EMA set. // @param: string _source: The source for the EMA set. Must be in standard format (open, close, ohlc4, etc.) // @returns: An integer, representing the bias: 1 is bearish, 2 is slightly bearish, 3 is neutral, 4 is slightly bullish, 5 is bullish. export f_emaFlowBiasSource(int _min=8, int _max=34, string _source="ohlc4") => // Error-checking var string errorTextFunctionName = "f_emaFlowBias" if (_max - _min) < 15 runtime.error("Max MA length must be at least 15 greater than min length [Error 001:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _min < 4 runtime.error("Min MA length cannot be less than 4. [Error 002:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _min > 50 runtime.error("Min MA length cannot be more than 50. [Error 003:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _max > 200 runtime.error("Max MA length cannot be more than 200. [Error 004:" + " from function " + errorTextFunctionName + " in library " + errorTextLibraryName + "]") _sourceFixed = f_source(_source) // Needed because Pine only accepts typed inputs to library functions and string doesn't work as an EMA input and source isn't a type, so we're stuck with string and if anyone knows a better fix feel free to comment. if na(_sourceFixed) runtime.error("Source must be in standard format") float _emaAdjustedRange = (_max - _min) / 55 // Because 8+13+21+34+55 = 5 Fib MAs float _ema1 = f_ema(_sourceFixed, _min) float _ema2 = f_ema(_sourceFixed, _min + int(9 * _emaAdjustedRange)) float _ema3 = f_ema(_sourceFixed, _min + int(21 * _emaAdjustedRange)) float _ema4 = f_ema(_sourceFixed, _min + int(34 * _emaAdjustedRange)) float _ema5 = f_ema(_sourceFixed, _max) float _rma = ta.rma(_sourceFixed,2) if barstate.isfirst // A way of ignoring the first bar (which can be useful to exclude strangeness on some charts) that doesn't give compilation warnings _ema1 := na, _ema2 := na, _ema3 := na, _ema4 := na, _ema5 := na, _rma := na bool _allEmasBearish = _ema1 < math.min(_ema2, _ema3, _ema4, _ema5) and _ema2 < math.min(_ema3, _ema4, _ema5) and _ema3 < math.min(_ema4, _ema5) and _ema4 < _ema5 bool _allEmasBullish = _ema1 > math.max(_ema2, _ema3, _ema4, _ema5) and _ema2 > math.max(_ema3, _ema4, _ema5) and _ema3 > math.max(_ema4, _ema5) and _ema4 > _ema5 _emasHowManyBearish = 0 _emasHowManyBearish := _ema1 < math.min(_ema2, _ema3, _ema4, _ema5) ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBearish := _ema2 < math.min(_ema3, _ema4, _ema5) ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBearish := _ema3 < math.min(_ema4, _ema5) ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBearish := _ema4 < _ema5 ? _emasHowManyBearish + 1 : _emasHowManyBearish _emasHowManyBullish = 0 _emasHowManyBullish := _ema1 > math.max(_ema2, _ema3, _ema4, _ema5) ? _emasHowManyBullish + 1 : _emasHowManyBullish _emasHowManyBullish := _ema2 > math.max(_ema3, _ema4, _ema5) ? _emasHowManyBullish + 1 : _emasHowManyBullish _emasHowManyBullish := _ema3 > math.max(_ema4, _ema5) ? _emasHowManyBullish + 1 : _emasHowManyBullish _emasHowManyBullish := _ema4 > _ema5 ? _emasHowManyBullish + 1 : _emasHowManyBullish bool _moreEmasBearish = _emasHowManyBearish > _emasHowManyBullish bool _moreEmasBullish = _emasHowManyBullish > _emasHowManyBearish int _bias = _allEmasBearish ? 1 : _allEmasBullish ? 5 : _moreEmasBearish and (_rma < _ema5) ? 2 : _moreEmasBullish and (_rma > _ema5) ? 4 : 3 // ============================== EXAMPLE USAGE ================================== int bias= f_emaFlowBias(_min=in_maMinLength, _max=in_maMaxLength, _source=ohlc4) color bgColour = switch bias 1 => color.new(color.red, 50) 2 => color.new(color.red, 80) 3 => na 4 => color.new(color.green,80) 5 => color.new(color.green,50) bgcolor(bgColour, title="Background for bias", editable=false) // END
TrailingStops
https://www.tradingview.com/script/Bv63ZaUQ-TrailingStops/
SimpleCryptoLife
https://www.tradingview.com/u/SimpleCryptoLife/
72
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© SimpleCryptoLife //@version=5 // @description This library contains functions to output trailing stop lines. library("TrailingStops", overlay=true) string in_showFunction = input.string(defval="f_complexStop", title="Function to display", options=["f_marketStructureStop","f_complexStop"]) in_restartMode_MS = input.string(defval="Flip", title="Restart Mode", group="f_marketStructureStop", options=["Always On","Flip","Manual"], tooltip="All options set _restartMode to the same value. \"Always On\" and \"Flip\" are built-in options in the function. If you choose \"Manual\", _restartLow and _restartHigh must then be calculated outside the function and supplied to it. Here, there is some demo code to do that. You can turn the trails on manually when your indicator takes a position, or just leave them always on here and sample them however you like.") in_flipMode_MS = input.string(defval="Wick", title="Flip On", options=["Wick","Close"], tooltip="Whether the stop lines flip when exceeded by a wick or a close in price.") in_strictMode_MS = input.bool(defval=false, title="Use Lows, Highs in Strict Order") in_flipMode_CX = input.string(defval="Wick", title="Flip On", group="f_complexStop", options=["Wick","Close"], tooltip="Whether the stop lines flip when exceeded by a wick or a close in price.") // Variables derived solely from inputs bool showMS = in_showFunction == "f_marketStructureStop" bool showComplex = in_showFunction == "f_complexStop" import SimpleCryptoLife/MarketStructure/1 as SCL_MS var string errorTextLibraryName = "TrailingStops" // Defined globally for use in error messages. // @function f_marketStructureStop - Outputs a stop line based on market structure generated by Local Lows and Highs. This is NOT a market structure indicator (for that, I've written a free, open-source indicator, and you could easily construct one yourself using my MarketStructure library). This function gives intuitive, rule-based places to put a stop loss; that's all. // @param string _restartMode="Flip" - Defines how the stop lines persist. Allowed values are: // "Always On" - The stop lines are always present and they just reset when they're crossed. This is the least intuitive but perhaps most useful option. Simply sample the line when you want to take a position; long and short stops are always available. // "Flip" - The stop lines flip when they're crossed. This looks like one would expect a trailing stop to look. // "Manual" - The stop lines turn off when they're crossed, and turn back on again when _restartLowIn or _restartHighIn are passed into the function as true. // @param string _flipMode="Wick" - Defines whether the stop lines are broken by wicks or closes. Allowed values are "Wick", and "Close". If you choose "Close", the stop line that's displayed can regress on a wick, but the underlying value for flipping does not regress. This is by design and is not a bug. The function doesn't know when you might take a position in either direction. If you choose to take a long when the long stop line has been pierced by a wick but not a close, it will display the appropriate value for a stop on that bar, which is the bar's Low. // @param bool _restartLowIn=true - If _restartMode is "Manual", passing this parameter as true restarts the Low stop line. // @param bool _restartHighIn=true - If _restartMode is "Manual", passing this parameter as true restarts the High stop line. // @param bool _strictMode - If false, this library uses Enhanced Simple Highs/Lows from the MarketStructure library. If true, it uses True Highs/Lows. // @returns - floats for the Low and High stop lines. // 🟦🟦🟦🟦 MARKET STRUCTURE TRAILING STOP 🟦🟦🟦🟦 export f_marketStructureStop(string _restartMode="Flip", string _flipMode="Wick", bool _restartLowIn=true, bool _restartHighIn=true, bool _strictMode=false) => // Error-checking var string _errorTextFunctionName = "f_marketStructureStop" if _flipMode != "Wick" and _flipMode != "Close" runtime.error("_flipMode must be either \"Wick\" or \"Close\". [Error 01:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") if _restartMode != "Always On" and _restartMode != "Flip" and _restartMode != "Manual" runtime.error("_restartMode must be one of \"Always On\", \"Flip\", or \"Manual\". [Error 02:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") // Define variables var float _lowStop = na, var float _highStop = na // The actual stop lines. We need them to be continuable (it's a word now). var bool _isActiveLow = true, var bool _isActiveHigh = true // We have to start off active. var bool _restartLow = na, var bool _restartHigh = na // Should we restart the stop lines? var bool _restartLowFlip = true, var bool _restartHighFlip = true // Separate bools for whether we should restart the stop lines in Flip mode // Choose the low and high break values (close/wicks) float _lowValue = switch _flipMode "Wick" => low "Close" => close float _highValue = switch _flipMode "Wick" => high "Close" => close // Get the market structure values [_isEnhancedHigh, _isEnhancedLow, _enhancedHighIndex, _enhancedLowIndex, _enhancedHighTrail, _enhancedHigh, _enhancedLowTrail, _enhancedLow, _enhancedBullish, _enhancedBearish] = SCL_MS.f_enhancedSimpleLowHigh() [_isTrueHigh, _isTrueLow, _trueHighIndex, _trueLowIndex, _trueHighTrail, _trueHigh, _trueLowTrail, _trueLow, _trueBullish, _trueBearish] = SCL_MS.f_trueLowHigh() // Choose the market structure values _pivotHighTrail = _strictMode ? _trueHighTrail : _enhancedHighTrail _pivotHigh = _strictMode ? _trueHigh : _enhancedHigh _pivotLowTrail = _strictMode ? _trueLowTrail : _enhancedLowTrail _pivotLow = _strictMode ? _trueLow : _enhancedLow // Sample the market structure lines to create the stop lines float _lowLine = na(_pivotLow) ? _pivotLowTrail : na(_pivotLowTrail) ? _pivotLow : math.min(_pivotLow, _pivotLowTrail) float _highLine = na(_pivotHigh) ? _pivotHighTrail : na(_pivotHighTrail) ? _pivotHigh : math.max(_pivotHigh, _pivotHighTrail) // Are the stop lines broken? bool _brokenLow = _lowValue < _pivotLow bool _brokenHigh = _highValue > _pivotHigh // Set restart values according to the restart mode _restartLowFlip := _brokenLow ? false : _brokenHigh ? true : _restartLowFlip // Restart the Low stop line when the High stop line is broken _restartHighFlip := _brokenHigh ? false : _brokenLow ? true : _restartHighFlip // Restart the High stop line when the Low stop line is broken _restartLow := switch _restartMode "Always On" => true "Manual" => _restartLowIn // The inputs only take effect in Manual mode "Flip" => _restartLowFlip // Using a separate variable isn't the most compact way but it's the clearest _restartHigh := switch _restartMode "Always On" => true "Manual" => _restartHighIn "Flip" => _restartHighFlip // Start off with the stop lines active and make them active and inactive according to the restart values _isActiveLow := _restartLow ? true : _brokenLow ? false : _isActiveLow _isActiveHigh := _restartHigh ? true : _brokenHigh ? false : _isActiveHigh // Actually set and unset the stop lines. Easy now we did all the other bits. _lowStop := _isActiveLow ? _lowLine : na _highStop := _isActiveHigh ? _highLine : na [_lowStop, _highStop] // 🟦🟦🟦 Example usage 🟦🟦🟦 // Calculate when to restart the stop lines when _restartMode is "Manual". This is just an example and you can do it any way. var bool restartLowIn_MS = false, var bool restartHighIn_MS = false if in_restartMode_MS == "Manual" restartLowIn_MS := close > high[1] ? true : false // Restart the low stop line on the next bullish candle restartHighIn_MS := close < low[1] ? true : false // Restart the high stop line on the next bearish candle // Call the function [lowStop_MS, highStop_MS] = f_marketStructureStop(_restartMode=in_restartMode_MS, _flipMode=in_flipMode_MS, _restartLowIn=restartLowIn_MS, _restartHighIn=restartHighIn_MS, _strictMode=in_strictMode_MS) // Plots plot(showMS ? lowStop_MS : na, title="Market Structure: Low Stop Background", linewidth=5, color=color.new(color.blue,70), style=plot.style_linebr) plot(showMS ? lowStop_MS : na, title="Market Structure: Low Stop Line", linewidth=2, color=color.green, style=plot.style_linebr) plot(showMS ? highStop_MS : na, title="Market Structure: High Stop Background", linewidth=5, color=color.new(color.orange,70), style=plot.style_linebr) plot(showMS ? highStop_MS : na, title="Market Structure: High Stop Line", linewidth=2, color=color.red, style=plot.style_linebr) // 🟦🟦🟦🟦 COMPLEX TRAILING STOP 🟦🟦🟦🟦 // @function f_complexStop - Outputs a stop line using more complex criteria than f_marketStructureStop, but still based on market structure generated by Local Lows and Highs. This is NOT a market structure indicator (for that, I've written a free, open-source indicator, and you could easily construct one yourself using my MarketStructure library). This function gives intuitive, rule-based places to put a stop loss; that's all. // @param float _high - Defaults to the High of the current chart bar. Included for HTF compatibility. // @param float _low - Defaults to the Low of the current chart bar. Included for HTF compatibility. // @param float _close - Defaults to the Close of the current chart bar. Included for HTF compatibility. // @param string _flipMode="Wick" - Defines whether the stop lines are broken by wicks or closes. Allowed values are "Wick", and "Close". If you choose "Close", the stop line that's displayed can regress on a wick, but the underlying value for flipping does not regress. This is by design and is not a bug. The function doesn't know when you might take a position in either direction. If you choose to take a long when the long stop line has been pierced by a wick but not a close, it will display the appropriate value for a stop on that bar, which is the bar's Low. // @param float _lowBuffer - You can add a buffer to the low stop. // @param float _highBuffer - You can add a buffer to the high stop. // @returns - floats for the Low and High stop lines. Bools for whether the lines are active. export f_complexStop(float _high=high, float _low=low, float _close=close, string _flipMode="Wick", float _lowBuffer=0, float _highBuffer=0) => var string _errorTextFunctionName = "f_complexStop" if _flipMode != "Wick" and _flipMode != "Close" runtime.error("_flipMode must be either \"Wick\" or \"Close\". [Error 01:" + " from function " + _errorTextFunctionName + " in library " + errorTextLibraryName + "]") // Get the market structure values [_isEnhancedHigh, _isEnhancedLow, _null3, _null4, _pivotHighTrail, _pivotHigh, _pivotLowTrail, _pivotLow, _null5, _null6] = SCL_MS.f_enhancedSimpleLowHigh() // 🟦🟦 HIGH AND LOW LINES // Sample the market structure lines to create the high and low lines float _lowLine = na(_pivotLow) ? _pivotLowTrail : na(_pivotLowTrail) ? _pivotLow : math.min(_pivotLow, _pivotLowTrail) float _highLine = na(_pivotHigh) ? _pivotHighTrail : na(_pivotHighTrail) ? _pivotHigh : math.max(_pivotHigh, _pivotHighTrail) // Are the high/low lines broken? bool _brokenLowLine = _close < _pivotLow // Close makes it slightly less reactive than low/high bool _brokenHighLine = _close > _pivotHigh // Has the line tightened? var bool _lowLineTightened = na, var bool _highLineTightened = na, _lowLineTightened := _brokenLowLine ? false : _lowLine > _lowLine[1] ? true : _lowLineTightened // Has the low line moved up? _highLineTightened := _brokenHighLine ? false : _highLine < _highLine[1] ? true : _highLineTightened // Has the high line moved down? // 🟦🟦 STOP LINES var float _lowStop = na, var float _highStop = na // The actual stop lines. We need them to be continuable (it's a word now). // Choose the low and high break values (close/wicks) float _lowStopFlipValue = switch _flipMode "Wick" => _low "Close" => _close float _highStopFlipValue = switch _flipMode "Wick" => _high "Close" => _close // Are the stop lines broken? bool _brokenLowStop = _lowStopFlipValue < _lowStop bool _brokenHighStop = _highStopFlipValue > _highStop // Is the stop line active? In Compression, prevent the stop lines advancing until we reach Expansion again (the absence of tightened opposite line) var bool _isLowStopActive = na, var bool _isHighStopActive = na var bool _isLowStopActive_setup1 = na, var bool _isHighStopActive_setup1 = na var bool _isLowStopActive_setup2 = na, var bool _isHighStopActive_setup2 = na _isLowStopActive_setup1 := not _brokenLowStop ? true : _brokenLowStop ? false : _isLowStopActive_setup1 // Setup1 starts when the stop line stops being broken, and persists until it is. _isLowStopActive_setup2 := _isEnhancedLow ? true : _brokenLowStop ? false : _isLowStopActive_setup2 // Setup 2 starts on an Enhanced Low and persists until setup1 is gone. bool _isLowStopActive_trigger = _isLowStopActive_setup1 and _isLowStopActive_setup2 and not _highLineTightened // Trigger is absence of opposite tightened line plus setups _isHighStopActive_setup1 := not _brokenHighStop ? true : _brokenHighStop ? false : _isHighStopActive_setup1 _isHighStopActive_setup2 := _isEnhancedHigh ? true : _brokenHighStop ? false : _isHighStopActive_setup2 bool _isHighStopActive_trigger = _isHighStopActive_setup1 and _isHighStopActive_setup2 and not _lowLineTightened _isLowStopActive := _brokenLowStop ? false : _isLowStopActive_trigger ? true : _isLowStopActive // Active when trigger fires; off when the stop line is broken _isHighStopActive := _brokenHighStop ? false : _isHighStopActive_trigger ? true : _isHighStopActive // Define and persist the stop lines. We output them constantly; you can colour them differently or hide them when not active in your script. var float lowLineBuffered = na, var float highLineBuffered = na lowLineBuffered := ta.change(_lowLine) ? _lowLine - _lowBuffer : lowLineBuffered // Only add the buffer when the line changes, so the stop line stays flat. highLineBuffered := ta.change(_highLine) ? _highLine + _highBuffer : highLineBuffered bool _goChangeLowStop = not (lowLineBuffered < _lowStop) // This awkwardness is required for the case where lines are na at the beginnig of the chart bool _goChangeHighStop = not (highLineBuffered > _highStop) _lowStop := _brokenLowStop ? lowLineBuffered : _goChangeLowStop and not _highLineTightened? lowLineBuffered : _lowStop // Finally we can be happy! _highStop := _brokenHighStop ? highLineBuffered : _goChangeHighStop and not _lowLineTightened ? highLineBuffered : _highStop [_lowStop, _highStop, _isLowStopActive, _isHighStopActive] // 🟦🟦🟦🟦 Example usage 🟦🟦🟦🟦 [lowStop_CX, highStop_CX, isLowStopActive_CX, isHighStopActive_CX] = f_complexStop(_high=high, _low=low, _close=close, _flipMode=in_flipMode_CX, _lowBuffer=0, _highBuffer=0) plot(showComplex ? lowStop_CX : na, title="Complex: Low Stop Background", linewidth=5, color=isLowStopActive_CX ? color.new(color.blue,70) : na, style=plot.style_linebr) plot(showComplex ? lowStop_CX : na, title="Complex: Low Stop Line", linewidth=2, color=isLowStopActive_CX ? color.green : color.new(color.gray,70), style=plot.style_linebr) plot(showComplex ? highStop_CX : na, title="Complex: High Stop Background", linewidth=5, color=isHighStopActive_CX ? color.new(color.orange,70) : na, style=plot.style_linebr) plot(showComplex ? highStop_CX : na, title="Complex: High Stop Line", linewidth=2, color=isHighStopActive_CX ? color.red : color.new(color.gray,70), style=plot.style_linebr) // ======================================================== // // // // (β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ˙ɹǝllα΄‰Κž-puᴉɯ ǝΙ₯Κ‡ sᴉ ɹɐǝℲ Λ™ΙΉΙΗΙŸ Κ‡ou llᴉʍ I // // // // ======================================================== //
DBMA - Dual Bollinger Moving Average
https://www.tradingview.com/script/5Q0rRNo6-DBMA-Dual-Bollinger-Moving-Average/
finallynitin
https://www.tradingview.com/u/finallynitin/
807
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© finallynitin //@version=5 indicator(title='Dual Bollinger Moving Average', shorttitle='DBMA', overlay=true) string GRP1 = "════════ Moving Average ═════════" MA_length = input.int(title='', minval=1, maxval=1000, defval=20, inline='line 1', group=GRP1) MA_type = input.string(title='', options=['SMA', 'EMA', 'WMA'], defval='SMA', inline='line 1', group=GRP1) MA_source = input.source(title='', defval=close, inline='line 1', group=GRP1) MA_color = input.color(title='', defval=color.green, inline='line 1', group=GRP1) MA_width = input.int(title='MA line width', defval=1, minval=1, maxval=4, inline='line 2', group=GRP1) string GRP2 = "════════ Bollinger Bands ═════════" BB_show_upper = input.bool(title='Show Upper Bands', defval=true, inline='line 1', group=GRP2) BB_show_lower = input.bool(title='Show Lower Bands', defval=false, inline='line 2', group=GRP2) BB_stdev_near = input.float(title='Near Band', minval=0, maxval=3, defval=0.5, step = 0.5, inline='line 3', group=GRP2) colorOrangeHalf = input.color(color.new(color.orange, 85), '', inline='line 3', group=GRP2) BB_stdev_far = input.float(title='Far Band', minval=0, maxval=3, defval=1, step = 0.5, inline='line 4', group=GRP2) colorOrangeOne = input.color(color.new(color.orange, 90), '', inline='line 4', group=GRP2) string GRP3 = "════════ Squeeze ═════════" toggleSQZColors = input.bool(title='Squeeze Colors', defval=true, inline='line 3', group=GRP3) colorRed = input.color(color.red, 'High-compression Squeeze', group=GRP3) colorOrange = input.color(color.orange, 'Mid-compression Squeeze', group=GRP3) colorYellow = input.color(color.yellow, 'Low-compression Squeeze', group=GRP3) colorGreen = input.color(color.green, 'Fired Squeeze', group=GRP3) colorBlue = input.color(color.blue, 'No Squeeze', group=GRP3) //--------BMA------ BMA = 0.0 BMA := MA_type == 'SMA' ? ta.sma(MA_source, MA_length) : MA_type == 'EMA' ? ta.ema(MA_source, MA_length) : MA_type == 'WMA' ? ta.vwma(MA_source, MA_length) : na p1 = plot(BMA, title='Bollingerised Moving Average', color=MA_color, linewidth=MA_width) //--------SQUEEZE------ // original concept from John Carter's book "Mastering the Trade" // based on LazyBear's script (Squeeze Momentum Indicator) https://in.tradingview.com/script/nqQ1DT5a-Squeeze-Momentum-Indicator-LazyBear/ devBB = BB_stdev_far * ta.stdev(MA_source, MA_length) devKC = ta.sma(ta.tr, MA_length) //Bollinger 2x upBB = BMA + devBB * 2 lowBB = BMA - devBB * 2 //Keltner 2x upKCWide = BMA + devKC * 2 lowKCWide = BMA - devKC * 2 //Keltner 1.5x upKCNormal = BMA + devKC * 1.5 lowKCNormal = BMA - devKC * 1.5 //Keltner 1x upKCNarrow = BMA + devKC lowKCNarrow = BMA - devKC sqzOnWide = lowBB >= lowKCWide and upBB <= upKCWide //Low-compression Squeeze: YELLOW sqzOnNormal = lowBB >= lowKCNormal and upBB <= upKCNormal //Mid-compression Squeeze: ORANGE sqzOnNarrow = lowBB >= lowKCNarrow and upBB <= upKCNarrow //High-compression Squeeze: RED sqzOffWide = lowBB < lowKCWide and upBB > upKCWide //Fired Squeeze: GREEN noSqz = sqzOnWide == false and sqzOffWide == false //No Squeeze: BLUE sq_color = noSqz ? colorBlue : sqzOnNarrow ? colorRed : sqzOnNormal ? colorOrange : sqzOnWide ? colorYellow : colorGreen bb_colorOne = toggleSQZColors ? color.new(sq_color, 80) : colorOrangeOne bb_colorHalf = toggleSQZColors ? color.new(sq_color, 80) : colorOrangeHalf //--------BOLLINGER BANDS------ upper = BMA + devBB lower = BMA - devBB p2 = plot(BB_show_upper ? upper : na, 'Upper Far Band', color=color.new(color.orange, 100)) p3 = plot(BB_show_lower ? lower : na, 'Lower Far Band', color=color.new(color.red, 100)) fill(p1, p2, title='BB Background', color=bb_colorOne) fill(p1, p3, title='BB Background', color=bb_colorOne) devhalf = BB_stdev_near * ta.stdev(close, 20) upperhalf = BMA + devhalf lowerhalf = BMA - devhalf p4 = plot(BB_show_upper ? upperhalf : na, 'Upper Near Band', color=color.new(color.orange, 100)) p5 = plot(BB_show_lower ? lowerhalf : na, 'Lower Near Band', color=color.new(color.red, 100)) fill(p1, p4, title='BB Background', color=bb_colorHalf) fill(p1, p5, title='BB Background', color=bb_colorHalf)
Dynamic Array Table (versatile display methods)
https://www.tradingview.com/script/ilUuDFpW-Dynamic-Array-Table-versatile-display-methods/
kaigouthro
https://www.tradingview.com/u/kaigouthro/
20
library
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© kaigouthro //@version=5 // @description Dynamic Array Table.... Configurable Shape/Size Table from Arrays // Allows for any data in any size combination of arrays to join together // with: // - all possible orientations! // - filling all cells contiguously and/orflipping at boundaries // - vertical or horizontal rotation // - x/y axis direction swapping // - all types array inputs for data. // please notify of any bugs. thanks library("datTable") import kaigouthro/hsvColor/11 as h import kaigouthro/into/2 import kaigouthro/font/4 import kaigouthro/calc/5 export type crd int x = 0 int y = 0 bool dirx = false bool diry = false export type tablesetting bool contiguous = false bool vertical = false bool reverse_y = false bool reverse_x = false bool live = true int textsize = 1 int truncate = 10 int count = 10 int font = 1 float cell_sizeX = 1 float cell_sizeY = 1 bool flip = true int gap = 0 int border = 0 color bg = #00000000 color bordercol = #00000000 color framecol = #00000000 int bordersize = 0 int framesize = 0 int largest = 0 export type arraytable table tbl tablesetting setting crd coords export type cellsize float [] width float [] height bool merge = false int max = na export type array_s string [] strings string [] datas color [] colors cellsize cells export type array_f string [] strings float [] datas color [] colors cellsize cells export type array_b string [] strings bool [] datas color [] colors cellsize cells export type array_i string [] strings int [] datas color [] colors cellsize cells //@funcction helper _init (_posit , _gap) => var displaytable = table.new(_posit, 100, 100, na, na,na, na, _gap) // @function Get Table (otional gapping cells) // @param _posit String or Int (1-9 3x3 grid L to R) // @returns Table export init (int _posit, int _gap = 0 ) => _pos = switch _posit 1 => 'top_left' 2 => 'top_center' 3 => 'top_right' 4 => 'middle_left' 5 => 'middle_center' 6 => 'middle_right' 7 => 'bottom_left' 8 => 'bottom_center' 9 => 'bottom_right' _init(_pos,_gap) // @function Get Table (otional gapping cells) export init (string _posit, int _gap = 0 ) => _init(_posit,_gap) // @function Req'd coords Seperate for VARIP table, non-varip coords export coords()=> crd.new(0,0,false,false) // helpers for matching arrray that is shorrt. resize(x,sz)=> while array.size(x) < sz array.push(x,na) _largest(a,b,c) => varip size = int(na) _sizea = array.size(a) _sizeb = array.size(b) _sizec = array.size(c) held = math.max(_sizea,_sizeb,_sizec) size := nz(size,held) if size != held resize(a,size) resize(b,size) resize(c,size) size := held[1] // Demo teplate ^^^^^^^^^^^^^^^^^^ /////////////////////////////////////////// show (arraytable displaytable, arr)=> tableconfig = tablesetting.copy(displaytable.setting) tableconfig := displaytable.setting coord = displaytable.coords varip contig = tableconfig.contiguous , contig := tableconfig.contiguous varip vertical = tableconfig.vertical , vertical := tableconfig.vertical varip reverse_y = tableconfig.reverse_y , reverse_y := tableconfig.reverse_y varip reverse_x = tableconfig.reverse_x , reverse_x := tableconfig.reverse_x varip live = tableconfig.live , live := tableconfig.live varip truncate = tableconfig.truncate , truncate := tableconfig.truncate varip textsize = tableconfig.textsize , textsize := tableconfig.textsize varip font = tableconfig.font , font := tableconfig.font varip cell_sizeX = tableconfig.cell_sizeX , cell_sizeX := tableconfig.cell_sizeX varip cell_sizeY = tableconfig.cell_sizeY , cell_sizeY := tableconfig.cell_sizeY varip flip = tableconfig.flip , flip := tableconfig.flip _textsize = switch textsize 0 => size.auto 1 => size.tiny 2 => size.small 3 => size.normal 4 => size.large 5 => size.huge => size.auto var int _x = na, var int _y = na _mergable = (arr.cells.merge == true) _texts = arr.strings _cols = arr.colors _minsize = truncate _sizeofarr = array.size(_texts) if not vertical and bar_index + 5 >= last_bar_index truncate := math.min (_sizeofarr,_minsize) if (live and bar_index + 2 >= last_bar_index) or barstate.islastconfirmedhistory _x := contig ? coord.x : vertical ? coord.x +1 : 0 _y := contig ? coord.y : vertical ? 0 : coord.y +1 _depth = _sizeofarr -1 _xMax = math.max ( 0 , ( not contig ? 0 : - 1 ) + (not vertical ? truncate : math.ceil( _depth/truncate ) ) ) _yMax = math.max ( 0 , ( not contig ? 0 : - 1 ) + (not vertical ? math.ceil( _depth/truncate ) : truncate ) ) _yis = 0, _xis = 0 _dirx = coord.dirx _diry = coord.diry _vsize = cell_sizeY != 0. ? cell_sizeY : 0. _hsize = cell_sizeX != 0. ? cell_sizeX : 0. _step = _mergable ? math.ceil( truncate / _sizeofarr) : 1 for _n = 0 to math.ceil(_mergable ? truncate : math.min(truncate/_sizeofarr*truncate, _sizeofarr/truncate*_sizeofarr)) - 1 i = _n if _mergable i := int ( _n * _sizeofarr / truncate ) _string = array.get (_texts,i) _string += not (_string == '') ? '\n' : '' switch flip => _xis := _dirx ? _xMax - _x : _x _yis := _diry ? _yMax - _y : _y => _xis := _x , _yis := _y if _mergable and _yis % _step == 0 switch vertical => table.merge_cells ( displaytable.tbl , reverse_x ? 99 - _xis : _xis , reverse_y ? 99 - _yis - _step + 1 : _yis , reverse_x ? 99 - _xis : _xis , reverse_y ? 99 - _yis : _step - 1 + _yis ) => table.merge_cells ( displaytable.tbl , reverse_x ? 99 - _xis - _step + 1 : _xis , reverse_y ? 99 - _yis : _yis , reverse_x ? 99 - _xis : _step - 1 + _xis , reverse_y ? 99 - _yis : _yis ) _bgcolor = array.get ( _cols , i ) _textcol = h.bright ( _bgcolor ) > 0.6 ? #000000 : #ffffff _data = array.get ( arr.datas , i ) _datastr = into.s ( _data ) _stringtext = _string + (na ( _data) or _datastr == 'NaN' or _datastr == '' ? '' : _datastr ) _text = font.uni ( _stringtext , font ) _hsize := nz(array.get(arr.cells.width , i ) , _hsize ) _vsize := nz(array.get(arr.cells.height , i ) , _vsize ) table.cell( displaytable.tbl , reverse_x ? 99 - _xis : _xis , reverse_y ? 99 - _yis : _yis , _text , _hsize , _vsize, _textcol , text.align_center , text.align_center , _textsize , _bgcolor ) switch vertical false => if _x >= _xMax _y += 1 _x := 0 _dirx := _dirx?false:true else _x += 1 => if _y >= _yMax _x += 1 _y := 0 _diry := _diry?false:true else _y += 1 coord.x := _x coord.y := _y coord.dirx := _dirx coord.diry := _diry if barstate.isconfirmed table.set_bgcolor (displaytable.tbl,tableconfig.bg ) table.set_border_color (displaytable.tbl,tableconfig.bordercol ) table.set_border_width (displaytable.tbl,tableconfig.bordersize ) table.set_frame_color (displaytable.tbl,tableconfig.framecol ) table.set_frame_width (displaytable.tbl,tableconfig.framesize ) displaytable.tbl //@function Array joiner to DAT table //@param displaytable (arraytable) Object table with settings and coords (refresh coords each calc) //@param _stringsin (string[]) (OPTIONAL) array of text titles/names for cells //@param _colsin (color[]) (OPTIONAL) array of background colors for cells //@param _datas (int/float/bool/string[]) array of data (int/bool/floats) //@param _cellsizes (cellsize) (OPTIONAL) object with specific cell sizes/merge option export add(arraytable displaytable, string[] _stringsin, color[] _colsin, string[] _datas , cellsize _cellsizes ) => _largest(_stringsin,_colsin,_datas) arr = array_s.new( _stringsin, _datas, _colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, bool[] _datas , cellsize _cellsizes ) => _largest(_stringsin,_colsin,_datas) arr = array_b.new( _stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, float[] _datas , cellsize _cellsizes ) => _largest(_stringsin,_colsin,_datas) arr = array_f.new( _stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, int [] _datas , cellsize _cellsizes ) => _largest(_stringsin,_colsin,_datas) arr = array_i.new( _stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, string[] _datas ) => _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_s.new( _stringsin, _datas, _colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, bool[] _datas ) => _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_b.new( _stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, float[] _datas ) => _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_f.new( _stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _stringsin, color[] _colsin, int [] _datas ) => _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_i.new( _stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _datas, color[] _colsin ) => varip _stringsin = array.new<string>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_s.new(_stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, float[] _datas, color[] _colsin ) => varip _stringsin = array.new<string>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_f.new(_stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, bool[] _datas, color[] _colsin ) => varip _stringsin = array.new<string>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_b.new(_stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, int [] _datas, color[] _colsin ) => varip _stringsin = array.new<string>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_f.new(_stringsin, _datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, string[] _datas ) => varip _stringsin = array.new<string>(array.size(_datas)) var _colsin = array.new<color>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_s.new(_stringsin,_datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, float[] _datas ) => varip _stringsin = array.new<string>(array.size(_datas)) var _colsin = array.new<color>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_f.new(_stringsin,_datas ,_colsin,_cellsizes) show ( displaytable, arr) export add(arraytable displaytable, bool[] _datas ) => varip _stringsin = array.new<string>(array.size(_datas)) var _colsin = array.new<color>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_b.new(_stringsin,_datas ,_colsin,_cellsizes) show (displaytable, arr) export add(arraytable displaytable, int[] _datas ) => varip _stringsin = array.new<string>(array.size(_datas)) var _colsin = array.new<color>(array.size(_datas)) _largest(_stringsin,_colsin,_datas) var _cellsizes = cellsize.new(array.new_float(1000,na),array.new_float(1000,na)) arr = array_f.new(_stringsin,_datas ,_colsin,_cellsizes) show (displaytable, arr) ////////////////////////////////////////////////////// // copy paste this to configure ////////////////////////////////////////////////////// _o =' β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ ' _o:=' β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ ' _o:=' β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆ ' _o:=' β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ ' _o:=' β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ ' // ========== input constants ============ { varip _CONTIGUOUS = 'Contiguous, Join Arrays' varip _VERTICAL = 'Rotate 90 deg.' varip _REVY = 'Flip Y axis' varip _REVX = 'Flip X axis' varip _LIVE = 'Realtime? (or last hist)' varip _TEXTSIZE = 'Text Size (0 = auto)' varip _TRUNCATE = 'Size Limit (break/flip if longer)' varip _FONT = 'Font Substitute (see \'font\' Lib' varip _CELLSIZEV = 'CellSize ↕ ' varip _CELLSIZEH = 'CellSize ↔ ' varip _FLIP = 'Flip at bounds' varip _COUNT = 'Columns' varip _BG = 'Background Color' varip _BORDERCOL = 'Border Color' varip _BORDERSIZE = 'Border Size' varip _FRAMESIZE = 'Frame Size' varip _FRAMECOL = 'Frame Color' // group names for inputs varip _settings = 'DAT Table Settings' varip _toggles = 'Toggles' // table position string tableYpos = input.string ('bottom' , '↕' , inline = '01', group = _settings , options=['top', 'middle', 'bottom']) string tableXpos = input.string ('right' , '↔' , inline = '01', group = _settings , options=['left', 'center', 'right'], tooltip='Position on the chart.') varip _pos = (tableYpos + '_' + tableXpos) // table var.. COORDS currently must not be var. var displaytable = init (_pos) var config = tablesetting.new() config.bg := input.color ( #00000000 , _BG , inline = 'col' , group = _settings + 'Adjutments') config.bordercol := input.color ( #00000000 , _BORDERCOL , inline = 'col' , group = _settings + 'Adjutments') config.framecol := input.color ( #00000000 , _FRAMECOL , inline = 'col' , group = _settings + 'Adjutments') config.bordersize := input.int ( 1 , _BORDERSIZE , 0 , 5 , inline = 'frame' , group = _settings + 'Adjutments') config.cell_sizeX := input.float ( 1 , _CELLSIZEH , 0 , 5 ,step=0.25, inline = 'adj' , group = _settings + 'Adjutments') config.cell_sizeY := input.float ( 1 , _CELLSIZEV , 0 , 5 ,step=0.25, inline = 'adj' , group = _settings + 'Adjutments') config.contiguous := input.bool ( false , _CONTIGUOUS , inline = 'modes' , group = _toggles ) config.count := input.int ( 5 , _COUNT , 5 , 100 , inline = 'adj' , group = _settings + 'Adjutments') config.flip := input.bool ( true , _FLIP , inline = 'modes' , group = _toggles ) config.font := input.int ( 1 , _FONT , 1 , 16 , inline = 'adj' , group = _settings + 'Adjutments') config.live := input.bool ( true , _LIVE , inline = 'modes' , group = _toggles ) config.reverse_x := input.bool ( true , _REVX , inline = 'orientation' , group = _toggles ) config.framesize := input.int ( 1 , _FRAMESIZE , 0 , 5 , inline = 'frame' , group = _settings + 'Adjutments') config.reverse_y := input.bool ( true , _REVY , inline = 'orientation' , group = _toggles ) config.textsize := input.int ( 1 , _TEXTSIZE , 0 , 5 , inline = 'adj' , group = _settings + 'Adjutments') config.truncate := input.int ( 10 , _TRUNCATE , 2 , 100 , inline = 'adj' , group = _settings + 'Adjutments') config.vertical := input.bool ( true , _VERTICAL , inline = 'orientation' , group = _toggles ) // // set up table object var arraytable tab = arraytable.new(init(_pos,input(1)),config,coords()) _l1 = input(5) _l2 = input(5) _l3 = input(5) // craete some arrays and plug them in.. if bar_index + 2 >= last_bar_index tab.coords := coords() for i = 1 to 1 str = array.new<string> (_l1 , '')//into.s(i)) // for [n,val] in str // array.set(str ,n, into.s(n) ) col = array.new<color> (_l1 , color(na)) for [n,val] in col array.set(col ,n, #ffe564) dat = array.new<string> (_l1 , '') // for [n,val] in dat // array.set(dat ,n, str.tostring(n))//str.format('close[{0}] by {1,number,#.##} %',n+1, (close[i]/close[n+1]-1)*100)) _x = array.new_float(100,na) _y = array.new_float(100,na) add ( tab,str,col,dat,cellsize.new(_x,_y,true,_l3)) for i = 1 to 1 str = array.new<string> (_l2 , '')//into.s(i)) // for [n,val] in str // array.set(str ,n, into.s(n) ) col = array.new<color> (_l2 , color(na)) for [n,val] in col array.set(col ,n, #67ffcf) dat = array.new<string> (_l2 , '') // for [n,val] in dat // array.set(dat ,n, str.tostring(n))//str.format('close[{0}] by {1,number,#.##} %',n+1, (close[i]/close[n+1]-1)*100)) _x = array.new_float(100,na) _y = array.new_float(100,na) add ( tab,str,col,dat,cellsize.new(_x,_y,true,_l3)) for i = 1 to 2 str = array.new<string> (_l2*2 , '')//into.s(i)) // for [n,val] in str // array.set(str ,n, into.s(n) ) col = array.new<color> (_l2*2 , color(na)) for [n,val] in col array.set(col ,n, #9c4aff) dat = array.new<string> (_l2*2 , '') // for [n,val] in dat // array.set(dat ,n, str.tostring(n))//str.format('close[{0}] by {1,number,#.##} %',n+1, (close[i]/close[n+1]-1)*100)) _x = array.new_float(100,na) _y = array.new_float(100,na) add ( tab,str,col,dat,cellsize.new(_x,_y,true,_l3)) // // craete some arrays and plug them in.. // if bar_index + 2 >= last_bar_index // tab.coords := coords() // for i = 1 to 3 // str = array.new<string> (6, into.s(i)) // for [n,val] in str // array.set(str ,n, 'close[' + into.s(i) + // '] is ' + (close[i] > close[n+1] ? 'above' : 'below')) // col = array.new<color> (6, color(na)) // for [n,val] in col // array.set(col ,n, h.hsv((close[i]/close[n+1]-1)*12000 + 60,1,1,1) ) // dat = array.new<string> (6, '') // for [n,val] in dat // array.set(dat ,n, str.format('close[{0}] by {1,number,#.##} %',n+1, (close[i]/close[n+1]-1)*100)) // array.unshift(str,'Changes for') // array.unshift(col,#ffffff ) // array.unshift(dat,'close[' + into.s(i)+']') // _x = array.new_float(100,na) // _y = array.new_float(100,na) // add ( tab,str,col,dat,cellsize.new(_x,_y,false,config.truncate)) // // craete merged // if bar_index + 2 >= last_bar_index // tab.coords := coords() // for i = 1 to 3 // str = array.new<string> (6, into.s(i)) // for [n,val] in str // array.set(str ,n, 'close[' + into.s(i) + // '] is ' + (close[i] > close[n+1] ? 'above' : 'below')) // col = array.new<color> (6, color(na)) // for [n,val] in col // array.set(col ,n, h.hsv((close[i]/close[n+1]-1)*12000 + 60,1,1,1) ) // dat = array.new<string> (6, '') // for [n,val] in dat // array.set(dat ,n, str.format('close[{0}] by {1,number,#.##} %',n+1, (close[i]/close[n+1]-1)*100)) // array.unshift(str,'Changes for') // array.unshift(col,#ffffff ) // array.unshift(dat,'close[' + into.s(i)+']') // _x = array.new_float(100,na) // _y = array.new_float(100,na) // add ( tab,str,col,dat,cellsize.new(_x,_y,true,config.truncate))
Normal Distribution Curve
https://www.tradingview.com/script/OvvrKMKJ-Normal-Distribution-Curve/
BlockchainSpecialists
https://www.tradingview.com/u/BlockchainSpecialists/
62
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Thanks to @ALifeToMake, @Bjorgum and vgladkov on stackoverflow for all the assistance! // Β© BlockchainSpecialists //@version=5 indicator('Distribution Curve', overlay = false, max_bars_back = 5000, max_lines_count = 100, max_labels_count = 15) //Inputs { src = input.source(close, title = 'Distribution Source', inline = '0') colour = input.color(color.orange, title = '', inline = '0') //} //Formulas { var array<float> src_rank = array.new<float>() var array<float> curve_sum = array.new<float>() var array<float> distribution = array.new<float>() method increaseCounterByIndex(int[] arr, index) => currentValue = arr.get(index) increasedValue = currentValue + 1 arr.set(index, increasedValue) createLinesArray(int size, float[] src_rank) => _linesArr = array.new<line>() for i = 0 to size - 1 l = line.new(na, na, na, na) _linesArr.push(l) _linesArr if not na(src) array.unshift(src_rank, src) if array.size(src_rank) > 5000 array.remove(src_rank, array.size(src_rank) - 1) high_src = array.percentile_linear_interpolation(src_rank, 100) low_src = array.percentile_linear_interpolation(src_rank, 0) lookback = 5000 > bar_index + 1 ? bar_index : 5000 distribution_count = bar_index - bar_index[1] var distribution_line = array.new_line() var line lines = na if bar_index == 0 for i = 0 to 100 - 1 array.push(distribution_line, line.new(na, na, na, na, color = colour, width = 2)) //} //Plotting { if barstate.islast for i = 0 to 100 array.push(distribution, low_src + ((high_src - low_src) * float(i * 0.01))) for x = 0 to 100 - 1 curve = float(0) for y = 0 to lookback - 1 if not na(src[y]) curve := (src[y] < array.get(distribution, x)) or (src[y] > array.get(distribution, x + 1)) ? curve : distribution_count[y] + curve array.push(curve_sum, curve) for z = 0 to 100 - 1 lines := array.get(distribution_line, z) lines_distribution = array.get(distribution, z) curve_max = float(array.get(curve_sum, z) / array.max(curve_sum)) line.set_xy1(lines, bar_index + 201, lines_distribution) line.set_xy2(lines, (bar_index + 201) - math.round(200 * curve_max), array.get(distribution, z)) //} //Data Labels { label_colour = color.new(chart.bg_color == color.white ? color.black : color.white, 100) var label[] percentile_labels = array.new_label(0) var label data_label = na label data_average = na if barstate.islast for i = 0 to 30 by 5 data_label := label.new(bar_index + 202, array.percentile_linear_interpolation(src_rank, i), text = str.tostring(i) + "th Percentile ~ " + str.tostring(math.round(array.percentile_linear_interpolation(src_rank, i), 3)), color = color.new(label_colour, 100), style = label.style_label_left, textcolor = colour, size = size.small, tooltip = str.tostring(i) + "th Percentile ~ " + str.tostring(math.round(array.percentile_linear_interpolation(src_rank, i), 3))) array.push(percentile_labels, data_label) for i = 70 to 100 by 5 data_label := label.new(bar_index + 202, array.percentile_linear_interpolation(src_rank, i), text = str.tostring(i) + "th Percentile ~ " + str.tostring(math.round(array.percentile_linear_interpolation(src_rank, i), 3)), color = color.new(label_colour, 100), style = label.style_label_left, textcolor = colour, size = size.small, tooltip = str.tostring(i) + "th Percentile ~ " + str.tostring(math.round(array.percentile_linear_interpolation(src_rank, i), 3))) array.push(percentile_labels, data_label) data_average := label.new(bar_index + 202, array.avg(src_rank), text = 'Average ~ ' + str.tostring(math.round(array.avg(src_rank), 3)), color = color.new(label_colour, 100), style = label.style_label_left, textcolor = colour, size = size.small, tooltip = 'Average ~ ' + str.tostring(math.round(array.avg(src_rank), 3))) if array.size(percentile_labels) > 0 for i = 0 to array.size(percentile_labels) - 1 array.remove(percentile_labels, array.size(percentile_labels) - 1) array.clear(percentile_labels) label.delete(data_average[1]) label.delete(data_label[1]) //}
ICT Daily Bias Finder [DTCC]
https://www.tradingview.com/script/ywW7Mg36-ICT-Daily-Bias-Finder-DTCC/
J_asper
https://www.tradingview.com/u/J_asper/
301
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© J_asper, credit to Patek Fynnip for DTCC //@version=5 indicator("ICT Daily Bias", overlay = true, shorttitle = "[Daily Bias]") dashboardInput = input.bool(true, "Dashboard", group = "Settings ") simpleDashboard = input.bool(false, "Simplified Dashboard", group = "Settings ") colorDashboard = input.bool(false, "Match Dashboard Color to Box Color", group = "Settings ") bullishColor = input.color(#37894990, "Bullish Color", group="Box Colors") bearishColor = input.color(#80192290, "Bearish Color", group="Box Colors") borderBullishColor = input.color(color.black, "Bullish Border Color", group = "Border Colors") borderBearishColor = input.color(color.black, "Bearish Border Color", group = "Border Colors") bullishText = input.string("Bullish", title="Bullish Text", group = "Box Text") bearishText = input.string("Bearish", title="Bearish Text", group = "Box Text") matchBoxColorBullish = input.bool(true, "Match Box Color? |", group = "Text Colors", inline = "1") matchBoxColorBearish = input.bool(true, "Match Box Color? |", group = "Text Colors", inline = "2") bullishTextColor = input.color(#37894990, "Bullish ", group = "Text Colors", inline = "1") bearishTextColor = input.color(#80192290, "Bearish ", group = "Text Colors", inline = "2") high5 = request.security(syminfo.tickerid, "5", high) low5 = request.security(syminfo.tickerid, "5", low) close5 = request.security(syminfo.tickerid, "5", close) timeinrange(res, sess) => not na(time(res, sess, "America/New_York")) ? 1 : 0 isTargetTime1 = timeinrange("7", "1400-1445") isTargetTime2 = timeinrange("7", "2000-2045") var float highestHigh = na var float lowestLow = na var float firstClose = na var int startBar = na var box b = na var box textBox = na var label textLabel = na var int centerBarIndex = na offset = ta.atr(20)/5 var bool isFirstBearOrBull = na var bool isSecondBearOrBull = na var color boxColor = na var string boxText = na var string firstBias = na var string secondBias = na if (isTargetTime1 or isTargetTime2) if (na(b)) b := box.new(na, na, na, na) textBox := box.new(na, na, na, na) highestHigh := high5 lowestLow := low5 firstClose := close5 startBar := bar_index highestHigh := math.max(highestHigh, high5) lowestLow := math.min(lowestLow, low5) box.set_left(b, startBar) box.set_right(b, bar_index) box.set_top(b, highestHigh) box.set_bottom(b, lowestLow) boxColor := close5 > firstClose ? bearishColor : bullishColor borderColor = close5 > firstClose ? borderBearishColor : borderBullishColor box.set_bgcolor(b, boxColor) box.set_border_color(b, borderColor) boxText := close5 > firstClose ? bearishText : bullishText box.set_text(textBox, boxText) centerBarIndex := box.get_left(b) + math.round((box.get_right(b) - box.get_left(b)) / 2) if (na(textLabel)) textLabel := label.new(x = centerBarIndex, y = box.get_top(b), text = boxText) label.set_x(textLabel, centerBarIndex) label.set_y(textLabel, box.get_top(b)+offset) label.set_text(textLabel, boxText) label.set_style(textLabel, label.style_none) textColor = close5 > firstClose ? (matchBoxColorBearish ? color.new(bearishColor, transp=0) : bearishTextColor) : (matchBoxColorBullish ? color.new(bullishColor, transp=0) : bullishTextColor) label.set_textcolor(textLabel, textColor) label.set_size(textLabel, size.small) box.set_bgcolor(b, boxColor) box.set_border_color(b, borderColor) else b := na textBox := na highestHigh := na lowestLow := na firstClose := na startBar := na textLabel := na if (isTargetTime1) firstBias := close5 > firstClose ? "Bullish" : "Bearish" if (isTargetTime2) secondBias := close5 > firstClose ? "Bullish" : "Bearish" var color londonTableColor = na var color newyorkTableColor = na if (firstBias == "Bullish") if (colorDashboard) londonTableColor := bearishColor else londonTableColor := color.rgb(117, 38, 45) if (firstBias == "Bearish") if (colorDashboard) londonTableColor := bullishColor else londonTableColor := color.rgb(44, 109, 58) if (secondBias == "Bullish") if (colorDashboard) newyorkTableColor := bearishColor else newyorkTableColor := color.rgb(117, 38, 45) if (secondBias == "Bearish") if (colorDashboard) newyorkTableColor := bullishColor else newyorkTableColor := color.rgb(44, 109, 58) if (dashboardInput and simpleDashboard == false) var dBoard = table.new(position = position.top_right, columns = 2, rows = 2, bgcolor = color.rgb(24, 24, 24), border_width = 3, border_color = color.rgb(41, 41, 41), frame_color = color.rgb(41, 41, 41), frame_width = 5) table.cell(table_id = dBoard, column = 0, row = 0, text = "London Bias", text_color = color.white, text_valign = text.align_center, text_halign = text.align_center, text_size = size.normal) table.cell(table_id = dBoard, column = 1, row = 0, text = "New-York Bias", text_color = color.white, text_valign = text.align_center, text_halign = text.align_center, text_size = size.normal) table.cell(table_id = dBoard, column = 0, row = 1, text = firstBias == "Bullish" ? "Bearish" : "Bullish", text_color = color.white, text_valign = text.align_center, text_halign = text.align_center, bgcolor = londonTableColor, text_size = size.small) table.cell(table_id = dBoard, column = 1, row = 1, text = secondBias == "Bullish" ? "Bearish" : "Bullish", text_color = color.white, text_valign = text.align_center, text_halign = text.align_center, bgcolor = newyorkTableColor, text_size = size.small) if (dashboardInput and simpleDashboard) var dBoard = table.new(position = position.top_right, columns = 2, rows = 2, bgcolor = color.rgb(24, 24, 24), border_width = 3, border_color = color.rgb(41, 41, 41), frame_color = color.rgb(41, 41, 41), frame_width = 5) table.cell(table_id = dBoard, column = 0, row = 1, text = "London: " + (firstBias == "Bullish" ? "Bearish" : "Bullish"), text_color = color.white, text_valign = text.align_center, text_halign = text.align_center, bgcolor = londonTableColor, text_size = size.small) table.cell(table_id = dBoard, column = 1, row = 1, text = "New-York: " + (secondBias == "Bullish" ? "Bearish" : "Bullish"), text_color = color.white, text_valign = text.align_center, text_halign = text.align_center, bgcolor = newyorkTableColor, text_size = size.small)
Extreme Entry with Mean Reversion and Trend Filter
https://www.tradingview.com/script/9wIuz66O-Extreme-Entry-with-Mean-Reversion-and-Trend-Filter/
spudow
https://www.tradingview.com/u/spudow/
392
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //spudow @ edri //rodavlas12 //@version=5 indicator(title='Extreme Entry with Mean Reversion and Trend Filter', overlay=true, shorttitle='Extreme Entry with MR and TR') // Input settings ccimomCross = input.string('CCI', 'Entry Signal Source', options=['CCI', 'Momentum'], tooltip='CCI or Momentum will be the final source of the Entry signal if selected.') ccimomLength = input.int(10, minval=1, title='CCI/Momentum Length') useDivergence = input.bool(false, title='Find Regular Bullish/Bearish Divergence', tooltip='If checked, it will only consider an overbought or oversold condition that has a regular bullish or bearish divergence formed inside that level.') rsiOverbought = input.int(65, minval=1, title='RSI Overbought Level', tooltip='Adjusting the level to extremely high may filter out some signals especially when the option to find divergence is checked.') rsiOversold = input.int(35, minval=1, title='RSI Oversold Level', tooltip='Adjusting this level extremely low may filter out some signals especially when the option to find divergence is checked.') rsiLength = input.int(14, minval=1, title='RSI Length') plotMeanReversion = input.bool(true, 'Plot Mean Reversion on the chart', tooltip='If checked, will use upper and lower bands to filter entry signals that are within or outside the range') meanReversionFilter = input.string('All Entries', 'Mean Reversion Signal Filter', options=['Range Entries', 'Extreme Entries', 'All Entries'], tooltip='Entry signals filter will function only when Plot Mean Reversal is enabled') emaPeriod = input(200, title='MR Lookback Period (EMA)') bandMultiplier = input.float(1.8, title='MR Bands Multiplier', tooltip='Multiplier for both upper and lower bands to adjust the range.') // Trend Filter Input enableTrendFilter = input.bool(false, "Enable Trend Filter", tooltip="When enabled, entry signals will be filtered based on the long-term trend.") emaPeriodFilter = input(200, title="EMA Period (Trend Filter)", tooltip="The period used for the EMA trend filter.") // CCI and Momentum calculation momLength = ccimomCross == 'Momentum' ? ccimomLength : 10 mom = close - close[momLength] cci = ta.cci(close, ccimomLength) ccimomCrossUp = ccimomCross == 'Momentum' ? ta.cross(mom, 0) : ta.cross(cci, 0) ccimomCrossDown = ccimomCross == 'Momentum' ? ta.cross(0, mom) : ta.cross(0, cci) // RSI calculation src = close up = ta.rma(math.max(ta.change(src), 0), rsiLength) down = ta.rma(-math.min(ta.change(src), 0), rsiLength) rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down) oversoldAgo = rsi[0] <= rsiOversold or rsi[1] <= rsiOversold or rsi[2] <= rsiOversold or rsi[3] <= rsiOversold overboughtAgo = rsi[0] >= rsiOverbought or rsi[1] >= rsiOverbought or rsi[2] >= rsiOverbought or rsi[3] >= rsiOverbought // Regular Divergence Conditions bullishDivergenceCondition = rsi[0] > rsi[1] and rsi[1] < rsi[2] bearishDivergenceCondition = rsi[0] < rsi[1] and rsi[1] > rsi[2] // Entry Conditions longEntryCondition = ccimomCrossUp and oversoldAgo and (not useDivergence or bullishDivergenceCondition) shortEntryCondition = ccimomCrossDown and overboughtAgo and (not useDivergence or bearishDivergenceCondition) // Mean Reversion Indicator meanReversion = plotMeanReversion ? ta.ema(close, emaPeriod) : na stdDev = plotMeanReversion ? ta.stdev(close, emaPeriod) : na upperBand = plotMeanReversion ? meanReversion + stdDev * bandMultiplier : na lowerBand = plotMeanReversion ? meanReversion - stdDev * bandMultiplier : na // Apply signal filtering based on mean reversion bands if plotMeanReversion if meanReversionFilter == 'Range Entries' longEntryCondition := na(longEntryCondition) ? na : longEntryCondition and (close > lowerBand and close < upperBand) shortEntryCondition := na(shortEntryCondition) ? na : shortEntryCondition and (close > lowerBand and close < upperBand) else if meanReversionFilter == 'Extreme Entries' longEntryCondition := na(longEntryCondition) ? na : longEntryCondition and (close < lowerBand or close > upperBand) shortEntryCondition := na(shortEntryCondition) ? na : shortEntryCondition and (close < lowerBand or close > upperBand) // Trend Filter emaPeriodFiltered = enableTrendFilter ? ta.ema(close, emaPeriodFilter) : na // Apply trend filter to entry conditions if enableTrendFilter longEntryCondition := longEntryCondition and (close > emaPeriodFiltered) shortEntryCondition := shortEntryCondition and (close < emaPeriodFiltered) // Plotting plotshape(longEntryCondition, title='BUY', style=shape.triangleup, text='B', location=location.belowbar, color=color.new(color.lime, 0), textcolor=color.new(color.white, 0), size=size.tiny) plotshape(shortEntryCondition, title='SELL', style=shape.triangledown, text='S', location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny) plot(plotMeanReversion ? upperBand : na, title='Upper Band', color=color.new(color.fuchsia, 0), linewidth=1) plot(plotMeanReversion ? meanReversion : na, title='Mean', color=color.new(color.gray, 0), linewidth=1) plot(plotMeanReversion ? lowerBand : na, title='Lower Band', color=color.new(color.blue, 0), linewidth=1) // Plot EMA when Trend Filter is enabled plot(enableTrendFilter ? emaPeriodFiltered : na, color=color.new(color.orange, 0), title="EMA (Trend Filter)") // Entry signal alerts alertcondition(longEntryCondition, title='BUY Signal', message='Buy Entry Signal') alertcondition(shortEntryCondition, title='SELL Signal', message='Sell Entry Signal') alertcondition(longEntryCondition or shortEntryCondition, title='BUY or SELL Signal', message='Entry Signal')
Auto Fibonacci TP Levels [WJ]
https://www.tradingview.com/script/Uw3e593p-Auto-Fibonacci-TP-Levels-WJ/
War-Jackel
https://www.tradingview.com/u/War-Jackel/
63
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© War-Jackel //@version=5 indicator("Auto Fibonacci TP Levels [WJ]", shorttitle = "Auto Fibs [WJ]", overlay=true, max_boxes_count = 500, max_labels_count = 500) tradeSource = input.source(close, "Trade Source 1" , group = "Trade Settings", tooltip = "Source entry value:\nLong = 1\nShort = 2") tradeSource2 = input.source(close, "Trade Source 2" , group = "Trade Settings", tooltip = "Source entry value:\nLong = 1\nShort = 2") fibStart1 = input.source(low, "Fib Start : Longs", group = "Trade Settings", tooltip = "Where to start the fib from") fibStart2 = input.source(open, "Fib Start : Shorts", group = "Trade Settings", tooltip = "Where to start the fib from") length_to_check = input(50, "HH/LL Bars Back", group = "Trade Settings", tooltip = "Historical bars for HH/LL") fibLabel = input.bool(true, "Fib 0.618 Distance from entry", group = "Labels & Lines", tooltip = "How far from the entry to the 0.618 Fib") showCrossLabels = input(true, title="Fib Crossing", group = "Labels & Lines", tooltip = "When a fib line was crossed") onlyGP = input.bool(false, "Only Golden Pocket Levels", group = "Labels & Lines", tooltip = "Show only the golden pocket (0.618,0.65) fib lines") chk1 = onlyGP ? false : input.bool(false, "", group = "Fibonacci", inline = "colors1") chk2 = onlyGP ? true : input.bool(true , "", group = "Fibonacci", inline = "colors2") chk3 = onlyGP ? true : input.bool(true , "", group = "Fibonacci", inline = "colors3") chk4 = onlyGP ? false : input.bool(true , "", group = "Fibonacci", inline = "colors4") chk5 = onlyGP ? false : input.bool(true , "", group = "Fibonacci", inline = "colors5") chk6 = onlyGP ? false : input.bool(true , "", group = "Fibonacci", inline = "colors6") chk7 = onlyGP ? false : input.bool(false, "", group = "Fibonacci", inline = "colors7") chk8 = onlyGP ? false : input.bool(true , "", group = "Fibonacci", inline = "colors8") chk9 = onlyGP ? false : input.bool(true , "", group = "Fibonacci", inline = "colors9") fib_level_1 = input.float(1., title="Fib Level 1" , group = "Fibonacci", inline = "colors1") fib_level_2 = input.float(0.618, title="Fib Level 2" , group = "Fibonacci", inline = "colors2") fib_level_3 = input.float(0.65, title="Fib Level 3" , group = "Fibonacci", inline = "colors3") fib_level_4 = input.float(0.236, title="Fib Level 4" , group = "Fibonacci", inline = "colors4") fib_level_5 = input.float(0.382, title="Fib Level 5" , group = "Fibonacci", inline = "colors5") fib_level_6 = input.float(0.786, title="Fib Level 6" , group = "Fibonacci", inline = "colors6") fib_level_7 = input.float(0., title="Fib Level 7" , group = "Fibonacci", inline = "colors7") fib_level_8 = input.float(1.286, title="Stop Loss Level: Short", group = "Fibonacci", inline = "colors8") // Stop loss for Bear fib_level_9 = input.float(-0.386, title="Stop Loss Level: Long ‏" , group = "Fibonacci", inline = "colors9") // Stop loss for Bull color_level_1 = input(color.gray , group = "Fibonacci", inline = "colors1", title = "") color_level_2 = input(color.orange, group = "Fibonacci", inline = "colors2", title = "") color_level_3 = input(color.orange, group = "Fibonacci", inline = "colors3", title = "") color_level_4 = input(color.lime , group = "Fibonacci", inline = "colors4", title = "") color_level_5 = input(color.lime , group = "Fibonacci", inline = "colors5", title = "") color_level_6 = input(color.lime , group = "Fibonacci", inline = "colors6", title = "") color_level_7 = input(color.gray , group = "Fibonacci", inline = "colors7", title = "") color_level_8 = input(color.red , group = "Fibonacci", inline = "colors8", title = "") // Stop loss color for Bear color_level_9 = input(color.red , group = "Fibonacci", inline = "colors9", title = "") // Stop loss color for Bull fib_levels_float = array.new_float(0) array.push(fib_levels_float, fib_level_1) array.push(fib_levels_float, fib_level_2) array.push(fib_levels_float, fib_level_3) array.push(fib_levels_float, fib_level_4) array.push(fib_levels_float, fib_level_5) array.push(fib_levels_float, fib_level_6) array.push(fib_levels_float, fib_level_7) array.push(fib_levels_float, fib_level_8) array.push(fib_levels_float, fib_level_9) fib_colors = array.new_color(0) array.push(fib_colors, chk1 ? color_level_1 : na) array.push(fib_colors, chk2 ? color_level_2 : na) array.push(fib_colors, chk3 ? color_level_3 : na) array.push(fib_colors, chk4 ? color_level_4 : na) array.push(fib_colors, chk5 ? color_level_5 : na) array.push(fib_colors, chk6 ? color_level_6 : na) array.push(fib_colors, chk7 ? color_level_7 : na) array.push(fib_colors, chk8 ? color_level_8 : na) array.push(fib_colors, chk9 ? color_level_9 : na) bull_cross = tradeSource == 1 or tradeSource2 == 1 bear_cross = tradeSource == 2 or tradeSource2 == 2 var float p1 = na var float p2 = na var int cross_bar = na var box[] fib_box = array.new_box(0) var label[] fib_label = array.new_label(0) var float high_level = na var float low_level = na var bool[] touchArray = array.new_bool(0) var int[] touchCounter = array.new_int(0, 0) var string crossedFibLevel = na var int hh_bar = na var int ll_bar = na var float hh = na var float ll = na var bool fibCross = false for i = 0 to array.size(fib_levels_float) - 1 level = array.get(fib_levels_float, i) if (bull_cross and level == fib_level_7) or (bear_cross and level == fib_level_4) b = box.new(left=cross_bar, top=p1+(p2-p1)*level, right=bar_index, bottom=p1+(p2-p1)*level, extend = extend.none, border_color = array.get(fib_colors, i), border_width=1) array.push(fib_box, b) array.push(touchArray, false) if level == 0.618 priceAtLevel = math.round(p1+(p2-p1)*level) if length_to_check > 0 hh := ta.highest(high, length_to_check) ll := ta.lowest(low, length_to_check) high_level := hh low_level := ll hh_bar := bar_index - ta.highestbars(high, length_to_check) // get the bar index of highest high ll_bar := bar_index - ta.lowestbars(low, length_to_check) // get the bar index of lowest low if bull_cross cross_bar := bar_index p1 := fibStart1 p2 := high_level else if bear_cross cross_bar := bar_index p1 := fibStart2 p2 := low_level if not na(p1) and not na(p2) and cross_bar[1] != cross_bar array.clear(fib_box) array.clear(touchArray) array.clear(touchCounter) array.clear(fib_label) for i = 0 to array.size(fib_levels_float) - 1 level = array.get(fib_levels_float, i) if bull_cross if level != fib_level_8 b = box.new(left=cross_bar, top=(p1-p2)*(1-level)+p2, right=bar_index, bottom=(p1-p2)*(1-level)+p2, extend = extend.none, border_color = array.get(fib_colors, i), border_width=1) array.push(fib_box, b) array.push(touchArray, false) array.push(touchCounter, 0) if level == 0.618 priceAtLevel = (p1-p2)*(1-level)+p2 priceAt0FibLevel = p1 percentageDifference = math.abs((priceAtLevel / priceAt0FibLevel) - 1) if fibLabel l = label.new(x=cross_bar, y=box.get_bottom(b), text=str.tostring((percentageDifference)*100,"0.000") + "% \n(" + str.tostring(priceAtLevel) + ")", xloc=xloc.bar_index, yloc=yloc.price, color=color.new(color.lime, 90), textcolor=color.white, style=label.style_label_down, size=size.small) array.push(fib_label, l) else if bear_cross if level != fib_level_9 b = box.new(left=cross_bar, top=p1+(p2-p1)*(1-level), right=bar_index, bottom=p1+(p2-p1)*(1-level), extend = extend.none, border_color = array.get(fib_colors, i), border_width=1) array.push(fib_box, b) array.push(touchArray, false) array.push(touchCounter, 0) if level == 0.618 priceAtLevel = p1+(p2-p1)*(1-level) priceAt0FibLevel = p1 percentageDifference = math.abs((priceAtLevel - priceAt0FibLevel) / priceAt0FibLevel) if fibLabel l = label.new(x=cross_bar, y=box.get_bottom(b), text=str.tostring((percentageDifference)*100,"0.000") + "% \n(" + str.tostring(priceAtLevel) + ")", xloc=xloc.bar_index, yloc=yloc.price, color=color.new(color.red, 90), textcolor=color.white, style=label.style_label_up, size=size.small) array.push(fib_label, l) if array.size(fib_box) > 0 for i = 0 to array.size(fib_box) - 1 b = array.get(fib_box, i) if not array.get(touchArray, i) if high >= box.get_top(b) and low <= box.get_bottom(b) array.set(touchCounter, i, array.get(touchCounter, i) + 1) levelValue = array.get(fib_levels_float, i) if (not na(levelValue)) crossedFibLevel := str.tostring(levelValue) else crossedFibLevel := "na" shouldShowLabel = false // Adjust which levels to show if crossedFibLevel == str.tostring(fib_level_1 ) shouldShowLabel := chk1 else if crossedFibLevel == str.tostring(fib_level_2) shouldShowLabel := chk2 else if crossedFibLevel == str.tostring(fib_level_3) shouldShowLabel := chk3 else if crossedFibLevel == str.tostring(fib_level_4) shouldShowLabel := chk4 else if crossedFibLevel == str.tostring(fib_level_5) shouldShowLabel := chk5 else if crossedFibLevel == str.tostring(fib_level_6) shouldShowLabel := chk6 else if crossedFibLevel == str.tostring(fib_level_7) shouldShowLabel := chk7 else if crossedFibLevel == str.tostring(fib_level_8) shouldShowLabel := chk8 else if crossedFibLevel == str.tostring(fib_level_9) shouldShowLabel := chk9 // create label every time the fib level is crossed but not for 0 and 1 if shouldShowLabel and showCrossLabels and crossedFibLevel != "0" and crossedFibLevel != "1" label.new(bar_index, close, text=" " + str.tostring(crossedFibLevel) + " Crossed", color=color.new(color.white, 70), style = label.style_label_down, textcolor=color.white, size = size.tiny) // Note that we are now converting the float to a string for the label text. fibCross := true if array.get(touchCounter, i) >= 1 array.set(touchArray, i, true) if i < array.size(fib_label) l = array.get(fib_label, i) label.set_x(l, bar_index) else box.set_right(b, bar_index) //// Entries plotshape(series=bull_cross,title="Long", location=location.belowbar, color=color.green, style=shape.labelup, text="" , textcolor =color.white) plotshape(series=bear_cross,title="Short", location=location.abovebar, color=color.red, style=shape.labeldown, text="", textcolor = color.white) //// Plots plot(chk1 ? p1+(p2-p1)*fib_level_1 : na, title="Fib 1", color=na, editable= false) plot(chk2 ? p1+(p2-p1)*fib_level_2 : na, title="Fib 2", color=na, editable= false) plot(chk3 ? p1+(p2-p1)*fib_level_3 : na, title="Fib 3", color=na, editable= false) plot(chk4 ? p1+(p2-p1)*fib_level_4 : na, title="Fib 4", color=na, editable= false) plot(chk5 ? p1+(p2-p1)*fib_level_5 : na, title="Fib 5", color=na, editable= false) plot(chk6 ? p1+(p2-p1)*fib_level_6 : na, title="Fib 6", color=na, editable= false) plot(chk7 ? p1+(p2-p1)*fib_level_7 : na, title="Fib 7", color=na, editable= false) plot(chk8 ? p1+(p2-p1)*fib_level_8 : na, title="Fib SSL", color=na, editable= false) plot(chk9 ? p1+(p2-p1)*fib_level_9 : na, title="Fib LSL", color=na, editable= false) ///// Alerts //Any alert() bAlert = '"Long Alert"' sAlert = '"Short Alert"' fibCrossAlert= '"Price crossed Fibonacci level" "'+ crossedFibLevel +'" ' alerts(sym) => if (bull_cross or bear_cross or fibCross) alert_text = bull_cross ? bAlert : bear_cross ? sAlert : fibCross ? fibCrossAlert : "na" alert(alert_text, alert.freq_once_per_bar_close) alerts(syminfo.tickerid) alertcondition(bull_cross, title="Bull Cross", message="Bull Cross has occurred") alertcondition(bear_cross, title="Bear Cross", message="Bear Cross has occurred") alertcondition(fibCross, title="Fib Cross", message="Fib Crossed") ///// Connector bool Out_Long = bull_cross bool Out_Short = bear_cross bool Out_LongX = bull_cross and fibCross bool Out_ShortX = bear_cross and fibCross plot(Out_Long ? 1 : Out_Short ? 2 : Out_LongX ? 3 : Out_ShortX ? 4 : 0, title = "⭐ Fib TP Outbound signal", display = display.none, editable = false)
Range Based Signals and Alerts
https://www.tradingview.com/script/UYAbENz0-Range-Based-Signals-and-Alerts/
serkany88
https://www.tradingview.com/u/serkany88/
152
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© serkany88 //@version=5 indicator("Range Based Signals and Alerts", shorttitle="RB S&A", overlay=true, precision=3) //To reduce frequency of signals on repeaded conds to avoid flooding of alerts f_ideal_TimesInLast(bool _cond, simple int _len) => math.sum(_cond ? 1 : 0, _len) //MA Function ma(simple string smt, float src, simple int len) => switch smt "RMA" => ta.rma(src, len) "SMA" => ta.sma(src, len) "EMA" => ta.ema(src, len) "VWMA" => ta.vwma(src, len) "WMA" => ta.wma(src, len) "HMA" => ta.hma(src, len) "LSMA" => ta.linreg(src, len, 0) => na // Calculating MACD f_getmacd(float src, simple int macd_fast, simple int macd_slow, simple int macd_sig, simple string maType) => _close = src[barstate.isrealtime ? 1 : 0] float[] macdArr = array.new<float>() fast_ma = ma(maType, _close, macd_fast) slow_ma = ma(maType, _close, macd_slow) macd = fast_ma - slow_ma sig = ma(maType, macd, macd_sig) hist = macd - sig macdArr.push(hist), macdArr.push(sig), macdArr.push(macd) macdArr //Let's get our inputs hi_lo_tf = input.timeframe("D", title="High-Low MTF", group="High-Low MTF", tooltip="For reliability make sure your choice is higher than your current chart timeframe") ma_type = input.string("EMA", title="MA Type", options =["RMA", "SMA", "EMA", "VWMA", "WMA", "HMA", "LSMA"] ,group="MA") ma_src = input.source(close, title="MA Source", group="MA" ) ma_length = input.int(20, title="MA Length", minval=1, group="MA") macd_enb = input.bool(true, title="Enable MACD Trend", group="MTF Macd") macd_tf = input.timeframe("D", title="MACD TF", group="MTF Macd", tooltip="For reliability make sure your choice is higher than your current chart timeframe") macd_src = input.source(close, title="MACD Source", group="MTF Macd") macd_fast = input.int(12, title="MACD Fast", minval=1, group="MTF Macd") macd_slow = input.int(26, title="MACD Slow", minval=1, group="MTF Macd") macd_sig = input.int(9, title="MACD Signal", minval=1, group="MTF Macd") macd_ma_type = input.string("EMA", title="MACD Smoothing Type", options =["RMA", "SMA", "EMA", "VWMA", "WMA", "HMA", "LSMA"] ,group="MTF Macd") //Let's get high and low [_hi, _lo] = request.security(syminfo.tickerid, hi_lo_tf, [high[barstate.isrealtime ? 1 : 0], low[barstate.isrealtime ? 1 : 0]]) //Let's get MACD macdArr = request.security(syminfo.tickerid, macd_tf, f_getmacd(macd_src, macd_fast, macd_slow, macd_sig, macd_ma_type)) //Let's get our MA based on our choice float ma = ma(ma_type, ma_src, ma_length) //Get macd results from array float macd = array.get(macdArr, 2) float sig = array.get(macdArr, 1) float hist = array.get(macdArr, 0) // We don't really use it but whatever //Rules of signal production bool longCond = (macd_enb ? macd > sig : true) and close < _lo and close > open and close > ma and open > ma and barstate.isconfirmed bool shortCond = (macd_enb ? macd < sig : true) and close > _hi and close < open and close < ma and open < ma and barstate.isconfirmed //Let's filter out repeated signals longCond := f_ideal_TimesInLast(longCond, 7) > 1 ? false : longCond shortCond := f_ideal_TimesInLast(shortCond, 7) > 1 ? false : shortCond //Plots plotshape(longCond, title="LongCond", style=shape.triangleup, color=color.green, size=size.small, location=location.belowbar) plotshape(shortCond, title="shortCond", style=shape.triangledown, color=color.red, size=size.small, location=location.abovebar) plot(ma, title="Moving Average", color=color.white) plot(_hi, title="Daily High", color=color.red, linewidth = 2) plot(_lo, title="Daily Low", color=color.green, linewidth= 2) //Alerts alertcondition(longCond, title="Long Signal", message="Long Signal Triggered") alertcondition(shortCond, title="Short Signal", message="Short Signal Triggered") //Functional Alert for Both condition string alertString = str.format("{0} Signal on {1}\nTF: {2}", longCond ? "Long" : "Short" ,syminfo.tickerid, timeframe.period) if longCond or shortCond alert(alertString, alert.freq_once_per_bar_close)
Equity Sessions [vnhilton]
https://www.tradingview.com/script/LbgRCluE-Equity-Sessions-vnhilton/
vnhilton
https://www.tradingview.com/u/vnhilton/
26
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© vnhilton //@version=5 indicator("Equity Sessions [vnhilton]", "Equity Sessions", true, max_boxes_count = 500) //________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ //Inputs errorMsg = input.bool(true, "Show Error Message On Non-Intraday Timeframes?") lookback = input.int(2, "Number of Day Lookbacks", 1, 250, group = "Main Settings") advPeriod = input.int(20, "ADV/DATR Period", 1, inline = "Period Settings", group = "Main Settings") datrPeriod = input.int(20, "", 1, inline = "Period Settings", group = "Main Settings") textSize = input.string("Small", "Text Size/Placement", ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], inline = "Text Settings", group = "Text Settings") dvFormat = input.string("%", "DV/ADV/ATR Format", ["%", "Multiplier"], inline = "Format Settings", group = "Text Settings") advFormat = input.string("Multiplier", "", ["%", "Multiplier"], inline = "Format Settings", group = "Text Settings") datrFormat = input.string("Multiplier", "", ["%", "Multiplier"], inline = "Format Settings", group = "Text Settings") sessionOn1 = input.bool(true, "", inline = "Toggles #1", group = "Session #1 (Pre-Market)") sessionOn2 = input.bool(true, "", inline = "Toggles #2", group = "Session #2") sessionOn3 = input.bool(true, "", inline = "Toggles #3", group = "Session #3") sessionOn4 = input.bool(true, "", inline = "Toggles #4", group = "Session #4") sessionOn5 = input.bool(true, "", inline = "Toggles #5", group = "Session #5") sessionOn6 = input.bool(true, "", inline = "Toggles #6", group = "Session #6") sessionOn7 = input.bool(true, "", inline = "Toggles #7", group = "Session #7 (After-Hours)") showVolume1 = input.bool(true, "", inline = "Toggles #1", group = "Session #1 (Pre-Market)") showVolume2 = input.bool(true, "", inline = "Toggles #2", group = "Session #2") showVolume3 = input.bool(true, "", inline = "Toggles #3", group = "Session #3") showVolume4 = input.bool(true, "", inline = "Toggles #4", group = "Session #4") showVolume5 = input.bool(true, "", inline = "Toggles #5", group = "Session #5") showVolume6 = input.bool(true, "", inline = "Toggles #6", group = "Session #6") showVolume7 = input.bool(true, "", inline = "Toggles #7", group = "Session #7 (After-Hours)") showDV1 = input.bool(true, "", inline = "Toggles #1", group = "Session #1 (Pre-Market)") showDV2 = input.bool(true, "", inline = "Toggles #2", group = "Session #2") showDV3 = input.bool(true, "", inline = "Toggles #3", group = "Session #3") showDV4 = input.bool(true, "", inline = "Toggles #4", group = "Session #4") showDV5 = input.bool(true, "", inline = "Toggles #5", group = "Session #5") showDV6 = input.bool(true, "", inline = "Toggles #6", group = "Session #6") showDV7 = input.bool(true, "", inline = "Toggles #7", group = "Session #7 (After-Hours)") showADV1 = input.bool(true, "", inline = "Toggles #1", group = "Session #1 (Pre-Market)") showADV2 = input.bool(true, "", inline = "Toggles #2", group = "Session #2") showADV3 = input.bool(true, "", inline = "Toggles #3", group = "Session #3") showADV4 = input.bool(true, "", inline = "Toggles #4", group = "Session #4") showADV5 = input.bool(true, "", inline = "Toggles #5", group = "Session #5") showADV6 = input.bool(true, "", inline = "Toggles #6", group = "Session #6") showADV7 = input.bool(true, "", inline = "Toggles #7", group = "Session #7 (After-Hours)") showSATR1 = input.bool(true, "", inline = "Toggles #1", group = "Session #1 (Pre-Market)") showSATR2 = input.bool(true, "", inline = "Toggles #2", group = "Session #2") showSATR3 = input.bool(true, "", inline = "Toggles #3", group = "Session #3") showSATR4 = input.bool(true, "", inline = "Toggles #4", group = "Session #4") showSATR5 = input.bool(true, "", inline = "Toggles #5", group = "Session #5") showSATR6 = input.bool(true, "", inline = "Toggles #6", group = "Session #6") showSATR7 = input.bool(true, "", inline = "Toggles #7", group = "Session #7 (After-Hours)") showATR1 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #1", group = "Session #1 (Pre-Market)") showATR2 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #2", group = "Session #2") showATR3 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #3", group = "Session #3") showATR4 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #4", group = "Session #4") showATR5 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #5", group = "Session #5") showATR6 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #6", group = "Session #6") showATR7 = input.bool(true, "Show Session/Volume/DV/ADV/SATR/ATR?", inline = "Toggles #7", group = "Session #7 (After-Hours)") name1 = input.string("Pre-Market", "Name/Placement", inline = "Name & Constraints #1", group = "Session #1 (Pre-Market)") name2 = input.string("Late Prints", "Name/Session/Placement", inline = "Name & Constraints #2", group = "Session #2") name3 = input.string("Morning", "Name/Session/Placement", inline = "Name & Constraints #3", group = "Session #3") name4 = input.string("Initial Balance", "Name/Session/Placement", inline = "Name & Constraints #4", group = "Session #4") name5 = input.string("Lunch", "Name/Session/Placement", inline = "Name & Constraints #5", group = "Session #5") name6 = input.string("Afternoon", "Name/Session/Placement", inline = "Name & Constraints #6", group = "Session #6") name7 = input.string("After-Hours", "Name/Placement", inline = "Name & Constraints #7", group = "Session #7 (After-Hours)") session2 = input.string("All", "", ["All", "Regular"], inline = "Name & Constraints #2", group = "Session #2") session3 = input.string("Regular", "", ["All", "Regular"], inline = "Name & Constraints #3", group = "Session #3") session4 = input.string("Regular", "", ["All", "Regular"], inline = "Name & Constraints #4", group = "Session #4") session5 = input.string("Regular", "", ["All", "Regular"], inline = "Name & Constraints #5", group = "Session #5") session6 = input.string("Regular", "", ["All", "Regular"], inline = "Name & Constraints #6", group = "Session #6") textPlace1 = input.string("Bottom", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #1 (Pre-Market)") textPlace2 = input.string("Top", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #2") textPlace3 = input.string("Bottom", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #3") textPlace4 = input.string("Top", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #4") textPlace5 = input.string("Bottom", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #5") textPlace6 = input.string("Bottom", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #6") textPlace7 = input.string("Bottom", "", ["Top", "Bottom"], inline = "Name & Constraints #1", group = "Session #7 (After-Hours)") time1 = input.session("0400-0930", "Time", tooltip = "Don't make the end time within after-hours", group = "Session #1 (Pre-Market)") time2 = input.session("0800-0815", "Time", group = "Session #2") time3 = input.session("0930-1130", "Time", group = "Session #3") time4 = input.session("0930-1030", "Time", group = "Session #4") time5 = input.session("1130-1400", "Time", group = "Session #5") time6 = input.session("1400-1600", "Time", group = "Session #6") time7 = input.session("0930-2000", "Time", tooltip = "Make the start time earlier than official after-hours start time in case of short days, but not when pre-market starts", group = "Session #7 (After-Hours)") borderColor1 = input.color(color.new(color.orange, 100), "Border/Background/Text/Color", inline = "Colors #1", group = "Session #1 (Pre-Market)") borderColor2 = input.color(color.new(color.yellow, 100), "Border/Background/Text Color", inline = "Colors #2", group = "Session #2") borderColor3 = input.color(color.new(color.green, 100), "Border/Background/Text Color", inline = "Colors #3", group = "Session #3") borderColor4 = input.color(color.new(color.silver, 100), "Border/Background/Text Color", inline = "Colors #4", group = "Session #4") borderColor5 = input.color(color.new(color.red, 100), "Border/Background/Text Color", inline = "Colors #5", group = "Session #5") borderColor6 = input.color(color.new(color.teal, 100), "Border/Background/Text Color", inline = "Colors #6", group = "Session #6") borderColor7 = input.color(color.new(color.blue, 100), "Border/Background/Text/Color", inline = "Colors #7", group = "Session #7 (After-Hours)") bgColor1 = input.color(color.new(color.orange, 90), "", inline = "Colors #1", group = "Session #1 (Pre-Market)") bgColor2 = input.color(color.new(color.yellow, 90), "", inline = "Colors #2", group = "Session #2") bgColor3 = input.color(color.new(color.green, 90), "", inline = "Colors #3", group = "Session #3") bgColor4 = input.color(color.new(color.silver, 90), "", inline = "Colors #4", group = "Session #4") bgColor5 = input.color(color.new(color.red, 90), "", inline = "Colors #5", group = "Session #5") bgColor6 = input.color(color.new(color.teal, 90), "", inline = "Colors #6", group = "Session #6") bgColor7 = input.color(color.new(color.blue, 90), "", inline = "Colors #7", group = "Session #7 (After-Hours)") textColor1 = input.color(color.orange, "", inline = "Colors #1", group = "Session #1 (Pre-Market)") textColor2 = input.color(color.yellow, "", inline = "Colors #2", group = "Session #2") textColor3 = input.color(color.green, "", inline = "Colors #3", group = "Session #3") textColor4 = input.color(color.silver, "", inline = "Colors #4", group = "Session #4") textColor5 = input.color(color.red, "", inline = "Colors #5", group = "Session #5") textColor6 = input.color(color.teal, "", inline = "Colors #6", group = "Session #6") textColor7 = input.color(color.blue, "", inline = "Colors #7", group = "Session #7 (After-Hours)") borderWidth1 = input.int(1, "Border Width/Style", 0, inline = "Border Type #1", group = "Session #1 (Pre-Market)") borderWidth2 = input.int(1, "Border Width/Style", 0, inline = "Border Type #2", group = "Session #2") borderWidth3 = input.int(1, "Border Width/Style", 0, inline = "Border Type #3", group = "Session #3") borderWidth4 = input.int(1, "Border Width/Style", 0, inline = "Border Type #4", group = "Session #4") borderWidth5 = input.int(1, "Border Width/Style", 0, inline = "Border Type #5", group = "Session #5") borderWidth6 = input.int(1, "Border Width/Style", 0, inline = "Border Type #6", group = "Session #6") borderWidth7 = input.int(1, "Border Width/Style", 0, inline = "Border Type #7", group = "Session #7 (After-Hours)") borderStyle1 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #1", group = "Session #1 (Pre-Market)") borderStyle2 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #2", group = "Session #2") borderStyle3 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #3", group = "Session #3") borderStyle4 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #4", group = "Session #4") borderStyle5 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #5", group = "Session #5") borderStyle6 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #6", group = "Session #6") borderStyle7 = input.string("Solid", "", ["Dashed", "Dotted", "Solid"], inline = "Border Type #7", group = "Session #7 (After-Hours)") //________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ //Boxes var box [] boxes1 = array.new<box>() var box [] boxes2 = array.new<box>() var box [] boxes3 = array.new<box>() var box [] boxes4 = array.new<box>() var box [] boxes5 = array.new<box>() var box [] boxes6 = array.new<box>() var box [] boxes7 = array.new<box>() var box [] boxesText1 = array.new<box>() var box [] boxesText2 = array.new<box>() var box [] boxesText3 = array.new<box>() var box [] boxesText4 = array.new<box>() var box [] boxesText5 = array.new<box>() var box [] boxesText6 = array.new<box>() var box [] boxesText7 = array.new<box>() //Variables var bool [] createdChecks = array.new<bool>(7, false) var float [] sessionHighs = array.new<float>(7, na) var float [] sessionLows = array.new<float>(7, na) var int [] sessionVols = array.new<int>(7, 0) //Table var table error = table.new(position.top_right, 1, 1, bgcolor=color.red) //Daily Values adv = ta.sma(volume, advPeriod) atr = ta.atr(datrPeriod) [dVol, dADV, dATR] = request.security(syminfo.tickerid, "D", [volume, adv[1], atr[1]], lookahead = barmerge.lookahead_on) //Text Size chosenTextSize = switch textSize "Auto" => size.auto "Tiny" => size.tiny "Small" => size.small "Normal" => size.normal "Large" => size.large => size.huge //________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ //Text Placement Function TextPlacement(choice) => choice == "Top" ? text.align_bottom : text.align_top //Format Text Function FormatText(number, reference, format) => if format == "%" str.tostring(number * 100 / reference, '#0.00') + "%" else str.tostring(number / reference, '#0.00') + "x" //Constraints Function Constraints(choice) => switch choice == "All" => time(timeframe.period, session.extended) choice == "Regular" => time(timeframe.period, session.regular) => not(time(timeframe.period, session.regular)) //Border Style Function BorderStyle(choice) => switch choice == "Dashed" => line.style_dashed choice == "Dotted" => line.style_dotted => line.style_solid //Plot Function Plot(number, created, session, sessionOn, constrained, boxes, borderColor, borderWidth, borderStyle, bgColor, boxesText, name, textColor, textAlign, showVol, showDV, showADV, showSATR, showATR) => if session and sessionOn and constrained if array.size(boxes) == lookback + 1 box.delete(array.shift(boxes)) box.delete(array.shift(boxesText)) if not created array.set(sessionHighs, number, high) array.set(sessionLows, number, low) array.push(boxes, box.new(bar_index, array.get(sessionHighs, number), bar_index, array.get(sessionLows, number), borderColor, borderWidth, borderStyle, bgcolor = bgColor)) array.push(boxesText, box.new(bar_index, array.get(sessionLows, number), bar_index, array.get(sessionLows, number), color.new(#000000, 100), bgcolor = color.new(#000000, 100), text_size = chosenTextSize, text_color = textColor, text_halign = text.align_left, text_valign = textAlign)) array.set(sessionVols, number, array.get(sessionVols, number) + int(volume)) array.set(createdChecks, number, true) else array.set(sessionHighs, number, math.max(array.get(sessionHighs, number), high)) array.set(sessionLows, number, math.min(array.get(sessionLows, number), low)) array.set(sessionVols, number, array.get(sessionVols, number) + int(volume)) box.set_top(array.last(boxes), array.get(sessionHighs, number)) box.set_right(array.last(boxes), bar_index) box.set_bottom(array.last(boxes), array.get(sessionLows, number)) box.set_top(array.last(boxesText), textAlign == text.align_top ? array.get(sessionLows, number) : array.get(sessionHighs, number)) box.set_bottom(array.last(boxesText), textAlign == text.align_top ? array.get(sessionLows, number) : array.get(sessionHighs, number)) dv = showDV ? " β€’ " + FormatText(array.get(sessionVols, number), dVol, dvFormat) : na adVol = showADV ? " β€’ " + FormatText(array.get(sessionVols, number), dADV, advFormat) : na sessionATR = array.get(sessionHighs, number) - array.get(sessionLows, number) dayATR = showATR ? " β€’ " + FormatText(sessionATR, dATR, datrFormat) : na finalText = name + "\n" + (showVol ? "Volume: " + str.tostring(array.get(sessionVols, number), format.volume) : na) + dv + adVol + "\n" + (showSATR ? "ATR: " + str.tostring(sessionATR) : na) + dayATR box.set_text(array.last(boxesText), finalText) if created and (na(session) or not constrained) array.set(sessionHighs, number, na) array.set(sessionLows, number, na) array.set(sessionVols, number, 0) array.set(createdChecks, number, false) //________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ //MAIN if timeframe.isdwm if errorMsg table.cell(error, 0, 0, "ERROR: Sessions indicator only works on intraday timeframes.", text_color=color.white) else Plot(0, array.get(createdChecks, 0), time(timeframe.period, time1), sessionOn1, Constraints("Extended"), boxes1, borderColor1, borderWidth1, BorderStyle(borderStyle1), bgColor1, boxesText1, name1, textColor1, TextPlacement(textPlace1), showVolume1, showDV1, showADV1, showSATR1, showATR1) Plot(1, array.get(createdChecks, 1), time(timeframe.period, time2), sessionOn2, Constraints(session2), boxes2, borderColor2, borderWidth2, BorderStyle(borderStyle2), bgColor2, boxesText2, name2, textColor2, TextPlacement(textPlace2), showVolume2, showDV2, showADV2, showSATR2, showATR2) Plot(2, array.get(createdChecks, 2), time(timeframe.period, time3), sessionOn3, Constraints(session3), boxes3, borderColor3, borderWidth3, BorderStyle(borderStyle3), bgColor3, boxesText3, name3, textColor3, TextPlacement(textPlace3), showVolume3, showDV3, showADV3, showSATR3, showATR3) Plot(3, array.get(createdChecks, 3), time(timeframe.period, time4), sessionOn4, Constraints(session4), boxes4, borderColor4, borderWidth4, BorderStyle(borderStyle4), bgColor4, boxesText4, name4, textColor4, TextPlacement(textPlace4), showVolume4, showDV4, showADV4, showSATR4, showATR4) Plot(4, array.get(createdChecks, 4), time(timeframe.period, time5), sessionOn5, Constraints(session5), boxes5, borderColor5, borderWidth5, BorderStyle(borderStyle5), bgColor5, boxesText5, name5, textColor5, TextPlacement(textPlace5), showVolume5, showDV5, showADV5, showSATR5, showATR5) Plot(5, array.get(createdChecks, 5), time(timeframe.period, time6), sessionOn6, Constraints(session6), boxes6, borderColor6, borderWidth6, BorderStyle(borderStyle6), bgColor6, boxesText6, name6, textColor6, TextPlacement(textPlace6), showVolume6, showDV6, showADV6, showSATR6, showATR6) Plot(6, array.get(createdChecks, 6), time(timeframe.period, time7), sessionOn7, Constraints("Extended"), boxes7, borderColor7, borderWidth7, BorderStyle(borderStyle7), bgColor7, boxesText7, name7, textColor7, TextPlacement(textPlace7), showVolume7, showDV7, showADV7, showSATR7, showATR7)
ATR Levels
https://www.tradingview.com/script/m5hohYOa-ATR-Levels/
angelh584
https://www.tradingview.com/u/angelh584/
66
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© angelh584 // Method by AdamSilverTrade //@version=5 indicator('ATR Levels', shorttitle='ATR Levels', overlay=true) // === Timeframe Selection === timeframe_choice = input.string(title="Select Timeframe", defval="Daily", options=["Daily", "Weekly"], tooltip="Choose the timeframe for ATR calculations.") // === General Inputs === group_general = "General" atr_length = input.int(14, title='ATR Length', group=group_general) trigger_percentage = input.float(0.236, title='Trigger Percentage', group=group_general) level_size = input.int(2, title='Level Size', group=group_general) // === Trigger Level Colors === group_trigger_levels = "Trigger Levels" lower_trigger_level_color = input.color(color.red, title='Lower Trigger Level Color', group=group_trigger_levels) upper_trigger_level_color = input.color(color.green, title='Upper Trigger Level Color', group=group_trigger_levels) // === ATR Target Colors === group_atr_targets = "ATR Targets" atr_target_color = input.color(color.purple, title='ATR Target Color', group=group_atr_targets) // === ATR Target Multipliers === atr_target_mult1 = input.float(0.5, title='ATR Target 1 Multiplier', group=group_atr_targets) atr_target_mult2 = input.float(0.723, title='ATR Target 2 Multiplier', group=group_atr_targets) // === Table Settings === group_table = "Table Settings" string tableYposInput = input.string("top", title="Panel position", options = ["top", "middle", "bottom"], group=group_table, tooltip="Select the vertical position of the table.") string tableXposInput = input.string("right", title="Horizontal position", options = ["left", "center", "right"], group=group_table, tooltip="Select the horizontal position of the table.") color bgColorInput = input.color(color.new(color.gray, 30), title="Background Color", group=group_table, tooltip="Choose the background color for the table.") // Set the appropriate timeframe based on user's choice timeframe_func() => timeframe_choice == 'Daily' ? 'D' : 'W' // Offset for label position offset = 10 // Data period_index = 1 ticker = ticker.new(syminfo.prefix, syminfo.ticker, session=session.extended) previous_close = request.security(ticker, timeframe_func(), close[period_index], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) atr = request.security(ticker, timeframe_func(), ta.atr(atr_length)[period_index], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) // === Trigger Levels === lower_trigger = previous_close - trigger_percentage * atr upper_trigger = previous_close + trigger_percentage * atr // Plot trigger levels as lines plot(lower_trigger, color=color.new(lower_trigger_level_color, 40), linewidth=level_size, title='Put Trigger', style=plot.style_stepline) plot(upper_trigger, color=color.new(upper_trigger_level_color, 40), linewidth=level_size, title='Call Trigger', style=plot.style_stepline) // Add text labels for trigger levels var label label1 = na var label label2 = na if (na(label1)) label1 := label.new(x=bar_index + offset, y=lower_trigger, text='Puts', color=color.new(lower_trigger_level_color, 0), style=label.style_label_center) else label.set_xy(label1, x=bar_index + offset, y=lower_trigger) if (na(label2)) label2 := label.new(x=bar_index + offset, y=upper_trigger, text='Calls', color=color.new(upper_trigger_level_color, 0), style=label.style_label_center) else label.set_xy(label2, x=bar_index + offset, y=upper_trigger) // === ATR Target Levels === atr_target1_bullish = previous_close + atr * atr_target_mult1 atr_target2_bullish = previous_close + atr * atr_target_mult2 atr_target1_bearish = previous_close - atr * atr_target_mult1 atr_target2_bearish = previous_close - atr * atr_target_mult2 // Plot ATR target levels as lines plot(atr_target1_bullish, color=color.new(atr_target_color, 40), linewidth=level_size, title='Bullish Target 1', style=plot.style_stepline) plot(atr_target2_bullish, color=color.new(atr_target_color, 40), linewidth=level_size, title='Bullish Target 2', style=plot.style_stepline) plot(atr_target1_bearish, color=color.new(atr_target_color, 40), linewidth=level_size, title='Bearish Target 1', style=plot.style_stepline) plot(atr_target2_bearish, color=color.new(atr_target_color, 40), linewidth=level_size, title='Bearish Target 2', style=plot.style_stepline) // Add text labels for ATR target levels var label label3 = na var label label4 = na var label label5 = na var label label6 = na // Create an array to hold label variables var label[] labels = array.new_label(4) if (na(label3)) label3 := label.new(x=bar_index + offset, y=atr_target1_bullish, text='Bullish Target 1', color=color.new(atr_target_color, 0), style=label.style_label_center) else label.set_xy(label3, x=bar_index + offset, y=atr_target1_bullish) if (na(label4)) label4 := label.new(x=bar_index + offset, y=atr_target2_bullish, text='Bullish Target 2', color=color.new(atr_target_color, 0), style=label.style_label_center) else label.set_xy(label4, x=bar_index + offset, y=atr_target2_bullish) if (na(label5)) label5 := label.new(x=bar_index + offset, y=atr_target1_bearish, text='Bearish Target 1', color=color.new(atr_target_color, 0), style=label.style_label_center) else label.set_xy(label5, x=bar_index + offset, y=atr_target1_bearish) if (na(label6)) label6 := label.new(x=bar_index + offset, y=atr_target2_bearish, text='Bearish Target 2', color=color.new(atr_target_color, 0), style=label.style_label_center) else label.set_xy(label6, x=bar_index + offset, y=atr_target2_bearish) // === Enhanced Table to Display Call Trigger, Put Trigger, and Current ATR === var table panel = table.new(tableYposInput + "_" + tableXposInput, 2, 4) // 2 columns, 4 rows // Define some colors and emojis headerColor = color.new(color.blue, 20) bullColor = color.new(color.green, 40) bearColor = color.new(color.red, 40) neutralColor = color.new(color.gray, 40) upArrow = "πŸ”Ό" downArrow = "πŸ”½" if barstate.islast // Table header table.cell(panel, 0, 0, "Parameter", bgcolor = headerColor, text_color = color.white) table.cell(panel, 1, 0, "Value", bgcolor = headerColor, text_color = color.white) // Call Trigger callTriggerColor = upper_trigger > close ? bullColor : bearColor table.cell(panel, 0, 1, upArrow + " Call Trigger", bgcolor = neutralColor) table.cell(panel, 1, 1, str.tostring(upper_trigger, format.mintick), text_color = color.black, bgcolor = callTriggerColor) // Put Trigger putTriggerColor = lower_trigger < close ? bearColor : bullColor table.cell(panel, 0, 2, downArrow + " Put Trigger", bgcolor = neutralColor) table.cell(panel, 1, 2, str.tostring(lower_trigger, format.mintick), text_color = color.black, bgcolor = putTriggerColor) // Current ATR table.cell(panel, 0, 3, "Current ATR", bgcolor = neutralColor) table.cell(panel, 1, 3, str.tostring(atr, format.mintick), text_color = color.black, bgcolor = neutralColor) // Alert Condition 1: Bullish Trigger Cross alertcondition(upper_trigger > close, title="Bullish Trigger Cross", message="Bullish Trigger Cross") // Alert Condition 2: Bearish Trigger Cross alertcondition(lower_trigger < close, title="Bearish Trigger Cross", message="Bearish Trigger Cross") // Alert Condition 3: ATR Target 1 Bullish alertcondition(close > atr_target1_bullish, title="ATR Target 1 Bullish", message="Price above ATR Target 1 (Bullish)") // Alert Condition 4: ATR Target 2 Bullish alertcondition(close > atr_target2_bullish, title="ATR Target 2 Bullish", message="Price above ATR Target 2 (Bullish)") // Alert Condition 5: ATR Target 1 Bearish alertcondition(close < atr_target1_bearish, title="ATR Target 1 Bearish", message="Price below ATR Target 1 (Bearish)") // Alert Condition 6: ATR Target 2 Bearish alertcondition(close < atr_target2_bearish, title="ATR Target 2 Bearish", message="Price below ATR Target 2 (Bearish)")
Bar Color Long / Short Indicator With Advised SL Rev 1
https://www.tradingview.com/script/o1jVHwVv-Bar-Color-Long-Short-Indicator-With-Advised-SL-Rev-1/
CR-JE
https://www.tradingview.com/u/CR-JE/
30
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© CR-JE //@version=5 indicator(title='Bar Color Long / Short Indicator With Advised SL Rev 4', shorttitle='SI', overlay=true) // Stop Loss Finder length = input.int(title='Length', defval=90, minval=1) smoothing = input.string(title='Smoothing', defval='RMA', options=['RMA', 'SMA', 'EMA', 'WMA']) m = input(1.5, 'Multiplier') src1 = high src2 = low pline = true show_bar_colors = input.bool(title='Bar Colors Orange-Blue and Signal Arrows ON/OFF', defval=false) show_bar_colorsLSonly = input.bool(title='Bar Colors Long-Short ON?OFF', defval=true) show_bar_colorsLS = input.bool(title='Bar Colors Red Yellow Green ON/OFF', defval=false) Arrow_colors = input.bool(title='Arrow Colors Black/White', defval=true) BG_colors = input.bool(title='Bg Colors ON/OFF', defval=false) Advised_SL = input.bool(title='Advised SL ON/OFF', defval=false) collong = not show_bar_colors ? color.green : color.orange colshort = not show_bar_colors ? color.red : color.blue ma_function(source, length) => if smoothing == 'RMA' ta.rma(source, length) else if smoothing == 'SMA' ta.sma(source, length) else if smoothing == 'EMA' ta.ema(source, length) else ta.wma(source, length) a = ma_function(ta.tr(true), length) * m x = ma_function(ta.tr(true), length) * m + src1 x2 = src2 - ma_function(ta.tr(true), length) * m // Custom max function to handle series and float arguments max_custom(x, y) => x > y ? x : y // User input for custom risk calculation customRiskPeriod = 14 // Custom risk calculation (resembling RSI) priceDelta = close - close[1] avgGain = ta.sma(max_custom(priceDelta, 0), customRiskPeriod) avgLoss = ta.sma(max_custom(-priceDelta, 0), customRiskPeriod) customRS = avgGain / avgLoss customRisk = 100 - (100 / (1 + customRS)) // Define risk levels lowRisk = 30 mediumRisk = 50 highRisk = 70 // Custom sentiment calculation (resembling EMA, MACD, and ROC) src = close shortPeriod = 9 longPeriod = 21 customShort = ta.vwap(src) customLong = ta.wma(src, longPeriod) customSignal = customShort > customLong ? 1 : -1 priceDelta2 = (src - src[1]) / src[1] * 100 customROC = ta.sma(priceDelta2, shortPeriod) rocSignal = customROC > 0 ? 1 : -1 sentimentScore = (customSignal + rocSignal) / 2 sentimentPositive = sentimentScore > 0 // Bollinger Bands Percent calculation length1 = 20 mult = 2 basis = ta.sma(close, length1) dev = mult * ta.stdev(close, length1) upper = basis + dev lower = basis - dev bbPercent = (close - lower) / (upper - lower) // Combine custom risk, sentiment score, and BB Percent for the new signal combinedSignal = customRisk + sentimentScore * 10 + bbPercent * 10 // EMA10 calculation ema10 = ta.ema(close, 10) ema20 = ta.ema(close, 20) sma50 = ta.sma(close, 50) // Long and Short long = sentimentPositive and (open > ema10 or close > ema10) and (ema10 > ema20) and (sma50 >= sma50[1]) short = not sentimentPositive and (open < ema10 or close < ema10) and (ema10 < ema20) and (sma50 <= sma50[1]) // Close Open Confirmation confirmOpenL = close >= open confirmOpenS = close <= open // Signal once Long & Short var isLong = false var isShort = false //Long buy = not isLong and long and confirmOpenL //Short sell = not isShort and short and confirmOpenS if (long) isLong := true isShort := false if (short) isLong := false isShort := true // Bar color based on Condition candle_color = long ? color.orange : short ? color.blue : color.gray candle_colorB = long ? color.green : short ? color.red : color.yellow candle_colorC = buy and BG_colors ? color.rgb(6, 223, 247, 85) : sell and BG_colors ? color.rgb(247, 5, 230, 85) : na candle_colorD = buy ? color.rgb(60, 233, 252) : sell ? color.rgb(245, 59, 232) : na // Shape color ShapeColor = Arrow_colors ? color.rgb(0, 1, 4) : color.white barcolor(show_bar_colors ? candle_color : show_bar_colorsLS ? candle_colorB : show_bar_colorsLSonly ? candle_colorD : na) bgcolor(candle_colorC) // Alert conditions alertcondition(buy, title="long Signal", message="Buy Signal triggered") alertcondition(sell, title="short Signal", message="Sell Signal triggered") alertcondition(buy or sell, title="long or short Signal", message="Long or short Signal triggered") // Added large arrow up and down for buy and sell signals plotshape(buy and not show_bar_colors, style=shape.arrowup, location=location.belowbar, color=ShapeColor, size=size.large) plotshape(sell and not show_bar_colors, style=shape.arrowdown, location=location.abovebar, color=ShapeColor, size=size.large) // Plot SL line at the last candle if barstate.islast and Advised_SL line.new(x1=bar_index, y1=x, x2=bar_index+1, y2=x, width=1, color=colshort) line.new(x1=bar_index, y1=x2, x2=bar_index+1, y2=x2, width=1, color=collong) label.new(x=bar_index + 1, y=x, text='Advised Short Stop Loss: ' + str.tostring(x, '#.##'), color=colshort, style=label.style_label_lower_left, textcolor=color.white) label.new(x=bar_index + 1, y=x2, text='Advised Long Stop Loss: ' + str.tostring(x2, '#.##'), color=collong, style=label.style_label_upper_left, textcolor=color.white)
Master Pattern [LuxAlgo]
https://www.tradingview.com/script/J9LyN92e-Master-Pattern-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
2,685
study
5
CC-BY-NC-SA-4.0
// 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("Master Pattern [LuxAlgo]", "LuxAlgo - Master Pattern Indicator", overlay = true, max_boxes_count = 500, max_lines_count = 500) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ length = input.int(3, 'Contraction Detection Lookback', minval = 1) liqLength = input.int(20, 'Liquidity Levels', minval = 1) showMajor = input(true, 'Show Major Pattern') showMinor = input(true, 'Show Minor Pattern') //Style bullCss = input.color(color.teal, 'Bullish Pattern', inline = 'bull', group = 'Pattern Style') showBullBox = input(true, 'Area', inline = 'bull', group = 'Pattern Style') showBullLvl = input(true, 'Line', inline = 'bull', group = 'Pattern Style') bearCss = input.color(color.red, 'Bearish Pattern', inline = 'bear', group = 'Pattern Style') showBearBox = input(true, 'Area', inline = 'bear', group = 'Pattern Style') showBearLvl = input(true, 'Line', inline = 'bear', group = 'Pattern Style') //Liquidity Style showLiq = input(true, 'Show Liquidity Levels', group = 'Liquidity') bullLiqCss = input.color(color.teal, 'Upper Liquidity', group = 'Liquidity') bearLiqCss = input.color(color.red, 'Lower Liquidity', group = 'Liquidity') //-----------------------------------------------------------------------------} //UDT //-----------------------------------------------------------------------------{ type mp box area line avg bool breakup bool breakdn //-----------------------------------------------------------------------------} //Detect contraction //-----------------------------------------------------------------------------{ var phy = 0., var phx = 0, var pht = 0. var ply = 0., var plx = 0, var plt = 0. var float top = na var float btm = na n = bar_index ph = ta.pivothigh(length, length) pl = ta.pivotlow(length, length) if ph pht := math.sign(ph - phy) phy := ph if pht == -1 and plt == 1 top := ph btm := ply phx := n-length if pl plt := math.sign(pl - ply) ply := pl if pht == -1 and plt == 1 top := phy btm := pl plx := n-length //-----------------------------------------------------------------------------} //Set pattern //-----------------------------------------------------------------------------{ var mp master = mp.new() //Detect master pattern isbull = high[length] > top and top > btm isbear = low[length] < btm and top > btm if isbull or isbear css = isbull ? bullCss : bearCss master.avg.set_x2(n-length) val = math.avg(top, btm) //Create new master pattern object master := mp.new( (isbull and showBullBox) or (isbear and showBearBox) ? box.new(math.max(phx, plx), top, n-length, btm, na, bgcolor = showMinor ? color.new(css, 50) : na) : na , (isbull and showBullLvl) or (isbear and showBearLvl) ? line.new(n-length, val, n, val, color = showMinor ? css : na) : na , isbull , isbear) top := na btm := na //Determine if pattern switch to major if master.breakup if low < master.area.get_bottom() if not showMajor master.area.delete() master.avg.delete() else master.area.set_border_color(bullCss) if not showMinor master.area.set_bgcolor(color.new(bullCss, 50)) master.avg.set_color(bullCss) else if master.breakdn if high > master.area.get_top() if not showMajor master.area.delete() master.avg.delete() else master.area.set_border_color(bearCss) if not showMinor master.area.set_bgcolor(color.new(bearCss, 50)) master.avg.set_color(bearCss) //Set friction level x2 coordinate to current bar if not na(master.avg) master.avg.set_x2(n) //-----------------------------------------------------------------------------} //Liquidity levels //-----------------------------------------------------------------------------{ var line liqup = na, var liqup_reach = false var line liqdn = na, var liqdn_reach = false liqph = ta.pivothigh(liqLength, liqLength) liqpl = ta.pivotlow(liqLength, liqLength) //Set upper liquidity if liqph and showLiq if not liqup_reach liqup.set_x2(n-liqLength) liqup := line.new(n-liqLength, liqph, n, liqph, color = bullLiqCss, style = line.style_dotted) liqup_reach := false else if not liqup_reach and showLiq liqup.set_x2(n) if high > liqup.get_y1() liqup_reach := true //Set lower liquidity if liqpl and showLiq if not liqdn_reach liqdn.set_x2(n-liqLength) liqdn := line.new(n-liqLength, liqpl, n, liqpl, color = bearLiqCss, style = line.style_dotted) liqdn_reach := false else if not liqdn_reach and showLiq liqdn.set_x2(n) if low < liqdn.get_y1() liqdn_reach := true //-----------------------------------------------------------------------------}
MACDh with divergences & impulse system (overlayed on prices)
https://www.tradingview.com/script/pnIcTKZS-MACDh-with-divergences-impulse-system-overlayed-on-prices/
jorgelg93
https://www.tradingview.com/u/jorgelg93/
114
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jorgelg93 //@version=5 indicator(title="MACDh with divergences & impulse system (overlayed on prices)", max_lines_count = 500, max_bars_back = 5000, overlay=true) //================= DIVERGENCE INDICATOR =========== { ======== buysignaltemp_divergencias = false sellsignaltemp_divergencias = false buysignalconfirmed = false sellsignalconfirmed = false var float dev_threshold_lows_def = 0 var float dev_threshold_highs_def = 0 var line lineLast_HistH = na //this is one of the lines we see on the chart var line lineLast_HistL = na //this is one of the lines we see on the chart var label labelLast_HistH = na //this is one of the lines we see on the chart var label labelLast_HistL = na //this is one of the lines we see on the chart var int histcruzodesdeabajoIndex_inmediato = 0 var int histcruzodesdearribaIndex_inmediato = 0 //variables to calculate Highs var int indexHistHighUltimo = 0 var int indexHistHighPenultimo = 0 var int indexHistHighAntepenultimo = 0 var int indexPriceHighUltimo = 0 var int indexPriceHighPenultimo = 0 var int indexPriceHighAntepenultimo = 0 //variables to calculate index Highs var float histHighUltimo = 0 var float histHighPenultimo = 0 var float histHighAntepenultimo = 0 var float priceHighUltimo = 0 var float priceHighPenultimo = 0 var float priceHighAntepenultimo = 0 //variables to calculate index Lows var int indexHistLowUltimo = 0 var int indexHistLowPenultimo = 0 var int indexHistLowAntepenultimo = 0 var int indexPriceLowUltimo = 0 var int indexPriceLowPenultimo = 0 var int indexPriceLowAntepenultimo = 0 //variables to calculate Lows var float histLowUltimo = 0 var float histLowPenultimo = 0 var float histLowAntepenultimo = 0 var float priceLowUltimo = 0 var float priceLowPenultimo = 0 var float priceLowAntepenultimo = 0 plotimpulse = input.bool(true, title="Show Impulse System over prices?") // Getting inputs fast_length = input(title="Fast Length", group="MACD", defval=12) slow_length = input(title="Slow Length", group="MACD", defval=26) signal_length = input.int(title="Signal Smoothing", group="MACD", minval = 1, maxval = 50, defval = 9) threshold_multiplier = input.float(title="Vertical deviation on Price peaks", group="MACD Histogram Divergences Criteria", defval=25, minval=0, tooltip = "Deviation refers to the difference/relation/vertical distance between the PRICE peaks involved in the divergence") hist_peaks_diff = input.float(title="Vertical deviation on MACD Histogram peaks", group="MACD Histogram Divergences Criteria", defval = 0, tooltip = "Refers to the difference/relation/vertical distance between the MACH HISTOGRAM peaks involved in the divergence: 1st Histogram Peak is X times the 2nd") minDivWidth = input.int(title="Divergence min width", group="MACD Histogram Divergences Criteria", defval = 0, tooltip = "Refers to the minimum horizontal distance between the MACH histogram peaks involved in the divergence") // minima_cantidad_de_barras_entre_los_picos maxDivWidth = input.int(title="Divergence max width", group="MACD Histogram Divergences Criteria", defval = 200, tooltip = "Refers to the maximum horizontal distance between the MACH histogram peaks involved in the divergence") // maxima_cantidad_de_barras_entre_los_picos plotBullDivergences = input.bool(true, title="Plot regular Bullish divergences?") plotBearDivergences = input.bool(true, title="Plot regular Bearish divergences?") deleteLastLines = input.bool(false, title="Delete Previous Cancelled Divergences?") plottempsignals = input.bool(true, title="Plot Temporary Buy/Sell Signals?") plotconfirmedsignals = input.bool(true, title="Plot Buy/Sell Confirmed Signals?") [macdLine, signalLine, hist] = ta.macd(close, fast_length,slow_length,signal_length) //================== impulse system =========================// [macdLine_impulse_div, signalLine_impulse_div, histline_impulse_div] = ta.macd(close, 12, 26, 9) ema_impulse_div = ta.ema(close, 13) greenimpulse_div = close > ema_impulse_div and histline_impulse_div > histline_impulse_div[1] redimpulse_div = close < ema_impulse_div and histline_impulse_div < histline_impulse_div[1] blueimpulse_div = (close > ema_impulse_div and histline_impulse_div < histline_impulse_div[1]) or (close < ema_impulse_div and histline_impulse_div > histline_impulse_div[1]) barcolor(plotimpulse and greenimpulse_div ? color.green : plotimpulse and redimpulse_div ? color.red : plotimpulse and blueimpulse_div ? color.blue : na) //===========================================// //This verifies if the MACD histogram crossed over or under the 0 axis during the previous bar/candle histcruzoover = ta.crossover(hist[1],0) histcruzounder = ta.crossunder(hist[1],0) //This verifies if the MACD histogram crossed over or under the 0 axis during the current bar/candle histcruzoover_inmediato = ta.crossover(hist,0) histcruzounder_inmediato = ta.crossunder(hist,0) //======================= //calculate the deviation of prices calc_dev(base_price, price) => 100 * (price - base_price) / price //Calculate deviation threshold for identifying major swings dev_threshold_high = ta.atr(10) / high * 100 * threshold_multiplier dev_threshold_low = ta.atr(10) / low * 100 * threshold_multiplier //======================= //these lines save the bar_index if the histogram bar in this tick is crossing over or under if histcruzoover_inmediato histcruzodesdeabajoIndex_inmediato := bar_index if histcruzounder_inmediato histcruzodesdearribaIndex_inmediato := bar_index //======================= //the Bear cycle is officially closed in the previous bar and we have to analize and see if during that cycle there was some bullish divergence and rewrite the variables if histcruzoover // if histcruzoover and barstate.isconfirmed //it saves the penultimate high of the histogram histLowAntepenultimo := histLowPenultimo histLowPenultimo := histLowUltimo //it saves the price Lows priceLowAntepenultimo := priceLowPenultimo priceLowPenultimo := priceLowUltimo //it saves the "histogram indexes" indexHistLowAntepenultimo := indexHistLowPenultimo indexHistLowPenultimo := indexHistLowUltimo //it saves the "price indexes" indexPriceLowAntepenultimo := indexPriceLowPenultimo indexPriceLowPenultimo := indexPriceLowUltimo label.delete(labelLast_HistH) label.delete(labelLast_HistL) line.delete(lineLast_HistH) line.delete(lineLast_HistL) //for BULLISH DIVERGENCES dev2 = calc_dev(priceLowPenultimo, priceLowAntepenultimo) dev3 = priceLowAntepenultimo/priceLowPenultimo if ( plotBullDivergences and math.abs(dev2) < dev_threshold_lows_def and priceLowPenultimo < priceLowAntepenultimo and histLowPenultimo > histLowAntepenultimo and indexPriceLowPenultimo - indexPriceLowAntepenultimo >= minDivWidth and indexPriceLowPenultimo - indexPriceLowAntepenultimo <= maxDivWidth and indexHistLowPenultimo - indexHistLowAntepenultimo >= minDivWidth and indexHistLowPenultimo - indexHistLowAntepenultimo <= maxDivWidth and histLowAntepenultimo / histLowPenultimo >= hist_peaks_diff ) buysignalconfirmed := true top1 = line.new(indexPriceLowAntepenultimo, priceLowAntepenultimo, indexPriceLowPenultimo, priceLowPenultimo, color=color.green, width=2) plotshape(plotconfirmedsignals and buysignalconfirmed ? low : na , style=shape.triangleup, text = "Bull \n confirmed", location=location.belowbar, color=color.green, size=size.small) //the Bull cycle officially ended during the last bar and we have to analize and see if during that cycle there was some bearish divergence and rewrite the variables if histcruzounder // if histcruzounder and barstate.isconfirmed //it saves the penultimate high of the histogram histHighAntepenultimo := histHighPenultimo histHighPenultimo := histHighUltimo //it saves the price highs priceHighAntepenultimo := priceHighPenultimo priceHighPenultimo := priceHighUltimo //it saves the "histogram indexes" indexHistHighAntepenultimo := indexHistHighPenultimo indexHistHighPenultimo := indexHistHighUltimo //it saves the "price indexes" indexPriceHighAntepenultimo := indexPriceHighPenultimo indexPriceHighPenultimo := indexPriceHighUltimo label.delete(labelLast_HistH) label.delete(labelLast_HistL) line.delete(lineLast_HistH) line.delete(lineLast_HistL) //for BEARISH DIVERGENCES dev2 = calc_dev(priceHighPenultimo, priceHighAntepenultimo) dev3 = priceHighPenultimo/priceHighAntepenultimo if ( plotBearDivergences and math.abs(dev2) < dev_threshold_highs_def and priceHighPenultimo > priceHighAntepenultimo and histHighPenultimo < histHighAntepenultimo and indexPriceHighPenultimo - indexPriceHighAntepenultimo >= minDivWidth and indexPriceHighPenultimo - indexPriceHighAntepenultimo <= maxDivWidth and indexHistHighPenultimo - indexHistHighAntepenultimo >= minDivWidth and indexHistHighPenultimo - indexHistHighAntepenultimo <= maxDivWidth and histHighAntepenultimo / histHighPenultimo >= hist_peaks_diff ) sellsignalconfirmed := true top1 = line.new(indexPriceHighAntepenultimo, priceHighAntepenultimo, indexPriceHighPenultimo, priceHighPenultimo, color=color.red, width=2) plotshape(plotconfirmedsignals and sellsignalconfirmed ? high : na, style=shape.triangledown,text = "Bear \n confirmed", location=location.abovebar, color=color.red, size=size.small) //======================================= // PIVOTS highs function pivotsH(src1, src2) => c = nz(src1) // this could be the histogram, the price or any other value from any indicator c2 = nz(src2) //as long as the histogram is greater than zero I will be looking for higher highs (anyways, I believe this "if" could be redundant) if hist > 0 ind = bar_index - histcruzodesdeabajoIndex_inmediato //OK checker ok = true for i = 0 to ind if src1[i] > c // IF THE CURRENT BAR IS SMALLER OR LESS POSITIVE THAN ANY OF THE OTHER PREVIOUS BARS THEN THE PIVOT HIGH REMAINS INVALIDATED ok := false if ok // If pivot is valid, return bar index + high of price values; PIVOT WILL ALWAYS BE TRUE IF ITS INDEX IS SAVED AND ITS CORRESPONDENT HIGH OR LOW AS LONG AS IT DOES NOT REMAIN INVALIDATED IN THE ABOVE LINES [bar_index, c, bar_index, c2] else [int(na), float(na), int(na), float(na)] //======================================= //======================================= // PIVOTS lows function pivotsL(src1, src2) => c = nz(src1) // this could be the histogram, the price or any other value from any indicator c2 = nz(src2) //as long as the histogram is lower than zero I will be looking for lower lows (anyways, I believe this "if" could be redundant) if hist < 0 ind = bar_index - histcruzodesdearribaIndex_inmediato //OK checker ok = true for i = 0 to ind if src1[i] < c // IF THE CURRENT BAR IS GREATER OR LESS NEGATIVE THAN ANY OF THE OTHER PREVIOUS BARS THEN THE PIVOT LOW REMAINS INVALIDATED ok := false if ok // If pivot is valid, return bar index + high price value; PIVOT WILL ALWAYS BE TRUE IF ITS INDEX IS SAVED AND ITS CORRESPONDENT HIGH OR LOW AS LONG AS IT DOES NOT REMAIN INVALIDATED IN THE ABOVE LINES [bar_index, c, bar_index, c2] else [int(na), float(na), int(na), float(na)] //======================================= //======================================= // FIND BEARISH DIVERGENCES by looking for higher highs of the histogram [iHist_H, pHist_H, indexPreciocuandoHistTieneHigherHigh, PreciocuandoHistTieneHigherHigh] = pivotsH(hist, high) //I want to know the histogram high [iPrice_H, pPrice_H, indexHistcuandoPrecioTieneHigherHigh, HistcuandoPrecioTieneHigherHigh] = pivotsH(high, hist) //I want to know the price high //if we have a valid pivot high, it saves the index and the value of that pivot high; this way the last pivot detected will always be saved if not na(iHist_H) indexHistHighUltimo := iHist_H histHighUltimo := pHist_H if not na(iPrice_H) indexPriceHighUltimo := iPrice_H priceHighUltimo := pPrice_H dev_threshold_highs_def := dev_threshold_high //I want to save the "threshold" of that maximum //======================================= //======================================= // FIND BULLISH DIVERGENCES by looking for lower lows of the histogram [iHist_L, pHist_L, indexPreciocuandoHistTieneLowerLow, PreciocuandoHistTieneLowerLow] = pivotsL(hist, low) //I want to know the histogram low [iPrice_L, pPrice_L, indexHistcuandoPrecioTieneLowerLow, HistcuandoPrecioTieneLowerLow] = pivotsL(low, hist) //I want to know the price low //if we have a valid pivot low, it saves the index and the value of that pivot low; this way the last pivot detected will always be saved if not na(iHist_L) indexHistLowUltimo := iHist_L histLowUltimo := pHist_L if not na(iPrice_L) indexPriceLowUltimo := iPrice_L priceLowUltimo := pPrice_L dev_threshold_lows_def := dev_threshold_low //I want to save the "threshold" of that minimum //======================================= //it calculates prices deviations dev300 = calc_dev(priceHighUltimo, priceHighPenultimo) dev301 = calc_dev(priceLowUltimo, priceLowPenultimo) dev33 = priceHighUltimo/priceHighPenultimo dev34 = priceLowPenultimo/priceLowUltimo if not na(iPrice_H) or not na(iHist_H)//it executes itself only when there is a new high of the price or a new high of the histogram // if not na(iPrice_H) or not na(iHist_H) and barstate.isconfirmed //it executes itself only when there is a new high of the price or a new high of the histogram //======================================= // to draw possible/temporary BEARISH DIVERGENCES if ( plotBearDivergences and math.abs(dev300) < dev_threshold_highs_def and priceHighUltimo > priceHighPenultimo and histHighUltimo < histHighPenultimo and indexPriceHighUltimo - indexPriceHighPenultimo >= minDivWidth and indexPriceHighUltimo - indexPriceHighPenultimo <= maxDivWidth and indexHistHighUltimo - indexHistHighPenultimo >= minDivWidth and indexHistHighUltimo - indexHistHighPenultimo <= maxDivWidth and histHighPenultimo / histHighUltimo >= hist_peaks_diff ) label.delete(labelLast_HistH) //it erases any previous label labelLast_HistH := label.new(indexPriceHighUltimo, priceHighUltimo, style= label.style_label_down, text = "Possible \n Bearish \n Div", color=color.red, size=size.small) // rewrites line.delete(lineLast_HistH) // this erase all the temporary/possible bearish divergences that took place in the past lineLast_HistH := line.new(indexPriceHighPenultimo, priceHighPenultimo, indexPriceHighUltimo, priceHighUltimo, color=color.red, width=1, style=line.style_dashed) //these two lines draw dotted lines everytime that a temporary/possible bearish divergence takes place // as long as "deleteLastLines" is unmarked in the options for the script if not deleteLastLines lineLast_HistH_temp = line.new(indexPriceHighPenultimo, priceHighPenultimo, indexPriceHighUltimo, priceHighUltimo, color=color.red, width=1, style=line.style_dashed) sellsignaltemp_divergencias := true else // ERASES THE CANCELLED DIVERGENCES if ( plotBearDivergences and math.abs(dev300) > dev_threshold_highs_def or priceHighUltimo < priceHighPenultimo or histHighUltimo > histHighPenultimo or indexPriceHighUltimo - indexPriceHighPenultimo <= minDivWidth or indexPriceHighUltimo - indexPriceHighPenultimo >= maxDivWidth or indexHistHighUltimo - indexHistHighPenultimo <= minDivWidth or indexHistHighUltimo - indexHistHighPenultimo >= maxDivWidth or histHighPenultimo / histHighUltimo <= hist_peaks_diff ) label.delete(labelLast_HistH) line.delete(lineLast_HistH) if not na(iPrice_L) or not na(iHist_L) //it executes itself only when there is a new low of the price or a new low of the histogram // if not na(iPrice_L) or not na(iHist_L) and barstate.isconfirmed //it executes itself only when there is a new low of the price or a new low of the histogram //======================================= // to draw possible/temporary BULLISH DIVERGENCES if ( plotBullDivergences and math.abs(dev301) < dev_threshold_lows_def and priceLowUltimo < priceLowPenultimo and histLowUltimo > histLowPenultimo and indexPriceLowUltimo - indexPriceLowPenultimo >= minDivWidth and indexPriceLowUltimo - indexPriceLowPenultimo <= maxDivWidth and indexHistLowUltimo - indexHistLowPenultimo >= minDivWidth and indexHistLowUltimo - indexHistLowPenultimo <= maxDivWidth and histLowPenultimo / histLowUltimo >= hist_peaks_diff ) label.delete(labelLast_HistL) //it erases any previous label labelLast_HistL := label.new(indexPriceLowUltimo, priceLowUltimo, style= label.style_label_up, text = "Possible \n Bullish \n Div", color=color.green, size=size.small) //rewrites line.delete(lineLast_HistL) //it erases any other temporary/possible bullish divergence that took place in the past lineLast_HistL := line.new(indexPriceLowPenultimo, priceLowPenultimo, indexPriceLowUltimo, priceLowUltimo, color=color.green, width=1, style=line.style_dashed) //these two lines draw dotted lines everytime that a temporary/possible divergence takes place // as long as "deleteLastLines" is unmarked in the options for the script if not deleteLastLines lineLast_HistL_temp = line.new(indexPriceLowPenultimo, priceLowPenultimo, indexPriceLowUltimo, priceLowUltimo, color=color.green, width=1, style=line.style_dashed) buysignaltemp_divergencias := true else // ERASES THE CANCELLED DIVERGENCES if ( plotBullDivergences and math.abs(dev301) > dev_threshold_lows_def or priceLowUltimo > priceLowPenultimo or histLowUltimo < histLowPenultimo or indexPriceLowUltimo - indexPriceLowPenultimo <= minDivWidth or indexPriceLowUltimo - indexPriceLowPenultimo >= maxDivWidth or indexHistLowUltimo - indexHistLowPenultimo <= minDivWidth or indexHistLowUltimo - indexHistLowPenultimo >= maxDivWidth or histLowPenultimo / histLowUltimo <= hist_peaks_diff ) label.delete(labelLast_HistL) line.delete(lineLast_HistL) buy_beautiful_temp_div = (buysignaltemp_divergencias) or (buysignaltemp_divergencias[1] and (low > low[1] or hist > hist[1]) and histLowUltimo > histLowPenultimo) or (buysignaltemp_divergencias[2] and ((low > low[2] and low[1] > low[2]) or (hist > hist[2] and hist[1] > hist[2])) and histLowUltimo > histLowPenultimo) or (buysignaltemp_divergencias[3] and ((low > low[3] and low[1] > low[3] and low[2] > low[3]) or ( hist > hist[3] and hist[1] > hist[3] and hist[2] > hist[3])) and histLowUltimo > histLowPenultimo) sell_beautiful_temp_div = (sellsignaltemp_divergencias) or (sellsignaltemp_divergencias[1] and (high < high[1] or hist < hist[1]) and histHighUltimo < histHighPenultimo) or (sellsignaltemp_divergencias[2] and ((high < high[2] and high[1] < high[2]) or (hist < hist[2] and hist[1] < hist[2])) and histHighUltimo < histHighPenultimo) or (sellsignaltemp_divergencias[3] and ((high < high[3] and high[1] < high[3] and high[2] < high[3]) or (hist < hist[3] and hist[1] < hist[3] and hist[2] < hist[3])) and histHighUltimo < histHighPenultimo) plotshape(plottempsignals and sell_beautiful_temp_div ? high : na, style=shape.triangledown, location=location.abovebar, color=color.rgb(255, 82, 82, 50), size=size.small) plotshape(plottempsignals and buy_beautiful_temp_div ? low : na , style=shape.triangleup, location=location.belowbar, color=color.rgb(76, 175, 79, 50), size=size.small) //END of the core divergence indicator //======= } ================================================ fast_ema = input(title="Fast Ema period", group="Other", defval=12) slow_ema = input(title="Slow Ema period", group="Other", defval=24) plotEmas = input.bool(true, title="Plot EMAs current timeframe?", group = "Other") plotATR1 = input.bool(true, title="Plot ATR1?", group = "Other") plotATR15 = input.bool(false, title="Plot ATR1.5?", group = "Other") plotATR2 = input.bool(true, title="Plot ATR2?", group = "Other") plotATR3 = input.bool(true, title="Plot ATR3?", group = "Other") emas12 = ta.ema(close, fast_ema) emas24 = ta.ema(close, slow_ema) plot(plotEmas ? ta.ema(close, 12) : na, color=color.yellow) plot(plotEmas ? ta.ema(close, 24) : na, color=color.red) //1 ATR Line UpperChannelLine1ATR = ta.ema(close, 20)+(1*ta.atr(10)) LowerChannelLine1ATR = ta.ema(close, 20)-(1*ta.atr(10)) //1.5 ATR LINE UpperChannelLine1ATR15 = ta.ema(close, 20)+(1.5*ta.atr(10)) LowerChannelLine1ATR15 = ta.ema(close, 20)-(1.5*ta.atr(10)) //2 ATR Line UpperChannelLine2ATR = ta.ema(close, 20)+(2*ta.atr(10)) LowerChannelLine2ATR = ta.ema(close, 20)-(2*ta.atr(10)) //3 ATR Line UpperChannelLine3ATR = ta.ema(close, 20)+(3*ta.atr(10)) LowerChannelLine3ATR = ta.ema(close, 20)-(3*ta.atr(10)) color_cond1 = (bar_index+1) % 2 == 0 color_cond2 = (bar_index+1) % 4 == 1 plot(plotATR1 ? UpperChannelLine1ATR : na, title="1ATR", color= color_cond1 ? color.rgb(120, 123, 134, 50) : #00000000, linewidth=1) plot(plotATR1 ? LowerChannelLine1ATR : na, title="-1ATR", color= color_cond1 ? color.rgb(120, 123, 134, 50) : #00000000, linewidth=1) plot(plotATR15 ? UpperChannelLine1ATR15 : na, title="1.5ATR", color=color.rgb(230,230,250, 80), linewidth=1) plot(plotATR15 ? LowerChannelLine1ATR15 : na, title="-1.5ATR", color=color.rgb(230,230,250, 80), linewidth=1) plot(plotATR2 ? UpperChannelLine2ATR : na, title="2ATR", color= color_cond2 ? #00000000 : color.rgb(120, 123, 134, 50), linewidth=1) plot(plotATR2 ? LowerChannelLine2ATR : na, title="-2ATR", color= color_cond2 ? #00000000 : color.rgb(120, 123, 134, 50), linewidth=1) plot(plotATR3 ? UpperChannelLine3ATR : na, title="-3ATR", color=color.rgb(230,230,250, 80), linewidth=2) plot(plotATR3 ? LowerChannelLine3ATR : na, title="-3ATR", color=color.rgb(230,230,250, 80), linewidth=2)
Upside Downside Unchanged Volume
https://www.tradingview.com/script/tvcmY47j-Upside-Downside-Unchanged-Volume/
insideandup
https://www.tradingview.com/u/insideandup/
7
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Nathan J. Hart (insideandup) // // Plot NYSE or NASDAQ Upside Volume, Downside Volume, or Unchanged Volume as a percent of Total Volume. // Values are plotted 0 to 1 (where 1 = 100%), or 1% to 100%. // Example of variables: USI:UPVOL.NY/DNVOL.NY/UNCHVOL.NY vs USI:TVOL.NY (Volume), USI:UVOL/DVOL/XVOL vs USI:TVOL (Volume), and USI:ADVN.NY/DECL.NY/UNCH.NY vs USI:ACTV.NY (Issues) // Compare plotted data with published data here: https://www.wsj.com/market-data/stocks/marketsdiary // Note: UVOL/DVOL option does not plot for DJIA and US stocks option. All other option combinations plot. // Plot Day, Week, and Month volume and/or chart timeframe period volume. // Plot volume as a histogram, line, or area. // Plot various moving averages of volume points. // Horizontal lines at 0, .10, .30, .50, .70, .90, and 1.00 levels. // Inspired by Paul Desmond of Lowry’s Reports: https://docs.cmtassociation.org/docs/2002DowAwardb.pdf // // Created: July 26, 2023 // Last edited: August 17, 2023 // // @version=5 indicator("Percent Upside Volume by 3iau", shorttitle="% Upside Vol", precision=2) // Tillson's Moving Average a = 0.618033989 // Tillson applied a = 0.7, here applying the Golden ratio conjugate = |(1-√5)/2| = 0.618033989 a1 = -1*math.pow(a, 3) a2 = 3*math.pow(a, 2) + 3*math.pow(a, 3) a3 = -6*math.pow(a, 2) - 3*a - 3*math.pow(a, 3) a4 = 1 + 3*a + math.pow(a, 3) + 3*math.pow(a, 2) // moving average type selection ma(source, length, type) => type == "SMA" ? ta.sma(source, length) : type == "EMA" ? ta.ema(source, length) : type == "DEMA" ? 2 * ta.ema(source, length) - ta.ema(ta.ema(source, length), length) : type == "TEMA" ? 3 * ta.ema(source, length) - 3 * ta.ema(ta.ema(source, length), length) + ta.ema(ta.ema(ta.ema(source, length), length), length) : type == "QEMA" ? 5 * ta.ema(source, length) - 10 * ta.ema(ta.ema(source, length), length) + 10 * ta.ema(ta.ema(ta.ema(source, length), length), length) - 5 * ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length) + ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length) : type == "PEMA" ? 8 * ta.ema(source, length) - 28 * ta.ema(ta.ema(source, length), length) + 56 * ta.ema(ta.ema(ta.ema(source, length), length), length) - 70 * ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length) + 56 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length) - 28 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length) + 8 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length), length) - ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length), length), length) : type == "ZLEMA" ? ta.ema(source + (source - source[math.round((length - 1) / 2)]), length) : type == "T3" ? a1 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length), length) + a2 * ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length), length) + a3 * ta.ema(ta.ema(ta.ema(ta.ema(source, length), length), length), length) + a4 * ta.ema(ta.ema(ta.ema(source, length), length), length) : type == "HMA" ? ta.hma(source, length) : type == "SMMA" ? ta.rma(source, length) : type == "WMA" ? ta.wma(source, length) : type == "VWMA" ? ta.vwma(source, length) : na // VARIABLES // // ADVN/DECL NUMBER OF NAMES // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:ADVN.NY USI:DECL.NY USI:UNCH.NY USI:ACTV.NY // NASDAQ USI:ADVN.NQ USI:DECL.NQ USI:UNCH.NQ USI:ACTV.NQ // DJIA USI:ADVN.DJ USI:DECL.DJ USI:UNCH.DJ USI:ACTV.DJ // US USI:ADVN.US USI:DECL.US USI:UNCH.US USI:ACTV.US // // UPVOL/DNVOL VOLUME OF SHARES IN THE GROUP "NUMBER OF NAMES" // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:UPVOL.NY USI:DNVOL.NY USI:UNCHVOL.NY USI:TVOL.NY // NASDAQ USI:UPVOL.NQ USI:DNVOL.NQ USI:UNCHVOL.NQ USI:TVOL.NQ // DJIA USI:UPVOL.DJ USI:DNVOL.DJ USI:UNCHVOL.DJ USI:TVOL.DJ // US USI:UPVOL.US USI:DNVOL.US USI:UNCHVOL.US USI:TVOL.US // // ADV/DECL NUMBER OF NAMES // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:ADV USI:DECL USI:UCHG USI:ADV+USI:DECL+USI:UCHG // NASDAQ USI:ADVQ USI:DECLQ USI:UCHGQ USI:ADVQ+USI:DECLQ+USI:UCHGQ // DJIA n.a. // US n.a. // // UVOL/DVOL VOLUME OF SHARES IN THE GROUP "NUMBER OF NAMES" // ADVANCING DECLINING UNCHANGED TRADING // NYSE USI:UVOL USI:DVOL USI:XVOL USI:TVOL // NASDAQ USI:UVOLQ USI:DVOLQ USI:XVOLQ USI:TVOLQ // DJIA n.a. // US n.a. // // Compare data https://www.wsj.com/market-data/stocks/marketsdiary volume_source = input.string(defval = "NYSE", title = "Exchange", options = ["NYSE", "NASDAQ", "DJIA", "US"], inline = "Source", group = "Volume Source, Type, and Direction") volume_type = input.string(defval = "ADVN/DECL", title = "Variables", options = ["ADVN/DECL", "UPVOL/DNVOL", "ADV/DECL", "UVOL/DVOL"], inline = "Type", group = "Volume Source, Type, and Direction") volume_direction = input.string(defval = "Upside", title = "Direction", options = ["Upside", "Downside", "Unchanged"], inline = "Direction", group = "Volume Source, Type, and Direction") up = "USI:ADVN.NY" down = "USI:DECL.NY" unchanged = "USI:UNCH.NY" total = "USI:ACTV.NY" if (volume_source == "NYSE") up := volume_type == "ADVN/DECL" ? "USI:ADVN.NY" : volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.NY" : volume_type == "ADV/DECL" ? "USI:ADV" : volume_type == "UVOL/DVOL" ? "USI:UVOL" : "USI:ADVN.NY" down := volume_type == "ADVN/DECL" ? "USI:DECL.NY" : volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.NY" : volume_type == "ADV/DECL" ? "USI:DECL" : volume_type == "UVOL/DVOL" ? "USI:DVOL" : "USI:DECL.NY" unchanged := volume_type == "ADVN/DECL" ? "USI:UNCH.NY" : volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.NY" : volume_type == "ADV/DECL" ? "USI:UCHG" : volume_type == "UVOL/DVOL" ? "USI:XVOL" : "USI:UNCH.NY" total := volume_type == "ADVN/DECL" ? "USI:ACTV.NY" : volume_type == "UPVOL/DNVOL" ? "USI:TVOL.NY" : volume_type == "ADV/DECL" ? "USI:ADV + USI:DECL + USI:UCHG" : volume_type == "UVOL/DVOL" ? "USI:TVOL" : "USI:TVOL.NY" else if (volume_source == "NASDAQ") up := volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:UVOLQ" : "USI:ADVN.NQ" down := volume_type == "UPVOL/DNVOL" ? "USI:DNVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:DVOLQ" : "USI:DECL.NQ" unchanged := volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:XVOLQ" : "USI:UNCH.NQ" total := volume_type == "UPVOL/DNVOL" ? "USI:TVOL.NQ" : volume_type == "UVOL/DVOL" ? "USI:TVOLQ" : "USI:ACTV.NQ" else if (volume_source == "DJIA") up := volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:ADVN.DJ" down := volume_type == "UPVOL/DNVOL" ? "USI:DNVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:DECL.DJ" unchanged := volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:UNCH.DJ" total := volume_type == "UPVOL/DNVOL" ? "USI:TVOL.DJ" : volume_type == "UVOL/DVOL" ? na : "USI:ACTV.DJ" else if (volume_source == "US") up := volume_type == "UPVOL/DNVOL" ? "USI:UPVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:ADVN.US" down := volume_type == "UPVOL/DNVOL" ? "USI:DNVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:DECL.US" unchanged := volume_type == "UPVOL/DNVOL" ? "USI:UNCHVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:UNCH.US" total := volume_type == "UPVOL/DNVOL" ? "USI:TVOL.US" : volume_type == "UVOL/DVOL" ? na : "USI:ACTV.US" // Calculations // request.security(symbol, timeframe, expression, gaps, lookahead, ignore_invalid_symbol, currency) // volume(up) / volume(total) returns a value is 0 to 1, 100 * volume(up) / volume(total) returns a percent 0 to 100% // Previous Day Close Percent Up-volume Calculations timeframe = input.string(defval = "Chart", title = "Timeframe", options = ["Chart", "Day", "Week", "Month"], inline = "Timeframe", group = "Plot Previous Day/Week/Month Volume") volumedayclose(x) => request.security(x, timeframe == "Day" ? "D" : timeframe == "Week" ? "W" : timeframe == "Month" ? "M" : timeframe.period, close) daypercentup = 100 * volumedayclose(up) / volumedayclose(total) daypercentdown = 100 * volumedayclose(down) / volumedayclose(total) daypercentunchanged = 100 * volumedayclose(unchanged) / volumedayclose(total) // Chart Time-Period Previous Period Close Up-volume Calculations volumeperiodclose(y) => request.security(y, timeframe.period, close) periodpercentup = 100 * volumeperiodclose(up) / volumeperiodclose(total) periodpercentdown = 100 * volumeperiodclose(down) / volumeperiodclose(total) periodpercentunchanged = 100 * volumeperiodclose(unchanged) / volumeperiodclose(total) // Plot Up, Down, or Unchanged daypercent = daypercentup if (volume_direction == "Upside") daypercent := daypercentup else if (volume_direction == "Downside") daypercent := daypercentdown else if (volume_direction == "Unchanged") daypercent := daypercentunchanged periodpercent = periodpercentup if (volume_direction == "Upside") periodpercent := periodpercentup else if (volume_direction == "Downside") periodpercent := periodpercentdown else if (volume_direction == "Unchanged") periodpercent := periodpercentunchanged // TABLE var table table_value = table.new(position.top_right, columns = 1, rows = 3) display_value_upside = periodpercentup display_value_downside = periodpercentdown if barstate.islast table.cell(table_value, column = 0, row = 0, text = volume_source, text_color = color.rgb(220, 223, 228, 0), text_halign = text.align_right, text_valign = text.align_center, text_size = size.small) table.cell(table_value, column = 0, row = 1, text = str.tostring(math.round(display_value_upside, 2)) + " % up", text_color = color.rgb(220, 223, 228, 0), text_halign = text.align_right, text_valign = text.align_center, text_size = size.small) table.cell(table_value, column = 0, row = 2, text = str.tostring(math.round(display_value_downside, 2)) + " % dn", text_color = color.rgb(220, 223, 228, 0), text_halign = text.align_right, text_valign = text.align_center, text_size = size.small) // Plot Previous Day Percent Up/Down/Unchanged Volume show_columns_daypercent = input(defval = false, title = "Columns", inline = "Day Columns", group = "Plot Previous Day/Week/Month Volume") show_line_daypercent = input(defval = false, title = "Line", inline = "Day Line", group = "Plot Previous Day/Week/Month Volume") show_area_daypercent = input(defval = false, title = "Area", inline = "Day Area", group = "Plot Previous Day/Week/Month Volume") plotcolor_daypercent_columns = daypercent >= 90 ? color.rgb(97, 175, 239, 10) : daypercent >= 80 and daypercent < 90 ? color.rgb(97, 175, 239, 30) : daypercent >= 70 and daypercent < 80 ? color.rgb(97, 175, 239, 50) : daypercent <= 30 and daypercent > 20 ? color.rgb(97, 175, 239, 50) : daypercent <= 20 and daypercent > 10 ? color.rgb(97, 175, 239, 30) : daypercent <= 10 ? color.rgb(97, 175, 239, 10) : color.rgb(97, 175, 239, 80) plotcolor_line_daypercent = color.rgb(97, 175, 239, 10) plotcolor_area_daypercent = color.rgb(97, 175, 239, 70) plot_columns_daypercent = plot(show_columns_daypercent ? daypercent : na, "Day Columns", plotcolor_daypercent_columns, style=plot.style_columns) plot_line_daypercent = plot(show_line_daypercent ? daypercent : na, "Day Line", plotcolor_line_daypercent, style=plot.style_line) plot_area_daypercent = plot(show_area_daypercent ? daypercent : na, "Day Area", plotcolor_area_daypercent, style=plot.style_area) // All Values Moving Average show_smoothed_daypercent = input(defval = false, title = "", inline = "Smoothing", group = "Plot Day/Week/Month Volume Moving Average") smoothed_daypercent_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA"], inline = "Smoothing", group = "Plot Day/Week/Month Volume Moving Average") smoothed_daypercent_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "Smoothing", group = "Plot Day/Week/Month Volume Moving Average") smoothed_daypercent = ma(daypercent, smoothed_daypercent_length, smoothed_daypercent_type) plotcolor_smoothed_daypercent = color.rgb(229, 192, 123, 0) plot_smoothed_daypercent = plot(show_smoothed_daypercent ? smoothed_daypercent : na, "Moving Average", plotcolor_smoothed_daypercent, style=plot.style_line) // High/Low Values Moving Averages daypercent_high = 0.00 daypercent_low = 0.00 if (volume_direction == "Upside") daypercent_high := daypercent >= smoothed_daypercent ? daypercentup : na daypercent_low := daypercent <= smoothed_daypercent ? daypercentup : na else if (volume_direction == "Downside") daypercent_high := daypercent >= smoothed_daypercent ? daypercentdown : na daypercent_low := daypercent <= smoothed_daypercent ? daypercentdown : na else if (volume_direction == "Unchanged") daypercent_high := daypercent >= smoothed_daypercent ? daypercentunchanged : na daypercent_low := daypercent <= smoothed_daypercent ? daypercentunchanged : na show_daypercent_high_ma = input(defval = true, title = "", inline = "High MA", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") daypercent_high_ma_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA"], inline = "High MA", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") daypercent_high_ma_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "High MA", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") show_daypercent_low_ma = input(defval = true, title = "", inline = "Low MA", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") daypercent_low_ma_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA"], inline = "Low MA", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") daypercent_low_ma_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "Low MA", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") daypercent_high_ma = ma(daypercent_high, daypercent_high_ma_length, daypercent_high_ma_type) daypercent_low_ma = ma(daypercent_low, daypercent_low_ma_length, daypercent_low_ma_type) plot_daypercent_high_ma = plot(show_daypercent_high_ma ? daypercent_high_ma : na, "Moving Average", color.rgb(97, 175, 239, 80), style=plot.style_line) plot_daypercent_low_ma = plot(show_daypercent_low_ma ? daypercent_low_ma : na, "Moving Average", color.rgb(97, 175, 239, 80), style=plot.style_line) show_daypercent_ma_fill = input(defval = true, title = "High/Low MA Fill", inline = "", group = "Plot Moving Averages of the High/Low Values--those values Above/Below the Moving Average of the values plotted") plot_daypercent_high_ma_fill = plot(show_daypercent_ma_fill ? daypercent_high_ma : na, "Moving Average", color.rgb(97, 175, 239, 90), style=plot.style_line) plot_daypercent_low_ma_fill = plot(show_daypercent_ma_fill ? daypercent_low_ma : na, "Moving Average", color.rgb(97, 175, 239, 90), style=plot.style_line) fill(plot1 = plot_daypercent_low_ma_fill, plot2 = plot_daypercent_high_ma_fill, title = "fill", editable = true, fillgaps = true, color = color.rgb(97, 175, 239, 90)) // Plot Chart Time-Period Previous Period Percent Up/Down/Unchanged Volume show_columns_periodpercent = input(defval = false, title = "Columns", inline = "Period Columns", group = "Plot Chart Timeframe Previous Period's Volume") show_line_periodpercent = input(defval = true, title = "Line", inline = "Period Line", group = "Plot Chart Timeframe Previous Period's Volume") show_area_periodpercent = input(defval = false, title = "Area", inline = "Period Area", group = "Plot Chart Timeframe Previous Period's Volume") plotcolor_periodpercent_columns = periodpercent >= 90 ? color.rgb(97, 175, 239, 10) : periodpercent >= 80 and periodpercent < 90 ? color.rgb(97, 175, 239, 30) : periodpercent >= 70 and periodpercent < 80 ? color.rgb(97, 175, 239, 50) : periodpercent <= 30 and periodpercent > 20 ? color.rgb(97, 175, 239, 50) : periodpercent <= 20 and periodpercent > 10 ? color.rgb(97, 175, 239, 30) : periodpercent <= 10 ? color.rgb(97, 175, 239, 10) : color.rgb(97, 175, 239, 80) plotcolor_line_periodpercent = color.rgb(97, 175, 239, 10) plotcolor_area_periodpercent = color.rgb(97, 175, 239, 70) plot_columns_periodpercent = plot(show_columns_periodpercent ? periodpercent : na, "Period Columns", plotcolor_periodpercent_columns, style=plot.style_columns) plot_line_periodpercent = plot(show_line_periodpercent ? periodpercent : na, "Period Line", plotcolor_line_periodpercent, style=plot.style_line) plot_area_periodpercent = plot(show_area_periodpercent ? periodpercent : na, "Period Area", plotcolor_area_periodpercent, style=plot.style_area) show_smoothed_periodpercent = input(defval = true, title = "", inline = "Period Smoothing", group = "Plot Period Volume Moving Average") smoothed_periodpercent_type = input.string(defval = "EMA", title = "", options = ["SMA", "EMA", "DEMA", "TEMA", "QEMA", "PEMA", "ZLEMA", "T3", "HMA", "SMMA", "WMA", "VWMA"], inline = "Period Smoothing", group = "Plot Period Volume Moving Average") smoothed_periodpercent_length = input.int(defval = 10, title = "", minval = 2, maxval = 2000, inline = "Period Smoothing", group = "Plot Period Volume Moving Average") smoothed_periodpercent = ma(periodpercent, smoothed_periodpercent_length, smoothed_periodpercent_type) plotcolor_smoothed_periodpercent = color.rgb(229, 192, 123, 0) plot_smoothed_periodpercent = plot(show_smoothed_periodpercent ? smoothed_periodpercent : na, "Period Moving Average", plotcolor_smoothed_periodpercent, style=plot.style_line) // Display Horizontal Lines obPlot = hline(103, title="Upper Band", linestyle=hline.style_solid, color=color.rgb(220, 223, 228, 95), linewidth=1) // white 220, 223, 228 hline(100, title="100% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 hline(90, title="90% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 50), linewidth=1) // white 220, 223, 228 hline(70, title="70% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 //hline(55, title="55% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 20), linewidth=1) // white 220, 223, 228 hline(50, title="50% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 20), linewidth=1) // white 220, 223, 228 //hline(45, title="45% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 20), linewidth=1) // white 220, 223, 228 hline(30, title="30% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 hline(10, title="10% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 50), linewidth=1) // white 220, 223, 228 hline(0, title="0% Level", linestyle=hline.style_dotted, color=color.rgb(220, 223, 228, 40), linewidth=1) // white 220, 223, 228 osPlot = hline(-3, title="Lower Band", linestyle=hline.style_solid, color=color.rgb(220, 223, 228, 95), linewidth=1) // white 220, 223, 228 fill(obPlot, osPlot, title="Background", color=color.rgb(220, 223, 228, 99)) // white 220, 223, 228 // NOTES // // COLOR SCHEMES // // ONE HALF DARK by Son A. Pham at github.com/sonph/onehalf // HEX RGB // black #282c34 40, 44, 52 // red #e06c75 224, 108, 117 // green #98c379 152, 195, 121 // yellow #e5c07b 229, 192, 123 // blue #61afef 97, 175, 239 // magenta #c678dd 198, 120, 221 // cyan #56b6c2 86, 182, 194 // white #dcdfe4 220, 223, 228 // foreground #dcdfe4 220, 223, 228 // background #282c34 40, 44, 52 // // // END
MACDh with divergences & impulse system
https://www.tradingview.com/script/f0Fj7aCr-MACDh-with-divergences-impulse-system/
jorgelg93
https://www.tradingview.com/u/jorgelg93/
183
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© jorgelg93 //@version=5 indicator(title="MACDh with divergences & impulse system", max_lines_count = 500, max_bars_back = 5000, overlay=false) buysignaltemp_divergencias = false sellsignaltemp_divergencias = false buysignalconfirmed = false sellsignalconfirmed = false var float dev_threshold_lows_def = 0 var float dev_threshold_highs_def = 0 var line lineLast_HistH = na //this is one of the lines we see on the chart var line lineLast_HistL = na //this is one of the lines we see on the chart var label labelLast_HistH = na //this is one of the lines we see on the chart var label labelLast_HistL = na //this is one of the lines we see on the chart var int histcruzodesdeabajoIndex_inmediato = 0 var int histcruzodesdearribaIndex_inmediato = 0 //variables to calculate Highs var int indexHistHighUltimo = 0 var int indexHistHighPenultimo = 0 var int indexHistHighAntepenultimo = 0 var int indexPriceHighUltimo = 0 var int indexPriceHighPenultimo = 0 var int indexPriceHighAntepenultimo = 0 //variables to calculate index Highs var float histHighUltimo = 0 var float histHighPenultimo = 0 var float histHighAntepenultimo = 0 var float priceHighUltimo = 0 var float priceHighPenultimo = 0 var float priceHighAntepenultimo = 0 //variables to calculate index Lows var int indexHistLowUltimo = 0 var int indexHistLowPenultimo = 0 var int indexHistLowAntepenultimo = 0 var int indexPriceLowUltimo = 0 var int indexPriceLowPenultimo = 0 var int indexPriceLowAntepenultimo = 0 //variables to calculate Lows var float histLowUltimo = 0 var float histLowPenultimo = 0 var float histLowAntepenultimo = 0 var float priceLowUltimo = 0 var float priceLowPenultimo = 0 var float priceLowAntepenultimo = 0 // Getting inputs fast_length = input(title="Fast Length", group="MACD", defval=12) slow_length = input(title="Slow Length", group="MACD", defval=26) signal_length = input.int(title="Signal Smoothing", group="MACD", defval = 9) PlotMACDandSignallines = input.bool(true, title="Plot Macd & Signal Lines?") plotImpulseSystem = input.bool(true, title="Show Impulse System over MACD histogram?") col_macd = #2962FF col_signal = #FF6D00 col_grow_above = #26A69A col_fall_above = #B2DFDB col_grow_below = #FFCDD2 col_fall_below = #FF5252 threshold_multiplier = input.float(title="Vertical deviation on Price peaks", group="MACD Histogram Divergences Criteria", defval=25, minval=0, tooltip = "Deviation refers to the difference/relation/vertical distance between the PRICE peaks involved in the divergence") hist_peaks_diff = input.float(title="Vertical deviation on MACD Histogram peaks", group="MACD Histogram Divergences Criteria", defval = 0, tooltip = "Refers to the difference/relation/vertical distance between the MACH HISTOGRAM peaks involved in the divergence: 1st Histogram Peak is X times the 2nd") minDivWidth = input.int(title="Divergence min width", group="MACD Histogram Divergences Criteria", defval = 0, tooltip = "Refers to the minimum horizontal distance between the MACH histogram peaks involved in the divergence") // minima_cantidad_de_barras_entre_los_picos maxDivWidth = input.int(title="Divergence max width", group="MACD Histogram Divergences Criteria", defval = 200, tooltip = "Refers to the maximum horizontal distance between the MACH histogram peaks involved in the divergence") // maxima_cantidad_de_barras_entre_los_picos plotBullDivergences = input.bool(true, title="Plot regular Bullish divergences?") plotBearDivergences = input.bool(true, title="Plot regular Bearish divergences?") deleteLastLines = input.bool(false, title="Delete Previous Cancelled Divergences?") plottempsignals = input.bool(true, title="Plot Temporary Buy/Sell Signals?") plotconfirmedsignals = input.bool(true, title="Plot Buy/Sell Confirmed Signals?") [macdLine, signalLine, hist] = ta.macd(close, fast_length,slow_length,signal_length) //================== impulse system =========================// [macdLine_impulse, signalLine_impulse, histline_impulse] = ta.macd(close, 12, 26, 9) ema_impulse = ta.ema(close, 13) //"13" es el periodo predeterminado de alex elder greenImpulse = close > ema_impulse and histline_impulse > histline_impulse[1] redImpulse = close < ema_impulse and histline_impulse < histline_impulse[1] blueImpulse = (close > ema_impulse and histline_impulse < histline_impulse[1]) or (close < ema_impulse and histline_impulse > histline_impulse[1]) //===========================================// //------ plot histogram ---------// hline(0, "Zero Line", color=color.new(#787B86, 50)) plot(PlotMACDandSignallines ? macdLine : na, title="MACD", color=col_macd) plot(PlotMACDandSignallines ? signalLine : na, title="Signal", color=col_signal) plot(hist, title="Histogram", style=plot.style_columns, color=(plotImpulseSystem and greenImpulse ? color.green : plotImpulseSystem and redImpulse ? color.red : plotImpulseSystem and blueImpulse ? color.blue : (hist>=0 and not plotImpulseSystem ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist and plotImpulseSystem ? col_grow_below : col_fall_below)))) //------ plot histogram ---------// //This verifies if the MACD histogram crossed over or under the 0 axis during the previous bar/candle histcruzoover = ta.crossover(hist[1],0) histcruzounder = ta.crossunder(hist[1],0) //This verifies if the MACD histogram crossed over or under the 0 axis during the current bar/candle histcruzoover_inmediato = ta.crossover(hist,0) histcruzounder_inmediato = ta.crossunder(hist,0) //======================= //calculate the deviation of prices calc_dev(base_price, price) => 100 * (price - base_price) / price //Calculate deviation threshold for identifying major swings dev_threshold_high = ta.atr(10) / high * 100 * threshold_multiplier dev_threshold_low = ta.atr(10) / low * 100 * threshold_multiplier //======================= //these lines save the bar_index if the histogram bar in this tick is crossing over or under if histcruzoover_inmediato histcruzodesdeabajoIndex_inmediato := bar_index if histcruzounder_inmediato histcruzodesdearribaIndex_inmediato := bar_index //======================= //the Bear cycle is officially closed in the previous bar and we have to analize and see if during that cycle there was some bullish divergence and rewrite the variables if histcruzoover // if histcruzoover and barstate.isconfirmed //it saves the penultimate high of the histogram histLowAntepenultimo := histLowPenultimo histLowPenultimo := histLowUltimo //it saves the price Lows priceLowAntepenultimo := priceLowPenultimo priceLowPenultimo := priceLowUltimo //it saves the "histogram indexes" indexHistLowAntepenultimo := indexHistLowPenultimo indexHistLowPenultimo := indexHistLowUltimo //it saves the "price indexes" indexPriceLowAntepenultimo := indexPriceLowPenultimo indexPriceLowPenultimo := indexPriceLowUltimo label.delete(labelLast_HistH) label.delete(labelLast_HistL) line.delete(lineLast_HistH) line.delete(lineLast_HistL) //for BULLISH DIVERGENCES dev2 = calc_dev(priceLowPenultimo, priceLowAntepenultimo) dev3 = priceLowAntepenultimo/priceLowPenultimo if ( plotBullDivergences and math.abs(dev2) < dev_threshold_lows_def and priceLowPenultimo < priceLowAntepenultimo and histLowPenultimo > histLowAntepenultimo and indexPriceLowPenultimo - indexPriceLowAntepenultimo >= minDivWidth and indexPriceLowPenultimo - indexPriceLowAntepenultimo <= maxDivWidth and indexHistLowPenultimo - indexHistLowAntepenultimo >= minDivWidth and indexHistLowPenultimo - indexHistLowAntepenultimo <= maxDivWidth and histLowAntepenultimo / histLowPenultimo >= hist_peaks_diff ) buysignalconfirmed := true top1 = line.new(indexHistLowAntepenultimo, histLowAntepenultimo, indexHistLowPenultimo, histLowPenultimo, color=color.green, width=2) plotshape(plotconfirmedsignals and buysignalconfirmed ? hist : na , style=shape.triangleup, text = "Bull \n confirmed", location=location.bottom, color=color.green, size=size.small) //the Bull cycle officially ended and we enter the Bear cycle now if histcruzounder // if histcruzounder and barstate.isconfirmed //it saves the penultimate high of the histogram histHighAntepenultimo := histHighPenultimo histHighPenultimo := histHighUltimo //it saves the price highs priceHighAntepenultimo := priceHighPenultimo priceHighPenultimo := priceHighUltimo //it saves the "histogram indexes" indexHistHighAntepenultimo := indexHistHighPenultimo indexHistHighPenultimo := indexHistHighUltimo //it saves the "price indexes" indexPriceHighAntepenultimo := indexPriceHighPenultimo indexPriceHighPenultimo := indexPriceHighUltimo label.delete(labelLast_HistH) label.delete(labelLast_HistL) line.delete(lineLast_HistH) line.delete(lineLast_HistL) //for BEARISH DIVERGENCES dev2 = calc_dev(priceHighPenultimo, priceHighAntepenultimo) dev3 = priceHighPenultimo/priceHighAntepenultimo if ( plotBearDivergences and math.abs(dev2) < dev_threshold_highs_def and priceHighPenultimo > priceHighAntepenultimo and histHighPenultimo < histHighAntepenultimo and indexPriceHighPenultimo - indexPriceHighAntepenultimo >= minDivWidth and indexPriceHighPenultimo - indexPriceHighAntepenultimo <= maxDivWidth and indexHistHighPenultimo - indexHistHighAntepenultimo >= minDivWidth and indexHistHighPenultimo - indexHistHighAntepenultimo <= maxDivWidth and histHighAntepenultimo / histHighPenultimo >= hist_peaks_diff ) sellsignalconfirmed := true top1 = line.new(indexHistHighAntepenultimo, histHighAntepenultimo, indexHistHighPenultimo, histHighPenultimo, color=color.red, width=2) plotshape(plotconfirmedsignals and sellsignalconfirmed ? hist : na, style=shape.triangledown,text = "Bear \n confirmed", location=location.top, color=color.red, size=size.small) //======================================= // PIVOTS highs function pivotsH(src1, src2) => c = nz(src1) // this could be the histogram, the price or any other value from any indicator c2 = nz(src2) //as long as the histogram is greater than zero I will be looking for higher highs (anyways, I believe this "if" could be redundant) if hist > 0 ind = bar_index - histcruzodesdeabajoIndex_inmediato //OK checker ok = true for i = 0 to ind if src1[i] > c // IF THE CURRENT BAR IS SMALLER OR LESS POSITIVE THAN ANY OF THE OTHER PREVIOUS BARS THEN THE PIVOT HIGH REMAINS INVALIDATED ok := false if ok // If pivot is valid, return bar index + high of price values; PIVOT WILL ALWAYS BE TRUE IF ITS INDEX IS SAVED AND ITS CORRESPONDENT HIGH OR LOW AS LONG AS IT DOES NOT REMAIN INVALIDATED IN THE ABOVE LINES [bar_index, c, bar_index, c2] else [int(na), float(na), int(na), float(na)] //======================================= //======================================= // Funcion PIVOTS lows pivotsL(src1, src2) => c = nz(src1) // this could be the histogram, the price or any other value from any indicator c2 = nz(src2) //as long as the histogram is lower than zero I will be looking for lower lows (anyways, I believe this "if" could be redundant) if hist < 0 ind = bar_index - histcruzodesdearribaIndex_inmediato //OK checker ok = true for i = 0 to ind if src1[i] < c // IF THE CURRENT BAR IS GREATER OR LESS NEGATIVE THAN ANY OF THE OTHER PREVIOUS BARS THEN THE PIVOT LOW REMAINS INVALIDATED ok := false if ok // If pivot is valid, return bar index + high price value; PIVOT WILL ALWAYS BE TRUE IF ITS INDEX IS SAVED AND ITS CORRESPONDENT HIGH OR LOW AS LONG AS IT DOES NOT REMAIN INVALIDATED IN THE ABOVE LINES [bar_index, c, bar_index, c2] else [int(na), float(na), int(na), float(na)] //======================================= //======================================= // FIND BEARISH DIVERGENCES by looking for higher highs of the histogram [iHist_H, pHist_H, indexPreciocuandoHistTieneHigherHigh, PreciocuandoHistTieneHigherHigh] = pivotsH(hist, high) //I want to know the histogram high [iPrice_H, pPrice_H, indexHistcuandoPrecioTieneHigherHigh, HistcuandoPrecioTieneHigherHigh] = pivotsH(high, hist) //I want to know the price high //if we have a valid pivot high, it saves the index and the value of that pivot high; this way the last pivot detected will always be saved if not na(iHist_H) indexHistHighUltimo := iHist_H histHighUltimo := pHist_H if not na(iPrice_H) indexPriceHighUltimo := iPrice_H priceHighUltimo := pPrice_H dev_threshold_highs_def := dev_threshold_high //I want to save the "threshold" of that maximum //======================================= //======================================= // FIND BULLISH DIVERGENCES by looking for lower lows of the histogram [iHist_L, pHist_L, indexPreciocuandoHistTieneLowerLow, PreciocuandoHistTieneLowerLow] = pivotsL(hist, low) //I want to know the histogram low [iPrice_L, pPrice_L, indexHistcuandoPrecioTieneLowerLow, HistcuandoPrecioTieneLowerLow] = pivotsL(low, hist) //I want to know the price low //if we have a valid pivot low, it saves the index and the value of that pivot low; this way the last pivot detected will always be saved if not na(iHist_L) indexHistLowUltimo := iHist_L histLowUltimo := pHist_L if not na(iPrice_L) indexPriceLowUltimo := iPrice_L priceLowUltimo := pPrice_L dev_threshold_lows_def := dev_threshold_low //I want to save the "threshold" of that minimum //======================================= //it calculates prices deviations dev300 = calc_dev(priceHighUltimo, priceHighPenultimo) dev301 = calc_dev(priceLowUltimo, priceLowPenultimo) dev33 = priceHighUltimo/priceHighPenultimo dev34 = priceLowPenultimo/priceLowUltimo if not na(iPrice_H) or not na(iHist_H) //it executes itself only when there is a new high of the price or a new high of the histogram // if not na(iPrice_H) or not na(iHist_H) and barstate.isconfirmed //it executes itself only when there is a new high of the price or a new high of the histogram //======================================= // to draw possible/temporary BEARISH DIVERGENCES if ( plotBearDivergences and math.abs(dev300) < dev_threshold_highs_def and priceHighUltimo > priceHighPenultimo and histHighUltimo < histHighPenultimo and indexPriceHighUltimo - indexPriceHighPenultimo >= minDivWidth and indexPriceHighUltimo - indexPriceHighPenultimo <= maxDivWidth and indexHistHighUltimo - indexHistHighPenultimo >= minDivWidth and indexHistHighUltimo - indexHistHighPenultimo <= maxDivWidth and histHighPenultimo / histHighUltimo >= hist_peaks_diff ) label.delete(labelLast_HistH) //it erases any previous label labelLast_HistH := label.new(indexHistHighUltimo, histHighUltimo, style= label.style_label_down, text = "Possible \n Bearish \n Div", color=color.red, size=size.small) // and rewrites line.delete(lineLast_HistH) // this erase all the temporary/possible bearish divergences that took place in the past lineLast_HistH := line.new(indexHistHighPenultimo, histHighPenultimo, indexHistHighUltimo, histHighUltimo, color=color.red, width=1, style=line.style_dashed) // and rewrites //these two lines draw dotted lines everytime that a temporary/possible bearish divergence takes place //as long as "deleteLastLines" is unmarked in the options for the script if not deleteLastLines lineLast_HistH_temp = line.new(indexHistHighPenultimo, histHighPenultimo, indexHistHighUltimo, histHighUltimo, color=color.red, width=1, style=line.style_dashed) sellsignaltemp_divergencias := true else // ERASES THE CANCELLED DIVERGENCES if ( plotBearDivergences and math.abs(dev300) > dev_threshold_highs_def or priceHighUltimo < priceHighPenultimo or histHighUltimo > histHighPenultimo or indexPriceHighUltimo - indexPriceHighPenultimo <= minDivWidth or indexPriceHighUltimo - indexPriceHighPenultimo >= maxDivWidth or indexHistHighUltimo - indexHistHighPenultimo <= minDivWidth or indexHistHighUltimo - indexHistHighPenultimo >= maxDivWidth or histHighPenultimo / histHighUltimo <= hist_peaks_diff ) label.delete(labelLast_HistH) line.delete(lineLast_HistH) if not na(iPrice_L) or not na(iHist_L) //it executes itself only when there is a new low of the price or a new low of the histogram // if not na(iPrice_L) or not na(iHist_L) and barstate.isconfirmed //it executes itself only when there is a new low of the price or a new low of the histogram //======================================= // to draw possible/temporary BULLISH DIVERGENCES if ( plotBullDivergences and math.abs(dev301) < dev_threshold_lows_def and priceLowUltimo < priceLowPenultimo and histLowUltimo > histLowPenultimo and indexPriceLowUltimo - indexPriceLowPenultimo >= minDivWidth and indexPriceLowUltimo - indexPriceLowPenultimo <= maxDivWidth and indexHistLowUltimo - indexHistLowPenultimo >= minDivWidth and indexHistLowUltimo - indexHistLowPenultimo <= maxDivWidth and histLowPenultimo / histLowUltimo >= hist_peaks_diff ) label.delete(labelLast_HistL) //it erases any previous label labelLast_HistL := label.new(indexHistLowUltimo, histLowUltimo, style= label.style_label_up, text = "Possible \n Bullish \n Div", color=color.green, size=size.small) //and rewrites line.delete(lineLast_HistL) //it erases any other temporary/possible bullish divergence that took place in the past lineLast_HistL := line.new(indexHistLowPenultimo, histLowPenultimo, indexHistLowUltimo, histLowUltimo, color=color.green, width=1, style=line.style_dashed) // and rewrites //these two lines draw dotted lines everytime that a temporary/possible bullish divergence takes place // as long as "deleteLastLines" is unmarked in the options for the script if not deleteLastLines lineLast_HistL_temp = line.new(indexHistLowPenultimo, histLowPenultimo, indexHistLowUltimo, histLowUltimo, color=color.green, width=1, style=line.style_dashed) buysignaltemp_divergencias := true else // ERASES THE CANCELLED DIVERGENCES if ( plotBullDivergences and math.abs(dev301) > dev_threshold_lows_def or priceLowUltimo > priceLowPenultimo or histLowUltimo < histLowPenultimo or indexPriceLowUltimo - indexPriceLowPenultimo <= minDivWidth or indexPriceLowUltimo - indexPriceLowPenultimo >= maxDivWidth or indexHistLowUltimo - indexHistLowPenultimo <= minDivWidth or indexHistLowUltimo - indexHistLowPenultimo >= maxDivWidth or histLowPenultimo / histLowUltimo <= hist_peaks_diff ) label.delete(labelLast_HistL) line.delete(lineLast_HistL) buy_beautiful_temp_div = (buysignaltemp_divergencias) or (buysignaltemp_divergencias[1] and (low > low[1] or hist > hist[1]) and histLowUltimo > histLowPenultimo) or (buysignaltemp_divergencias[2] and ((low > low[2] and low[1] > low[2]) or (hist > hist[2] and hist[1] > hist[2])) and histLowUltimo > histLowPenultimo) or (buysignaltemp_divergencias[3] and ((low > low[3] and low[1] > low[3] and low[2] > low[3]) or ( hist > hist[3] and hist[1] > hist[3] and hist[2] > hist[3])) and histLowUltimo > histLowPenultimo) sell_beautiful_temp_div = (sellsignaltemp_divergencias) or (sellsignaltemp_divergencias[1] and (high < high[1] or hist < hist[1]) and histHighUltimo < histHighPenultimo) or (sellsignaltemp_divergencias[2] and ((high < high[2] and high[1] < high[2]) or (hist < hist[2] and hist[1] < hist[2])) and histHighUltimo < histHighPenultimo) or (sellsignaltemp_divergencias[3] and ((high < high[3] and high[1] < high[3] and high[2] < high[3]) or (hist < hist[3] and hist[1] < hist[3] and hist[2] < hist[3])) and histHighUltimo < histHighPenultimo) plotshape(plottempsignals and sell_beautiful_temp_div ? hist : na , style=shape.triangledown, location=location.top, color=color.rgb(255, 82, 82, 50), size=size.small) plotshape(plottempsignals and buy_beautiful_temp_div ? hist : na , style=shape.triangleup, location=location.bottom, color=color.rgb(76, 175, 79, 50), size=size.small) //END
Volume [Entoryx]
https://www.tradingview.com/script/Lx5KC28V-Volume-Entoryx/
Entoryx
https://www.tradingview.com/u/Entoryx/
28
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Entoryx //@version=5 indicator("Volume [Entoryx]") n=input(100,"Bars lenth") highest=ta.highest(high,n) lowest=ta.lowest(low,n) delta=highest-lowest current_value=-(open-close)/delta*100 color1=color.new(color.white,0) color2=color.white if close>ta.ema(close,n) color1:=color.new(color.green,0) color2:=color.green else color1:=color.new(color.red,0) color2:=color.red zero=plot(0,color=color.new(color.white,100)) plot(10,color = color.new(color.yellow,0)) plot(-10,color = color.new(color.yellow,0)) current=plot(current_value, color = color1) fill(plot1 = current, plot2 = zero, color=color.new(color2,90)) change=input(false,"Order block bar detection") if current_value[1]>10 and current_value<-10 and current_value>-20 and change==true label.new(bar_index, current_value-10, style=label.style_triangleup, color=color.yellow, textcolor=color.white, size = size.tiny) if current_value[1]<-10 and current_value>10 and current_value<20 and change==true label.new(bar_index, current_value+10, style=label.style_triangledown, color=color.yellow, textcolor=color.white, size = size.tiny)
Candlestick Patterns Screener [By MUQWISHI]
https://www.tradingview.com/script/xiWQuGOq-Candlestick-Patterns-Screener-By-MUQWISHI/
MUQWISHI
https://www.tradingview.com/u/MUQWISHI/
213
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© MUQWISHI //@version=5 indicator("Candle Patterns Screener", overlay = true) import MUQWISHI/CandlestickPatterns/2 as cp // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | INPUT | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // +++++++ Table Settings // Location tablePos = input.string("Middle Right", "Table Location", ["Top Right", "Middle Right" , "Bottom Right" , "Top Center", "Middle Center" , "Bottom Center", "Top Left" , "Middle Left" , "Bottom Left" ], inline = "1", group = "Table Setting") // Size tableSiz = input.string("Small", " Size", ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], inline = "1", group = "Table Setting") // Timezone timzon = input.string("GMT-4", "Timezone  ", group = "Table Setting", inline = "2") // Number of rows rowNum = input.int(20, " β„– of Rows   ‏", 0, 100, group = "Table Setting", inline = "3") // Table Color tBgCol = input.color(#696969, "   Titles ‏ ‏", group = "Table Setting", inline = "2") txtCol = input.color(#ffffff, "   Text  ", group = "Table Setting" , inline = "3") bulCol = input.color(#006400, "Bullish", group = "Table Setting" , inline = "4") berCol = input.color(#882336, "  Bearish", group = "Table Setting" , inline = "4") neuCol = input.color(#929191, "  Neutral", group = "Table Setting" , inline = "4") // +++++++ Technical Settings // Moving Average maChk = input.bool(true, "Detect Trend Based on SMA", inline = "0", group = "Technical") maLen = input.int(50, "", 1, inline = "0", group = "Technical") // +++++++ Candle Patterns // Type ptrnTyp = input.string("Both", "Pattern Type", ["Bullish", "Bearish", "Both"], group = "Candle Patterns") // Patterns abandonedBabyChk = input.bool(true, "Abandoned Baby", group = "Candle Patterns", inline = "01") dbarkCloudCoverChk = input.bool(true, "Dark Cloud Cover", group = "Candle Patterns", inline = "01") dojiChk = input.bool(true, "Doji", group = "Candle Patterns", inline = "02") dojiStarChk = input.bool(true, "Doji Star", group = "Candle Patterns", inline = "02") downsideTasukiGapChk = input.bool(true, "Downside Tasuki Gap", group = "Candle Patterns", inline = "02") dragonflyDojiChk = input.bool(true, "Dragonfly Doji", group = "Candle Patterns", inline = "03") engulfingChk = input.bool(true, "Engulfing", group = "Candle Patterns", inline = "03") eveningDojiStarChk = input.bool(true, "Evening Doji Star", group = "Candle Patterns", inline = "03") eveningStarChk = input.bool(true, "Evening Star", group = "Candle Patterns", inline = "04") fallingThreeMethodsChk = input.bool(true, "Falling Three Methods", group = "Candle Patterns", inline = "04") fallingWindowChk = input.bool(true, "Falling Window", group = "Candle Patterns", inline = "05") gravestoneDojiChk = input.bool(true, "Gravestone Doji", group = "Candle Patterns", inline = "05") hammerChk = input.bool(true, "Hammer", group = "Candle Patterns", inline = "05") hangingManChk = input.bool(true, "Hanging Man", group = "Candle Patterns", inline = "06") haramiCrossChk = input.bool(true, "Harami Cross", group = "Candle Patterns", inline = "06") haramiChk = input.bool(true, "Harami", group = "Candle Patterns", inline = "06") invertedHammerChk = input.bool(true, "Inverted Hammer", group = "Candle Patterns", inline = "07") kickingChk = input.bool(true, "Kicking", group = "Candle Patterns", inline = "07") longLowerShadowChk = input.bool(true, "Long Lower Shadow", group = "Candle Patterns", inline = "08") longUpperShadowChk = input.bool(true, "Long Upper Shadow", group = "Candle Patterns", inline = "08") marubozuBlackChk = input.bool(true, "Marubozu Black", group = "Candle Patterns", inline = "09") marubozuWhiteChk = input.bool(true, "Marubozu White", group = "Candle Patterns", inline = "09") morningDojiStarChk = input.bool(true, "Morning Doji Star", group = "Candle Patterns", inline = "10") morningStarChk = input.bool(true, "Morning Star", group = "Candle Patterns", inline = "10") onNeckChk = input.bool(true, "On Neck", group = "Candle Patterns", inline = "10") piercingChk = input.bool(true, "Piercing", group = "Candle Patterns", inline = "11") risingThreeMethodsChk = input.bool(true, "Rising Three Methods", group = "Candle Patterns", inline = "11") risingWindowChk = input.bool(true, "Rising Window", group = "Candle Patterns", inline = "12") shootingStarChk = input.bool(true, "Shooting Star ", group = "Candle Patterns", inline = "12") spinningTopBlackChk = input.bool(true, "Spinning Top Black", group = "Candle Patterns", inline = "13") spinningTopWhiteChk = input.bool(true, "Spinning Top White", group = "Candle Patterns", inline = "13") threeBlackCrowsChk = input.bool(true, "Three Black Crows", group = "Candle Patterns", inline = "14") threeWhiteSoldiersChk = input.bool(true, "Three White Soldiers", group = "Candle Patterns", inline = "14") triStarChk = input.bool(true, "Tri-Star", group = "Candle Patterns", inline = "15") tweezerBottomChk = input.bool(true, "Tweezer Bottom", group = "Candle Patterns", inline = "15") tweezerTopChk = input.bool(true, "Tweezer Top", group = "Candle Patterns", inline = "15") upsideTasukiGapChk = input.bool(true, "Upside Tasuki Gap", group = "Candle Patterns", inline = "16") // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | SYMBOLS | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Symbols Checkmark c01 = input.bool(true, "", group = "Symbols", inline = "s01") c02 = input.bool(true, "", group = "Symbols", inline = "s02") c03 = input.bool(true, "", group = "Symbols", inline = "s03") c04 = input.bool(true, "", group = "Symbols", inline = "s04") c05 = input.bool(true, "", group = "Symbols", inline = "s05") c06 = input.bool(true, "", group = "Symbols", inline = "s06") c07 = input.bool(true, "", group = "Symbols", inline = "s07") c08 = input.bool(true, "", group = "Symbols", inline = "s08") c09 = input.bool(true, "", group = "Symbols", inline = "s09") c10 = input.bool(true, "", group = "Symbols", inline = "s10") c11 = input.bool(true, "", group = "Symbols", inline = "s11") c12 = input.bool(true, "", group = "Symbols", inline = "s12") c13 = input.bool(true, "", group = "Symbols", inline = "s13") c14 = input.bool(true, "", group = "Symbols", inline = "s14") c15 = input.bool(true, "", group = "Symbols", inline = "s15") c16 = input.bool(true, "", group = "Symbols", inline = "s16") c17 = input.bool(true, "", group = "Symbols", inline = "s17") c18 = input.bool(true, "", group = "Symbols", inline = "s18") c19 = input.bool(true, "", group = "Symbols", inline = "s19") c20 = input.bool(true, "", group = "Symbols", inline = "s20") c21 = input.bool(true, "", group = "Symbols", inline = "s21") c22 = input.bool(true, "", group = "Symbols", inline = "s22") c23 = input.bool(true, "", group = "Symbols", inline = "s23") c24 = input.bool(true, "", group = "Symbols", inline = "s24") c25 = input.bool(true, "", group = "Symbols", inline = "s25") c26 = input.bool(true, "", group = "Symbols", inline = "s26") c27 = input.bool(true, "", group = "Symbols", inline = "s27") c28 = input.bool(true, "", group = "Symbols", inline = "s28") c29 = input.bool(true, "", group = "Symbols", inline = "s29") c30 = input.bool(true, "", group = "Symbols", inline = "s30") c31 = input.bool(true, "", group = "Symbols", inline = "s31") c32 = input.bool(true, "", group = "Symbols", inline = "s32") c33 = input.bool(true, "", group = "Symbols", inline = "s33") c34 = input.bool(true, "", group = "Symbols", inline = "s34") c35 = input.bool(true, "", group = "Symbols", inline = "s35") c36 = input.bool(false, "", group = "Symbols", inline = "s36") c37 = input.bool(false, "", group = "Symbols", inline = "s37") c38 = input.bool(false, "", group = "Symbols", inline = "s38") c39 = input.bool(false, "", group = "Symbols", inline = "s39") c40 = input.bool(false, "", group = "Symbols", inline = "s40") // Symbol Input s01 = input.symbol("QQQ", "", group = "Symbols", inline = "s01") s02 = input.symbol("TSLA", "", group = "Symbols", inline = "s02") s03 = input.symbol("AAPL", "", group = "Symbols", inline = "s03") s04 = input.symbol("META", "", group = "Symbols", inline = "s04") s05 = input.symbol("AMZN", "", group = "Symbols", inline = "s05") s06 = input.symbol("MSFT", "", group = "Symbols", inline = "s06") s07 = input.symbol("NVDA", "", group = "Symbols", inline = "s07") s08 = input.symbol("AMD", "", group = "Symbols", inline = "s08") s09 = input.symbol("OXY", "", group = "Symbols", inline = "s09") s10 = input.symbol("NIO", "", group = "Symbols", inline = "s10") s11 = input.symbol("RIVN", "", group = "Symbols", inline = "s11") s12 = input.symbol("PYPL", "", group = "Symbols", inline = "s12") s13 = input.symbol("PLUG", "", group = "Symbols", inline = "s13") s14 = input.symbol("ZM", "", group = "Symbols", inline = "s14") s15 = input.symbol("AMC", "", group = "Symbols", inline = "s15") s16 = input.symbol("GME", "", group = "Symbols", inline = "s16") s17 = input.symbol("BABA", "", group = "Symbols", inline = "s17") s18 = input.symbol("LCID", "", group = "Symbols", inline = "s18") s19 = input.symbol("AAL", "", group = "Symbols", inline = "s19") s20 = input.symbol("RBLX", "", group = "Symbols", inline = "s20") s21 = input.symbol("NFLX", "", group = "Symbols", inline = "s21") s22 = input.symbol("XPEV", "", group = "Symbols", inline = "s22") s23 = input.symbol("CCL", "", group = "Symbols", inline = "s23") s24 = input.symbol("BILI", "", group = "Symbols", inline = "s24") s25 = input.symbol("UBER", "", group = "Symbols", inline = "s25") s26 = input.symbol("GOOG", "", group = "Symbols", inline = "s26") s27 = input.symbol("JNJ", "", group = "Symbols", inline = "s27") s28 = input.symbol("UNH", "", group = "Symbols", inline = "s28") s29 = input.symbol("V", "", group = "Symbols", inline = "s29") s30 = input.symbol("XOM", "", group = "Symbols", inline = "s30") s31 = input.symbol("JPM", "", group = "Symbols", inline = "s31") s32 = input.symbol("MA", "", group = "Symbols", inline = "s32") s33 = input.symbol("WMT", "", group = "Symbols", inline = "s33") s34 = input.symbol("CVX", "", group = "Symbols", inline = "s34") s35 = input.symbol("PFE", "", group = "Symbols", inline = "s35") s36 = input.symbol("HD", "", group = "Symbols", inline = "s36") s37 = input.symbol("BAC", "", group = "Symbols", inline = "s37") s38 = input.symbol("LLY", "", group = "Symbols", inline = "s38") s39 = input.symbol("KO", "", group = "Symbols", inline = "s39") s40 = input.symbol("SPCE", "", group = "Symbols", inline = "s40") // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | CALCULATION | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| bull = not(ptrnTyp == "Bearish") bear = not(ptrnTyp == "Bullish") main(flg) => uTrd = maChk ? close > ta.sma(close, maLen) : true dTrd = maChk ? close < ta.sma(close, maLen) : true prc = float(na), tim = int(na), pt = "", typ = int(na) if flg and barstate.isconfirmed if fallingThreeMethodsChk and cp.fallingThreeMethods() and bear and dTrd[4] pt := "Falling Three Methods", typ := -1 else if risingThreeMethodsChk and cp.risingThreeMethods() and bull and uTrd[4] pt := "Rising Three Methods", typ := 1 else if abandonedBabyChk and cp.abandonedBaby("bull") and bull and dTrd[2] pt := "Abandoned Baby", typ := 1 else if abandonedBabyChk and cp.abandonedBaby("bear") and bear and uTrd[2] pt := "Abandoned Baby", typ := -1 else if downsideTasukiGapChk and cp.downsideTasukiGap() and bear and dTrd pt := "Downside Tasuki Gap", typ := -1 else if eveningDojiStarChk and cp.eveningDojiStar() and bear and uTrd pt := "Evening Doji Star", typ := -1 else if eveningStarChk and cp.eveningStar() and bear and uTrd pt := "Evening Star", typ := -1 else if morningDojiStarChk and cp.morningDojiStar() and bull and dTrd pt := "Morning Doji Star", typ := 1 else if morningStarChk and cp.morningStar() and bull and dTrd pt := "Morning Star", typ := 1 else if threeBlackCrowsChk and cp.threeBlackCrows() and bear pt := "Three Black Crows", typ := -1 else if threeWhiteSoldiersChk and cp.threeWhiteSoldiers() and bull pt := "Three White Soldiers", typ := 1 else if triStarChk and cp.triStar("bear") and bear and uTrd[2] pt := "Tri Star", typ := -1 else if triStarChk and cp.triStar("bull") and bull and dTrd[2] pt := "Tri Star", typ := 1 else if upsideTasukiGapChk and cp.upsideTasukiGap() and bull and uTrd pt := "Upside Tasuki Gap", typ := 1 else if dbarkCloudCoverChk and cp.darkCloudCover() and bear and uTrd[1] pt := "Dark Cloud Cover", typ := -1 else if dojiStarChk and cp.dojiStar("bear") and bear and uTrd pt := "Doji Star", typ := -1 else if dojiStarChk and cp.dojiStar("bull") and bull and dTrd pt := "Doji Star", typ := 1 else if engulfingChk and cp.engulfing("bull") and bull and dTrd pt := "Engulfing", typ := 1 else if engulfingChk and cp.engulfing("bear") and bear and uTrd pt := "Engulfing", typ := -1 else if fallingWindowChk and cp.fallingWindow() and bear and dTrd[1] pt := "Falling Window", typ := -1 else if haramiCrossChk and cp.haramiCross("bull") and bull and dTrd[1] pt := "Harami Cross", typ := 1 else if haramiCrossChk and cp.haramiCross("bear") and bear and uTrd[1] pt := "Harami Cross", typ := -1 else if haramiChk and cp.harami("bull") and bull and dTrd[1] pt := "Harami", typ := 1 else if haramiChk and cp.harami("bear") and bear and uTrd[1] pt := "Harami", typ := -1 else if kickingChk and cp.kicking("bull") and bull pt := "Kicking", typ := 1 else if kickingChk and cp.kicking("bear") and bear pt := "Kicking", typ := -1 else if onNeckChk and cp.onNeck() and bear and dTrd pt := "On Neck", typ := -1 else if piercingChk and cp.piercing() and bull and dTrd[1] pt := "Piercing", typ := 1 else if risingWindowChk and cp.risingWindow() and bull and uTrd[1] pt := "Rising Window", typ := 1 else if tweezerBottomChk and cp.tweezerBottom() and bull and dTrd[1] pt := "Tweezer Bottom", typ := 1 else if tweezerTopChk and cp.tweezerTop() and bear and uTrd[1] pt := "Tweezer Top", typ := -1 else if dojiChk and cp.doji() pt := "Doji", typ := 0 else if dragonflyDojiChk and cp.dragonflyDoji() and bull pt := "Dragon Fly Doji", typ := 1 else if gravestoneDojiChk and cp.gravestoneDoji() and bear pt := "Gravestone Doji", typ := -1 else if hammerChk and cp.hammer() and bull and dTrd pt := "Hammer", typ := 1 else if hangingManChk and cp.hangingMan() and bear and uTrd pt := "Hanging Man", typ := -1 else if invertedHammerChk and cp.invertedHammer() and bull and dTrd pt := "Inverted Hammer", typ := 1 else if longLowerShadowChk and cp.longLowerShadow() and bull pt := "Long Lower Shadow", typ := 1 else if longUpperShadowChk and cp.longUpperShadow() and bear pt := "Long Upper Shadow", typ := -1 else if marubozuBlackChk and cp.marubozuBlack() and bear pt := "Marubozu Black", typ := -1 else if marubozuWhiteChk and cp.marubozuWhite() and bull pt := "Marubozu White", typ := 1 else if shootingStarChk and cp.shootingStar() and bear and uTrd pt := "Shooting Star", typ := -1 else if spinningTopBlackChk and cp.spinningTopBlack() pt := "Spinning Top Black", typ := 0 else if spinningTopWhiteChk and cp.spinningTopWhite() pt := "Spinning Top White", typ := 0 if not na(typ) prc := math.round_to_mintick(close) tim := time [prc, pt, tim, typ] // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | SCREENER | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Get Time Format timForm(x) => timeframe.isintraday ? str.format_time(x, "HH:mm MM-dd-yyyy", timzon) : str.format_time(x, "MM-dd-yyyy", timzon) // Get Symbol Name symbol(s) => array.get(str.split(s, ":"), 1) // Set Up Matrix var mtx = matrix.new<string>(0, 5, na) mtxFun(symbol, price, pattern, tim, typ) => matrix.add_row(mtx, 0, array.from(symbol, price, pattern, tim, typ)) // Screener Function screenerFun(s, flg) => sym = ticker.modify(s, syminfo.session) [prc, pt, tim, typ] = request.security(sym, timeframe.period, main(flg)) if flg if not na(typ) and tim == time mtxFun(symbol(s), str.tostring(prc), pt, timForm(tim), str.tostring(typ)) // Call Symbols screenerFun(s01, c01), screenerFun(s02, c02), screenerFun(s03, c03), screenerFun(s04, c04), screenerFun(s05, c05), screenerFun(s06, c06), screenerFun(s07, c07), screenerFun(s08, c08), screenerFun(s09, c09), screenerFun(s10, c10), screenerFun(s11, c11), screenerFun(s12, c12), screenerFun(s13, c13), screenerFun(s14, c14), screenerFun(s15, c15), screenerFun(s16, c16), screenerFun(s17, c17), screenerFun(s18, c18), screenerFun(s19, c19), screenerFun(s20, c20), screenerFun(s21, c21), screenerFun(s22, c22), screenerFun(s23, c23), screenerFun(s24, c24), screenerFun(s25, c25), screenerFun(s26, c26), screenerFun(s27, c27), screenerFun(s28, c28), screenerFun(s29, c29), screenerFun(s30, c30), screenerFun(s31, c31), screenerFun(s32, c32), screenerFun(s33, c33), screenerFun(s34, c34), screenerFun(s35, c35), screenerFun(s36, c36), screenerFun(s37, c37), screenerFun(s38, c38), screenerFun(s39, c39), screenerFun(s40, c40), if matrix.rows(mtx) > rowNum while matrix.rows(mtx) > rowNum matrix.remove_row(mtx, matrix.rows(mtx)-1) // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | TABLE | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // Get Tbale Location & Size locNsze(x) => y = str.split(str.lower(x), " ") out = "" for i = 0 to array.size(y) - 1 out := out + array.get(y, i) if i != array.size(y) - 1 out := out + "_" out // Create Table var tbl = table.new(locNsze(tablePos), 4, 102, frame_width = 1, frame_color = color.new(tBgCol, 100), border_width = 1, border_color = color.new(tBgCol, 100)) // Cell Function cell(col, row, txt, color) => table.cell(tbl, col, row, text = txt, text_color = txtCol, bgcolor = color, text_size = locNsze(tableSiz)) if barstate.islast table.clear(tbl, 0, 0, 3, 101) cell(0, 0, "Symbol", tBgCol) cell(1, 0, "Price", tBgCol) cell(2, 0, "Pattern" , tBgCol) cell(3, 0, "Signal Time", tBgCol) j = 1 if matrix.rows(mtx) > 0 for i = 0 to matrix.rows(mtx) - 1 col = matrix.get(mtx, i, 4) == "1" ? bulCol : matrix.get(mtx, i, 4) == "-1" ? berCol : neuCol cell(0, j, matrix.get(mtx, i, 0), tBgCol) cell(1, j, matrix.get(mtx, i, 1), col) cell(2, j, matrix.get(mtx, i, 2), col) cell(3, j, matrix.get(mtx, i, 3), col) j += 1
Bars Above/Below Donchian Channel [ScalpTradr]
https://www.tradingview.com/script/vvHzjlgJ-Bars-Above-Below-Donchian-Channel-ScalpTradr/
scalptradr
https://www.tradingview.com/u/scalptradr/
63
study
5
CC-BY-NC-SA-4.0
// 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/ // Β©ScalpTradr //@version=5 indicator("Bars Above/Below Donchian Channel [ScalpTradr]", shorttitle="ST AB Donchian", overlay=true) colorPriceBars = input(false, "Color price bars") length = input(20, title="Length of Donchian Channel") // Calculate Donchian Channel upper_channel = ta.highest(high, length) lower_channel = ta.lowest(low, length) basis = (upper_channel + lower_channel) / 2 // Count Bars above or below var int aboveCount = 0 var int belowCount = 0 // Label IDs var label aboveLabel = na var label belowLabel = na if close > basis if na(aboveCount) or close[1] <= basis[1] aboveCount := 1 else aboveCount := aboveCount + 1 if na(aboveLabel) aboveLabel := label.new(bar_index, high, text = str.tostring(aboveCount), color=color.green, textcolor=color.white, style=label.style_label_down, yloc = yloc.price) else label.set_xy(aboveLabel, bar_index, upper_channel) label.set_text(aboveLabel, str.tostring(aboveCount)) else aboveCount := na if close < basis if na(belowCount) or close[1] >= basis[1] belowCount := 1 else belowCount := belowCount + 1 if na(belowLabel) belowLabel := label.new(bar_index, low, text = str.tostring(belowCount), color=color.red, textcolor=color.white, style=label.style_label_up, yloc = yloc.price) else label.set_xy(belowLabel, bar_index, lower_channel) label.set_text(belowLabel, str.tostring(belowCount)) else belowCount := na plot(upper_channel, color=color.blue, title='Bollinger bands upper') plot(lower_channel, color=color.blue, title='Bollinger bands lower') plot(basis, color=color.orange, title='Bollinger bands basis') // If option enabled color the price bars red or green depening on if price closes below or above basis barcolor(colorPriceBars ? close < basis ? color.red : color.green : na)
ICT Institutional Order Flow (fadi)
https://www.tradingview.com/script/RoK9cao8-ICT-Institutional-Order-Flow-fadi/
fadizeidan
https://www.tradingview.com/u/fadizeidan/
997
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© fadizeidan // // // Displacement logic Credit: Visualizing Displacement [TFO] // https://www.tradingview.com/script/n6djFgQH-Visualizing-Displacement-TFO/ // FTO creates other great indicators that I personally use. //@version=5 indicator("ICT Institutional Order Flow (fadi)", overlay=true, max_bars_back = 5000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500) //+------------------------------------------------------------------------------------------------------------+// //+--- Types ---+// //+------------------------------------------------------------------------------------------------------------+// type Settings string liquidity_open_style string liquidity_claimed_style bool ST_show string ST_text_size color ST_color_bull color ST_color_bear color ST_label_color bool ST_liquidity_show color ST_liquidity_open_color int ST_liquidity_size color ST_liquidity_claimed_color bool IT_show string IT_text_size color IT_color_bull color IT_color_bear color IT_label_color bool IT_liquidity_show color IT_liquidity_open_color int IT_liquidity_size color IT_liquidity_claimed_color bool LT_show string LT_text_size color LT_color_bull color LT_color_bear color LT_label_color bool LT_liquidity_show color LT_liquidity_open_color int LT_liquidity_size color LT_liquidity_claimed_color int max_labels bool liquidity_open_show int max_lines int extend bool displacement_show bool displacement_fvg int displacement_length int displacement_factor color displacement_bull color displacement_bear type Imbalance_Settings bool show color color_bull color color_bear bool CE_show string CE_style color CE_color string fvg_type bool mitigated_show string mitigated_type color mitigated_color_bull color mitigated_color_bear int max_count type Pivot int time = 0 float price = 0 int time_last = 0 bool claimed = false bool isHigh = na string lbl_text = "" label lbl = na line ln = na type MarketStructure string name Pivot[] ST Pivot[] IT Pivot[] LT Pivot[] STH Pivot[] ITH Pivot[] STL Pivot[] ITL Settings settings type Imbalance int open_time int close_time float open float middle float close bool mitigated int mitigated_time line line_middle box box type ImbalanceStructure Imbalance[] imbalance Imbalance_Settings settings type Helper string name = "Helper" //+------------------------------------------------------------------------------------------------------------+// //+--- Settings ---+// //+------------------------------------------------------------------------------------------------------------+// int MAX_BUFFER = 500 // internal maximum node count limit for performance ICT_Group = "ICT Market Structure" settings_liquidity = "Liquidity" settings_liquidity_style = "Liquidity Style" settings_displacement = "Displacement" FVG_Group = "Fair Value Gap" Imb_Group = "Volume Imbalance" Gap_Group = "Open Gaps" inline_st = "ST" inline_st_liquidity = "ST liquidity" inline_it = "IT" inline_it_liquidity = "IT liquidity" inline_lt = "LT" inline_lt_liquidity = "LT liquidity" inline_liquidity_open = "open liquidity" inline_liquidity_claimed = "claimed liquidity" inline_displacement = "displacement" Settings Trend_Settings = Settings.new() Imbalance_Settings FVG_Settings = Imbalance_Settings.new() Imbalance_Settings VI_Settings = Imbalance_Settings.new() Imbalance_Settings Gap_Settings = Imbalance_Settings.new() Trend_Settings.ST_show := input.bool(false, "Short      ", group=ICT_Group, inline=inline_st) Trend_Settings.ST_text_size := input.string(size.tiny, "", [size.tiny, size.small, size.normal, size.large, size.huge], group=ICT_Group, inline=inline_st) Trend_Settings.ST_color_bull := input.color(color.black, "", group=ICT_Group, inline=inline_st) Trend_Settings.ST_color_bear := input.color(color.black, "", group=ICT_Group, inline=inline_st) Trend_Settings.ST_label_color := input.color(#ffffff00, "",group=ICT_Group, inline=inline_st) Trend_Settings.IT_show := input.bool(true, "Intermediate", group=ICT_Group, inline=inline_it) Trend_Settings.IT_text_size := input.string(size.small, "", [size.tiny, size.small, size.normal, size.large, size.huge], group=ICT_Group, inline=inline_it) Trend_Settings.IT_color_bull := input.color(color.purple, "", group=ICT_Group, inline=inline_it) Trend_Settings.IT_color_bear := input.color(color.purple, "", group=ICT_Group, inline=inline_it) Trend_Settings.IT_label_color := input.color(#ffffff00, "",group=ICT_Group, inline=inline_it) Trend_Settings.LT_show := input.bool(true, "Long       ", group=ICT_Group, inline=inline_lt) Trend_Settings.LT_text_size := input.string(size.normal, "", [size.tiny, size.small, size.normal, size.large, size.huge], group=ICT_Group, inline=inline_lt) Trend_Settings.LT_color_bull := input.color(color.blue, "", group=ICT_Group, inline=inline_lt) Trend_Settings.LT_color_bear := input.color(color.blue, "", group=ICT_Group, inline=inline_lt) Trend_Settings.LT_label_color := input.color(#ffffff00, "", group=ICT_Group, inline=inline_lt) Trend_Settings.max_labels := input.int(50, "Maximum number of labels", group=ICT_Group) Trend_Settings.ST_liquidity_show := input.bool(false, "Short      ", group = settings_liquidity, inline=inline_st_liquidity) Trend_Settings.ST_liquidity_open_color := input.color(color.new(color.black, 50), '', group=settings_liquidity, inline=inline_st_liquidity) Trend_Settings.ST_liquidity_claimed_color := input.color(color.new(color.black, 50), '', group=settings_liquidity, inline=inline_st_liquidity) Trend_Settings.ST_liquidity_size := input.int(1, "", options = [1,2,3,4], group=settings_liquidity, inline=inline_st_liquidity) Trend_Settings.IT_liquidity_show := input.bool(true, "Intermediate", group = settings_liquidity, inline=inline_it_liquidity) Trend_Settings.IT_liquidity_open_color := input.color(color.purple, '', group=settings_liquidity, inline=inline_it_liquidity) Trend_Settings.IT_liquidity_claimed_color := input.color(color.purple, '', group=settings_liquidity, inline=inline_it_liquidity) Trend_Settings.IT_liquidity_size := input.int(1, "", options = [1,2,3,4], group=settings_liquidity, inline=inline_it_liquidity) Trend_Settings.LT_liquidity_show := input.bool(true, "Long       ", group = settings_liquidity, inline=inline_lt_liquidity) Trend_Settings.LT_liquidity_open_color := input.color(color.blue, '', group=settings_liquidity, inline=inline_lt_liquidity) Trend_Settings.LT_liquidity_claimed_color := input.color(color.blue, '', group=settings_liquidity, inline=inline_lt_liquidity) Trend_Settings.LT_liquidity_size := input.int(2, "", options = [1,2,3,4], group=settings_liquidity, inline=inline_lt_liquidity) Trend_Settings.liquidity_open_style := input.string('⎯⎯⎯', 'Open          ', options = ['⎯⎯⎯', '----', 'Β·Β·Β·Β·'], group=settings_liquidity_style) Trend_Settings.liquidity_claimed_style := input.string('Β·Β·Β·Β·', 'Claimed        ', options = ['⎯⎯⎯', '----', 'Β·Β·Β·Β·'], group=settings_liquidity_style) Trend_Settings.extend := input.int(10, title="Extend", minval = 1, group=settings_liquidity_style) Trend_Settings.max_lines := input.int(50, "Maximum number of lines", minval=1, maxval=250, group=settings_liquidity_style) Trend_Settings.displacement_show := input.bool(true, "Highlight    ", group=settings_displacement, inline=inline_displacement) Trend_Settings.displacement_bull := input.color(color.blue, "", group=settings_displacement, inline=inline_displacement) Trend_Settings.displacement_bear := input.color(color.orange, "", group=settings_displacement, inline=inline_displacement) Trend_Settings.displacement_fvg := input.bool(true, "Require FVG", group=settings_displacement) Trend_Settings.displacement_length := input.int(100, minval = 1, title = "Use last X bars to calculate", group=settings_displacement) Trend_Settings.displacement_factor := input.int(2, options = [1,2,3,4], title = "Displacement Strength", group=settings_displacement) FVG_Settings.show := input.bool(true, "Show FVG    ", group=FVG_Group, inline="1") FVG_Settings.color_bull := input.color(color.new(color.green,90), "", group=FVG_Group, inline="1") FVG_Settings.color_bear := input.color(color.new(color.blue,90), "", group=FVG_Group, inline="1") FVG_Settings.fvg_type := input.string("Always Display", options = ["Always Display", "Same As Displacement", "Level 1", "Level 2", "Level 3", "Level 4"], group=FVG_Group, inline="1") FVG_Settings.mitigated_show := input.bool(true, "Show Mitigated", group=FVG_Group, inline="2") FVG_Settings.mitigated_color_bull := input.color(color.new(color.gray,95), "", group=FVG_Group, inline="2") FVG_Settings.mitigated_color_bear := input.color(color.new(color.gray,95), "", group=FVG_Group, inline="2") FVG_Settings.mitigated_type := input.string('Wick filled', 'when', options = ['None', 'Wick filled', 'Body filled', 'Wick filled half', 'Body filled half'], group=FVG_Group, inline="2") FVG_Settings.CE_show := input.bool(true, "Show C.E.    ", group=FVG_Group, inline="3") FVG_Settings.CE_color := input.color(color.new(color.black,60), "", group=FVG_Group, inline="3") FVG_Settings.CE_style := input.string('Β·Β·Β·Β·', '     ', options = ['⎯⎯⎯', '----', 'Β·Β·Β·Β·'], group=FVG_Group, inline="3") FVG_Settings.max_count := input.int(20, "Maximum number of FVGs", group=FVG_Group) VI_Settings.show := input.bool(true, "Show Volume Imbalance", group=Imb_Group, inline="1") VI_Settings.color_bull := input.color(color.new(color.red,85), "", group=Imb_Group, inline="1") VI_Settings.color_bear := input.color(color.new(color.red,85), "", group=Imb_Group, inline="1") VI_Settings.mitigated_show := input.bool(true, "Show Mitigated        ", group=Imb_Group, inline="2") VI_Settings.mitigated_type := 'Body filled' VI_Settings.mitigated_color_bull := input.color(color.new(color.red,95), "", group=Imb_Group, inline="2") VI_Settings.mitigated_color_bear := input.color(color.new(color.red,95), "", group=Imb_Group, inline="2") VI_Settings.CE_show := false VI_Settings.max_count := input.int(20, "Maximum number of Imbalances", group=Imb_Group) Gap_Settings.show := input.bool(true, "Show Open Gaps", group=Gap_Group, inline="1") Gap_Settings.color_bull := input.color(color.new(color.green,85), "", group=Gap_Group, inline="1") Gap_Settings.color_bear := input.color(color.new(color.green,85), "", group=Gap_Group, inline="1") Gap_Settings.mitigated_show := false Gap_Settings.mitigated_type := 'Body filled' Gap_Settings.mitigated_color_bull := VI_Settings.color_bull Gap_Settings.mitigated_color_bear := VI_Settings.color_bear Gap_Settings.CE_show := false Gap_Settings.max_count := input.int(5, "Maximum number of Gaps", group=Gap_Group) //+------------------------------------------------------------------------------------------------------------+// //+--- Variables ---+// //+------------------------------------------------------------------------------------------------------------+// color color_transparent = #ffffff00 Helper helper = Helper.new() var MarketStructure Term = MarketStructure.new("Term") var Pivot[] ST_array = array.new<Pivot>() var Pivot[] IT_array = array.new<Pivot>() var Pivot[] LT_array = array.new<Pivot>() var Pivot[] STH_array = array.new<Pivot>() var Pivot[] ITH_array = array.new<Pivot>() var Pivot[] STL_array = array.new<Pivot>() var Pivot[] ITL_array = array.new<Pivot>() Term.ST := ST_array Term.IT := IT_array Term.LT := LT_array Term.STH := STH_array Term.ITH := ITH_array Term.STL := STL_array Term.ITL := ITL_array Term.settings := Trend_Settings var ImbalanceStructure FVGs = ImbalanceStructure.new() var Imbalance[] imbalance_array = array.new<Imbalance>() FVGs.imbalance := imbalance_array FVGs.settings := FVG_Settings var ImbalanceStructure VI = ImbalanceStructure.new() var Imbalance[] VI_array = array.new<Imbalance>() VI.imbalance := VI_array VI.settings := VI_Settings var ImbalanceStructure Gaps = ImbalanceStructure.new() var Imbalance[] Gap_array = array.new<Imbalance>() Gaps.imbalance := Gap_array Gaps.settings := Gap_Settings var label[] labels = array.new_label() var line[] lines = array.new_line() body = math.abs(open - close) std = ta.stdev(math.abs(open - close), Trend_Settings.displacement_length) //+------------------------------------------------------------------------------------------------------------+// //+--- Functions ---+// //+------------------------------------------------------------------------------------------------------------+// // The formatting is ugly, but Tradingview doesn't allow using barcolor inside of a function f_highlightDisplacement() => if barstate.isconfirmed if Trend_Settings.displacement_show candle_range = math.abs(open - close) fvg = close[1] > open[1] ? high[2] < low : low[2] > high Trend_Settings.displacement_fvg ? candle_range[1] > std[1] * Trend_Settings.displacement_factor and fvg : candle_range > std else false displaced = f_highlightDisplacement() //+------------------------------------------------------------------------------------------------------------+// //+--- Methods ---+// //+------------------------------------------------------------------------------------------------------------+// method GetFVGDisplacementLevel(Helper helper) => helper.name := "FVG Displacement Level" out = switch FVG_Settings.fvg_type 'Same As Displacement' => Trend_Settings.displacement_factor 'Level 1' => 1 'Level 2' => 2 'Level 3' => 3 'Level 4' => 4 out method LineStyle(Helper helper, string style) => helper.name := style out = switch style '----' => line.style_dashed 'Β·Β·Β·Β·' => line.style_dotted => line.style_solid out // SkipEQHigh returns the first bar_index of before the equal highs // This is used to compare pivot points, if two at equal levels // then we need to compare it to previous high, otherwise it will // not identify the right STH/STL method SkipEQHigh(Helper helper, int idx) => helper.name := "Skip EQ Highs" i = idx while high[i] == high[i-1] i := i+1 i // SkipEQLows returns the first bar_index of before the equal lows method SkipEQLow(Helper helper, int idx) => helper.name := "Skip EQ Lows" i = idx while low[i] == low[i-1] i := i+1 i // Same as above, but works on pivot points. it also doesn't care for // high or low since Pivot is a single price point method SkipEQPivot(Pivot[] p, int idx) => i = idx while p.get(i).price == p.get(i-1).price and p.get(i).lbl_text == p.get(i-1).lbl_text and p.size() < i i := i+1 i // isHigh returns true if the Pivot point is a high Pivot (STH, ITH, LTH) method isHigh(Helper helper, string lbl) => helper.name := "isHigh" str.endswith(lbl, "H") //isLow returns true if the Pivot is a low Pivot method isLow(Helper helper, string lbl) => helper.name := "isLow" str.endswith(lbl, "L") //+------------------------------------------------------------------------------------------------------------+// //+--- ICT Market Structure Methods ---+// //+------------------------------------------------------------------------------------------------------------+// // getLabelSettings calculates and returns the Pivot Point settings // based on what is configured in the properties window method getLabelSettings(MarketStructure MS, Pivot pivot) => color lbl_color = na string lbl_text_size = na color txt_color = na string lbl_style = na string lbl = na if (MS.settings.ST_show or MS.settings.IT_show or MS.settings.LT_show) lbl_color := MS.settings.ST_label_color lbl_text_size := MS.settings.ST_text_size txt_color := str.endswith(pivot.lbl_text,"H") ? MS.settings.ST_color_bull : MS.settings.ST_color_bear lbl_style := str.endswith(pivot.lbl_text,"H") ? label.style_label_down : label.style_label_up lbl := str.endswith(pivot.lbl_text,"H") ? "STH" : "STL" if MS.settings.IT_show lbl_color := pivot.lbl_text == "ITH" or pivot.lbl_text == "LTH" or pivot.lbl_text == "ITL" or pivot.lbl_text == "LTL" ? MS.settings.IT_label_color : lbl_color lbl_text_size := pivot.lbl_text == "ITH" or pivot.lbl_text == "LTH" or pivot.lbl_text == "ITL" or pivot.lbl_text == "LTL" ? MS.settings.IT_text_size : lbl_text_size txt_color := pivot.lbl_text == "ITH" or pivot.lbl_text == "LTH" ? MS.settings.IT_color_bull : pivot.lbl_text == "ITL" or pivot.lbl_text == "LTL" ? MS.settings.IT_color_bear : txt_color lbl_style := pivot.lbl_text == "ITH" or pivot.lbl_text == "LTH" ? label.style_label_down : pivot.lbl_text == "ITI" or pivot.lbl_text == "LTI" ? label.style_label_up : lbl_style lbl := pivot.lbl_text == "ITH" or pivot.lbl_text == "LTH" ? "ITH" : pivot.lbl_text == "ITL" or pivot.lbl_text == "LTL" ? "ITL" : lbl if MS.settings.LT_show if pivot.lbl_text == "LTH" or pivot.lbl_text == "LTL" lbl_color := MS.settings.LT_label_color lbl_text_size := MS.settings.LT_text_size txt_color := pivot.lbl_text == "LTH" ? MS.settings.LT_color_bull : pivot.lbl_text == "LTL" ? MS.settings.LT_color_bear : txt_color lbl_style := pivot.lbl_text == "LTH" ? label.style_label_down : pivot.lbl_text == "LTI" ? label.style_label_up : lbl_style lbl := pivot.lbl_text [lbl_color, lbl_text_size, txt_color, lbl_style, lbl] // AddLabel displays the Pivot label with the proper settings. it is used for both adding the initial // Pivot and renaming/adjusting it if it is converted from STH to ITH for example method AddLabel(MarketStructure MS, Pivot pivot) => if MS.settings.ST_show or (MS.settings.IT_show and (pivot.lbl_text == "ITH" or pivot.lbl_text == "ITL" or pivot.lbl_text == "LTH" or pivot.lbl_text == "LTL")) or (MS.settings.LT_show and (pivot.lbl_text == "LTH" or pivot.lbl_text == "LTL")) [lbl_color, lbl_text_size, txt_color, lbl_style, lbl] = MS.getLabelSettings(pivot) if na(pivot.lbl) pivot.lbl := label.new(pivot.time, pivot.price, xloc=xloc.bar_time, color=lbl_color, size=lbl_text_size, textcolor= txt_color, style = lbl_style, text=lbl) labels.unshift(pivot.lbl) if labels.size() >= MS.settings.max_labels label l = labels.pop() label.delete(l) else label.set_style(pivot.lbl, lbl_style) label.set_color(pivot.lbl, lbl_color) label.set_size(pivot.lbl, lbl_text_size) label.set_textcolor(pivot.lbl, txt_color) label.set_text(pivot.lbl, lbl) MS // AddLiquidity adds the liquidity lines method AddLiquidity(MarketStructure MS, Pivot pivot) => lbl = pivot.lbl_text color liquidity_open_color = str.startswith(lbl, "ST") ? MS.settings.ST_liquidity_open_color : str.startswith(lbl, "IT") ? MS.settings.IT_liquidity_open_color : str.startswith(lbl, "LT") ? MS.settings.LT_liquidity_open_color : na color liquidity_claimed_color = str.startswith(lbl, "ST") ? MS.settings.ST_liquidity_claimed_color : str.startswith(lbl, "IT") ? MS.settings.IT_liquidity_claimed_color : str.startswith(lbl, "LT") ? MS.settings.LT_liquidity_claimed_color : na int liquidity_size = str.startswith(lbl, "ST") ? MS.settings.ST_liquidity_size : str.startswith(lbl, "IT") ? MS.settings.IT_liquidity_size : str.startswith(lbl, "LT") ? MS.settings.LT_liquidity_size : na if MS.settings.ST_liquidity_show or (MS.settings.IT_liquidity_show and (pivot.lbl_text == "ITH" or pivot.lbl_text == "ITL" or pivot.lbl_text == "LTH" or pivot.lbl_text == "LTL")) or (MS.settings.LT_liquidity_show and (pivot.lbl_text == "LTH" or pivot.lbl_text == "LTL")) if na(pivot.ln) pivot.ln := line.new(pivot.time, pivot.price, time+((time-time[1])*MS.settings.extend), pivot.price, xloc=xloc.bar_time, style=helper.LineStyle(MS.settings.liquidity_open_style), color=liquidity_open_color, width=liquidity_size) lines.unshift(pivot.ln) if lines.size() > MS.settings.max_lines line l = lines.pop() line.delete(l) else line.set_color(pivot.ln, pivot.claimed ? liquidity_claimed_color : liquidity_open_color) line.set_width(pivot.ln, liquidity_size) line.set_x2(pivot.ln, pivot.claimed ? pivot.time_last : time+((time-time[1])*MS.settings.extend)) line.set_style(pivot.ln, helper.LineStyle(pivot.claimed ? MS.settings.liquidity_claimed_style : MS.settings.liquidity_open_style)) MS // Add method handles the addition of newly discovered ST[H/L] Pivot Point method Add(MarketStructure MS, float p_price, int p_time, lbl) => Pivot pivot = Pivot.new() pivot.price := p_price pivot.time := p_time pivot.lbl_text := lbl MS.ST.unshift(pivot) if lbl == "STH" MS.STH.unshift(pivot) else MS.STL.unshift(pivot) MS.AddLabel(pivot).AddLiquidity(pivot) if MS.ST.size() > MAX_BUFFER Pivot temp = MS.ST.pop() line.delete(temp.ln) label.delete(temp.lbl) MS // FindIT rechecks the Pivot points and renames the Pivot point from ST to IT method FindIT(MarketStructure MS) => if MS.STH.size() > 2 h1 = MS.STH.first() h2 = MS.STH.get(1) h3 = MS.STH.get(MS.STH.SkipEQPivot(2)) if h2.price > h3.price and h2.price > h1.price and h2.lbl_text == "STH" h2.lbl_text := "ITH" MS.ITH.unshift(h2) MS.AddLabel(h2).AddLiquidity(h2) if MS.STL.size() > 2 l1 = MS.STL.first() l2 = MS.STL.get(1) l3 = MS.STL.get(MS.STL.SkipEQPivot(2)) if l2.price < l3.price and l2.price < l1.price and l2.lbl_text == "STL" l2.lbl_text := "ITL" MS.ITL.unshift(l2) MS.AddLabel(l2).AddLiquidity(l2) MS // FindLT rechecks the IT Pivot points and renames the Pivot point from IT to LT method FindLT(MarketStructure MS) => if MS.ITH.size() > 2 h1 = MS.ITH.first() h2 = MS.ITH.get(1) h3 = MS.ITH.get(MS.ITH.SkipEQPivot(2)) if h2.price > h3.price and h2.price > h1.price and h2.lbl_text == "ITH" h2.lbl_text := "LTH" MS.LT.unshift(h2) MS.AddLabel(h2).AddLiquidity(h2) if MS.ITL.size() > 2 l1 = MS.ITL.first() l2 = MS.ITL.get(1) l3 = MS.ITL.get(MS.ITL.SkipEQPivot(2)) if l2.price < l3.price and l2.price < l1.price and l2.lbl_text == "ITL" l2.lbl_text := "LTL" MS.LT.unshift(l2) MS.AddLabel(l2).AddLiquidity(l2) MS // FindST checks for ST[H/L] and calls the Add method method FindST(MarketStructure MS) => h = high[1] > high[helper.SkipEQHigh(2)] and high[1] > high l = low[1] < low[helper.SkipEQLow(2)] and low[1] < low if h MS.Add(high[1], time[1], "STH") if l MS.Add(low[1], time[1], "STL") MS // CheckClaimed checks if liquidity has been swept method CheckClaimed(MarketStructure MS) => if MS.ST.size() > 0 for i = 0 to MS.ST.size() - 1 pivot = MS.ST.get(i) if not na(pivot.ln) if not pivot.claimed if helper.isHigh(pivot.lbl_text) pivot.claimed := high > pivot.price if helper.isLow(pivot.lbl_text) pivot.claimed := low < pivot.price if pivot.claimed pivot.time_last := time pivot.claimed := true MS.AddLiquidity(pivot) else line.set_x2(pivot.ln, time+((time-time[1])*MS.settings.extend)) MS //+------------------------------------------------------------------------------------------------------------+// //+--- Imbalances Methods ---+// //+------------------------------------------------------------------------------------------------------------+// // AddZone is used to display and manage imbalance related boxes method AddZone(ImbalanceStructure IS, Imbalance imb) => if IS.settings.show if na(imb.box) imb.box := box.new(imb.open_time, imb.open, time+((time-time[1])*Trend_Settings.extend), imb.close, color_transparent, 0, bgcolor = imb.open < imb.close ? IS.settings.color_bull : IS.settings.color_bear, xloc=xloc.bar_time) if IS.settings.CE_show imb.line_middle := line.new(imb.open_time, imb.middle, time+((time-time[1])*Trend_Settings.extend), imb.middle, xloc=xloc.bar_time, style=helper.LineStyle(IS.settings.CE_style), color=IS.settings.CE_color) else //if imb.mitigated box.set_right(imb.box, imb.mitigated ? imb.mitigated_time : time+((time-time[1])*Trend_Settings.extend)) box.set_bgcolor(imb.box, imb.open < imb.close ? imb.mitigated ? IS.settings.mitigated_color_bull : IS.settings.color_bull : imb.mitigated ? IS.settings.mitigated_color_bear : IS.settings.color_bear) if IS.settings.CE_show line.set_x2(imb.line_middle, imb.mitigated ? imb.mitigated_time : time+((time-time[1])*Trend_Settings.extend)) if imb.mitigated and not IS.settings.mitigated_show box.delete(imb.box) line.delete(imb.line_middle) IS // AddImbalance adds a newly discovered imbalance. this applies for both FVG and Volume Imbalance method AddImbalance(ImbalanceStructure IS, float o, float c, int o_time, int c_time) => Imbalance imb = Imbalance.new() imb.open_time := o_time imb.close_time := c_time imb.open := o imb.middle := (o+c)/2 imb.close := c IS.imbalance.unshift(imb) IS.AddZone(imb) if IS.imbalance.size() > IS.settings.max_count temp = IS.imbalance.pop() box.delete(temp.box) line.delete(temp.line_middle) IS // CheckMitigated checks if the imbalance has been mitigated based on the settings method CheckMitigated(ImbalanceStructure IS) => if IS.imbalance.size() > 0 for i = IS.imbalance.size() - 1 to 0 imb = IS.imbalance.get(i) if not imb.mitigated switch IS.settings.mitigated_type "None" => imb.mitigated := false 'Wick filled' => imb.mitigated := imb.open <= imb.close ? low <= imb.open : high >= imb.open 'Body filled' => imb.mitigated := imb.open < imb.close ? math.min(open, close) <= imb.open : math.max(open, close) >= imb.open 'Wick filled half' => imb.mitigated := imb.open <= imb.close ? low <= imb.middle : high >= imb.middle 'Body filled half' => imb.mitigated := imb.open <= imb.close ? math.min(open, close) <= imb.middle : math.max(open, close) >= imb.middle if imb.mitigated imb.mitigated_time := time IS.AddZone(imb) else box.set_right(imb.box, time+((time-time[1])*Trend_Settings.extend)) if IS.settings.CE_show line.set_x2(imb.line_middle, time+((time-time[1])*Trend_Settings.extend)) IS // FindImbalance looks for imbalances and, if found, adds it to the list method FindImbalance(ImbalanceStructure IS, string t) => if barstate.isconfirmed Gap = low > high[1] or high < low[1] if t == "GAP" and Gap o = high < low[1] ? low[1] : high[1] c = high < low[1] ? high : low IS.AddImbalance(o, c, time[1], time) if t == "FVG" and IS.settings.show and (high < low[2] or low > high[2]) and not Gap o = high < low[2] ? low[2] : high[2] c = high < low[2] ? high : low if FVG_Settings.fvg_type == "Always Display" or (FVG_Settings.fvg_type != "Always Display" and body[1] > std[1] * helper.GetFVGDisplacementLevel()) IS.AddImbalance(o, c, time[2], time) if t == "VI" and IS.settings.show and ((math.min(open, close) > math.max(open[1], close[1])) or (math.max(open, close) < math.min(open[1], close[1]))) and not Gap c = math.max(open, close) > math.min(open[1], close[1]) ? math.min(open, close) : math.max(open, close) o = math.min(open, close) > math.max(open[1], close[1]) ? math.max(open[1], close[1]) : math.min(open[1], close[1]) IS.AddImbalance(o, c, time[1], time) IS //+------------------------------------------------------------------------------------------------------------+// //+--- Displacement ---+// //+------------------------------------------------------------------------------------------------------------+// // Credit: FTO - original content found at // https://www.tradingview.com/script/n6djFgQH-Visualizing-Displacement-TFO/ int offset = na color candle = open < close ? Trend_Settings.displacement_bull : Trend_Settings.displacement_bear if Trend_Settings.displacement_fvg offset := -1 candle := open[1] < close[1] ? Trend_Settings.displacement_bull : Trend_Settings.displacement_bear barcolor(f_highlightDisplacement() ? candle : na, offset = offset) //+------------------------------------------------------------------------------------------------------------+// //+--- Main call to start the process ---+// //+------------------------------------------------------------------------------------------------------------+// if barstate.isconfirmed or barstate.islastconfirmedhistory FVGs.FindImbalance("FVG") VI.FindImbalance("VI") Gaps.FindImbalance("GAP") FVGs.CheckMitigated() VI.CheckMitigated() Gaps.CheckMitigated() if barstate.isconfirmed or barstate.islastconfirmedhistory Term.FindST().FindIT().FindLT() Term.CheckClaimed()
5Ema Indicator only sell signals
https://www.tradingview.com/script/QAuoIBuu-5Ema-Indicator-only-sell-signals/
JOJO_MOJO_
https://www.tradingview.com/u/JOJO_MOJO_/
6
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© JOJO //@version=5 indicator(title='5Ema Indicator only sell signals', overlay=true) RR = input.int(defval=3, title='Risk to Reward Ratio', minval=1, maxval=100) ema = ta.ema(close,5) pema = plot(ema, '5 Ema', color=color.black, linewidth=2) var bool Short = na var int shortC = 0 var int sellstoplosshitC = 0 var int selltargethitC = 0 var float sellstoploss = na var float selltargetl = na var float selltarget = na var float sellat = na var float alert_shorthigh = na var float alert_shortlow = na Short := shortC == 0 and low[1] > ema[1] and low[1] > low sellstoplosshit = high > sellstoploss and shortC > 0 and sellstoplosshitC == 0 selltargethit = low < selltarget and shortC > 0 and selltargethitC == 0 if Short shortC := shortC + 1 sellstoplosshitC := 0 selltargethitC := 0 alert_shorthigh := high[1] sellstoploss := high[1] selltargetl := (high[1] - low[1]) * RR selltarget := low[1] - selltargetl sellat := low[1] if sellstoplosshit == false and selltargethit == false and shortC > 0 sellstoplosshitC := 0 selltargethitC := 0 else if sellstoplosshit shortC := 0 sellstoplosshitC := sellstoplosshitC + 1 else if low < selltarget and shortC > 0 and selltargethitC == 0 shortC := 0 selltargethitC := selltargethitC + 1 plotshape(Short, title='Sell', location=location.abovebar, color=color.teal, style=shape.arrowdown, text='Sell', textcolor=color.teal) plotshape(sellstoplosshit, title='Short SL Hit', location=location.abovebar, color=color.red, style=shape.arrowdown, text='Short SL Hit', textcolor=color.red) plotshape(selltargethit, title='Short Target Hit', location=location.belowbar, color=color.green, style=shape.arrowup, text='Short Target Hit', textcolor=color.green) alertcondition(Short, "Go Short", "Go Short") alertcondition(sellstoplosshit, "Stop-loss hit", "Stop-loss hit") alertcondition(selltargethit, "Target hit", "Target hit")
Bollinger Bands Percentile Stdev Channels (BBPct) [AlgoAlpha]
https://www.tradingview.com/script/d4xGYHl1-Bollinger-Bands-Percentile-Stdev-Channels-BBPct-AlgoAlpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
9
study
5
MPL-2.0
// This Pine Scriptβ„’ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Algoalpha X Β© Sushiboi77 //@version=5 indicator(shorttitle="β—­ BBPCT% [AlgoAlpha]", title="β—­ Bollinger Bands Percent", overlay=false) //Symmetrical Standard Deviation Channels neon = input.bool(title = 'Neon Color Theme', defval = true) upper1 = close + 0.05 * close lower1 = close - 0.05 * close stdL = close > lower1 stdS = close < upper1 //BBPCT length = input.int(20, minval=1, group='Bollinger Band') src = input(close, title="Source", group='Bollinger Band') mult = input.float(2.0, minval=0.001, maxval=50, title="Multiplier", group='Bollinger Band') lookback = 750 showStdev = input.bool(false, title='Show Bollinger Band Stdev %', group='Settings') var stdevArray = array.new_float(lookback,0.0) basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) upper = basis + dev lower = basis - dev positionBetweenBands = 100 * (src - lower)/(upper - lower) array.push(stdevArray, dev/close) if array.size(stdevArray)>=lookback array.remove(stdevArray, 0) rank = array.percentrank(stdevArray, lookback-1) hist = 100*dev/close bullcolor = neon ? #00ffbb : #00b712 bearcolor = neon ? #ff1100 : #c30010 //PLOTS plot1 = plot(positionBetweenBands, color = color.new(color.white, 100)) obupper = plot(130, color = color.new(bearcolor, 0), display = display.none) oblower = plot(110, color = color.new(bearcolor, 0), display = display.none) obmid = plot(95, display = display.none) osupper = plot(10, color = color.new(bullcolor, 30), display = display.none) oslower = plot(-10, color = color.new(bullcolor, 30), display = display.none) osmid = plot(25, color = color.new(bullcolor, 70), display = display.none) hline(50) z = plot(positionBetweenBands, "Z", positionBetweenBands > 50 ? bullcolor : bearcolor) mid = plot(50, display = display.none, editable = false) fill(z, mid, positionBetweenBands > 50 ? positionBetweenBands : 50, positionBetweenBands > 50 ? 50 : positionBetweenBands, positionBetweenBands > 50 ? bullcolor : #00000000, positionBetweenBands > 50 ? #00000000 : bearcolor) fill(obupper, oblower, color.new(bearcolor, 80)) fill (oblower, obmid, color.new(bearcolor, 87)) fill(osupper, oslower, color.new(bullcolor, 87)) fill(osupper, osmid, color.new(bullcolor, 93)) plotshape(ta.crossover(positionBetweenBands,-8) and stdL, style = shape.triangleup, color = bullcolor, location = location.bottom, size = size.tiny) plotshape(ta.crossunder(positionBetweenBands,108) and stdS, style = shape.triangledown, color = bearcolor, location = location.top, size = size.tiny) plot(showStdev ? hist : na, style=plot.style_columns, color=(hist[1] < hist ? #26A69A : #B2DFDB) , title='Stdev %') //Alerts alertcondition(ta.crossover(positionBetweenBands,-10), title="Bullish Reversal", message="Bullish Reversal {{exchange}}:{{ticker}}") alertcondition(ta.crossunder(positionBetweenBands,110), title="Bearish Reversal", message="Bearish Reversal {{exchange}}:{{ticker}}") alertcondition(ta.crossover(positionBetweenBands,50), title="Bullish Trend", message="Bullish Trend {{exchange}}:{{ticker}}") alertcondition(ta.crossunder(positionBetweenBands,50), title="Bearish Trend", message="Bearish Trend {{exchange}}:{{ticker}}")
HyperTrend [LuxAlgo]
https://www.tradingview.com/script/Bcufg8oX-HyperTrend-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
3,599
study
5
CC-BY-NC-SA-4.0
// 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("HyperTrend [LuxAlgo]", "LuxAlgo - HyperTrend", overlay = true) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ mult = input.float(5, 'Multiplicative Factor', minval = 0) slope = input.float(14, 'Slope', minval = 0) width = input.float(80, 'Width %', minval = 0, maxval = 100) / 100 //Style bullCss = input.color(color.teal, 'Average Color', inline = 'avg', group = 'Style') bearCss = input.color(color.red, '' , inline = 'avg', group = 'Style') area = input.string('Gradient', 'Area', options = ['Gradient', 'Solid'], group = 'Style') upperCss = input.color(color.new(color.red, 70), 'Upper Area', group = 'Style') lowerCss = input.color(color.new(color.teal, 70) , 'Lower Area', group = 'Style') //-----------------------------------------------------------------------------} //Calculation //-----------------------------------------------------------------------------{ var float upper = na var float lower = na var float avg = close var hold = 0. var os = 1. atr = nz(ta.atr(200)) * mult avg := math.abs(close - avg) > atr ? math.avg(close, avg) : avg + os * (hold / mult / slope) os := math.sign(avg - avg[1]) hold := os != os[1] ? atr : hold upper := avg + width * hold lower := avg - width * hold //-----------------------------------------------------------------------------} //Plots //-----------------------------------------------------------------------------{ css = os == 1 ? bullCss : bearCss plot_upper = plot(upper, 'Upper', na) plot_avg = plot(avg, 'Average', os != os[1] ? na : css) plot_lower = plot(lower, 'Lower', na) var color upper_topcol = na var color upper_btmcol = na var color lower_topcol = na var color lower_btmcol = na //Fill if area == 'Gradient' upper_topcol := upperCss upper_btmcol := color.new(chart.bg_color, 100) lower_topcol := color.new(chart.bg_color, 100) lower_btmcol := lowerCss else upper_topcol := upperCss upper_btmcol := upperCss lower_topcol := lowerCss lower_btmcol := lowerCss //Upper Area fill(plot_upper, plot_avg , top_color = os != os[1] ? na : upper_topcol , bottom_color = os != os[1] ? na : upper_btmcol , top_value = upper , bottom_value = avg) //Lower Area fill(plot_avg, plot_lower , top_color = os != os[1] ? na : lower_topcol , bottom_color = os != os[1] ? na : lower_btmcol , top_value = avg , bottom_value = lower) //-----------------------------------------------------------------------------}
Price breakout and reversal [TCS] | PA
https://www.tradingview.com/script/lMvj1v6W-Price-breakout-and-reversal-TCS-PA/
zendrer
https://www.tradingview.com/u/zendrer/
148
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© zendrer //@version=5 indicator(title='TCSβ€’BREAKS AND REVERSALS', shorttitle='TCSβ€’BREAKS AND REVERSALS', overlay=true, max_bars_back=5000) //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //INPUT //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //---------------------------------------------------------------- breaks = input(true, title='SHOW BREAKS') reversals = input(true, title='SHOW REVERSALS') fairbreak = input(true, title='SHOW FAIR VALUE BREAKS') leftBars = input(8, title='LOOKBACK') //---------------------------------------------------------------- //---------------------------------------------------------------- //CRYPTO RISK CALC //---------------------------------------------------------------- labels = input(true, "SHOW RISK", group = "ACCOUNT RISK - CRYPTO") risk = input.float(3, "ACCOUNT RISK % ", step = 0.1, group = "ACCOUNT RISK - CRYPTO") account = input(10000,"ACCOUNT AMOUNT ", group = "ACCOUNT RISK - CRYPTO") fees = input(0.07,"BROKER FEES ENTRY %", group = "ACCOUNT RISK - CRYPTO") feesex = input(0.07,"BROKER FEES EXIT %", group = "ACCOUNT RISK - CRYPTO") //---------------------------------------------------------------- //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //FUNCTION //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //---------------------------------------------------------------- highPivot = fixnan(ta.pivothigh(leftBars, 0)[1]) lowPivot = fixnan(ta.pivotlow(leftBars, 0)[1]) fairvalue = fixnan((highPivot+lowPivot)/2) //---------------------------------------------------------------- //BB TO FILTER REVERSALS //---------------------------------------------------------------- length = 20 src = close mult = 2 basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) upper = basis + dev lower = basis - dev //---------------------------------------------------------------- //BULLISH CONDITIONS //---------------------------------------------------------------- bullishbreaks = ta.crossover(close, highPivot) and not (open - low > close - open) and breaks bullishfairbreaks = ta.crossover(close, fairvalue) and not (open - low > close - open) and fairbreak bullishreversals = ((ta.crossover(close, lowPivot[1]) and not (open - low > close - open)) or (low < lowPivot[1] and close > lowPivot[1] and open > lowPivot[1] and close > open)) and reversals and ta.crossover(close,lower) //---------------------------------------------------------------- //BEARISH CONDITIONS //---------------------------------------------------------------- bearishbreaks = ta.crossunder(close, lowPivot) and not (open - close < high - open) and breaks bearishfairbreaks = ta.crossunder(close, fairvalue) and not (open - close < high - open) and fairbreak bearishreversals = ((ta.crossunder(close, highPivot[1]) and not (open - close < high - open)) or (high > highPivot[1] and close < highPivot[1] and open < highPivot[1] and close < open)) and reversals and ta.crossunder(close,upper) //---------------------------------------------------------------- //SIZE CALC LONG //---------------------------------------------------------------- changesl = (((close/lowPivot)-1)*100)+fees accval = risk*account relative = (changesl*accval)/risk accquant = accval/relative //---------------------------------------------------------------- //SIZE CALC SHORT //---------------------------------------------------------------- changesl1 = (((highPivot/close)-1)*100)+fees accval1 = risk*account relative1 = (changesl1*accval1)/risk accquant1 = accval1/relative1 //---------------------------------------------------------------- //SIZE CALC LONG FAIR VALUE //---------------------------------------------------------------- changesl2 = (((close/fairvalue)-1)*100)+fees accval2 = risk*account relative2 = (changesl2*accval2)/risk accquant2 = accval2/relative2 //---------------------------------------------------------------- //SIZE CALC SHORT FAIR VALUE //---------------------------------------------------------------- changesl3 = (((fairvalue/close)-1)*100)+fees accval3 = risk*account relative3 = (changesl3*accval3)/risk accquant3 = accval3/relative3 //---------------------------------------------------------------- //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //PLOT //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //---------------------------------------------------------------- plot(highPivot, color = ta.change(highPivot) ? na : color.new(color.lime,0), linewidth = 2, title ='HIGH PIVOT') plot(lowPivot, color = ta.change(lowPivot) ? na : color.new(color.purple, 0), linewidth = 2, title ='LOW PIVOT') plot(fairvalue, color = color.new(color.gray, 0), linewidth = 1, style = plot.style_circles, title = 'FAIR VALUE') plotshape(bullishbreaks, title = 'BULLISH BREAK', text = 'B', color = color.new(color.lime, 0), style = shape.triangleup, location = location.belowbar, textcolor = color.new(color.white, 0), size = size.tiny) plotshape(bearishbreaks, title = 'BEARISH BREAK', text = 'S', color = color.new(color.purple, 0), style = shape.triangledown, location = location.abovebar, textcolor = color.new(color.white, 0), size = size.tiny) plotshape(bullishfairbreaks, title ='FAIR BULLISH BREAK', color = color.new(color.lime, 0), style = shape.circle, location = location.belowbar, size = size.tiny) plotshape(bearishfairbreaks, title = 'FAIR BEARISH BREAK', color = color.new(color.purple, 0), style = shape.circle, location = location.abovebar, size = size.tiny) plotshape(bullishreversals, title = 'BULLISH REVERSAL', text = 'R+', color = color.new(color.lime, 0), style = shape.diamond, location = location.belowbar, textcolor = color.new(color.white, 0), size = size.tiny) plotshape(bearishreversals, title = 'BULLISH REVERSAL', text = 'R-', color = color.new(color.purple, 0), style = shape.diamond, location = location.abovebar, textcolor = color.new(color.white, 0), size = size.tiny) //---------------------------------------------------------------- //---------------------------------------------------------------- accqty = (labels ? label.new(bar_index+9, close[1], color =color.new(color.white,100), style = label.style_label_left, text="QTY x "+ "|LONG ON LOW| x" + str.tostring(accquant,"#.##") + " β€’ |SHORT ON HIGH| x" + str.tostring(accquant1,"#.##") + " \n β€’ |LONG ON FAIR| x" + str.tostring(accquant2,"#.##") + " β€’ |SHORT ON FAIR| x" + str.tostring(accquant3,"#.##"), textcolor = color.new(color.white, 20), textalign = text.align_left) : na) label.delete(accqty[1]) //---------------------------------------------------------------- //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //ALERTS //β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’ //---------------------------------------------------------------- alertcondition(bullishbreaks, title = 'Bullish breakout', message = 'Bullish breakout') alertcondition(bearishbreaks, title = 'Bearish breakout', message = 'Bearish breakout') alertcondition(bullishfairbreaks, title = 'Bullish fair value breakout', message = 'Bullish fair value breakout') alertcondition(bearishfairbreaks, title = 'Bearish fair value breakout', message = 'Bearish fair value breakout') alertcondition(bullishreversals, title = 'Bullish reversal', message = 'Bullish reversal') alertcondition(bearishreversals, title = 'Bearish reversal', message = 'Bearish reversal') //---------------------------------------------------------------- //END
DCA Liquidation Calculation [ChartPrime]
https://www.tradingview.com/script/DkEc7RrD-DCA-Liquidation-Calculation-ChartPrime/
ChartPrime
https://www.tradingview.com/u/ChartPrime/
171
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© ChartPrime //@version=5 indicator("DCA Liquidation Calculation [ChartPrime]",shorttitle = "DLC [ChartPrime]",overlay = true) // color bgray = color.rgb(118, 124, 118, 37) color WHITE = color.rgb(210, 210, 210) color red = color.rgb(128, 49, 49, 67) color white = color.rgb(248, 248, 248, 14) color olive = color.olive color blue = color.rgb(23, 43, 77) color Yellow = color.rgb(255, 186, 75) string core = "➞ Main Core Settings πŸ”Έ" string DCAg = "➞ DCA Logic Settings πŸ”Έ" string visual = "➞ Visuals SettingsπŸ”Έ" float Wallet = input.float(1000,title = "Wallet ➞",group = core,inline = "01") string symbol = input.symbol("BTCUSDT",group = core,inline = "01") bool IS_LONG = input.string(title='Strategy Type ➞ ', defval='long', options=['long', 'short'],group=DCAg,inline = "001") == "long" var float BO_price = 0.0 int decimals = 3 float base_order_value = input.float(title='        Base orderβ€„β€„β€…βžž              ', defval=200, step=50, group=DCAg,inline = "002") float Safety_order_value = input.float(title='        Safety order ➞              ', defval=300, step=50, group=DCAg,inline = "003") int leverage = input.int (title='        leverage ➞                  ', defval=10, minval=1,step=1, group=DCAg,inline = "004") float Safety_orders = input.float(title='        Max Safety Count ➞', defval=10, group=DCAg) float price_deviation = input.float(title='        Price Deviation ➞', minval=0.0, step=0.1, defval=2.2, group=DCAg) float Volume_Scale = input.float(title='        Safety Volume Scale ➞', defval=1.5, step=0.1, group=DCAg) float Step_Scale = input.float(title='        Safety Step Scale ➞', defval=1.0, step=0.1, group=DCAg) bool Showmain = input.bool(true, "Show Main Table ❓",group = visual,inline = "01") string position = input.string("Middle Center", options = ["Middle Right","Top Center","Top Right","Middle Left","Middle Center","Bottom Left","Bottom Center","Bottom Right"], title = 'Position', inline = "01", group = visual ) bool Showstats = input.bool(true, "Show Stats Table ❓",group = visual,inline = "02") string _position = input.string("Top Right", options = ["Middle Right","Top Center","Top Right","Middle Left","Middle Center","Bottom Left","Bottom Center","Bottom Right"], title = 'Position', inline = "02", group = visual ) symbol_price()=> request.security(symbol,"D", close[1]) BO_price := symbol_price() plot(symbol_price(),display = display.data_window) plot(BO_price,display = display.data_window) stepped_deviation(so_index) => float SD = 0 if so_index > 0 for _i = 1 to so_index by 1 SD := SD + price_deviation * math.pow(Step_Scale, _i - 1) else SD := 0 next_so_price(so_index, _bo_price) => float SD = stepped_deviation(so_index) if IS_LONG float _next_so_price = _bo_price * (1 - SD / 100) else float _next_so_price = _bo_price * (1 + SD / 100) next_so_size_usd(so_index) => float next_so_value = (Safety_order_value) * math.pow(Volume_Scale, so_index - 1) next_so_qty(so_index, _bo_price) => float next_so_value = next_so_size_usd(so_index) float _next_so_qty = next_so_value / next_so_price(so_index, _bo_price) base()=> str.replace(syminfo.ticker(symbol), "USDT", "", 0) liq_balance(wallet_balance, contract_qty, entry_price)=> liq_price = (wallet_balance + 0 - contract_qty * entry_price) / (math.abs(contract_qty) * ((0.5 / 100) - (1))) math.round(liq_price, 2) _steps_bo_size = (base_order_value) / BO_price table_position(type) => switch type "Middle Right" => position.middle_right "Top Center" => position.top_center "Top Right" => position.top_right "Middle Left" => position.middle_left "Middle Center" => position.middle_center "Bottom Left" => position.bottom_left "Bottom Center" => position.bottom_center "Bottom Right" => position.bottom_right // if Showmain color2 = color.from_gradient(ta.rsi(close, 3), 0, 100, #E6DADA, #274046) table main = table.new(table_position(position), columns=20, rows=int(Safety_orders) + 4, frame_width=4, frame_color=color.rgb(71, 71, 71) , border_width=2, border_color=color.black, bgcolor=bgray) table.cell(main, 0, 0, 'Order # no', text_color=color.white, text_size=size.normal, width = 5, height=4) table.cell(main, 1, 0, 'Deviation ( % )', text_color=color.white, text_size=size.normal) table.cell(main, 2, 0, 'Size ( ' + str.tostring(base()) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 3, 0, 'Volume ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 4, 0, 'Price ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 5, 0, 'Avg price ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 6, 0, 'PNL ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 7, 0, 'Liquidation Price ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 8, 0, 'Total size ( ' + str.tostring(base()) + ' )', text_color=color.white, text_size=size.normal) table.cell(main, 9, 0, 'Total Vol ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.normal) float _steps_total_size = _steps_bo_size float _steps_total_volume = BO_price * _steps_bo_size row_color = _steps_total_volume < Wallet ? color.green : red //base order table.cell(main, 0, 1, 'BO', text_color=color.white, text_size=size.normal,bgcolor = row_color) table.cell(main, 1, 1, '0', text_color=color.white, text_size=size.normal,bgcolor = row_color) table.cell(main, 2, 1, str.tostring(math.round(_steps_bo_size, decimals)), text_color=color.white, text_size=size.normal,bgcolor = row_color) table.cell(main, 3, 1, str.tostring(math.round(BO_price * _steps_bo_size, decimals)), text_color=color.white, text_size=size.normal,bgcolor = row_color) table.cell(main, 4, 1, str.tostring(math.round(BO_price, decimals)), text_color=color.white, text_size=size.normal,bgcolor = row_color) table.cell(main, 5, 1, str.tostring(math.round(_steps_total_volume / _steps_total_size, decimals)), text_color=color.white, text_size=size.normal,bgcolor = row_color) float next_so_price = 0 float next_so_qty = 0 if Safety_orders > 0 for _i = 1 to Safety_orders by 1 next_so_price := next_so_price(_i, BO_price) next_so_qty := next_so_qty(_i, BO_price) _steps_total_size += next_so_qty _steps_total_volume += next_so_qty * next_so_price inrow_color = _steps_total_volume < Wallet * leverage ? color.rgb(30, 96, 86) : color.red avg = math.round(_steps_total_volume / _steps_total_size, decimals) PNL = IS_LONG ? (next_so_qty * next_so_price) - (next_so_qty * avg) : (next_so_qty * avg) - (next_so_qty * next_so_price) Liq = math.round(liq_balance(Wallet,_steps_total_size,avg), decimals) liq_color2 = ((math.abs(PNL) + (_steps_total_volume / leverage) ) > Wallet) liqcon = Liq > 0 and _steps_total_volume < ( Wallet * leverage ) and liq_color2 _liqcon = Liq > 0 and _steps_total_volume < ( Wallet * leverage ) and not liq_color2 liq_color = liqcon ? color.yellow : Liq < 0 and _steps_total_volume < (Wallet * leverage) ? color.green : _liqcon ? color.rgb(191, 17, 165): color.red volwithlev = leverage > 1 ? str.tostring(math.round(next_so_qty * next_so_price, 3))+" β‡’ "+"Lev: " + str.tostring(math.round((next_so_qty * next_so_price / leverage), 3)) + "πŸ’²" : str.tostring(math.round(next_so_qty * next_so_price, decimals)) totalwithlev = leverage > 1 ? str.tostring(math.round(_steps_total_volume, decimals))+ " β‡’ " +"Lev: " + str.tostring(math.round((_steps_total_volume / leverage), decimals)) + "πŸ’²" : str.tostring(math.round(_steps_total_volume, decimals)) table.cell(main, 0, _i + 2, str.tostring(_i), text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 1, _i + 2, str.tostring(math.round(stepped_deviation(_i),decimals)) + " %", text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 2, _i + 2, str.tostring(math.round(next_so_qty, decimals)), text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 3, _i + 2, volwithlev, text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 4, _i + 2, str.tostring(math.round(next_so_price, decimals)), text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 5, _i + 2, str.tostring(math.round(_steps_total_volume / _steps_total_size, decimals)), text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 6, _i + 2, str.tostring(math.round(PNL, decimals)) + "πŸ’²", text_color=color.white, text_size=size.normal,bgcolor = PNL > 0 ? color.green:color.rgb(169, 35, 35, 21)) table.cell(main, 7, _i + 2, Liq < 0 ? "----": str.tostring(Liq), text_color=liqcon ? color.black : color.white, text_size=size.normal,bgcolor = liq_color) table.cell(main, 8, _i + 2, str.tostring(math.round(_steps_total_size, decimals)), text_color=color.white, text_size=size.normal,bgcolor = inrow_color) table.cell(main, 9, _i + 2, str.tostring(totalwithlev), text_color=color.white, text_size=size.normal,bgcolor = inrow_color) if Showstats table stats = table.new(table_position(_position), columns=20, rows=int(Safety_orders) + 4, frame_width=3, frame_color=color.black, border_width=2, border_color=color.black, bgcolor=color.rgb(213, 220, 220, 48)) table.cell(stats, 0, 0, 'BOT info', text_color=color.white, text_size=size.auto, width = 5, height=4) table.cell(stats, 1, 0, '', text_color=color.white, text_size=size.auto) table.merge_cells(stats, 0, 0, 1, 0) table.cell(stats, 0, 1, 'Required Capital ( ' + str.tostring(syminfo.currency) + ' )', text_color=color.white, text_size=size.auto) capitalcon = Wallet<math.round((_steps_total_volume / leverage),decimals) table.cell(stats, 1, 1, capitalcon ? "😞" + " " + str.tostring(math.round((_steps_total_volume / leverage),decimals)) + " " +str.tostring(syminfo.currency) : "πŸ₯³" + " " + str.tostring(math.round((_steps_total_volume / leverage),decimals)) + " " +str.tostring(syminfo.currency), text_color=color.white, text_size=size.auto, bgcolor=capitalcon ? color.red : color.green) table.cell(stats, 0, 2, "Max Deal Value\nwith leverage", text_color=color.white, text_size=size.auto) table.cell(stats, 1, 2, str.tostring(math.round((_steps_total_volume),decimals)) + " " +str.tostring(syminfo.currency), text_color=color.white, text_size=size.auto, bgcolor=Wallet * leverage < math.round((_steps_total_volume),decimals)? color.red : color.green) table.cell(stats, 0, 3, "Leverage", text_color=color.white, text_size=size.auto) table.cell(stats, 1, 3, "X " + str.tostring(leverage), text_color=color.white, text_size=size.auto) table.cell(stats, 0, 4, "Maximum coverage", text_color=color.white, text_size=size.auto) table.cell(stats, 1, 4, str.tostring(math.round(stepped_deviation(_i),decimals)) + " %", text_color=color.white, text_size=size.auto)
ATR Stop Loss v4
https://www.tradingview.com/script/GRrkyhsz-ATR-Stop-Loss-v4/
dratzlogic
https://www.tradingview.com/u/dratzlogic/
32
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© dratzlogic //@version=5 indicator("ATR Stop Loss v4.1", overlay=true, shorttitle="ATR SL v4.1") // Inputs atrLength = input(14, title="ATR Length") stopMultiplier = input(1.5, title="ATR Stop Multiplier") BoxPlacement = input.string(position.top_right, "Box Placement", options=[position.bottom_right, position.bottom_left, position.top_right, position.top_left, position.top_center, position.bottom_center]) plotATR = input(true, title="Plot ATR Stop?") plotTrailing = input(true, title="Plot Trailing Stop?") plotLong = input(true, title="Plot Long Stop?") plotShort = input(true, title="Plot Short Stop?") // Colors text_color = input(color.white, "Text Color") atr_bg_color = input(color.blue, "ATR Row Background Color") trailing_bg_color = input(color.purple, "Trailing Row Background Color") long_bg_color = input(color.green, "Long Row Background Color") short_bg_color = input(color.red, "Short Row Background Color") // Calculate ATR and stop values atrValue = ta.atr(atrLength) longStop = close - atrValue * stopMultiplier shortStop = close + atrValue * stopMultiplier trailingStop = atrValue * stopMultiplier // Prepare a table var table myTable = table.new(BoxPlacement, 1, 4) if barstate.islast // Populate table table.cell(myTable, 0, 0, text="ATR: " + str.tostring(atrValue, "#.##"), text_color=text_color, bgcolor=atr_bg_color) table.cell(myTable, 0, 1, text="Trailing: " + str.tostring(trailingStop, "#.##"), text_color=text_color, bgcolor=trailing_bg_color) table.cell(myTable, 0, 2, text="Long: " + str.tostring(longStop, "#.##"), text_color=text_color, bgcolor=long_bg_color) table.cell(myTable, 0, 3, text="Short: " + str.tostring(shortStop, "#.##"), text_color=text_color, bgcolor=short_bg_color) // Plotting stop lines plot(plotATR ? atrValue : na, title="ATR Stop", color=color.blue) plot(plotTrailing ? trailingStop : na, title="Trailing Stop", color=color.purple) plot(plotLong ? longStop : na, title="Long Stop", color=color.green) plot(plotShort ? shortStop : na, title="Short Stop", color=color.red)
Relative Daily Change% by SUMIT
https://www.tradingview.com/script/zWRrLEqR-Relative-Daily-Change-by-SUMIT/
Sumit44812
https://www.tradingview.com/u/Sumit44812/
34
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Sumit44812 // Disclaimer : **This is for educational purpose only. // "Relative Daily Change%" Indicator // The "Relative Daily Change%" indicator compares a stock's average daily price change percentage over the last 200 days with a chosen index. // It plots a colored curve. If the stock's change% is higher than the index, the curve is green, indicating it's doing better. Red means the stock is underperforming. // This indicator is designed to compare the perfomrace of a stock with specific index (as selected) for last 200 candles. // I use this during a breakout to see whether the stock is perfmorming well with comprison to it`s index. // You can select Index from the list available in input // **Line Color Green = Avg Change% per day of the stock is more than the Selected Index // **Line Color White = Avg Change% per day of the stock is less than the Selected Index // Disclaimer : **This is for educational purpose only. //@version=5 indicator("Relative Daily Change% by SUMIT", overlay=false) // SELECT THE APPLICABLE INDEX TO COMPARE WITH symbol_index = input.string("NSE:NIFTY","REF INDEX", options=["NSE:NIFTY", "NSE:BANKNIFTY","NSE:CNXAUTO", "NSE:CNXFMCG", "NSE:NIFTY_HEALTHCARE", "NSE:CNXIT", "NSE:CNXMEDIA", "NSE:CNXMETAL", "NSE:CNXPHARMA", "NSE:CNXREALTY", "NSE:NIFTY_OIL_AND_GAS"]) // Fetch the stock and index index data stock_close = request.security(syminfo.tickerid, "D", close) index_close = request.security(symbol_index, "D", close) // Calculate the average percentage price change per day for last 200 candles (KEEP TIMEFRAME AS DAILY) avgprice_change_stock = (((stock_close - stock_close[200]) / stock_close[200])/200) * 100 avgprice_change_index = (((index_close - index_close[200]) / index_close[200])/200) * 100 // If stock 200 day average price change is higher than selected index than the curve color will be green lineColour = avgprice_change_stock > avgprice_change_index ? color.green : color.red // Plot the curve plot(avgprice_change_stock, title="AVG CHANGE% / DAY", color=lineColour, linewidth = 2)
Double Relative Strength Index (Double RSI)
https://www.tradingview.com/script/oY0g0Nxo-Double-Relative-Strength-Index-Double-RSI/
Arun_K_Bhaskar
https://www.tradingview.com/u/Arun_K_Bhaskar/
196
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Arun_K_Bhaskar //@version=5 indicator(title="Double Relative Strength Index (Double RSI)", shorttitle="Double RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true) i_show_rsi_1 = input.bool(defval=true, title='', inline='R1') i_length_1 = input.int(defval=5, title='Length', minval=1, inline='R1') i_show_rsi_2 = input.bool(defval=true, title='', inline='R2') i_length_2 = input.int(defval=10, title='Length', minval=1, inline='R2') i_source = input.source(defval=close, title='Source', inline='') i_smoothing = input.string(defval='RMA', title='Smoothing', options=['None', 'RMA', 'SMA', 'EMA', 'WMA', 'HMA'], inline='') i_show_candle = input.bool(defval=true, title='Crossing Candles', tooltip='', inline='') moving_average(source, length) => switch i_smoothing "RMA" => ta.rma(source, length) "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "WMA" => ta.wma(source, length) "HMA" => ta.hma(source, length) rsi_1 = i_smoothing == "None" ? ta.rsi(i_source, i_length_1) : moving_average(ta.rsi(i_source, i_length_1), i_length_1) rsi_2 = i_smoothing == "None" ? ta.rsi(i_source, i_length_2) : moving_average(ta.rsi(i_source, i_length_2), i_length_1) color_1 = #00ff00 color_2 = #ff0000 rsi_col = rsi_1 > rsi_2 ? color_1 : color_2 crossover_color = i_show_candle and ta.crossover(rsi_1, rsi_2) ? #00FFFF : na crossunder_color = i_show_candle and ta.crossunder(rsi_1, rsi_2) ? #FF00FF : na plot(i_show_rsi_1 ? rsi_1 : na, title = "RSI Fast", color=rsi_col) plot(i_show_rsi_2 ? rsi_2 : na, title = "RSI Slow", color=rsi_col) barcolor(color=crossover_color, title='Crossover Candle') barcolor(color=crossunder_color, title='Crossunder Candle') // RSI Bands band90 = hline(80, "RSI 90%", linestyle=hline.style_dotted, color=color.new(color_2, 75)) band80 = hline(75, "RSI 80%", linestyle=hline.style_dotted, color=color.new(color_2, 75)) band60 = hline(55, "RSI 60%", linestyle=hline.style_dotted, color=color.new(color.silver, 75), linewidth=1) band50 = hline(50, "RSI 50%", linestyle=hline.style_dotted, color=color.new(color.silver, 75), linewidth=1) band40 = hline(45, "RSI 40%", linestyle=hline.style_dotted, color=color.new(color.silver, 75), linewidth=1) band20 = hline(25, "RSI 20%", linestyle=hline.style_dotted, color=color.new(color_1, 75)) band10 = hline(20, "RSI 10%", linestyle=hline.style_dotted, color=color.new(color_1, 75)) fill(band80, band90, color=color.new(color_2, 95), title="RSI Upper") fill(band40, band60, color=color.new(color.silver, 95), title="RSI Middle") fill(band10, band20, color=color.new(color_1, 95), title="RSI Lower")
ATR Extension [QuantVue]
https://www.tradingview.com/script/JEew0HGJ-ATR-Extension-QuantVue/
QuantVue
https://www.tradingview.com/u/QuantVue/
183
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© QuantVue //@version=5 indicator("ATR Extension [QuantVue]", overlay = true) /////////// //inputs// var g1 = 'ATR Options' atrLen = input.int(14, 'ATR Length', group = g1) extMult = input.float(3.0, 'Extension Multiple', group = g1) var g2 = 'Moving Average Options' maLen = input.int(21, 'Moving Average', inline = '1', group = g2) maType = input.string('EMA', ' ', options = ['EMA', 'SMA'], inline = '1', group = g2) maWidth = input.int(4, 'MA Thickness', minval = 1, maxval = 5, step = 1, group = g2) var g3 = 'Color Options' upCol = input.color(color.green, 'Low > MA Color', inline = '2', group = g3) dnCol = input.color(color.yellow, 'Low <= MA Color', inline = '2', group = g3) extUpCol = input.color(color.red, 'Extended Up', inline = '3', group = g3) extDnCol = input.color(color.aqua, 'Extended Down', inline = '3', group = g3) ///////////////// //calculations// atr = ta.atr(atrLen) ma = maType == 'EMA' ? ta.ema(close,maLen) : ta.sma(close,maLen) lowVma = low - ma highVma = ma - high rsiPos = lowVma / atr rsiNeg = highVma / atr /////////// //colors// posCol = rsiPos >= extMult ? extUpCol : rsiPos >= 0 ? upCol : rsiPos < 0 and rsiNeg < 0 ? upCol : color.new(color.white,100) negCol = rsiNeg >= extMult ? extDnCol : rsiNeg > 0 ? dnCol: rsiPos < 0 and rsiNeg < 0 ? dnCol : color.new(color.white,100) ///////// //plot// plot(ma, 'EMA', low > ma ? posCol : negCol, linewidth = maWidth) /////////// //alerts// alertcondition(rsiPos >= extMult, 'Extended Up', '{{ticker}} is extended up from it\'s moving average') alertcondition(rsiNeg >= extMult, 'Extended Down', '{{ticker}} is extended down from it\'s moving average')
Japanese Candlestick Patterns
https://www.tradingview.com/script/r3Hqfawn-Japanese-Candlestick-Patterns/
Marceeelll
https://www.tradingview.com/u/Marceeelll/
93
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // Β© Marceeelll //@version=5 indicator("Japanese Candlestick Patterns", overlay=true, max_labels_count = 500) import Marceeelll/JapaneseCandlestickPatterns/1 as jcp /////////////////// // --- TREND --- // /////////////////// var GROUP_TREND = "TREND" C_TrendRuleSMA = "SMA" I_TrendRule = input.string(C_TrendRuleSMA, "Detect Trend Based On", options = [C_TrendRuleSMA, "No Trend"], group = GROUP_TREND) I_TrendLength = input.int(50, 'Trend Length', 0, group = GROUP_TREND) I_PlotTrendLine = input.bool(true, 'Show Trend Line', group = GROUP_TREND) C_IsDownTrend = true C_IsUpTrend = true sma = ta.sma(close, I_TrendLength) plot(I_TrendRule == C_TrendRuleSMA and I_PlotTrendLine ? sma : na, color = color.red, title = "Trend Line") if I_TrendRule == C_TrendRuleSMA C_IsDownTrend := close < sma C_IsUpTrend := close > sma ///////////////////////////// // --- CANDLE SETTINGS --- // ///////////////////////////// I_CandleType = input.string(title = "Pattern Type", defval="Both", options=["Bullish", "Bearish", "Both"]) C_IsCandleTypeBoth = I_CandleType == "Both" C_IsCandleTypeBearish = I_CandleType == "Bearish" C_IsCandleTypeBullish = I_CandleType == "Bullish" /////////////////// // --- STYLE --- // /////////////////// var GROUP_STYLE = "Style" C_LabelColorBullish = input(color.rgb(73, 151, 75), "Label Color Bullish", group = GROUP_STYLE) C_LabelColorBearish = input(color.rgb(195, 67, 67), "Label Color Bearish", group = GROUP_STYLE) C_LabelColorNeutral = input(color.gray, "Label Color Neutral", group = GROUP_STYLE) //////////////////////////////// // --- DETECTION SETTINGS --- // //////////////////////////////// var GROUP_REVERSAL_PATTERNS = "Reversal Patterns" I_ShowCounterattackLines = input(title ="Counterattack Lines", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowDarkCloudCover = input(title="Dark-Cloud Cover", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowEngulfing = input(title="Engulfing", defval = true, group=GROUP_REVERSAL_PATTERNS) I_ShowHammer = input(title="Hammer", defval=true, group=GROUP_REVERSAL_PATTERNS) I_ShowHangingMan = input(title="Hanging Man", defval=true, group=GROUP_REVERSAL_PATTERNS) I_ShowHarami = input(title ="Harami", defval=true, group=GROUP_REVERSAL_PATTERNS) I_ShowInNeck = input(title="In Neck", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowOnNeck = input(title="On Neck", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowPiercing = input(title="Piercing", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowThreeBlackCrows = input(title ="Three Black Crows", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowThrusting = input(title="Thrusting", defval=false, group=GROUP_REVERSAL_PATTERNS) I_ShowUpsideGapTwoCrows = input(title ="Upside Gap Two Crows", defval=false, group=GROUP_REVERSAL_PATTERNS) var GROUP_STARS_PATTERNS = "Stars" I_ShowAbandonedBaby = input(title ="Abandoned Baby", defval=false, group=GROUP_STARS_PATTERNS) I_ShowEveningStar = input(title ="Evening star", defval=true, group=GROUP_STARS_PATTERNS) I_ShowInvertedHammer = input(title ="Inverted Hammer", defval=true, group=GROUP_STARS_PATTERNS) I_ShowMorningStar = input(title ="Morning Star", defval=true, group=GROUP_STARS_PATTERNS) I_ShowShootingStar = input(title ="Shooting Star", defval=false, group=GROUP_STARS_PATTERNS) var GROUP_DOJI_PATTERNS = "Doji" I_ShowDoji = input(title="Doji", defval = false, group=GROUP_DOJI_PATTERNS) I_ShowDragonflyDoji = input(title="Dragonfly Doji", defval = false, group=GROUP_DOJI_PATTERNS) I_ShowEveningDojiStar = input(title="Evening Doji Star", defval = true, group=GROUP_DOJI_PATTERNS) I_ShowGravestoneDoji = input(title="Gravestone Doji", defval = false, group=GROUP_DOJI_PATTERNS) I_ShowLongLeggedDoji = input(title="Long Legged Doji", defval = false, group=GROUP_DOJI_PATTERNS) I_ShowMorningDojiStar = input(title="Morning Doji Star", defval = true, group=GROUP_DOJI_PATTERNS) var GROUP_CONTINUATION_PATTERNS = "Continuation Patterns" I_ShowRisingThreeMethods = input(title ="Falling Three Methods", defval=false, group=GROUP_CONTINUATION_PATTERNS) I_ShowFallingThreeMethods = input(title ="Rising Three Methods", defval=false, group=GROUP_CONTINUATION_PATTERNS) I_ShowTasuki = input(title ="Tasuki", defval=false, group=GROUP_CONTINUATION_PATTERNS) var GROUP_UTILITY_PATTERNS = "Utility" I_ShowLongLowerShadow = input(title ="Long Lower Shadow", defval=false, group=GROUP_UTILITY_PATTERNS) I_ShowLongUpperShadow = input(title ="Long Upper Shadow", defval=false, group=GROUP_UTILITY_PATTERNS) //////////////////// // --- LABELS --- // //////////////////// LABEL_BULLISH_TITLES = array.new_string() LABEL_BULLISH_DESCRIPTIONS = array.new_string() LABEL_BEARISH_TITLES = array.new_string() LABEL_BEARISH_DESCRIPTIONS = array.new_string() LABEL_NEUTRAL_TITLES = array.new_string() LABEL_NEUTRAL_DESCRIPTIONS = array.new_string() //////////////////////////// // --- HELPER METHODS --- // //////////////////////////// str_array_to_string(array, separator) => result = "" lastIndex = array.size(array) - 1 for i = 0 to lastIndex result := result + array.get(array, lastIndex - i) + (i == lastIndex ? "" : "\n") result /////////////////////////// // --- DOJI PATTERNS --- // /////////////////////////// // // --- DOJI PATTERN --- // if I_ShowDoji and jcp.isDojiCandle() LABEL_NEUTRAL_TITLES.push("Doji") LABEL_NEUTRAL_DESCRIPTIONS.push("Doji") // // --- GRAVESTONE DOJI PATTERN --- // if I_ShowGravestoneDoji and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isGravestoneDojiCandle() LABEL_BEARISH_TITLES.push('GD') LABEL_BEARISH_DESCRIPTIONS.push('Gravestone Doji') // // --- DRAGONFLY DOJI PATTERN --- // if I_ShowDragonflyDoji and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isDragonflyDojiCandle() LABEL_BULLISH_TITLES.push('DD') LABEL_BULLISH_DESCRIPTIONS.push('Dragonfly Doji') // // --- EVENING DOJI STAR PATTERN --- // if I_ShowEveningDojiStar and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isEveningDojiStarCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('EDS') LABEL_BEARISH_DESCRIPTIONS.push('Evening Doji Star') // // --- LONG LEGGED DOJI PATTERN --- // if I_ShowLongLeggedDoji and jcp.isLongLeggedDojiCandle() LABEL_NEUTRAL_TITLES.push('LLD') LABEL_NEUTRAL_DESCRIPTIONS.push('Long Legged Doji') // // --- MORNING DOJI STAR PATTERN --- // if I_ShowMorningDojiStar and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isMorningDojiStarCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('MDJ') LABEL_BULLISH_DESCRIPTIONS.push('Morning Doji Star') /////////////////////////////// // --- REVERSAL PATTERNS --- // /////////////////////////////// // // --- COUNTERATTACK LINES PATTERN --- // if I_ShowCounterattackLines and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isBullishCounterattackLinesCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('CAL') LABEL_BULLISH_DESCRIPTIONS.push('Counterattack Lines') if I_ShowCounterattackLines and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isBearishCounterattackLinesCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('CAL') LABEL_BEARISH_DESCRIPTIONS.push('Counterattack Lines') // // --- DARK-CLOUD COVER PATTERN --- // if I_ShowDarkCloudCover and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) [darkCloudCoverPattern, darkCloudCoverPatternPenetrationInPercentage] = jcp.isDarkCloudCoverCandle(isUpTrend = C_IsUpTrend) if darkCloudCoverPattern LABEL_BEARISH_TITLES.push("DCC (" + str.tostring(darkCloudCoverPatternPenetrationInPercentage, "#.##") + "%)") LABEL_BEARISH_DESCRIPTIONS.push("Dark-Cloud Cover (Penetration " + str.tostring(darkCloudCoverPatternPenetrationInPercentage, "#.##") + "%)") // // --- ENGULFING PATTERN --- // if I_ShowEngulfing and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isBullishEngulfingCandle() LABEL_BULLISH_TITLES.push("EG") LABEL_BULLISH_DESCRIPTIONS.push("Engulfing") if I_ShowEngulfing and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isBearishEngulfingCandle() LABEL_BEARISH_TITLES.push("EG") LABEL_BEARISH_DESCRIPTIONS.push("Engulfing") // // --- HAMMER & HANGING MAN PATTERN --- // if I_ShowHammer and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isHammerCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push("HM") LABEL_BULLISH_DESCRIPTIONS.push("Hammer") // // --- HAMMER & HANGING MAN PATTERN --- // if I_ShowHangingMan and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isHangingManCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push("HM") LABEL_BEARISH_DESCRIPTIONS.push("Hanging Man") // // --- HARAMI PATTERN --- // if I_ShowHarami and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isHaramiBearishCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('HR') LABEL_BEARISH_DESCRIPTIONS.push('Harami') if I_ShowHarami and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isHaramiBullishCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('HR') LABEL_BULLISH_DESCRIPTIONS.push('Harami') // // --- IN-NECK PATTERN --- // if I_ShowInNeck and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isInNeckCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('IN') LABEL_BULLISH_DESCRIPTIONS.push('In Neck') // // --- ON-NECK PATTERN --- // if I_ShowOnNeck and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isOnNeckCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('ON') LABEL_BULLISH_DESCRIPTIONS.push('On Neck') // // --- PIERCING PATTERN --- // if I_ShowPiercing and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isPiercingCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('PI') LABEL_BULLISH_DESCRIPTIONS.push('Piercing') // // --- THREE BLACK CROWS PATTERN --- // if I_ShowThreeBlackCrows and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.threeBlackCrowsCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('3BC') LABEL_BEARISH_DESCRIPTIONS.push('Three Black Crows') // // --- THRUSTING-NECK PATTERN --- // if I_ShowThrusting and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isThrustingNeckCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('TN') LABEL_BULLISH_DESCRIPTIONS.push('Thrusting Neck') // // --- UPSIDE-GAP TWO CROWS PATTERN --- // if I_ShowUpsideGapTwoCrows and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isUpsideGapTwoCrowsCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('UGTC') LABEL_BEARISH_DESCRIPTIONS.push('Upside-Gap Two Crows') /////////////////////////// // --- STAR PATTERNS --- // /////////////////////////// // // --- ABANDONED BABY TOP (BEARISH) PATTERN --- // if I_ShowAbandonedBaby and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isAbandonedBabyTopCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('ABT') LABEL_BEARISH_DESCRIPTIONS.push('Abandoned Baby Top') // // --- ABANDONED BABY BOTTOM (BULLISH) PATTERN --- // if I_ShowAbandonedBaby and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isAbandonedBabyBottomCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('ABB') LABEL_BULLISH_DESCRIPTIONS.push('Abandoned Baby Bottom') // // --- EVENING STAR PATTERN --- // if I_ShowEveningStar and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) [isEveningStarPattern, isEveningStarPatternIdeal] = jcp.isEveningStarCandle(isUpTrend = C_IsUpTrend) if isEveningStarPattern LABEL_BEARISH_TITLES.push(isEveningStarPatternIdeal ? 'ES (i)' : 'ES') LABEL_BEARISH_DESCRIPTIONS.push(isEveningStarPatternIdeal ? 'Evening Star (ideal)' : 'Evening Star') // // --- INVERTED HAMMER PATTERN --- // if I_ShowInvertedHammer and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isInvertedHammerCandle(isDownTrend = C_IsDownTrend) LABEL_BULLISH_TITLES.push('IH') LABEL_BULLISH_DESCRIPTIONS.push('Inverted Hammer') // // --- MORNING STAR PATTERN --- // if I_ShowMorningStar and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) [isMorningStarPattern, isMorningStarPatternIdeal] = jcp.isMorningStarCandle(isDownTrend = C_IsDownTrend) if isMorningStarPattern LABEL_BULLISH_TITLES.push(isMorningStarPatternIdeal ? 'MS (i)' : 'MS') LABEL_BULLISH_DESCRIPTIONS.push(isMorningStarPatternIdeal ? 'Morning Star (ideal)' : 'Morning Star') // // --- SHOOTING STAR --- // if I_ShowShootingStar and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isShootingStarCandle(isUpTrend = C_IsUpTrend) LABEL_BEARISH_TITLES.push('SS') LABEL_BEARISH_DESCRIPTIONS.push('Shooting Star') /////////////////////////////////// // --- CONTINUATION PATTERNS --- // /////////////////////////////////// // // --- RISING THREE METHODS PATTERN --- // if I_ShowRisingThreeMethods and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isRisingThreeMethodsCandle(isUpTrend = C_IsUpTrend) LABEL_BULLISH_TITLES.push('RTM') LABEL_BULLISH_DESCRIPTIONS.push('Rising Three Methods') // // --- FALLING THREE METHODS PATTERN --- // if I_ShowFallingThreeMethods and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isFallingThreeMethodsCandle(isDownTrend = C_IsDownTrend) LABEL_BEARISH_TITLES.push('FTM') LABEL_BEARISH_DESCRIPTIONS.push('Falling Three Methods') // // --- UPSIDE TASUKI GAP PATTERN --- // if I_ShowTasuki and (C_IsCandleTypeBoth or C_IsCandleTypeBullish) and jcp.isUpsideTasukiGapCandle(isUpTrend = C_IsUpTrend) LABEL_BULLISH_TITLES.push('UTG') LABEL_BULLISH_DESCRIPTIONS.push('Upside Tasuki Gap') // // --- DOWNSIDE TASUKI GAP PATTERN --- // if I_ShowTasuki and (C_IsCandleTypeBoth or C_IsCandleTypeBearish) and jcp.isDownsideGapTasukiCandle(isDownTrend = C_IsDownTrend) LABEL_BEARISH_TITLES.push('DTG 2') LABEL_BEARISH_DESCRIPTIONS.push('Downside Tasuki Gap') /////////////////////// // --- UTILITIES --- // /////////////////////// // // --- LONG LOWER SHADDOW --- // if I_ShowLongLowerShadow and jcp.isLongLowerShadowCandle() LABEL_BULLISH_TITLES.push('LLS') LABEL_BULLISH_DESCRIPTIONS.push('Long Lower Shaddow') // // --- LONG UPPER SHADDOW --- // if I_ShowLongUpperShadow and jcp.isLongUpperShadowCandle() LABEL_BEARISH_TITLES.push('LUS') LABEL_BEARISH_DESCRIPTIONS.push('Long Upper Shaddow') ////////////////////// // --- PAINTING --- // ////////////////////// if LABEL_NEUTRAL_TITLES.size() != 0 label.new(bar_index, high, text=str_array_to_string(LABEL_NEUTRAL_TITLES, "\n") , yloc=yloc.abovebar, style=label.style_label_down, color=C_LabelColorNeutral, textcolor=color.white, tooltip=str_array_to_string(LABEL_NEUTRAL_DESCRIPTIONS, "\n"), size=size.small) if LABEL_BEARISH_TITLES.size() != 0 label.new(bar_index, high, text=str_array_to_string(LABEL_BEARISH_TITLES, "\n") , yloc=yloc.abovebar, style=label.style_label_down, color=C_LabelColorBearish, textcolor=color.white, tooltip=str_array_to_string(LABEL_BEARISH_DESCRIPTIONS, "\n"), size=size.small) if LABEL_BULLISH_TITLES.size() != 0 label.new(bar_index, high, text=str_array_to_string(LABEL_BULLISH_TITLES, "\n") , yloc=yloc.belowbar, style=label.style_label_up, color=C_LabelColorBullish, textcolor=color.white, tooltip=str_array_to_string(LABEL_BULLISH_DESCRIPTIONS, "\n"), size=size.small)