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
Global Leaders M2
https://www.tradingview.com/script/cEwMVPFC-Global-Leaders-M2/
kikfraben
https://www.tradingview.com/u/kikfraben/
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/ // © kikfraben // Updated last on 27. Oct, 2023 //@version=5 indicator("Global Leaders M2", shorttitle = "GL_M2", overlay = false, precision = 2) // Get Chart Currency cur = input.string("USD", title = "Currency", options = ["USD", "EUR"]) // Get M2 Data of Global Leaders (Top 10) CN = request.security("ECONOMICS:CNM2", "D", close, currency = cur) // CHINA US = request.security("ECONOMICS:USM2", "D", close, currency = cur) // USA JP = request.security("ECONOMICS:JPM2", "D", close, currency = cur) // JAPAN DE = request.security("ECONOMICS:DEM2", "D", close, currency = cur) // GERMANY UK = request.security("ECONOMICS:GBM2", "D", close, currency = cur) // UNITED KINGDOM FR = request.security("ECONOMICS:FRM2", "D", close, currency = cur) // FRANCE IT = request.security("ECONOMICS:ITM2", "D", close, currency = cur) // ITALY CA = request.security("ECONOMICS:CAM2", "D", close, currency = cur) // CANADA RU = request.security("ECONOMICS:RUM2", "D", close, currency = cur) // RUSSIA IN = request.security("ECONOMICS:INM2", "D", close, currency = cur) // INDIA // Get Global Leaders M2 GL_M2 = CN + US + JP + DE + UK + FR + IT + CA + RU + IN // Define Length for Rate of Change roc_len = input(1, "Rate of Change Length", group = "Rate of Change") // Get Rate of Change CN_roc = ta.roc(CN, roc_len) US_roc = ta.roc(US, roc_len) JP_roc = ta.roc(JP, roc_len) DE_roc = ta.roc(DE, roc_len) UK_roc = ta.roc(UK, roc_len) FR_roc = ta.roc(FR, roc_len) IT_roc = ta.roc(IT, roc_len) CA_roc = ta.roc(CA, roc_len) RU_roc = ta.roc(RU, roc_len) IN_roc = ta.roc(IN, roc_len) GL_roc = ta.roc(GL_M2, roc_len) // User Inputs plot_gl = input(true, "Plot Global Leaders M2", group = "Global Leaders Data") plot_table = input(true, "Plot Overview Table", group = "Global Leaders Data") plot_cn = input(false, "Plot China M2", group = "Country Specific Data") plot_us = input(false, "Plot United States M2", group = "Country Specific Data") plot_jp = input(false, "Plot Japan M2", group = "Country Specific Data") plot_de = input(false, "Plot Germany M2", group = "Country Specific Data") plot_uk = input(false, "Plot United Kingdom M2",group = "Country Specific Data") plot_fr = input(false, "Plot France M2", group = "Country Specific Data") plot_it = input(false, "Plot Italy M2", group = "Country Specific Data") plot_ca = input(false, "Plot Canada M2", group = "Country Specific Data") plot_ru = input(false, "Plot Russia M2", group = "Country Specific Data") plot_in = input(false, "Plot India M2", group = "Country Specific Data") // M2 Plots plot(plot_gl ? GL_M2 : na, color = #3fa8c9) plot(plot_cn ? CN : na, color = color.red) plot(plot_us ? US : na, color = color.blue) plot(plot_jp ? JP : na, color = color.white) plot(plot_de ? DE : na, color = color.yellow) plot(plot_uk ? UK : na, color = color.orange) plot(plot_fr ? FR : na, color = color.lime) plot(plot_it ? IT : na, color = color.green) plot(plot_ca ? CA : na, color = color.purple) plot(plot_ru ? RU : na, color = color.silver) plot(plot_in ? IN : na, color = color.navy) // Format Data cn_val = str.tostring(CN / 1000000000000, "#.0") + "T" us_val = str.tostring(US / 1000000000000, "#.0") + "T" jp_val = str.tostring(JP / 1000000000000, "#.0") + "T" de_val = str.tostring(DE / 1000000000000, "#.0") + "T" uk_val = str.tostring(UK / 1000000000000, "#.0") + "T" fr_val = str.tostring(FR / 1000000000000, "#.0") + "T" it_val = str.tostring(IT / 1000000000000, "#.0") + "T" ca_val = str.tostring(CA / 1000000000000, "#.0") + "T" ru_val = str.tostring(RU / 1000000000000, "#.0") + "T" in_val = str.tostring(IN / 1000000000000, "#.0") + "T" gl_val = str.tostring(GL_M2 / 1000000000000, "#.0") + "T" // Color Conditions up_col = #3fa8c9 down_col = #c93f3f bg_col = color.new(color.white, 95) txt_col = color.white txt_col1 = color.new(color.white, 25) txt_col2 = color.new(color.green, 35) cn_col = CN_roc > 0 ? up_col : down_col us_col = US_roc > 0 ? up_col : down_col jp_col = JP_roc > 0 ? up_col : down_col de_col = DE_roc > 0 ? up_col : down_col uk_col = UK_roc > 0 ? up_col : down_col fr_col = FR_roc > 0 ? up_col : down_col it_col = IT_roc > 0 ? up_col : down_col ca_col = CA_roc > 0 ? up_col : down_col ru_col = RU_roc > 0 ? up_col : down_col in_col = IN_roc > 0 ? up_col : down_col gl_col = GL_roc > 0 ? up_col : down_col // Get Overview Table if plot_table == true table = table.new(position = position.top_right, columns = 13, rows = 13, frame_color = color.new(color.white, 70), border_color = color.new(color.white, 70), frame_width = 2, border_width = 2) table.merge_cells(table, 0, 0, 2, 0) // Layout table.cell(table, 0, 0, text = "Global Leaders M2", bgcolor = bg_col, text_color = color.yellow) table.cell(table, 0, 1, "Country", bgcolor = bg_col, text_color = txt_col) table.cell(table, 1, 1, "Current Value", bgcolor = bg_col, text_color = txt_col, tooltip = "Displays the current value in the predefined currency in cur in trillions") table.cell(table, 2, 1, "RoC", bgcolor = bg_col, text_color = txt_col, tooltip = "Displays the Rate of Change of the predefined time horizon in roc_len") table.cell(table, 0, 2, "China", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 3, "United States", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 4, "Japan", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 5, "Germany", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 6, "United Kingdom", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 7, "France", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 8, "Italy", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 9, "Canada", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 10, "Russia", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 11, "India", text_color = txt_col1, bgcolor = bg_col) table.cell(table, 0, 12, "Total", text_color = color.yellow, bgcolor = bg_col) // Current Value table.cell(table, 1, 2, text = cn_val, text_color = cn_col, bgcolor = bg_col) table.cell(table, 1, 3, text = us_val, text_color = us_col, bgcolor = bg_col) table.cell(table, 1, 4, text = jp_val, text_color = jp_col, bgcolor = bg_col) table.cell(table, 1, 5, text = de_val, text_color = de_col, bgcolor = bg_col) table.cell(table, 1, 6, text = uk_val, text_color = uk_col, bgcolor = bg_col) table.cell(table, 1, 7, text = fr_val, text_color = fr_col, bgcolor = bg_col) table.cell(table, 1, 8, text = it_val, text_color = it_col, bgcolor = bg_col) table.cell(table, 1, 9, text = ca_val, text_color = ca_col, bgcolor = bg_col) table.cell(table, 1, 10, text = ru_val, text_color = ru_col, bgcolor = bg_col) table.cell(table, 1, 11, text = in_val, text_color = in_col, bgcolor = bg_col) table.cell(table, 1, 12, text = gl_val, text_color = gl_col, bgcolor = bg_col) // Rate of Change table.cell(table, 2, 2, text = str.tostring(math.round(CN_roc, 2)), text_color = cn_col, bgcolor = bg_col) table.cell(table, 2, 3, text = str.tostring(math.round(US_roc, 2)), text_color = us_col, bgcolor = bg_col) table.cell(table, 2, 4, text = str.tostring(math.round(JP_roc, 2)), text_color = jp_col, bgcolor = bg_col) table.cell(table, 2, 5, text = str.tostring(math.round(DE_roc, 2)), text_color = de_col, bgcolor = bg_col) table.cell(table, 2, 6, text = str.tostring(math.round(UK_roc, 2)), text_color = uk_col, bgcolor = bg_col) table.cell(table, 2, 7, text = str.tostring(math.round(FR_roc, 2)), text_color = fr_col, bgcolor = bg_col) table.cell(table, 2, 8, text = str.tostring(math.round(IT_roc, 2)), text_color = it_col, bgcolor = bg_col) table.cell(table, 2, 9, text = str.tostring(math.round(CA_roc, 2)), text_color = ca_col, bgcolor = bg_col) table.cell(table, 2, 10, text = str.tostring(math.round(RU_roc, 2)), text_color = ru_col, bgcolor = bg_col) table.cell(table, 2, 11, text = str.tostring(math.round(IN_roc, 2)), text_color = in_col, bgcolor = bg_col) table.cell(table, 2, 12, text = str.tostring(math.round(GL_roc, 2)), text_color = gl_col, bgcolor = bg_col)
[KVA]nRSI
https://www.tradingview.com/script/66pF1KrF-KVA-nRSI/
Kamvia
https://www.tradingview.com/u/Kamvia/
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/ // © Kamvia //@version=5 indicator(shorttitle="[KVA]nRSI", title="[KVA]nRSI", overlay=false,format=format.price, precision=2, timeframe="", timeframe_gaps=true) length = input(14, title="nRsi Length") n = input(2, title="Number of Periods for Change") _src = input.source(close,"Source") RSIcalc(src) => delta = ta.change(src, n) gain = math.max(delta, 0) loss = math.abs(math.min(delta, 0)) avg_gain = ta.sma(gain, length) avg_loss = ta.sma(loss, length) rs = avg_gain / avg_loss rsi = 100 - (100 / (1 + rs)) rsi rsi = RSIcalc(_src) ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "RMA" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) maTypeInput = input.string("SMA", title="MA Type", options=["SMA", "EMA", "RMA", "WMA", "VWMA"], group="MA Settings") maLengthInput = input.int(14, title="MA Length", group="MA Settings") rsiMA = ma(rsi, maLengthInput, maTypeInput) rsiPlot = plot(rsi, "RSI", color=#7E57C2) plot(rsiMA, title="N-Day RSI MA " ,color= color.green) rsiUpperBand = hline(80, "RSI Upper Band", color=#787B86) midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50)) rsiLowerBand = hline(20, "RSI Lower Band", color=#787B86) fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill") midLinePlot = plot(50, color = na, editable = false, display = display.none) fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill") fill(rsiPlot, midLinePlot, 30, 0, top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")
Anchored Average Price by Atilla Yurtseven (AAP)
https://www.tradingview.com/script/YBB9USDe-Anchored-Average-Price-by-Atilla-Yurtseven-AAP/
AtillaYurtseven
https://www.tradingview.com/u/AtillaYurtseven/
16
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/ // © AtillaYurtseven //@version=5 indicator("Anchored Average Price // Atilla Yurtseven", shorttitle="AAP", overlay=true, max_bars_back=300) src = input.source(hlc3, title="Source") startCalculationDate = input.time(timestamp("01 Jun 2023"), "Start Date", confirm=true) clr = input.color(color.green, title="Color") var arr = array.new_float(na) var float val = na if time >= startCalculationDate array.push(arr, src) val := array.avg(arr) else array.clear(arr) val := na plot(val, color=clr, title="Average Price")
Libre
https://www.tradingview.com/script/L0Zpnytu-Libre/
Schwehng
https://www.tradingview.com/u/Schwehng/
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/ // © Schwehng //@version=5 library("Libre") rng_size(x, qty, n)=> wper = (n*2) - 1 avrng = ta.ema(math.abs(x - x[1]), n) AC = ta.ema(avrng, wper)*qty rng_size = AC rng_filt(x, rng_, n)=> r = rng_ var rfilt = array.new_float(2, x) array.set(rfilt, 1, array.get(rfilt, 0)) if x - r > array.get(rfilt, 1) array.set(rfilt, 0, x - r) if x + r < array.get(rfilt, 1) array.set(rfilt, 0, x + r) rng_filt1 = array.get(rfilt, 0) hi_band = rng_filt1 + r lo_band = rng_filt1 - r rng_filt = rng_filt1 [hi_band, lo_band, rng_filt] donchian(int len) => math.avg(ta.lowest(len), ta.highest(len)) variant1(src) => a1 = math.exp(-1.414*3.14159 / 8) b1 = 2*a1*math.cos(1.414*3.14159 / 8) c3 = (-a1)*a1 v12 = 0.0 v12 := (1 - b1 - c3)*(src + nz(src[1])) / 2 + b1*nz(v12[1]) + c3*nz(v12[2]) v12 variant2(src) => vsrc=ta.sma(src, 8) v7 = 0.0 v7 := na(v7[1]) ? vsrc : (v7[1] * (8 - 1) + src) / 8 v7 isBat(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.382 and xab <= 0.5 _abc = abc >= 0.382 and abc <= 0.886 _bcd = bcd >= 1.618 and bcd <= 2.618 _xad = xad <= 0.618 and xad <= 1.000 // 0.886 _xab and _abc and _bcd and _xad and (_mode) isAntiBat(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.500 and xab <= 0.886 // 0.618 _abc = abc >= 1.000 and abc <= 2.618 // 1.13 --> 2.618 _bcd = bcd >= 1.618 and bcd <= 2.618 // 2.0 --> 2.618 _xad = xad >= 0.886 and xad <= 1.000 // 1.13 _xab and _abc and _bcd and _xad and (_mode) isAltBat(xab,abc,bcd,xad,_mode)=> _xab = xab <= 0.382 _abc = abc >= 0.382 and abc <= 0.886 _bcd = bcd >= 2.0 and bcd <= 3.618 _xad = xad <= 1.13 _xab and _abc and _bcd and _xad and (_mode) isButterfly(xab,abc,bcd,xad,_mode)=> _xab = xab <= 0.786 _abc = abc >= 0.382 and abc <= 0.886 _bcd = bcd >= 1.618 and bcd <= 2.618 _xad = xad >= 1.27 and xad <= 1.618 _xab and _abc and _bcd and _xad and (_mode) isAntiButterfly(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.236 and xab <= 0.886 // 0.382 - 0.618 _abc = abc >= 1.130 and abc <= 2.618 // 1.130 - 2.618 _bcd = bcd >= 1.000 and bcd <= 1.382 // 1.27 _xad = xad >= 0.500 and xad <= 0.886 // 0.618 - 0.786 _xab and _abc and _bcd and _xad and (_mode) isABCD(xab,abc,bcd,xad,_mode)=> _abc = abc >= 0.382 and abc <= 0.886 _bcd = bcd >= 1.13 and bcd <= 2.618 _abc and _bcd and (_mode) isGartley(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.5 and xab <= 0.618 // 0.618 _abc = abc >= 0.382 and abc <= 0.886 _bcd = bcd >= 1.13 and bcd <= 2.618 _xad = xad >= 0.75 and xad <= 0.875 // 0.786 _xab and _abc and _bcd and _xad and (_mode) isAntiGartley(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.500 and xab <= 0.886 // 0.618 -> 0.786 _abc = abc >= 1.000 and abc <= 2.618 // 1.130 -> 2.618 _bcd = bcd >= 1.500 and bcd <= 5.000 // 1.618 _xad = xad >= 1.000 and xad <= 5.000 // 1.272 _xab and _abc and _bcd and _xad and (_mode) isCrab(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.500 and xab <= 0.875 // 0.886 _abc = abc >= 0.382 and abc <= 0.886 _bcd = bcd >= 2.000 and bcd <= 5.000 // 3.618 _xad = xad >= 1.382 and xad <= 5.000 // 1.618 _xab and _abc and _bcd and _xad and (_mode) isAntiCrab(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.250 and xab <= 0.500 // 0.276 -> 0.446 _abc = abc >= 1.130 and abc <= 2.618 // 1.130 -> 2.618 _bcd = bcd >= 1.618 and bcd <= 2.618 // 1.618 -> 2.618 _xad = xad >= 0.500 and xad <= 0.750 // 0.618 _xab and _abc and _bcd and _xad and (_mode) isShark(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.500 and xab <= 0.875 // 0.5 --> 0.886 _abc = abc >= 1.130 and abc <= 1.618 // _bcd = bcd >= 1.270 and bcd <= 2.240 // _xad = xad >= 0.886 and xad <= 1.130 // 0.886 --> 1.13 _xab and _abc and _bcd and _xad and (_mode) isAntiShark(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.382 and xab <= 0.875 // 0.446 --> 0.618 _abc = abc >= 0.500 and abc <= 1.000 // 0.618 --> 0.886 _bcd = bcd >= 1.250 and bcd <= 2.618 // 1.618 --> 2.618 _xad = xad >= 0.500 and xad <= 1.250 // 1.130 --> 1.130 _xab and _abc and _bcd and _xad and (_mode) is5o(xab,abc,bcd,xad,_mode)=> _xab = xab >= 1.13 and xab <= 1.618 _abc = abc >= 1.618 and abc <= 2.24 _bcd = bcd >= 0.5 and bcd <= 0.625 // 0.5 _xad = xad >= 0.0 and xad <= 0.236 // negative? _xab and _abc and _bcd and _xad and (_mode) isWolf(xab,abc,bcd,xad,_mode)=> _xab = xab >= 1.27 and xab <= 1.618 _abc = abc >= 0 and abc <= 5 _bcd = bcd >= 1.27 and bcd <= 1.618 _xad = xad >= 0.0 and xad <= 5 _xab and _abc and _bcd and _xad and (_mode) isHnS(xab,abc,bcd,xad,_mode)=> _xab = xab >= 2.0 and xab <= 10 _abc = abc >= 0.90 and abc <= 1.1 _bcd = bcd >= 0.236 and bcd <= 0.88 _xad = xad >= 0.90 and xad <= 1.1 _xab and _abc and _bcd and _xad and (_mode) isConTria(xab,abc,bcd,xad,_mode)=> _xab = xab >= 0.382 and xab <= 0.618 _abc = abc >= 0.382 and abc <= 0.618 _bcd = bcd >= 0.382 and bcd <= 0.618 _xad = xad >= 0.236 and xad <= 0.764 _xab and _abc and _bcd and _xad and (_mode) isExpTria(xab,abc,bcd,xad,_mode)=> _xab = xab >= 1.236 and xab <= 1.618 _abc = abc >= 1.000 and abc <= 1.618 _bcd = bcd >= 1.236 and bcd <= 2.000 _xad = xad >= 2.000 and xad <= 2.236 _xab and _abc and _bcd and _xad and (_mode) f_last_fib(_rate,dzz,czz,fib_range)=>dzz > czz ? dzz-(fib_range*_rate):dzz+(fib_range*_rate) export OOO(simple string tuuw) => bool ixet = na var bool lmode = na bool lube = na barm = bar_index var tyme = str.format('{0,date,d-M-YYYY}', time) var Sharp1 = tuuw == "Sharp 1" var Sharp2 = tuuw == "Sharp 2" var Sharp3 = tuuw == "Sharp 3" var Sharp4 = tuuw == "Sharp 4" var Sharp5 = tuuw == "Sharp 5" var Sharp6 = tuuw == "Sharp 6" var Oscil1 = tuuw == "Oscil 1" var Oscil2 = tuuw == "Oscil 2" var Oscil3 = tuuw == "Oscil 3" var Oscil4 = tuuw == "Oscil 4" var Oscil5 = tuuw == "Oscil 5" var Oscil6 = tuuw == "Oscil 6" var Trend1 = tuuw == "Trend 1" var Trend2 = tuuw == "Trend 2" var Trend3 = tuuw == "Trend 3" var Trend4 = tuuw == "Trend 4" var Trend5 = tuuw == "Trend 5" var Trend6 = tuuw == "Trend 6" var Border1 = tuuw == "Border 1" var Border2 = tuuw == "Border 2" var Border3 = tuuw == "Border 3" var Border4 = tuuw == "Border 4" var Border5 = tuuw == "Border 5" var Border6 = tuuw == "Border 6" float resulta = 0.0 var hayay= array.new_float(0) var lowow= array.new_float(0) var payer= array.new_float(0) var gain = array.new_float(0) var loss = array.new_float(0) var int posak = 0 var float aver = 0.0 var float ktpb = 0.0 var float Pgains = 0.0 var float DIFF = 0.0 var float prast = close var float sumo = 0.0 array.push(hayay, high) array.push(lowow, low) if Sharp1 resulta := ta.linreg(close - math.avg(math.avg(ta.highest(high, 20), ta.lowest(low, 20)),ta.sma(close,20)), 20,0) if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Sharp2 price=open hma1=ta.hma(price, 14) hma2=ta.hma(price[1], 14) conversionLine = donchian(9) baseLine = donchian(26) leadLine1 = math.avg(conversionLine, baseLine) leadLine2 = donchian(52) MACD = ta.hma(price, 12) - ta.hma(price, 26) aMACD = ta.hma(MACD, 9) resulta := (hma1>hma2 and price>hma2 and leadLine1>leadLine2 and MACD>aMACD) ? 1 : (hma1<hma2 and price<hma2 and leadLine1<leadLine2 and MACD<aMACD) ? -1 : 0 if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Sharp3 [h_band, l_band, filt] = rng_filt(close, rng_size(close, 3.5, 20), 20) var fdir = 0.0 fdir := filt > filt[1] ? 1 : filt < filt[1] ? -1 : fdir upward = fdir==1 ? 1 : 0 downward = fdir==-1 ? 1 : 0 longCond = close > filt and close > close[1] and upward > 0 or close > filt and close < close[1] and upward > 0 shortCond = close < filt and close < close[1] and downward > 0 or close < filt and close > close[1] and downward > 0 CondIni = 0 CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1] resulta := (longCond and CondIni[1] == -1) ? 1 : (shortCond and CondIni[1] == 1) ? -1 : 0 if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Sharp4 awesome=(ta.sma(hl2,5)-ta.sma(hl2,34))*1000 k=ta.sma(ta.stoch(close,high,low,14),3) d=ta.sma(14,3) rsi=ta.rsi(close,10) atrvalue=ta.rma(ta.tr,14) resulta := (k<20 and rsi<30 and awesome>awesome[1]) ? 1 : (k>80 and rsi>70 and awesome<awesome[1]) ? -1 : 0 if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false // if (LongCondition) // stoploss=low-atrvalue // takeprofit=close+atrvalue // strategy.entry("Long Position", strategy.long) // strategy.exit("TP/SL",stop=stoploss,limit=takeprofit) // if (ShortCondition) // stoploss=high+atrvalue // takeprofit=close-atrvalue // strategy.entry("Short Position",strategy.short) // strategy.exit("TP/SL",stop=stoploss,limit=takeprofit) else if Sharp5 Rsi = ta.rsi(close, 14) RsiMa = ta.ema(Rsi, 5) AtrRsi = math.abs(RsiMa[1] - RsiMa) MaAtrRsi = ta.ema(AtrRsi, 27) longband = 0.0 shortband = 0.0 trend = 0 DeltaFastAtrRsi = ta.ema(MaAtrRsi, 27) * 4.238 newshortband = RsiMa + DeltaFastAtrRsi newlongband = RsiMa - DeltaFastAtrRsi longband := RsiMa[1] > longband[1] and RsiMa > longband[1] ? math.max(longband[1], newlongband) : newlongband shortband := RsiMa[1] < shortband[1] and RsiMa < shortband[1] ? math.min(shortband[1], newshortband) : newshortband cross_1 = ta.cross(longband[1], RsiMa) trend := ta.cross(RsiMa, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1) FastAtrRsiTL = trend == 1 ? longband : shortband QQExlong = 0 QQExlong := nz(QQExlong[1]) QQExshort = 0 QQExshort := nz(QQExshort[1]) QQExlong := FastAtrRsiTL < RsiMa ? QQExlong + 1 : 0 QQExshort := FastAtrRsiTL > RsiMa ? QQExshort + 1 : 0 if QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na lube := true if QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na lube := false else if Sharp6 vrsi = ta.rsi(close, 6) [BBmid, BBup, BBlow] = ta.bb(close, 200, 2) Bbuy = ta.crossover(close, BBlow) Ssell = ta.crossunder(close, BBup) Vbuy = ta.crossover(vrsi, 50) Vsell = ta.crossunder(vrsi, 50) if (not na(vrsi)) if Vbuy and Bbuy lube := true if Vsell and Ssell lube := false else if Oscil1 TRIX = 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(close), 18), 18), 18)) TSI1 = ta.tsi(close, 25, 13) TSI2 = ta.tsi(close, 50, 26) resulta += (TRIX>0?1:TRIX<0?-1:0) resulta += (TSI1>0?1:TSI1<0?-1:0) resulta += (TSI2>0?1:TSI2<0?-1:0) if ta.crossover(resulta,1) lube := true if ta.crossunder(resulta,-1) lube := false else if Oscil2 HULL = ta.wma(2 * ta.wma(close,27) - ta.wma(close,55), math.round(math.sqrt(55))) HULLx = HULL[2] resulta += (HULL>HULLx?1:HULL<HULLx?-1:0) if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Oscil3 HULL = ta.ema(2 * ta.ema(close, 27) - ta.ema(close, 55), math.round(math.sqrt(55))) HULLx = HULL[2] resulta += (HULL>HULLx?1:HULL<HULLx?-1:0) if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Oscil4 HULL = ta.wma(ta.wma(close,9) * 3 - ta.wma(close, 13) - ta.wma(close, 27), 27) HULLx = HULL[2] resulta += (HULL>HULLx?1:HULL<HULLx?-1:0) if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Oscil5 ten=ta.sma(hl2,9) kij=ta.sma(hl2,26) sen=ta.sma(hl2,52) sen := ta.change(sen,26) bull = ten > kij and close > sen bear = ten < kij and close < sen resulta += (ten>kij and close>sen?1: ten<kij and close<sen?-1: 0) if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Oscil6 k=ta.sma(ta.stoch(close,high,low,14),3) trsi=ta.rsi(close,10) awesome=(ta.sma(hl2,5)-ta.sma(hl2,34))*1000 //d=sma(k,3) //atrvalue=ta.rma(ta.tr,14) resulta += (k<20 and trsi<30 and awesome>awesome[1]?1:k>80 and trsi>70 and awesome<awesome[1]?-1:0) // if (LongCondition) // stoploss=low-atrvalue // takeprofit=close+atrvalue // strategy.entry("Long Position", strategy.long) // strategy.exit("TP/SL",stop=stoploss,limit=takeprofit) // if (ShortCondition) // stoploss=high+atrvalue // takeprofit=close-atrvalue // strategy.entry("Short Position",strategy.short) // strategy.exit("TP/SL",stop=stoploss,limit=takeprofit) if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Trend1 [nook,gook] = ta.supertrend(3, 10) resulta := -gook if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Trend2 TRIX = 10000 * ta.change(ta.ema(ta.ema(ta.ema(math.log(ta.vwap), 18), 18), 18)) TSI1 = ta.tsi(ta.vwap, 25, 13) TSI2 = ta.tsi(ta.vwap, 50, 26) resulta += (TRIX>0?1:TRIX<0?-1:0) resulta += (TSI1>0?1:TSI1<0?-1:0) resulta += (TSI2>0?1:TSI2<0?-1:0) if ta.crossover(resulta,2) lube := true if ta.crossunder(resulta,2) lube := false else if Trend3 price=ta.vwap hma1=ta.hma(price, 14) hma2=ta.hma(price[1], 14) conversionLine = donchian(9) baseLine = donchian(26) leadLine1 = math.avg(conversionLine, baseLine) leadLine2 = donchian(52) MACD = ta.hma(price, 12) - ta.hma(price, 26) aMACD = ta.hma(MACD, 9) resulta := (hma1>hma2 and price>hma2 and leadLine1>leadLine2 and MACD>aMACD) ? 1 : (hma1<hma2 and price<hma2 and leadLine1<leadLine2 and MACD<aMACD) ? -1 : 0 if ta.crossover(resulta,0) lube := true if ta.crossunder(resulta,0) lube := false else if Trend4 ATR = ta.sma(ta.tr, 14) upT = low - ATR downT = high + ATR AlphaTrend = 0.0 AlphaTrend := (false ? ta.rsi(close, 14) >= 50 : ta.mfi(hlc3, 14) >= 50) ? upT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : upT : downT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : downT if ta.crossover(AlphaTrend, AlphaTrend[2]) lube := true if ta.crossunder(AlphaTrend, AlphaTrend[2]) lube := false else if Trend5 fastL = ta.highest(20) fastLC = ta.lowest(10) fastS = ta.lowest(20) fastSC = ta.highest(10) if high > fastL[1] lube := true if low < fastS[1] lube := false ixet := (low<=fastLC[1])?true : (high>=fastSC[1])?false : na else if Trend6 slowL = ta.highest(55) slowLC = ta.lowest(20) slowS = ta.lowest(55) slowSC = ta.highest(20) if high > slowL[1] lube := true if low < slowS[1] lube := false ixet := (low<=slowLC[1])?true : (high>=slowSC[1])?false : na else if Border1 RSI = ta.rsi(close,14) CCI = ta.cci(close,20) WERP = ta.wpr(14) STOCH = ta.stoch(close,high,low,14) rsik = ta.sma(ta.stoch(RSI, RSI, RSI, 14), 3) STOCHr = ta.sma(rsik, 3) resulta += (RSI>70?-1:RSI<30?1:0) resulta += (CCI>100?-1:CCI<-100?1:0) resulta += (WERP>-20?-1:WERP<-80?1:0) resulta += (STOCH>80?-1:STOCH<20?1:0) resulta += (STOCHr>80?-1:STOCHr<20?1:0) if ta.crossover(resulta,3) lube := true if ta.crossunder(resulta,3) lube := false else if Border2 k = ta.sma(ta.stoch(close, high, low, 14), 3) dd = ta.sma(k, 3) vrsi = ta.rsi(close, 14) if (not na(k) and not na(dd)) if (k[1] <= dd and k > dd and k < 20) if (not na(vrsi)) and (vrsi[1] <= 30 and vrsi > 30) lube := true if (ta.crossunder(k,dd) and k > 80) if (vrsi[1] >= 70 and vrsi < 70) lube := false else if Border3 nLoss = ta.atr(10) xATRTrailingStop = 0.0 xATRTrailingStop := ( (close>nz(xATRTrailingStop[1],0) and close[1]>nz(xATRTrailingStop[1],0)) ? math.max(nz(xATRTrailingStop[1]),close -nLoss) : ( (close<nz(xATRTrailingStop[1],0) and close[1]<nz(xATRTrailingStop[1],0)) ? math.min(nz(xATRTrailingStop[1]), (close+nLoss)): (close>nz(xATRTrailingStop[1],0)?(close - nLoss):(close + nLoss))) ) ema = ta.ema(close,1) above = ta.crossover(ema, xATRTrailingStop) below = ta.crossover(xATRTrailingStop, ema) if close > xATRTrailingStop and above lube := true if close < xATRTrailingStop and below lube := false else if Border4 closeSeries = variant1(close) openSeries = variant1(open) if ta.crossover(closeSeries, openSeries) lube := true if ta.crossunder(closeSeries, openSeries) lube := false else if Border5 closeSeries = variant2(close) openSeries = variant2(open) if ta.crossover(closeSeries, openSeries) lube := true if ta.crossunder(closeSeries, openSeries) lube := false else if Border6 _isUp = close >= open _isDown = close <= open zhz = ta.highest(2) zlz = ta.lowest(2) int _direction = na _direction := _isUp[1] and _isDown ? -1 : _isDown[1] and _isUp ? 1 : nz(_direction[1]) sz = _isUp[1] and _isDown and _direction[1] != -1 ? zhz : _isDown[1] and _isUp and _direction[1] != 1 ? zlz : na zxz = ta.valuewhen(sz, sz, 4) zaz = ta.valuewhen(sz, sz, 3) zbz = ta.valuewhen(sz, sz, 2) zcz = ta.valuewhen(sz, sz, 1) zdz = ta.valuewhen(sz, sz, 0) fib_range = math.abs(zdz-zcz) xab = (math.abs(zbz-zaz)/math.abs(zxz-zaz)) xad = (math.abs(zaz-zdz)/math.abs(zxz-zaz)) abc = (math.abs(zbz-zcz)/math.abs(zaz-zbz)) bcd = (math.abs(zcz-zdz)/math.abs(zbz-zcz)) negat = (zdz > zcz) posit = (zdz < zcz) buy_patterns_00 = isABCD(xab,abc,bcd,xad,posit) or isBat(xab,abc,bcd,xad,posit) or isAltBat(xab,abc,bcd,xad,posit) or isButterfly(xab,abc,bcd,xad,posit) or isGartley(xab,abc,bcd,xad,posit) or isCrab(xab,abc,bcd,xad,posit) or isShark(xab,abc,bcd,xad,posit) or is5o(xab,abc,bcd,xad,posit) or isWolf(xab,abc,bcd,xad,posit) or isHnS(xab,abc,bcd,xad,posit) or isConTria(xab,abc,bcd,xad,posit) or isExpTria(xab,abc,bcd,xad,posit) buy_patterns_01 = isAntiBat(xab,abc,bcd,xad,posit) or isAntiButterfly(xab,abc,bcd,xad,posit) or isAntiGartley(xab,abc,bcd,xad,posit) or isAntiCrab(xab,abc,bcd,xad,posit) or isAntiShark(xab,abc,bcd,xad,posit) sel_patterns_00 = isABCD(xab,abc,bcd,xad,negat) or isBat(xab,abc,bcd,xad,negat) or isAltBat(xab,abc,bcd,xad,negat) or isButterfly(xab,abc,bcd,xad,negat) or isGartley(xab,abc,bcd,xad,negat) or isCrab(xab,abc,bcd,xad,negat) or isShark(xab,abc,bcd,xad,negat) or is5o(xab,abc,bcd,xad,negat) or isWolf(xab,abc,bcd,xad,negat) or isHnS(xab,abc,bcd,xad,negat) or isConTria(xab,abc,bcd,xad,negat) or isExpTria(xab,abc,bcd,xad,negat) sel_patterns_01 = isAntiBat(xab,abc,bcd,xad,negat) or isAntiButterfly(xab,abc,bcd,xad,negat) or isAntiGartley(xab,abc,bcd,xad,negat) or isAntiCrab(xab,abc,bcd,xad,negat) or isAntiShark(xab,abc,bcd,xad,negat) ixet := (high >= f_last_fib(0.618,zdz,zcz,fib_range) or low <= f_last_fib(-0.236,zdz,zcz,fib_range)) ? true : (low <= f_last_fib(0.618,zdz,zcz,fib_range) or high >= f_last_fib(-0.236,zdz,zcz,fib_range)) ? false : na if (buy_patterns_00 or buy_patterns_01) and close <= f_last_fib(0.236,zdz,zcz,fib_range) lube := true if (sel_patterns_00 or sel_patterns_01) and close >= f_last_fib(0.236,zdz,zcz,fib_range) lube := false var color cor = na bool bloo = na var hig = 0.0 var owl = 0.0 if lube == true cor := color.rgb(33, 149, 243, 66) if lmode == false hig := array.max(hayay) owl := array.min(lowow) ssol = -(math.round(((hig - prast) / prast) * 100,2)) niag = -(math.round(((owl - prast) / prast) * 100,2)) tpos = -(math.round(((close - prast) / prast) * 100,2)) array.push(payer, tpos) array.push(gain, niag) array.push(loss, ssol) array.clear(hayay) array.clear(lowow) prast := close posak += 1 else if lmode hig := array.max(hayay) owl := array.min(lowow) niag = math.round(((hig - prast) / prast) * 100,2) ssol = math.round(((owl - prast) / prast) * 100,2) tpos = math.round(((close - prast) / prast) * 100,2) array.push(payer, tpos) array.push(gain, niag) array.push(loss, ssol) array.clear(hayay) array.clear(lowow) prast := close posak += 1 lmode := true else if lube == false cor := color.rgb(243, 33, 33, 67) if lmode == false hig := array.max(hayay) owl := array.min(lowow) ssol = -(math.round(((hig - prast) / prast) * 100,2)) niag = -(math.round(((owl - prast) / prast) * 100,2)) tpos = -(math.round(((close - prast) / prast) * 100,2)) array.push(payer, tpos) array.push(gain, niag) array.push(loss, ssol) array.clear(hayay) array.clear(lowow) prast := close posak += 1 else if lmode hig := array.max(hayay) owl := array.min(lowow) niag = math.round(((hig - prast) / prast) * 100,2) ssol = math.round(((owl - prast) / prast) * 100,2) tpos = math.round(((close - prast) / prast) * 100,2) array.push(payer, tpos) array.push(gain, niag) array.push(loss, ssol) array.clear(hayay) array.clear(lowow) prast := close posak += 1 lmode := false if barstate.islastconfirmedhistory sumo := array.sum(payer) aver := sumo/posak ktpb := aver / (barm / posak) Pgains:= array.sum(gain) DIFF := Pgains / sumo //REMARK := DIFF < 1.0? str.tostring(DIFF) : "xxxx" [tyme,barm,sumo,posak,aver,ktpb,Pgains,DIFF,lube,open,high,low,close,hig,owl,cor,ixet]//,REMARK] export MMMM(simple string toe,simple bool CLUST1,simple string SYM) => string tex = CLUST1?toe:SYM export WWWW(simple string oet, simple bool CLUST2, simple string STR) => string tex = CLUST2?oet: STR export OOOO(simple string inputs, simple string tmp, simple bool CLUST3, simple bool CLUST4, simple string RES, simple string toe1, simple string toe2, simple string toe3, simple string toe4, simple string toe5) => string tex=CLUST3?(CLUST4?(tmp=="1"?toe3: tmp=="5"?toe5: tmp=="15"?toe2: tmp=="30"?toe4: tmp=="60"?toe1:inputs): inputs==""?tmp:inputs): RES==""?tmp: RES export XXXX(simple float toe) => float tex = toe export SSSS(simple string toe) => string tex = toe export HHHH(bool bowl,int bar,float hig,float owl,bool xet) => var bool lmode = na var color cor = na var float prast = close var int galaw = 0 if bowl cor := color.rgb(63, 70, 255) if lmode == false ssol = -(math.round(((hig - prast) / prast) * 100,2)) niag = -(math.round(((owl - prast) / prast) * 100,2)) tpos = -(math.round(((close - prast) / prast) * 100,2)) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_bottom, bgcolor=na, text_size=size.normal) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_top, bgcolor=color.rgb(91, 82, 255, 49), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) if lmode == true niag = math.round(((hig - prast) / prast) * 100,2) ssol = math.round(((owl - prast) / prast) * 100,2) tpos = math.round(((close - prast) / prast) * 100,2) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_top, bgcolor=na, text_size=size.normal) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_bottom, bgcolor=color.rgb(243, 33, 33, 52), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) galaw := bar_index prast := close strategy.entry("long",strategy.long) lmode := true else if bowl == false cor := color.rgb(255, 66, 66) if lmode == false ssol = -(math.round(((hig - prast) / prast) * 100,2)) niag = -(math.round(((owl - prast) / prast) * 100,2)) tpos = -(math.round(((close - prast) / prast) * 100,2)) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_bottom, bgcolor=na, text_size=size.normal) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_top, bgcolor=color.rgb(91, 82, 255, 49), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) if lmode == true niag = math.round(((hig - prast) / prast) * 100,2) ssol = math.round(((owl - prast) / prast) * 100,2) tpos = math.round(((close - prast) / prast) * 100,2) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_top, bgcolor=na, text_size=size.normal) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_bottom, bgcolor=color.rgb(243, 33, 33, 52), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) galaw := bar_index prast := close strategy.entry("short",strategy.short) lmode := false if xet strategy.close("long") else if xet==false strategy.close("short") cor export DDDD(bool bwol,float num,int bmun,bool xet) => var bool lmode = na bar = bar_index var hayay= array.new_float(0) var lowow= array.new_float(0) array.push(hayay, high) array.push(lowow, low) var float prast = close var int galaw = 0 if bwol if num >= bmun if (bar - galaw) > 900 galaw := (bar - 900) hig = array.max(hayay) owl = array.min(lowow) if lmode == false ssol = -(math.round(((hig - prast) / prast) * 100,2)) niag = -(math.round(((owl - prast) / prast) * 100,2)) tpos = -(math.round(((close - prast) / prast) * 100,2)) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_bottom, bgcolor=na, text_size=size.normal) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_top, bgcolor=color.rgb(91, 82, 255, 49), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) if lmode == true niag = math.round(((hig - prast) / prast) * 100,2) ssol = math.round(((owl - prast) / prast) * 100,2) tpos = math.round(((close - prast) / prast) * 100,2) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_top, bgcolor=na, text_size=size.normal) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_bottom, bgcolor=color.rgb(243, 33, 33, 52), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) galaw := bar_index prast := close array.clear(hayay) array.clear(lowow) strategy.entry("long",strategy.long) lmode := true else if bwol == false if num <= -bmun if (bar - galaw) > 900 galaw := (bar - 900) hig = array.max(hayay) owl = array.min(lowow) if lmode == false ssol = -(math.round(((hig - prast) / prast) * 100,2)) niag = -(math.round(((owl - prast) / prast) * 100,2)) tpos = -(math.round(((close - prast) / prast) * 100,2)) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_bottom, bgcolor=na, text_size=size.normal) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_top, bgcolor=color.rgb(91, 82, 255, 49), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) if lmode == true niag = math.round(((hig - prast) / prast) * 100,2) ssol = math.round(((owl - prast) / prast) * 100,2) tpos = math.round(((close - prast) / prast) * 100,2) box.new(galaw,hig,bar,prast,color.blue,2,text=str.tostring(niag), text_color=color.white,text_valign=text.align_top, bgcolor=na, text_size=size.normal) box.new(galaw,prast,bar,owl,color.red,2,text=str.tostring(ssol), text_color=color.white,text_valign=text.align_bottom, bgcolor=color.rgb(243, 33, 33, 52), text_size=size.normal) box.new(galaw,prast,bar,close,color.yellow,2, text=str.tostring(tpos), text_color=color.white, bgcolor=na, text_size=size.normal) galaw := bar_index prast := close array.clear(hayay) array.clear(lowow) strategy.entry("short",strategy.short) lmode := false if xet strategy.close("long") else if xet==false strategy.close("short") export IIII(float swap)=> median = ta.percentile_nearest_rank(swap, 3, 50) atr_ = 2 * ta.atr(14) lwr = median - atr_ gap = ((median + atr_) - lwr) / 15 [lwr,gap] export QQQQ(bool bol1,simple float harang1,bool bol2,simple float harang2,bool bol3,simple float harang3, bool bol4,simple float harang4,bool bol5,simple float harang5)=> var DG = array.new_float(5,0) if bol1 array.set(DG,0,harang1) else if bol1 == false array.set(DG,0,-harang1) if bol2 array.set(DG,1,harang2) else if bol2 == false array.set(DG,1,-harang2) if bol3 array.set(DG,2,harang3) else if bol3 == false array.set(DG,2,-harang3) if bol4 array.set(DG,3,harang4) else if bol4 == false array.set(DG,3,-harang4) if bol5 array.set(DG,4,harang5) else if bol5 == false array.set(DG,4,-harang5) oist = array.sum(DG) oist
Volume Spike Analysis [Trendoscope]
https://www.tradingview.com/script/ZaliXFLV-Volume-Spike-Analysis-Trendoscope/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
213
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 // ░▒ // ▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒ // ▒▒▒▒▒▒▒░ ▒ ▒▒ // ▒▒▒▒▒▒ ▒ ▒▒ // ▓▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒▒▒ ▒ ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ // ▒ ▒ ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒ // ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒ // ▒▒▒▒▒ ▒▒▒▒▒▒▒ // ▒▒▒▒▒▒▒▒▒ // ▒▒▒▒▒ ▒▒▒▒▒ // ░▒▒▒▒ ▒▒▒▒▓ ████████╗██████╗ ███████╗███╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗ // ▓▒▒▒▒ ▒▒▒▒ ╚══██╔══╝██╔══██╗██╔════╝████╗ ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ██║ ██████╔╝█████╗ ██╔██╗ ██║██║ ██║██║ ██║███████╗██║ ██║ ██║██████╔╝█████╗ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██╔══██╗██╔══╝ ██║╚██╗██║██║ ██║██║ ██║╚════██║██║ ██║ ██║██╔═══╝ ██╔══╝ // ▒▒▒▒▒ ▒▒▒▒▒ ██║ ██║ ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║ ███████╗ // ▒▒ ▒ //@version=5 indicator("Volume Spike Analysis [Trendoscope]", max_lines_count = 500, overlay = false, format = format.volume) import HeWhoMustNotBeNamed/BinaryInsertionSort/1 as bis highVolumeDistanceThreshold = input.int(90, 'Last High Volume Distance Percentile', 5, 100, 5, 'Minimum percentile of last high volume distance to be considered for highlighting', display = display.none) volumeSpikeReference = input.string('median', 'Volume Spike Reference', ['median', 'average', 'lowest'], 'Method to calculate the measure of volume spike', display = display.none) volumeSpikeThreshold = input.int(85, 'Volume Spike Threshold', 5, 100, 5, 'Minimum Volume Spike threshold to be considered for highlighting', display = display.none) lastHighDistance(float source)=> var sourceArray = array.new<float>() sourceArray.push(source) var lastHighIndex = 0 currentLastHighIndex = source < nz(source[1], source)? sourceArray.size()-2 : lastHighIndex while (source > sourceArray.get(currentLastHighIndex) and currentLastHighIndex !=0) currentLastHighIndex-=1 lastHighIndex := currentLastHighIndex == 0? sourceArray.size()-1 : currentLastHighIndex lastHighDistance = sourceArray.size()-lastHighIndex-1 [valueArray, sortedArray, sortIndex] = bis.get_array_of_series(lastHighDistance) lastDistancePercentile = math.round(sortIndex*100/valueArray.size(), 2) [lastHighIndex, sourceArray, lastHighDistance, lastDistancePercentile] type LineProperties string xloc = xloc.bar_index string extend = extend.none color color = chart.fg_color string style = line.style_arrow_right int width = 1 type LabelProperties float positionRatio = 0.5 string xloc = xloc.bar_index string yloc = yloc.price color color = color.blue string style = label.style_none color textcolor = chart.fg_color string size = size.normal string textalign = text.align_center string text_font_family = font.family_default type LabelledLine line ln label lbl method flush(array<LabelledLine> this)=> while this.size() > 0 l = this.pop() l.ln.delete() l.lbl.delete() method getLabelPosition(LabelProperties this, chart.point first, chart.point other)=> chart.point.new( first.time + int(math.abs(first.time-other.time)*this.positionRatio), first.index + int(math.abs(first.index - other.index)*this.positionRatio), first.price + math.abs(first.price-other.price)*this.positionRatio ) method add(array<LabelledLine> this, chart.point start, chart.point end, string lableText, string tooltip = na, LineProperties lineProps = na, LabelProperties labelProps = na)=> lp = na(lineProps)? LineProperties.new() : lineProps lap = na(labelProps)? LabelProperties.new() : labelProps this.push(LabelledLine.new( line.new(start, end, lp.xloc, lp.extend, lp.color, lp.style, lp.width), label.new(lap.getLabelPosition(start, end), lableText, lap.xloc, lap.yloc, lap.color, lap.style, lap.textcolor, lap.size, lap.textalign, tooltip, lap.text_font_family) )) [lastHighIndex, sourceArray, volumeLastHighDistance, lastDistancePercentile] = lastHighDistance(volume) var array<LabelledLine> markers = array.new<LabelledLine>() transparency = 90 if(lastDistancePercentile >= highVolumeDistanceThreshold and lastHighIndex < sourceArray.size()-3) subArray = sourceArray.slice(lastHighIndex+1, sourceArray.size()-1) sortIndicesOfSubArray = subArray.sort_indices(order.ascending) lowestVolumeIndex = lastHighIndex + sortIndicesOfSubArray.first() + 1 lowestPoint = subArray.min() medianPoint = subArray.median() medianIndex = lastHighIndex + sortIndicesOfSubArray.get(sortIndicesOfSubArray.size()/2) + 1 averagePoint = subArray.avg() distanceFromReference = volume - (volumeSpikeReference == 'median'? medianPoint : volumeSpikeReference == 'average'? averagePoint : lowestPoint) [valueArray, sortedArray, sortIndex] = bis.get_array_of_series(distanceFromReference/volume) lowToHighVolumeDiffPercentile = math.round(sortIndex*100/valueArray.size()) highlight = lastDistancePercentile >= highVolumeDistanceThreshold and lowToHighVolumeDiffPercentile >= volumeSpikeThreshold transparency := int(highlight? (100-(lastDistancePercentile+lowToHighVolumeDiffPercentile)/2)*0.9: 90) var line averageLine = na if(highlight) markers.flush() lowestTimes = math.round(volume/lowestPoint, 2) medianTimes = math.round(volume/medianPoint, 2) averageTimes = math.round(volume/averagePoint, 2) labelContent = str.tostring(volumeLastHighDistance)+' Bars ('+str.tostring(lastDistancePercentile)+'th Percentile)\n'+ str.tostring(lowestTimes) + ' times lowest volume\n' + str.tostring(medianTimes) + ' times median volume\n' + str.tostring(averageTimes) + ' times average volume' markers.add( chart.point.from_index(lastHighIndex+1, volume), chart.point.from_index(bar_index-1, volume), labelContent ) markers.add( chart.point.from_index(lowestVolumeIndex, lowestPoint), chart.point.from_index(lowestVolumeIndex, volume), '🟡', 'Lowest Volume '+str.tostring(lowestPoint), labelProps = LabelProperties.new(0) ) markers.add( chart.point.from_index(medianIndex, medianPoint), chart.point.from_index(medianIndex, volume), '🟡', 'Median Volume '+str.tostring(medianPoint), labelProps = LabelProperties.new(0) ) markers.add( chart.point.from_index(lastHighIndex+1, averagePoint), chart.point.from_index(bar_index-1, averagePoint), '▶', 'Average Volume '+str.tostring(averagePoint), lineProps = LineProperties.new(style = line.style_dotted), labelProps = LabelProperties.new(0, textcolor = color.yellow) ) averageLine.delete() averageLine := line.new(chart.point.from_index(bar_index-1, averagePoint), chart.point.from_index(lastHighIndex+1, averagePoint), style = line.style_dotted) barColor = color.new(close > open? color.lime : color.orange, transparency) plot(volume, 'Volume', barColor, style = plot.style_columns, display = display.pane)
Market Internals (TICK, ADD, VOLD, TRIN, VIX)
https://www.tradingview.com/script/aNrCpO4C-Market-Internals-TICK-ADD-VOLD-TRIN-VIX/
liquid-trader
https://www.tradingview.com/u/liquid-trader/
119
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/ // © liquid-trader // This script allows you to perform data transformations on Market Internals, across exchanges, and specify // signal parameters, to more easily identify sentiment extremes. // More here: https://www.tradingview.com/script/aNrCpO4C-Market-Internals-TICK-ADD-VOLD-TRIN-VIX/ //@version=5 indicator("Market Internals (TICK, ADD, VOLD, TRIN, VIX)", "Mkt Int", overlay=false, format=format.volume, precision=2) // ---------------------------------------------------- SETTINGS --------------------------------------------------- // // Base Colors none = color.rgb(0,0,0,100), clr0 = color.new(color.black, 100), clr1 = color.rgb(175, 235, 245), clr2 = color.aqua, clr3 = color.rgb(35, 150, 245, 50), clr4 = color.new(color.red, 50), clr5 = color.red, clr6 = color.rgb(255, 205, 205), clr7 = color.orange, clr8 = color.lime, clr9 = color.new(color.gray, 50) // Group Labels g1 = "Signal", g2 = "Plot Colors", g3 = "Ancillary Options" // Market Internal Settings all = "All Stocks (USA)", sum = "Sum of NYSE & NASDAQ", avg = "Avg. of NYSE & NASDAQ", both = "Both NYSE & NASDAQ", ny = "NYSE", nq = "NASDAQ", TICK = "TICK", ADD = "ADD", VOLD = "VOLD", TRIN = "TRIN", VIX = "VIX", ABVD = "ABVD", TKCD = "TKCD" ind = input.string(TICK, "Indicator   ", [TICK, ADD, VOLD, TRIN, VIX, ABVD, TKCD], "TICK\nThe TICK subtracts the total number of stocks making a downtick from the total number of stocks making an uptick.\n\nADD\nThe Advance Decline Difference subtracts the total number of stocks below yesterdays close from the total number of stocks above yesterdays close.\n\nVOLD\nThe Volume Difference subtracts the total declining volume from the total advancing volume.\n\nTRIN\nThe Arms Index (aka. Trading Index) divides the ratio of Advancing Stocks / Volume by the ratio of Declining Stocks / Volume.\n\nVIX\nThe CBOE Volatility Index is derived from SPX index option prices, generating a 30-day forward projection of volatility.\n\nABVD\nAn unofficial index measuring all stocks above VWAP as a percent difference.\n\nTKCD\nAn unofficial index subtracting the total number of market down ticks from the total number of market up ticks.", inline="internal") exch = input.string(all, "", [all, sum, avg, both, ny, nq], inline="internal") // Plot Type Settings m1 = "Candles", m2 = "Bars", m3 = "Line", m4 = "Circles", m5 = "Columns" mode = input.string(m1, "Mode        ", [m1, m2, m3, m4, m5], "How the data will be displayed and the source used for colors / non-OHLC plots.\n\n\"Max\" is the value furthest from zero.\n\"Min\"is the value nearest to zero.", inline="mode", display=display.none) // Source Settings O = "open", H = "high", L = "low", C = "close", HL2 = "hl2", HLC3 = "hlc3", OHLC4 = "ohlc4", HLCC4 = "hlcc4", MAX = "Max", MIN = "Min" src = input.string(C, "", [O,H,L,C,HL2, HLC3, OHLC4, HLCC4, MAX, MIN], "", inline="mode", display=display.none) // Scale Settings bv = "Bar Value", cm = "Cumulative", ra = "Raw", ro = "Ratio", pd = "Percent Diff." scale = input.string(bv, "Scale        ", [bv,cm],"Bar Value\nThe value of a given bar.\n\nCumulative\nThe value of a given bar and all preceeding bars in a session.\n\nRaw\nThe exact value of the underlying indicator.\n\nRatio\nA directionalized ratio, where values > 1 are positive and bullish, and values < 1 are negative and bearish. For example, a ratio of \"0.5\" would be a bearish \"-2\", \"0.25\" would be \"-4\", etc. The VIX and TRIN are automatically inverted to retain the scales bull-bear intention.\n\nPercent Diff.\nThe bull-bear difference as a precentage. As with the ratio, the VIX and TRIN are automatically inverted to retain the scales bull-bear intention.", inline="scale"), cumulative = scale == cm barVal = input.string(ra, "", [ra, ro, pd], inline="scale"), raw = barVal == ra, ratio = barVal == ro, pctDif = barVal == pd norm = input.bool(true, "Ratio Norm. Threshold ", "A ratio will be normalized to 0 when 1:1, scaled linearly toward the specified threshold when greater than 1:1, and then retain its exact value when the threshold is crossed.\n\nFor example, with a threshold of \"2\":\n1:1 = 0, 1.5:1 = 1, 2:1 = 2, 3:1 = 3, etc.\n\nThis helps create continuity between positive and negative ratios, where the plot might otherwise display unexpectedly, at the expense of being technically incorrect between 0 and the threshold.\n\nWith this in mind, most traders will want to set the ratios threshold at a level where accuracy becomes more important than visual continuity. If this level is unknown, \"2\" is a good baseline, as it represents one side of the ratio being double the other.", inline="normalize", display=display.none) normLvl = input.float(2, "", 1, inline="normalize", display=display.none) reset = input.bool(true, "Reset cumulative total with each new session.") // Signal Range Settings shoSig = input.bool(true, "Show signal ranges", tooltip="Displays ranges for a given market internal. The signal ranges are hidden when values are cumulative.", group=g1, display=display.none) ovrMax = input.bool(false, "Override Max ", tooltip="Overrides the signals default Max level. Each level is multiplied by -1 to get an equivalent range below zero.", inline="sigMax", group=g1, display=display.none) sigMax = input.float(3000, "", 0, inline="sigMax", group=g1, display=display.none) ovrMin = input.bool(false, "Override Min  ", tooltip="Overrides the signals default Min level. Each level is multiplied by -1 to get an equivalent range below zero.", inline="sigMin", group=g1, display=display.none) sigMin = input.float(1500, "", 0, inline="sigMin", group=g1, display=display.none) noise = input.bool(false, "Reduce Noise", "Shifts values closer to zero when they are below the lower signal threshold. The specified number is the exponent in a power function. For candle / bar modes, each value will be adjusted toward zero. For line / circle / column modes, the value closest to zero will display.", inline="noise", group=g1, display=display.none) nosLvl = input.float(1.5, "", inline="noise", group=g1, display=display.none) shoBthSig = input.bool(false, "Always keep both signal zones visible", group=g1, display=display.none) // Plot Color Settings clrUp = input.color(clr3, "Bull  ", "Default, within signal, and beyond signal colors.", inline="bullColors", group=g2, display=display.none) sigHi = input.color(clr2, "", inline="bullColors", group=g2, display=display.none) maxHi = input.color(clr1, "", inline="bullColors", group=g2, display=display.none) clrDn = input.color(clr4, "Bear", "Default, within signal, and beyond signal colors.", inline="bearColors", group=g2, display=display.none) sigLo = input.color(clr5, "", inline="bearColors", group=g2, display=display.none) maxLo = input.color(clr6, "", inline="bearColors", group=g2, display=display.none) relZro = input.bool(true, "Plot colors should be relative to zero", "When enabled, the plot will inherit \"bull\" colors when above zero and \"bear\" colors when below zero. When disabled and directional colors are enabled, the plot will inherit the default \"bull\" color when rising, and the default \"bear\" color when falling. Otherwise, the plot will use the default \"bull\" color.", group=g2, display=display.none) clrDif = input.bool(true, "Directional colors", "When the plot colors are relative to zero, changes the opacity of a bars color if moving toward zero, where \"100\" percent is the full value of the original color and \"0\" is transparent. When the plot colors are NOT relative to zero, the plot will inherit \"bull\" colors when rising and \"bear\" colors when falling.", inline="clrDif", group=g2, display=display.none) difPct = input.int(50, "", 0, 100, 1, inline="clrDif", group=g2, display=display.none) bullLine = clrUp, bullFill = color.new(clrUp, 95) bearLine = clrDn, bearFill = color.new(clrDn, 95) // Line Settings shoNmh = input.bool(true, "Differentiate RTH from ETH", "Changes the indicators background as a reminder that data is not available outide regular trading hours (RTH), if the chart is showing electronic trading hours (ETH).", inline="nmh", group=g3, display=display.none) nmhClr = input.color(color.new(color.gray, 95), "", inline="nmh", group=g3, display=display.none) shoZro = input.bool(false, "Show zero line      ", inline="zro", group=g3, display=display.none) zroClr = input.color(color.gray,"", inline="zro", group=g3, display=display.none) // Linear Regression Settings shoLinReg = input.bool(false, "Linear Regression", "Color and length of a linear regression line.", inline="linreg", group=g3, display=display.none) linRegclr = input.color(clr7, "", inline="linreg", group=g3, display=display.none) linRegLen = input.int(30, "", inline="linreg", group=g3, display=display.none) // Table Settings shoSym = input.bool(false, "Symbol    ", inline="symbol", group=g3, display=display.none) txtClr = input.color(clr9, "", inline="symbol", group=g3, display=display.none) celClr = input.color(clr0, "", inline="symbol", group=g3, display=display.none) symSiz = input.string(size.huge, "", [size.tiny, size.small, size.normal, size.large, size.huge, size.auto], inline="symbol", group=g3, display=display.none) yPos = input.string("Middle", "Symbol Loc. ", ["Top", "Middle", "Bottom"], inline="table", group=g3, display=display.none) xPos = input.string("Center", "",["Left", "Center", "Right"], inline="table", group=g3, display=display.none) // ----------------------------------------------------- CORE ------------------------------------------------------ // // Define session segments. market = time("1440", "0930-1600", "America/New_York") newSession = session.isfirstbar firstMarketBar = market and (not market[1] or newSession) // Initialize constants for the signal property functions. // This is to circumvent a Pine Script limitaiton; hline plots do not work with variables, otherwise these would simply // be values in the setSig() ind switch, or in an array or matrix. const float tikRawLo = 600, const float addRawLo = 1000, const float vldRawLo = 500000000, const float trnRawLo = 1.5, const float tikRawHi = 1000, const float addRawHi = 2000, const float vldRawHi = 1000000000, const float trnRawHi = 2, const float tikRtoLo = 0.25, const float addRtoLo = 2, const float vldRtoLo = 2.5, const float trnRtoLo = 0.75, const float tikRtoHi = 0.5, const float addRtoHi = 5, const float vldRtoHi = 5, const float trnRtoHi = 2, const float tikPctLo = 6, const float addPctLo = 30, const float vldPctLo = 25, const float trnPctLo = 20, const float tikPctHi = 11, const float addPctHi = 60, const float vldPctHi = 50, const float trnPctHi = 35, const float vixRawLo = 20, const float abdRawLo = 50, const float tkdRawLo = 45000, const float vixRawHi = 30, const float abdRawHi = 75, const float tkdRawHi = 90000, const float vixRtoLo = 0.075, const float abdRtoLo = 1, const float tkdRtoLo = 0.025, const float vixRtoHi = 0.15, const float abdRtoHi = 2.25, const float tkdRtoHi = 0.05, const float vixPctLo = 0.6, const float abdPctLo = 20, const float tkdPctLo = 0.625, const float vixPctHi = 1.2, const float abdPctHi = 40, const float tkdPctHi = 1.25, // Signal property functions. sigLvl(ms, raLo, raHi, roLo, roHi, pdLo, pdHi) => raw ? ms ? raLo : raHi : ratio ? ms ? roLo : roHi : ms ? pdLo : pdHi setSig(s) => minSig = s == sigMin, maxSig = s == sigMax if (minSig and ovrMin) or (maxSig and ovrMax) s else switch ind TICK => sigLvl(minSig, tikRawLo, tikRawHi, tikRtoLo, tikRtoHi, tikPctLo, tikPctHi) ADD => sigLvl(minSig, addRawLo, addRawHi, addRtoLo, addRtoHi, addPctLo, addPctHi) VOLD => sigLvl(minSig, vldRawLo, vldRawHi, vldRtoLo, vldRtoHi, vldPctLo, vldPctHi) TRIN => sigLvl(minSig, trnRawLo, trnRawHi, trnRtoLo, trnRtoHi, trnPctLo, trnPctHi) VIX => sigLvl(minSig, vixRawLo, vixRawHi, vixRtoLo, vixRtoHi, vixPctLo, vixPctHi) ABVD => sigLvl(minSig, abdRawLo, abdRawHi, abdRtoLo, abdRtoHi, abdPctLo, abdPctHi) TKCD => sigLvl(minSig, tkdRawLo, tkdRawHi, tkdRtoLo, tkdRtoHi, tkdPctLo, tkdPctHi) // Set signal properties. sMin = setSig(sigMin) sMax = setSig(sigMax) // Source function. source(s, o, h, l, c) => candle = array.from(nz(o), nz(h), nz(l), nz(c), math.avg(nz(h), nz(l)), math.avg(nz(h), nz(l), nz(c)), math.avg(nz(o), nz(h), nz(l), nz(c))) candAbs = candle.abs() iMin = candAbs.indexof(candAbs.min()) iMax = candAbs.indexof(candAbs.max()) r = switch s O => o H => h L => l C => c HL2 => math.avg(h, l) HLC3 => math.avg(h, l, c) OHLC4 => math.avg(o, h, l, c) HLCC4 => math.avg(h, l, c, c) MAX => candle.get(iMax) MIN => candle.get(iMin) nz(r) // Security request symbol functions. dataType(raX, roX, pdX) => raw ? raX : ratio ? roX : pdX setT1(ra1, ro1, pd1, ra2, ro2, pd2) => exch == all ? dataType(ra1, ro1, pd1) : dataType(ra2, ro2, pd2) setT2(ra1, ro1, pd1) => dataType(ra1, ro1, pd1) // Set the symbol to request. t1 = "", t2 = "" switch ind TICK => t1 := setT1("USI:TICK.US","(USI:ACTV.US+USI:TICK.US)/(USI:ACTV.US-USI:TICK.US)","USI:TICK.US/USI:ACTV.US*100","USI:TICK", "(USI:ACTV.NY+USI:TICK.NY)/(USI:ACTV.NY-USI:TICK.NY)","USI:TICK.NY/USI:ACTV.NY*100"), t2 := setT2("USI:TICKQ","(USI:ACTV.NQ+USI:TICK.NQ)/(USI:ACTV.NQ-USI:TICK.NQ)","USI:TICK.NQ/USI:ACTV.NQ*100") ADD => t1 := setT1("USI:ADVDEC.US","USI:ADVN.US/USI:DECL.US","USI:ADVDEC.US/(USI:ADVN.US+USI:DECL.US)*100","USI:ADD","USI:ADV/USI:DECL","(USI:ADV-USI:DECL)/(USI:ADV+USI:DECL)*100"), t2 := setT2("USI:ADDQ","USI:ADVQ/USI:DECLQ","(USI:ADVQ-USI:DECLQ)/(USI:ADVQ+USI:DECLQ)*100") VOLD => t1 := setT1("USI:UPVOL.US-USI:DNVOL.US","USI:UPVOL.US/USI:DNVOL.US","(USI:UPVOL.US-USI:DNVOL.US)/USI:TVOL.US*100","USI:VOLD","USI:UVOL/USI:DVOL","USI:VOLD/USI:TVOL*100"), t2 := setT2("USI:VOLDQ","USI:UVOLQ/USI:DVOLQ","USI:VOLDQ/USI:TVOLQ*100") TRIN => t1 := setT1("USI:TRIN.US","USI:TRIN.US","((USI:TRIN.US-1)/(USI:TRIN.US+1))*100", "USI:TRIN.NY","USI:TRIN.NY","((USI:TRIN.NY-1)/(USI:TRIN.NY+1))*100"), t2 := setT2("USI:TRIN.NQ","USI:TRIN.NQ","((USI:TRIN.NQ-1)/(USI:TRIN.NQ+1))*100") VIX => t1 := "CBOE:VIX", t2 := t1 ABVD => t1 := setT1("USI:PCTABOVEVWAP.US","USI:PCTABOVEVWAP.US/(100-USI:PCTABOVEVWAP.US)","(USI:PCTABOVEVWAP.US-50)*2","USI:PCTABOVEVWAP.NY","USI:PCTABOVEVWAP.NY/(100-USI:PCTABOVEVWAP.NY)","(USI:PCTABOVEVWAP.NY-50)*2"), t2 := setT2("USI:PCTABOVEVWAP.NQ","USI:PCTABOVEVWAP.NQ/(100-USI:PCTABOVEVWAP.NQ)","(USI:PCTABOVEVWAP.NQ-50)*2") TKCD => t1 := setT1("USI:UPTKS.US-DNTKS.US","USI:UPTKS.US/DNTKS.US","(USI:UPTKS.US-USI:DNTKS.US)/(USI:UPTKS.US+USI:DNTKS.US)*100","USI:UPTKS.NY-DNTKS.NY","USI:UPTKS.NY/DNTKS.NY","(USI:UPTKS.NY-USI:DNTKS.NY)/(USI:UPTKS.NY+USI:DNTKS.NY)*100"), t2 := setT2("USI:UPTKS.NQ-DNTKS.NQ","USI:UPTKS.NQ/DNTKS.NQ","(USI:UPTKS.NQ-USI:DNTKS.NQ)/(USI:UPTKS.NQ+USI:DNTKS.NQ)*100") // Security request candle value functions. var vixNormVal = 0. noise(v) => noise and math.abs(v) < sMin ? v * math.pow(math.abs(v) / sMin, nosLvl) : v normalize(v) => norm and math.abs(v) < normLvl ? math.sign(v) * normLvl * ((math.abs(v) - 1) / (normLvl - 1)) : v v(v) => r = ind == VIX and not raw ? not market ? na : ratio ? v / vixNormVal : v - vixNormVal : v r := noise(ratio ? r < 1 ? normalize(-1 / r) : normalize(r) : r) (ind == TRIN or ind == VIX) and not raw ? r * -1 : r // Set a normalized value for VIX. setvnv(t) => request.security(t, timeframe.period, open) if ind == VIX and not raw and firstMarketBar vixNormVal := setvnv(t1) // Set candle values. getSec(t) => [o, h, l, c] = request.security(t, timeframe.period, [v(open), v(high), v(low), v(close)]) [o1, h1, l1, c1] = getSec(t1) [o2, h2, l2, c2] = getSec(t2) // Set source values. s1 = source(src, o1, h1, l1, c1) s2 = source(src, o2, h2, l2, c2) // Adjust source to the value nearest zero, based on plot and noise settings. if noise and mode != m1 and mode != m2 if math.abs(s1) < sMin s1 := source(MIN, o1, h1, l1, c1) if math.abs(s2) < sMin s2 := source(MIN, o2, h2, l2, c2) // Set the first plot values. plotVal(y, q) => ind != VIX ? exch == sum ? y + q : exch == avg ? math.avg(y, q) : exch == nq ? q : y : y p1S = plotVal(s1, s2), p1O = plotVal(o1, o2), p1H = plotVal(h1, h2), p1L = plotVal(l1, l2), p1C = plotVal(c1, c2) // Set the second plot values. p2S = s2, p2O = o2, p2H = h2, p2L = l2, p2C = c2 // Color functions. trp(a) => 100 - math.round((100-color.t(a))*(difPct/100)) getColor(s) => if s > sMax and shoSig or (not relZro and s < -sMax and shoSig) [maxHi, color.new(maxHi, trp(maxHi)), maxLo] else if s > sMin and shoSig or (not relZro and s < -sMin and shoSig) [sigHi, color.new(sigHi, trp(sigHi)), sigLo] else if s > 0 or (not relZro and s <= 0) [clrUp, color.new(clrUp, trp(clrUp)), clrDn] else if s < -sMax and shoSig [color.new(maxLo, trp(maxLo)), maxLo, clrUp] else if s < -sMin and shoSig [color.new(sigLo, trp(sigLo)), sigLo, clrUp] else [color.new(clrDn, trp(clrDn)), clrDn, clrUp] rgb(s, o, c) => [a, b, d] = getColor(s) market ? clrDif ? o <= c ? a : relZro ? b : d : not relZro ? a : s > 0 ? a : b : na // Set colors. p2_rgb = rgb(p2S, p2O, p2C) p1_rgb = exch == nq ? p2_rgb : rgb(p1S, p1O, p1C) // Track cumulative total if enabled. var cty = 0., var ctq = 0. if cumulative if reset and firstMarketBar cty := 0., p1S := 0., p1O := 0., p1H := 0., p1L := 0., p1C := 0. ctq := 0., p2S := 0., p2O := 0., p2H := 0., p2L := 0., p2C := 0. else if market and (not reset or not firstMarketBar) cty := cty + p1S, p1S := cty, p1O := cty[1], p1H := cty > cty[1] ? cty : cty[1], p1L := cty < cty[1] ? cty : cty[1], p1C := cty ctq := ctq + p2S, p2S := ctq, p2O := ctq[1], p2H := ctq > ctq[1] ? ctq : ctq[1], p2L := ctq < ctq[1] ? ctq : ctq[1], p2C := ctq // ---------------------------------------------------- PLOTS ------------------------------------------------------ // // Change background color when outside regular trading hours. bgcolor(shoNmh and not market ? nmhClr : na, 0, false) // Plot zero level. hline(0, "", zroClr, hline.style_dotted, 1, false, shoZro ? display.all : display.none) // Signal display logic. dhls = not shoBthSig or not shoSig or cumulative ? display.none : display.all // Plot upper signal. bull1 = hline(sMin, color = none, editable = false, display = dhls) bull2 = hline(sMax, color = none, editable = false, display = dhls) fill(bull1, bull2, bullFill, display = shoSig and not cumulative ? display.all : display.none) // Plot lower signal. bear1 = hline(-sMin, color = none, editable = false, display = dhls) bear2 = hline(-sMax, color = none, editable = false, display = dhls) fill(bear1, bear2, relZro ? bearFill : bullFill, display = shoSig and not cumulative ? display.all : display.none) // Plot display logic. mode(m, ifTrue) => if m == m1 or m == m2 mode == m and ifTrue ? display.pane+display.price_scale : display.none else mode != m1 and mode != m2 and ifTrue ? display.pane+display.price_scale : display.none // Plot style logic. plotStyle = switch mode m3 => plot.style_linebr m4 => plot.style_circles m5 => plot.style_columns // First plot. plotcandle(p1O, p1H, p1L, p1C, "", p1_rgb, p1_rgb, false, na, p1_rgb, mode(m1, true)) plotbar(p1O, p1H, p1L, p1C, "", p1_rgb, false, na, mode(m2, true)) plot(p1S, "", newSession ? none : p1_rgb, 2, plotStyle, false, 0, 0, false, false, na, mode(m3, true)) // Second plot, if both exchanges were selected. plotcandle(p2O, p2H, p2L, p2C, "", p2_rgb, p2_rgb, false, na, p2_rgb, mode(m1, exch == both and ind != VIX)) plotbar(p2O, p2H, p2L, p2C, "", p2_rgb, false, na, mode(m2, exch == both)) plot(p2S, "", newSession ? none : p2_rgb, 2, plotStyle, false, 0, 0, false, false, na, mode(m3, exch == both and ind != VIX)) // Label each plot, if showing multiple. if market and exch == both and ind != VIX lbl1 = label.new(bar_index, p1S, ny, style=label.style_label_left, color=none, textcolor=color.gray), label.delete(lbl1[1]) lbl2 = label.new(bar_index, p2S, nq, style=label.style_label_left, color=none, textcolor=color.gray), label.delete(lbl2[1]) // Plot linear regression line, if enabled. var lrCount = 2, lrCount := firstMarketBar ? 2 : lrCount < linRegLen ? lrCount + 1 : lrCount lrP1 = math.avg(p1O, p1H, p1L, p1C) lrP2 = math.avg(p2O, p2H, p2L, p2C) lrB = math.avg(lrP1, lrP2) linreg = ta.linreg(exch == both ? lrB : lrP1, lrCount, 0) lrClr = clrDif ? linreg > linreg[1] ? linRegclr : color.new(linRegclr, trp(linRegclr)) : linRegclr plot(market ? linreg : na, "", lrClr, 2, plot.style_linebr, false, 0, 0, false, false, na, shoLinReg ? display.pane+display.price_scale : display.none) // Show symbol, if enabled. if shoSym symTbl = table.new(str.lower(yPos) + "_" + str.lower(xPos), 1, 1, none, none, 0, none, 1) symTbl.cell(0, 0, "\t\t"+ind+"\t\t", 0, 0, txtClr, text.align_center, text.align_center, symSiz, celClr)
SMC by FXBreakout
https://www.tradingview.com/script/lACKZH50-SMC-by-FXBreakout/
fxbreakout
https://www.tradingview.com/u/fxbreakout/
23
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/ // © FXBreakout //@version=5 indicator("SMC by FXBreakout", overlay = true, max_labels_count = 500, max_boxes_count = 500, max_lines_count = 500, max_bars_back = 1000) // //SETTINGS // // INDICATOR SETTINGS swing_length = input.int(10, title = 'Swing High/Low Length', group = 'Settings', minval = 1, maxval = 50) history_of_demand_to_keep = input.int(20, title = 'History To Keep', minval = 5, maxval = 50) box_width = input.float(2.5, title = 'Supply/Demand Box Width', group = 'Settings', minval = 1, maxval = 10, step = 0.5) // INDICATOR VISUAL SETTINGS show_zigzag = input.bool(false, title = 'Show Zig Zag', group = 'Visual Settings', inline = '1') show_price_action_labels = input.bool(false, title = 'Show Price Action Labels', group = 'Visual Settings', inline = '2') supply_color = input.color(color.new(#EDEDED,70), title = 'Supply', group = 'Visual Settings', inline = '3') supply_outline_color = input.color(color.new(color.white,75), title = 'Outline', group = 'Visual Settings', inline = '3') demand_color = input.color(color.new(#00FFFF,70), title = 'Demand', group = 'Visual Settings', inline = '4') demand_outline_color = input.color(color.new(color.white,75), title = 'Outline', group = 'Visual Settings', inline = '4') bos_label_color = input.color(color.white, title = 'BOS Label', group = 'Visual Settings', inline = '5') poi_label_color = input.color(color.white, title = 'POI Label', group = 'Visual Settings', inline = '7') swing_type_color = input.color(color.black, title = 'Price Action Label', group = 'Visual Settings', inline = '8') zigzag_color = input.color(color.new(#000000,0), title = 'Zig Zag', group = 'Visual Settings', inline = '9') // //END SETTINGS // // //FUNCTIONS // // FUNCTION TO ADD NEW AND REMOVE LAST IN ARRAY f_array_add_pop(array, new_value_to_add) => array.unshift(array, new_value_to_add) array.pop(array) // FUNCTION SWING H & L LABELS f_sh_sl_labels(array, swing_type) => var string label_text = na if swing_type == 1 if array.get(array, 0) >= array.get(array, 1) label_text := 'HH' else label_text := 'LH' label.new(bar_index - swing_length, array.get(array,0), text = label_text, style=label.style_label_down, textcolor = swing_type_color, color = color.new(swing_type_color, 100), size = size.tiny) else if swing_type == -1 if array.get(array, 0) >= array.get(array, 1) label_text := 'HL' else label_text := 'LL' label.new(bar_index - swing_length, array.get(array,0), text = label_text, style=label.style_label_up, textcolor = swing_type_color, color = color.new(swing_type_color, 100), size = size.tiny) // FUNCTION MAKE SURE SUPPLY ISNT OVERLAPPING f_check_overlapping(new_poi, box_array, atr) => atr_threshold = atr * 2 okay_to_draw = true for i = 0 to array.size(box_array) - 1 top = box.get_top(array.get(box_array, i)) bottom = box.get_bottom(array.get(box_array, i)) poi = (top + bottom) / 2 upper_boundary = poi + atr_threshold lower_boundary = poi - atr_threshold if new_poi >= lower_boundary and new_poi <= upper_boundary okay_to_draw := false break else okay_to_draw := true okay_to_draw // FUNCTION TO DRAW SUPPLY OR DEMAND ZONE f_supply_demand(value_array, bn_array, box_array, label_array, box_type, atr) => atr_buffer = atr * (box_width / 10) box_left = array.get(bn_array, 0) box_right = bar_index var float box_top = 0.00 var float box_bottom = 0.00 var float poi = 0.00 if box_type == 1 box_top := array.get(value_array, 0) box_bottom := box_top - atr_buffer poi := (box_top + box_bottom) / 2 else if box_type == -1 box_bottom := array.get(value_array, 0) box_top := box_bottom + atr_buffer poi := (box_top + box_bottom) / 2 okay_to_draw = f_check_overlapping(poi, box_array, atr) // okay_to_draw = true //delete oldest box, and then create a new box and add it to the array if box_type == 1 and okay_to_draw box.delete( array.get(box_array, array.size(box_array) - 1) ) f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = supply_outline_color, bgcolor = supply_color, extend = extend.right, text = 'SUPPLY', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index)) box.delete( array.get(label_array, array.size(label_array) - 1) ) f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = color.new(poi_label_color,90), bgcolor = color.new(poi_label_color,90), extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index)) else if box_type == -1 and okay_to_draw box.delete( array.get(box_array, array.size(box_array) - 1) ) f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right = box_right, bottom = box_bottom, border_color = demand_outline_color, bgcolor = demand_color, extend = extend.right, text = 'DEMAND', text_halign = text.align_center, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index)) box.delete( array.get(label_array, array.size(label_array) - 1) ) f_array_add_pop(label_array, box.new( left = box_left, top = poi, right = box_right, bottom = poi, border_color = color.new(poi_label_color,90), bgcolor = color.new(poi_label_color,90), extend = extend.right, text = 'POI', text_halign = text.align_left, text_valign = text.align_center, text_color = poi_label_color, text_size = size.small, xloc = xloc.bar_index)) // FUNCTION TO CHANGE SUPPLY/DEMAND TO A BOS IF BROKEN f_sd_to_bos(box_array, bos_array, label_array, zone_type) => if zone_type == 1 for i = 0 to array.size(box_array) - 1 level_to_break = box.get_top(array.get(box_array,i)) // if ta.crossover(close, level_to_break) if close >= level_to_break copied_box = box.copy(array.get(box_array,i)) f_array_add_pop(bos_array, copied_box) mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2 box.set_top(array.get(bos_array,0), mid) box.set_bottom(array.get(bos_array,0), mid) box.set_extend( array.get(bos_array,0), extend.none) box.set_right( array.get(bos_array,0), bar_index) box.set_text( array.get(bos_array,0), 'BOS' ) box.set_text_color( array.get(bos_array,0), bos_label_color) box.set_text_size( array.get(bos_array,0), size.small) box.set_text_halign( array.get(bos_array,0), text.align_center) box.set_text_valign( array.get(bos_array,0), text.align_center) box.delete(array.get(box_array, i)) box.delete(array.get(label_array, i)) if zone_type == -1 for i = 0 to array.size(box_array) - 1 level_to_break = box.get_bottom(array.get(box_array,i)) // if ta.crossunder(close, level_to_break) if close <= level_to_break copied_box = box.copy(array.get(box_array,i)) f_array_add_pop(bos_array, copied_box) mid = (box.get_top(array.get(box_array,i)) + box.get_bottom(array.get(box_array,i))) / 2 box.set_top(array.get(bos_array,0), mid) box.set_bottom(array.get(bos_array,0), mid) box.set_extend( array.get(bos_array,0), extend.none) box.set_right( array.get(bos_array,0), bar_index) box.set_text( array.get(bos_array,0), 'BOS' ) box.set_text_color( array.get(bos_array,0), bos_label_color) box.set_text_size( array.get(bos_array,0), size.small) box.set_text_halign( array.get(bos_array,0), text.align_center) box.set_text_valign( array.get(bos_array,0), text.align_center) box.delete(array.get(box_array, i)) box.delete(array.get(label_array, i)) // FUNCTION MANAGE CURRENT BOXES BY CHANGING ENDPOINT f_extend_box_endpoint(box_array) => for i = 0 to array.size(box_array) - 1 box.set_right(array.get(box_array, i), bar_index + 100) // //END FUNCTIONS // // //CALCULATIONS // // CALCULATE ATR atr = ta.atr(50) // CALCULATE SWING HIGHS & SWING LOWS swing_high = ta.pivothigh(high, swing_length, swing_length) swing_low = ta.pivotlow(low, swing_length, swing_length) // ARRAYS FOR SWING H/L & BN var swing_high_values = array.new_float(5,0.00) var swing_low_values = array.new_float(5,0.00) var swing_high_bns = array.new_int(5,0) var swing_low_bns = array.new_int(5,0) // ARRAYS FOR SUPPLY / DEMAND var current_supply_box = array.new_box(history_of_demand_to_keep, na) var current_demand_box = array.new_box(history_of_demand_to_keep, na) // ARRAYS FOR SUPPLY / DEMAND POI LABELS var current_supply_poi = array.new_box(history_of_demand_to_keep, na) var current_demand_poi = array.new_box(history_of_demand_to_keep, na) // ARRAYS FOR BOS var supply_bos = array.new_box(5, na) var demand_bos = array.new_box(5, na) // //END CALCULATIONS // // NEW SWING HIGH if not na(swing_high) //MANAGE SWING HIGH VALUES f_array_add_pop(swing_high_values, swing_high) f_array_add_pop(swing_high_bns, bar_index[swing_length]) if show_price_action_labels f_sh_sl_labels(swing_high_values, 1) f_supply_demand(swing_high_values, swing_high_bns, current_supply_box, current_supply_poi, 1, atr) // NEW SWING LOW else if not na(swing_low) //MANAGE SWING LOW VALUES f_array_add_pop(swing_low_values, swing_low) f_array_add_pop(swing_low_bns, bar_index[swing_length]) if show_price_action_labels f_sh_sl_labels(swing_low_values, -1) f_supply_demand(swing_low_values, swing_low_bns, current_demand_box, current_demand_poi, -1, atr) f_sd_to_bos(current_supply_box, supply_bos, current_supply_poi, 1) f_sd_to_bos(current_demand_box, demand_bos, current_demand_poi, -1) f_extend_box_endpoint(current_supply_box) f_extend_box_endpoint(current_demand_box) //ZIG ZAG h = ta.highest(high, swing_length * 2 + 1) l = ta.lowest(low, swing_length * 2 + 1) f_isMin(len) => l == low[len] f_isMax(len) => h == high[len] var dirUp = false var lastLow = high * 100 var lastHigh = 0.0 var timeLow = bar_index var timeHigh = bar_index var line li = na f_drawLine() => _li_color = show_zigzag ? zigzag_color : color.new(#ffffff,100) line.new(timeHigh - swing_length, lastHigh, timeLow - swing_length, lastLow, xloc.bar_index, color=_li_color, width=2) if dirUp if f_isMin(swing_length) and low[swing_length] < lastLow lastLow := low[swing_length] timeLow := bar_index line.delete(li) li := f_drawLine() li if f_isMax(swing_length) and high[swing_length] > lastLow lastHigh := high[swing_length] timeHigh := bar_index dirUp := false li := f_drawLine() li if not dirUp if f_isMax(swing_length) and high[swing_length] > lastHigh lastHigh := high[swing_length] timeHigh := bar_index line.delete(li) li := f_drawLine() li if f_isMin(swing_length) and low[swing_length] < lastHigh lastLow := low[swing_length] timeLow := bar_index dirUp := true li := f_drawLine() if f_isMax(swing_length) and high[swing_length] > lastLow lastHigh := high[swing_length] timeHigh := bar_index dirUp := false li := f_drawLine() li // if barstate.islast // label.new(x = bar_index + 10, y = close[1], text = str.tostring( array.size(current_supply_poi) )) // label.new(x = bar_index + 20, y = close[1], text = str.tostring( box.get_bottom( array.get(current_supply_box, 0)))) // label.new(x = bar_index + 30, y = close[1], text = str.tostring( box.get_bottom( array.get(current_supply_box, 1)))) // label.new(x = bar_index + 40, y = close[1], text = str.tostring( box.get_bottom( array.get(current_supply_box, 2)))) // label.new(x = bar_index + 50, y = close[1], text = str.tostring( box.get_bottom( array.get(current_supply_box, 3)))) // label.new(x = bar_index + 60, y = close[1], text = str.tostring( box.get_bottom( array.get(current_supply_box, 4))))
Astro: Planetary Aspects v2.0
https://www.tradingview.com/script/jDZDTzyQ-Astro-Planetary-Aspects-v2-0/
Yevolution
https://www.tradingview.com/u/Yevolution/
72
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/ // © BarefootJoey // With much respect to @BarefootJoey, the following small changes have been implemented by @Yevolution: // 1. Overlay the indicator plot on top of the main chart, with the indicator's scale placed on the left - I found it easier to spot price reactions at a given planetary aspect vs seeing the plot in a separate frame // 2. Add options to plot a vertical bar for every occurrence of chosen aspects // 3. The "Precision" setting changes the width of each plotted bar to shade in the calculated window of time while the aspect is in progress. // - eg. 1: if "Precision" is set to 3 degrees, then the "Trine" aspect bar will appear when the aspect is between 117 & 123 degrees // - eg. 2: if "Precision" is set to 15 degrees, then the "Opposition" aspect bar will appear when the aspect is between 165 & 195 degrees // - eg. 3: if "Precision" is set to 6 degrees, then the "Conjunction" aspect bar will appear when the aspect is between 0 & 6 degrees (though technically the aspect moves from 253 to 0 to 6 degrees covering a span of 12 degrees) // Additional comments for specific functions have been placed above the function in question // ██████████████████████████████████████████████████████████████████████ _____ __ _ _______ _____ _______ _______ _______ // █▄─▄─▀██▀▄─██▄─▄▄▀█▄─▄▄─█▄─▄▄─█─▄▄─█─▄▄─█─▄─▄─███▄─▄█─▄▄─█▄─▄▄─█▄─█─▄█ | | \ | |______ |_____] |_____| | |______ // ██─▄─▀██─▀─███─▄─▄██─▄█▀██─▄███─██─█─██─███─███─▄█─██─██─██─▄█▀██▄─▄██ __|__ | \_| ______| | | | |_____ |______ // █▄▄▄▄██▄▄█▄▄█▄▄█▄▄█▄▄▄▄▄█▄▄▄███▄▄▄▄█▄▄▄▄██▄▄▄██▄▄▄███▄▄▄▄█▄▄▄▄▄██▄▄▄██ //@version=5 indicator("Astro: Planetary Aspects v2.0", overlay=true, scale=scale.left, max_boxes_count = 500) import BarefootJoey/AstroLib/1 as AL interplanet = input.bool(false, "Interplanetary aspects?", tooltip="Leave this box unchecked for single planet aspects.") planet1_in = input.string("☿ Mercury", "Which planets?", options=["☉︎ Sun", "☽︎ Moon", "☿ Mercury", "♀ Venus", "🜨 Earth", "♂ Mars", "♃ Jupiter", "♄ Saturn", "⛢ Uranus", "♆ Neptune", "♇ Pluto"], inline="3") planet2_in = input.string("♂ Mars", " ", options=["☉︎ Sun", "☽︎ Moon", "☿ Mercury", "♀ Venus", "🜨 Earth", "♂ Mars", "♃ Jupiter", "♄ Saturn", "⛢ Uranus", "♆ Neptune", "♇ Pluto"], inline="3") precision = input.float(6.0, "Aspect Precision (+/- °)", minval=0, maxval=15) showlast = input.int(1000, "Show last?", minval=1, tooltip="Number of historical plots to display. The fewer plots, the faster the load time (especially on loweer timeframes).") col_asp = input.color(color.white, "Aspect & Info Color") iTxtSize=input.string("Normal", title="Text & Symbol Size", options=["Auto", "Tiny", "Small", "Normal", "Large"], inline="1") vTxtSize=iTxtSize == "Auto" ? size.auto : iTxtSize == "Tiny" ? size.tiny : iTxtSize == "Small" ? size.small : iTxtSize == "Normal" ? size.normal : iTxtSize == "Large" ? size.large : size.small position = input.string(position.top_center, "Aspect Info Position", [position.top_center, position.top_right, position.middle_right, position.bottom_right, position.bottom_center, position.bottom_left, position.middle_left, position.top_left]) //// The "Time Machine" function is no longer necessary and has been effectively replaced by drawing vertical bars at each occurence of an aspect. To re-enable it, simply uncomment lines #36 & #37 and comment lines #38 & #39. @Yevolution //// grtm = "🕜 Time Machine 🕜" //gsd = input.bool(false, "Activate Time Machine", group=grtm) //sdms = input.time(timestamp("2022-04-20T00:00:00"), "Select Date", group=grtm) gsd = false sdms = timestamp("2022-04-20T00:00:00") gt = gsd ? sdms : time //// The latitude/longitude variables do not appear to have any effect, however I've left them enabled in order not to break anything. @Yevolution //// grol = "🔭 Observer Location 🔭" htz = input.float(0, "Hour", step=0.5, inline="2", group=grol) mtz = input.int(0, "Minute", minval=0, maxval=45, inline="2", group=grol) tz = htz + math.round(mtz / 60, 4) latitude = input.float(0, "Latitude", inline="1", group=grol) longitude = input.float(0, "Longitude", inline="1", group=grol) geo = input.bool(false, "Geocentric?", tooltip="Leave this box unchecked for heliocentric.", group=grol) geoout = geo ? 1 : 0 day = AL.J2000(AL.JDN(gt, 0, tz)) dayr = AL.J2000(AL.JDN(gt, 1, tz)) if interplanet and planet1_in == planet2_in runtime.error("Planet cannot aspect itself. Please select 2 different planets for interplanetary analysis.") long1_out = planet1_in == "☉︎ Sun" ? AL.getsun(geoout, day, dayr, latitude, longitude, tz) : planet1_in == "☽︎ Moon" ? AL.getmoon(geoout, day, dayr, latitude, longitude) : planet1_in == "☿ Mercury" ? AL.getplanet(1, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "♀ Venus" ? AL.getplanet(2, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "🜨 Earth" ? AL.getplanet(3, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "♂ Mars" ? AL.getplanet(4, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "♃ Jupiter" ? AL.getplanet(5, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "♄ Saturn" ? AL.getplanet(6, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "⛢ Uranus" ? AL.getplanet(7, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "♆ Neptune" ? AL.getplanet(8, geoout, day, dayr, latitude, longitude, tz) : planet1_in == "♇ Pluto" ? AL.getplanet(9, geoout, day, dayr, latitude, longitude, tz) : na long2_out = planet2_in == "☉︎ Sun" ? AL.getsun(geoout, day, dayr, latitude, longitude, tz) : planet2_in == "☽︎ Moon" ? AL.getmoon(geoout, day, dayr, latitude, longitude) : planet2_in == "☿ Mercury" ? AL.getplanet(1, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "♀ Venus" ? AL.getplanet(2, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "🜨 Earth" ? AL.getplanet(3, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "♂ Mars" ? AL.getplanet(4, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "♃ Jupiter" ? AL.getplanet(5, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "♄ Saturn" ? AL.getplanet(6, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "⛢ Uranus" ? AL.getplanet(7, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "♆ Neptune" ? AL.getplanet(8, geoout, day, dayr, latitude, longitude, tz) : planet2_in == "♇ Pluto" ? AL.getplanet(9, geoout, day, dayr, latitude, longitude, tz) : na p1p2=math.abs(AL.degtolowest180(AL.AngToCirc(long1_out - (interplanet?long2_out:0)))) plot(p1p2, color=col_asp, linewidth=2, show_last=showlast) htrans=66 hline(0, color=color.new(color.red, htrans)) hline(30, color=color.new(color.orange, htrans)) hline(60, color=color.new(color.yellow, htrans)) hline(90, color=color.new(color.green, htrans)) hline(120, color=color.new(color.aqua, htrans)) hline(150, color=color.new(color.navy, htrans)) hline(180, color=color.new(color.purple, htrans)) var label conj = na var label ssex = na var label sext = na var label squa = na var label trin = na var label inco = na var label oppo = na if barstate.islast conj := label.new(bar_index, y=0, text="☌", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.red,0), tooltip="☌ Conjunction 0°\n" + "") label.delete(conj[1]) ssex := label.new(bar_index, y=30, text="⊻", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.orange,0), tooltip="⊻ Semi Sextile 30°\n" + "") label.delete(ssex[1]) sext := label.new(bar_index, y=60, text="🞶", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.yellow,0), tooltip="🞶 Sextile 60°\n" + "") label.delete(sext[1]) squa := label.new(bar_index, y=90, text="□", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.green,0), tooltip="□ Square 90°\n" + "") label.delete(squa[1]) trin := label.new(bar_index, y=120, text="△", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.aqua,0), tooltip="△ Trine 120°\n" + "") label.delete(trin[1]) inco := label.new(bar_index, y=150, text="⊼", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.navy,0), tooltip="⊼ Inconjunct 150°\n" + "") label.delete(inco[1]) oppo := label.new(bar_index, y=180, text="☍", size=vTxtSize, style=label.style_label_left, color=color.new(color.white,100), textcolor=color.new(color.purple,0), tooltip="☍ Opposition 180°\n" + "") label.delete(oppo[1]) retro_tt(deg) => deg > deg[1] ? "" : " ℞" retro_tt_out = retro_tt(AL.AngToCirc(long1_out - (interplanet?long2_out:0))) var table Info = na table.delete(Info) Info := table.new(position, 1, 1) if barstate.islast table.cell(Info, 0, 0, text = planet1_in + (interplanet?" ∡ "+planet2_in:"") + retro_tt_out, text_size = vTxtSize, text_color = color.new(col_asp,0), tooltip = AL.aspectsignprecisionV2ext(p1p2, precision) + "°\nPrecision: +/- " + str.tostring(precision) + "°") //// Vertical bars for Aspect time windows by @Yevolution //// // Inputs to allow (de)selection of individual aspects grvb = "Aspects marked with a vertical Bar:" ConjunctVertBar = input.bool(true, "Conjunction", group = grvb) SemiSextVertBar = input.bool(true, "Semi Sextile", group = grvb) SextVertBar = input.bool(true, "Sextile", group = grvb) SquareVertBar = input.bool(true, "Square", group = grvb) TrineVertBar = input.bool(true, "Trine", group = grvb) InConjunctVertBar = input.bool(true, "Inconjunct", group = grvb) OppositVertBar = input.bool(true, "Opposition", group = grvb) // Logic to determine if an aspect is currently in progress conjunctionActive = p1p2 <= (0 + precision) semiSextActive = p1p2 >= (30 - precision) and p1p2 <= (30 + precision) sextActive = p1p2 >= (60 - precision) and p1p2 <= (60 + precision) squareActive = p1p2 >= (90 - precision) and p1p2 <= (90 + precision) trineActive = p1p2 >= (120 - precision) and p1p2 <= (120 + precision) inConjunctActive = p1p2 >= (150 - precision) and p1p2 <= (150 + precision) oppositionActive = p1p2 >= (180 - precision) // Plot vertical bars on chart line1 = plot(conjunctionActive and ConjunctVertBar ? 0 : na, color = color.new(color.red, 100)) line2 = plot(conjunctionActive and ConjunctVertBar ? 180 : na, color = color.new(color.red, 100)) line3 = plot(semiSextActive and SemiSextVertBar ? 0 : na, color = color.new(color.orange, 100)) line4 = plot(semiSextActive and SemiSextVertBar ? 180 : na, color = color.new(color.orange, 100)) line5 = plot(sextActive and SextVertBar ? 0 : na, color = color.new(color.yellow, 100)) line6 = plot(sextActive and SextVertBar ? 180 : na, color = color.new(color.yellow, 100)) line7 = plot(squareActive and SquareVertBar ? 0 : na, color = color.new(color.green, 100)) line8 = plot(squareActive and SquareVertBar ? 180 : na, color = color.new(color.green, 100)) line9 = plot(trineActive and TrineVertBar ? 0 : na, color = color.new(color.aqua, 100)) line10 = plot(trineActive and TrineVertBar ? 180 : na, color = color.new(color.aqua, 100)) line11 = plot(inConjunctActive and InConjunctVertBar ? 0 : na, color = color.new(color.navy, 100)) line12 = plot(inConjunctActive and InConjunctVertBar ? 180 : na, color = color.new(color.navy, 100)) line13 = plot(oppositionActive and OppositVertBar ? 0 : na, color = color.new(color.purple, 100)) line14 = plot(oppositionActive and OppositVertBar ? 180 : na, color = color.new(color.purple, 100)) fill(line1, line2, color=color.new(color.red, 75)) fill(line3, line4, color=color.new(color.orange, 75)) fill(line5, line6, color=color.new(color.yellow, 75)) fill(line7, line8, color=color.new(color.green, 75)) fill(line9, line10, color=color.new(color.aqua, 75)) fill(line11, line12, color=color.new(color.navy, 75)) fill(line13, line14, color=color.new(color.purple, 75)) // EoS made w/ ❤ by @BarefootJoey ✌💗📈 // Respectfully updated with additional functions by @Yevolution
PhantomFlow DynamicLevels
https://www.tradingview.com/script/mflbmRpo-PhantomFlow-DynamicLevels/
PhantomFlow
https://www.tradingview.com/u/PhantomFlow/
87
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/ // Credit to LonesomeTheBlue for the calculate/get volume function: // https://www.tradingview.com/script/kIY0znXs-Volume-Profile-Fixed-Range/ // © mxrshxl_trxde //@version=5 indicator(title = "PhantomFlow DynamicLevels", shorttitle = "PhantomFlow DynamicLevels", overlay = true) tooltip_period = 'If the indicator does not show anything, but only an error about the execution time, try to reduce the period, or the period multiplier. For free TradingView - it is desirable that the Period * Multiplier does not exceed 1000' period = input.int(defval = 40, title = "Period", minval = 40, maxval = 100, step = 10, tooltip = tooltip_period) period_multiplier = input.int(defval = 10, title = "Period Multiplier", minval = 10, maxval = 100, step = 1) cnum = input.int(defval = 20, title = "Accuracy", minval = 20, maxval = 100, step = 10) wide_channel = input.bool(true, title='Wide Channel') poc_color = input.color(title='POC', defval = color.rgb(0, 255, 255), group="Visual Settings", inline = 'ltf_color_liquidity') val_color = input.color(title='VAL', defval = color.rgb(0, 42, 255), group="Visual Settings", inline = 'ltf_color_liquidity') vah_color = input.color(title='VAH', defval = color.rgb(255, 0, 238), group="Visual Settings", inline = 'ltf_color_liquidity') up_color = input.color(title='VAL Area', defval = color.rgb(17, 0, 255, 90), group="Visual Settings", inline = 'ltf_color_liquidity_area') down_color = input.color(title='VAH Area', defval = color.rgb(255, 0, 221, 90), group="Visual Settings", inline = 'ltf_color_liquidity_area') rangema = ta.atr(10) va_percent = 70. var float _lastVah = 0 var float _lastVal = 0 var float _lastPoc = 0 get_vol(y11, y12, y21, y22, height, vol) => nz(math.max(math.min(math.max(y11, y12), math.max(y21, y22)) - math.max(math.min(y11, y12), math.min(y21, y22)), 0) * vol / height) levels = array.new_float(cnum + 1) totalvols = array.new_float(cnum, 0.) d_switch = bar_index > period top = ta.highest(high, period) bot = ta.lowest(low, period) float poc_level = na float val_level = na float vah_level = na bool plotLines = false calculateLevels(int bar_end, int bar_start) => step = (top - bot) / cnum for x = 0 to cnum by 1 array.set(levels, x, bot + step * x) if bar_index >= last_bar_index - period * period_multiplier bar_end = bar_index bar_start = bar_index - period volumes = array.new_float(cnum * 2, 0.) all_bars = bar_end - bar_start calculateLevels(bar_end, bar_start) for bars = 0 to period by 1 body_top = math.max(close[bars], open[bars]) body_bot = math.min(close[bars], open[bars]) itsgreen = close[bars] >= open[bars] topwick = high[bars] - body_top bottomwick = body_bot - low[bars] body = body_top - body_bot bodyvol = body * volume[bars] / (2 * topwick + 2 * bottomwick + body) topwickvol = 2 * topwick * volume[bars] / (2 * topwick + 2 * bottomwick + body) bottomwickvol = 2 * bottomwick * volume[bars] / (2 * topwick + 2 * bottomwick + body) for x = 0 to cnum - 1 by 1 array.set(volumes, x, array.get(volumes, x) + (itsgreen ? get_vol(array.get(levels, x), array.get(levels, x + 1), body_bot, body_top, body, bodyvol) : 0) + get_vol(array.get(levels, x), array.get(levels, x + 1), body_top, high[bars], topwick, topwickvol) / 2 + get_vol(array.get(levels, x), array.get(levels, x + 1), body_bot, low[bars], bottomwick, bottomwickvol) / 2) array.set(volumes, x + cnum, array.get(volumes, x + cnum) + (itsgreen ? 0 : get_vol(array.get(levels, x), array.get(levels, x + 1), body_bot, body_top, body, bodyvol)) + get_vol(array.get(levels, x), array.get(levels, x + 1), body_top, high[bars], topwick, topwickvol) / 2 + get_vol(array.get(levels, x), array.get(levels, x + 1), body_bot, low[bars], bottomwick, bottomwickvol) / 2) for x = 0 to cnum - 1 by 1 array.set(totalvols, x, array.get(volumes, x) + array.get(volumes, x + cnum)) int poc = array.indexof(totalvols, array.max(totalvols)) totalmax = array.sum(totalvols) * va_percent / 100. va_total = array.get(totalvols, poc) int up = poc int down = poc for x = 0 to cnum - 1 by 1 above = 0.0 if up + 1 < array.size(totalvols) - 1 above += nz(array.get(totalvols, up + 1), 0.0) above if up + 2 < array.size(totalvols) - 1 above += nz(array.get(totalvols, up + 2), 0.0) above below = 0.0 if down - 1 > 0 below += nz(array.get(totalvols, down - 1), 0.0) below if down - 2 > 0 below += nz(array.get(totalvols, down - 2), 0.0) below if above > below up := math.min(up + 2, array.size(totalvols) - 1) va_total += above va_total else down := math.max(down - 2, 0) va_total += below va_total if va_total >= totalmax or down <= 0 and up >= array.size(totalvols) - 1 break maxvol = array.max(totalvols) for x = 0 to cnum * 2 - 1 by 1 array.set(volumes, x, array.get(volumes, x) * all_bars / (3 * maxvol)) poc_level := (array.get(levels, poc) + array.get(levels, poc + 1)) / 2 val_level := (array.get(levels, down) + array.get(levels, down + 1)) / 2 vah_level := (array.get(levels, up) + array.get(levels, up + 1)) / 2 bot := low top := high plotLines := true if wide_channel vah_level += rangema * 2 val_level -= rangema * 2 vah = plot(plotLines ? vah_level : na, "Up", vah_color) val = plot(plotLines ? val_level : na, "Down", val_color) poc = plot(plotLines ? poc_level : na, "Medium", poc_color) fill(poc, vah, color=down_color, title="Background Down") fill(poc, val, color=up_color, title="Background Up")
Supply and Demand Visible Range + EMA
https://www.tradingview.com/script/iJNXb1G8/
ehisonbp
https://www.tradingview.com/u/ehisonbp/
22
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("Supply and Demand Visible Range + EMA", overlay = true, max_boxes_count = 500, max_bars_back = 500) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ per = input.float(10., 'Threshold %', minval = 0, maxval = 100) div = input.int(50, 'Resolution' , minval = 2, maxval = 500) tf = input.timeframe('', 'Intrabar TF') //Colors showSupply = input(true ,'Supply        ', inline = 'supply', group = 'Style') supplyCss = input(#2157f3, '' , inline = 'supply', group = 'Style') supplyArea = input(true ,'Area' , inline = 'supply', group = 'Style') supplyAvg = input(true ,'Average' , inline = 'supply', group = 'Style') supplyWavg = input(true ,'Weighted' , inline = 'supply', group = 'Style') showEqui = input(true ,'Equilibrium' , inline = 'equi' , group = 'Style') equiCss = input(color.gray, '' , inline = 'equi' , group = 'Style') equiAvg = input(true ,'Average' , inline = 'equi' , group = 'Style') equiWavg = input(true ,'Weighted' , inline = 'equi' , group = 'Style') showDemand = input(true ,'Demand    ' , inline = 'demand', group = 'Style') demandCss = input(#ff5d00, '' , inline = 'demand', group = 'Style') demandArea = input(true ,'Area' , inline = 'demand', group = 'Style') demandAvg = input(true ,'Average' , inline = 'demand', group = 'Style') demandWavg = input(true ,'Weighted' , inline = 'demand', group = 'Style') //-----------------------------------------------------------------------------} //UDT's //-----------------------------------------------------------------------------{ type bin float lvl float prev float sum float prev_sum float csum float avg bool isreached type area box bx line avg line wavg //-----------------------------------------------------------------------------} //Functions //-----------------------------------------------------------------------------{ n = bar_index get_hlv()=> [high, low, volume] method set_area(area id, x1, top, btm, avg, wavg, showArea, showAvg, showWavg)=> if showArea id.bx.set_lefttop(x1, top) id.bx.set_rightbottom(n, btm) if showAvg id.avg.set_xy1(x1, avg) id.avg.set_xy2(n, avg) if showWavg id.wavg.set_xy1(x1, wavg) id.wavg.set_xy2(n, wavg) //-----------------------------------------------------------------------------} //Main variables //-----------------------------------------------------------------------------{ var max = 0. var min = 0. var x1 = 0 var csum = 0. //Intrabar data [h, l, v] = request.security_lower_tf(syminfo.tickerid, tf, get_hlv()) //Init on left bar if time == chart.left_visible_bar_time max := high min := low csum := volume x1 := n else //Accumulate max := math.max(high, max) min := math.min(low, min) csum += volume //-----------------------------------------------------------------------------} //Set zones //-----------------------------------------------------------------------------{ var supply_area = area.new( box.new(na, na, na, na, na, bgcolor = color.new(supplyCss, 80)) , line.new(na, na, na, na, color = supplyCss) , line.new(na, na, na, na, color = supplyCss, style = line.style_dashed)) var demand_area = area.new( box.new(na, na, na, na, na, bgcolor = color.new(demandCss, 80)) , line.new(na, na, na, na, color = demandCss) , line.new(na, na, na, na, color = demandCss, style = line.style_dashed)) var equi = line.new(na, na, na, na, color = equiCss) var wequi = line.new(na, na, na, na, color = equiCss, style = line.style_dashed) var float supply_wavg = na var float demand_wavg = na if time == chart.right_visible_bar_time r = (max - min) / div supply = bin.new(max, max, 0, 0, 0, 0, false) demand = bin.new(min, min, 0, 0, 0, 0, false) //Loop trough intervals for i = 0 to div-1 supply.lvl -= r demand.lvl += r //Accumulated volume column if not supply.isreached and showSupply and supplyArea box.new(x1, supply.prev, x1 + int(supply.sum / csum * (n - x1)), supply.lvl, na , bgcolor = color.new(supplyCss, 50)) if not demand.isreached and showDemand and demandArea box.new(x1, demand.lvl, x1 + int(demand.sum / csum * (n - x1)), demand.prev, na , bgcolor = color.new(demandCss, 50)) //Loop trough bars for j = 0 to (n - x1)-1 //Loop trough intrabars for k = 0 to (v[j]).size()-1 //Accumulate if within upper internal supply.sum += (h[j]).get(k) > supply.lvl and (h[j]).get(k) < supply.prev ? (v[j]).get(k) : 0 supply.avg += supply.lvl * (supply.sum - supply.prev_sum) supply.csum += supply.sum - supply.prev_sum supply.prev_sum := supply.sum //Accumulate if within lower interval demand.sum += (l[j]).get(k) < demand.lvl and (l[j]).get(k) > demand.prev ? (v[j]).get(k) : 0 demand.avg += demand.lvl * (demand.sum - demand.prev_sum) demand.csum += demand.sum - demand.prev_sum demand.prev_sum := demand.sum //Test if supply accumulated volume exceed threshold and set box if supply.sum / csum * 100 > per and not supply.isreached avg = math.avg(max, supply.lvl) supply_wavg := supply.avg / supply.csum //Set Box/Level coordinates if showSupply supply_area.set_area(x1, max, supply.lvl, avg, supply_wavg, supplyArea, supplyAvg, supplyWavg) supply.isreached := true //Test if demand accumulated volume exceed threshold and set box if demand.sum / csum * 100 > per and not demand.isreached and showDemand avg = math.avg(min, demand.lvl) demand_wavg := demand.avg / demand.csum //Set Box/Level coordinates if showDemand demand_area.set_area(x1, demand.lvl, min, avg, demand_wavg, demandArea, demandAvg, demandWavg) demand.isreached := true if supply.isreached and demand.isreached break if supply.isreached and demand.isreached and showEqui //Set equilibrium if equiAvg avg = math.avg(max, min) equi.set_xy1(x1, avg) equi.set_xy2(n, avg) //Set weighted equilibrium if equiWavg wavg = math.avg(supply_wavg, demand_wavg) wequi.set_xy1(x1, wavg) wequi.set_xy2(n, wavg) break supply.prev := supply.lvl demand.prev := demand.lvl //-----------------------------------------------------------------------------} // Function for moving averages ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) // Parameters for EMA len = input.int(9, minval=1, title="EMA Length") src = input(close, title="EMA Source") offset = input.int(title="EMA Offset", defval=0, minval=-500, maxval=500) // Calculate EMA emaValue = ta.ema(src, len) plot(emaValue, title="EMA", color=color.blue, offset=offset) // Parameters for smoothing typeMA = input.string(title = "Smoothing Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing") smoothingLength = input.int(title = "Smoothing Length", defval = 55, minval = 1, maxval = 100, group="Smoothing") // Apply smoothing smoothingLine = ma(emaValue, smoothingLength, typeMA) plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset, display=display.none)
Supertrend Forecast - vanAmsen
https://www.tradingview.com/script/md0PV7Yo-Supertrend-Forecast-vanAmsen/
vanAmsen
https://www.tradingview.com/u/vanAmsen/
57
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/ // © vanAmsen //@version=5 indicator("vanAmsen - Supertrend Forecast", overlay = true) atrPeriod = input.int(10, title="ATR Length", tooltip="Specifies the period over which the Average True Range (ATR) is calculated.", minval=1) factor = input.float(5.5, title="Factor", tooltip="Multiplier factor for the ATR to define the distance of the Supertrend line from the price.", minval=0.1, step=0.1) upColor = input.color(color.rgb(122,244,122), title="Up Color", tooltip="Color for the Supertrend line when the trend is upwards or bullish.") downColor = input.color(color.rgb(244,122,122), title="Down Color", tooltip="Color for the Supertrend line when the trend is downwards or bearish.") // Add switchers showLabel = input.bool(true, title="Show Label", tooltip="Toggle to show or hide labels indicating statistical metrics like win rate and expected return.") showTable = input.bool(true, title="Show Table", tooltip="Toggle to show or hide the interactive table summarizing key metrics.") showLine = input.bool(true, title="Show Line", tooltip="Toggle to show or hide the Supertrend lines on the chart.") [supertrend, direction] = ta.supertrend(factor, atrPeriod) // Lists to store durations and percentage changes for up and down trends var int[] durations_up_win = array.new_int(0) var int[] durations_up_loss = array.new_int(0) var int[] durations_down_win = array.new_int(0) var int[] durations_down_loss = array.new_int(0) var float[] pct_changes_up_win = array.new_float(0) var float[] pct_changes_up_loss = array.new_float(0) var float[] pct_changes_down_win = array.new_float(0) var float[] pct_changes_down_loss = array.new_float(0) // Additional arrays to store max running profit for uptrend and min running profit for downtrend var float[] pct_changes_up_max = array.new_float(0) var float[] pct_changes_down_min = array.new_float(0) // Track the starting bar and price of the current trend var int startBar = na var float startPrice = na // Track max running profit for uptrend and min running profit for downtrend var float max_up = na var float min_down = na float pct_change = (close / startPrice) - 1 // Tracking max and min running profits for the current trend if (direction[1] < 0) // Uptrend max_up := math.max(nz(max_up), pct_change) else min_down := math.min(nz(min_down), pct_change) if (direction != direction[1]) if (na(startBar) == false) if (direction[1] < 0) // Uptrend array.push(pct_changes_up_max, max_up) if (pct_change > 0) // Win scenario for uptrend array.push(pct_changes_up_win, pct_change) array.push(durations_up_win, bar_index - startBar) else // Loss scenario for uptrend array.push(pct_changes_up_loss, pct_change) array.push(durations_up_loss, bar_index - startBar) else // Downtrend array.push(pct_changes_down_min, min_down) if (pct_change < 0) // Win scenario for downtrend array.push(pct_changes_down_win, pct_change) array.push(durations_down_win, bar_index - startBar) else // Loss scenario for downtrend array.push(pct_changes_down_loss, pct_change) array.push(durations_down_loss, bar_index - startBar) // Reset max and min values when the direction changes max_up := na min_down := na // Start of new trend startBar := bar_index startPrice := close // Calculate average durations for up and down trends avg_duration_up_win = bar_index + array.avg(durations_up_win) avg_duration_up_loss = bar_index + array.avg(durations_up_loss) avg_duration_down_win = bar_index + array.avg(durations_down_win) avg_duration_down_loss = bar_index + array.avg(durations_down_loss) // Calculate average percentage changes for wins and losses float avg_pct_change_up_win = array.avg(pct_changes_up_win) float avg_pct_change_up_loss = array.avg(pct_changes_up_loss) float avg_pct_change_down_win = array.avg(pct_changes_down_win) float avg_pct_change_down_loss = array.avg(pct_changes_down_loss) // Calculate the average max percentage change for uptrends and the average min percentage change for downtrends float avg_max_pct_change_up = array.avg(pct_changes_up_max) float avg_min_pct_change_down = array.avg(pct_changes_down_min) avg_pct_up_win = close * (1 + avg_pct_change_up_win) avg_pct_up_loss = close * (1 + avg_pct_change_up_loss) avg_pct_down_win = close * (1 + avg_pct_change_down_win) avg_pct_down_loss = close * (1 + avg_pct_change_down_loss) // Calculate win rates float win_rate_up = array.size(pct_changes_up_win) / (array.size(pct_changes_up_win) + array.size(pct_changes_up_loss)) float win_rate_down = array.size(pct_changes_down_win) / (array.size(pct_changes_down_win) + array.size(pct_changes_down_loss)) // Calculate expected returns float expected_return_up = win_rate_up * avg_pct_change_up_win + (1 - win_rate_up) * avg_pct_change_up_loss float expected_return_down = win_rate_down * avg_pct_change_down_win + (1 - win_rate_down) * avg_pct_change_down_loss // Draw the lines for win and loss scenarios and display win rate and expected return if (direction != direction[1]) label_text_up = "WR:" + str.tostring(win_rate_up * 100, "#.#") + "% / ER:" + str.tostring(expected_return_up * 100, "#.#") + "%\nEW:" + str.tostring(avg_pct_change_up_win * 100, "#.#") + "% / EL:" + str.tostring(avg_pct_change_up_loss * 100, "#.#") + "%" label_text_down = "WR:" + str.tostring(win_rate_down * 100, "#.#") + "% / ER:" + str.tostring(expected_return_down * 100, "#.#") + "%\nEW:" + str.tostring(avg_pct_change_down_win * 100, "#.#") + "% / EL:" + str.tostring(avg_pct_change_down_loss * 100, "#.#") + "%" if (direction < 0) // Uptrend if showLine line.new(x1=startBar, y1=startPrice, x2=avg_duration_up_win, y2=avg_pct_up_win, width=1, color=upColor, style=line.style_dashed) line.new(x1=startBar, y1=startPrice, x2=avg_duration_up_loss, y2=avg_pct_up_loss, width=1, color=downColor, style=line.style_dashed) if showLabel // Add label for win rate, expected return, and average percentage changes label.new(x=startBar, y=supertrend , text=label_text_up, style=label.style_label_up, color=upColor) else // Downtrend if showLine line.new(x1=startBar, y1=startPrice, x2=avg_duration_down_win, y2=avg_pct_down_win, width=1, color=downColor, style=line.style_dashed) line.new(x1=startBar, y1=startPrice, x2=avg_duration_down_loss, y2=avg_pct_down_loss, width=1, color=upColor, style=line.style_dashed) if showLabel // Add label for win rate, expected return, and average percentage changes label.new(x=startBar, y=supertrend, text=label_text_down, style=label.style_label_down, color=downColor) if showTable // Create a table with 3 columns and 4 rows in the top right corner of the chart var table t = table.new(position = position.top_right, columns = 3, rows = 4, bgcolor = color.new(color.gray, 90)) // Update the table data each bar with the latest metrics // Define the text to be displayed in the cells string wr_text_up = str.tostring(win_rate_up * 100, "#.#") + "%" string er_text_up = str.tostring(expected_return_up * 100, "#.#") + "%" string ew_text_up = str.tostring(avg_pct_change_up_win * 100, "#.#") + "%" string el_text_up = str.tostring(avg_pct_change_up_loss * 100, "#.#") + "%" string wr_text_down = str.tostring(win_rate_down * 100, "#.#") + "%" string er_text_down = str.tostring(expected_return_down * 100, "#.#") + "%" string ew_text_down = str.tostring(avg_pct_change_down_win * 100, "#.#") + "%" string el_text_down = str.tostring(avg_pct_change_down_loss * 100, "#.#") + "%" // Update the table every bar, so the table always displays the latest metrics table.cell(t, 0, 0, "WR:", bgcolor=color.silver) table.cell(t, 1, 0, wr_text_up, bgcolor=upColor) table.cell(t, 2, 0, wr_text_down, bgcolor=downColor) table.cell(t, 0, 1, "ER:", bgcolor=color.silver) table.cell(t, 1, 1, er_text_up, bgcolor=upColor) table.cell(t, 2, 1, er_text_down, bgcolor=downColor) table.cell(t, 0, 2, "EW:", bgcolor=color.silver) table.cell(t, 1, 2, ew_text_up, bgcolor=upColor) table.cell(t, 2, 2, ew_text_down, bgcolor=downColor) table.cell(t, 0, 3, "EL:", bgcolor=color.silver) table.cell(t, 1, 3, el_text_up, bgcolor=upColor) table.cell(t, 2, 3, el_text_down, bgcolor=downColor) plot(direction < 0 ? supertrend : na, "Up Trend", color = upColor, style = plot.style_linebr) plot(direction > 0 ? supertrend : na, "Down Trend", color = downColor, style = plot.style_linebr)
Bar Retracement
https://www.tradingview.com/script/z9hqD6pV-Bar-Retracement/
grnghost
https://www.tradingview.com/u/grnghost/
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/ // © grnghost //@version=5 indicator("Retracement", "Bar RR", overlay = false, precision = 1) var bw = high - low var ret = open- close bw_av = ta.sma(bw,4) max_bw = ta.highest(bw,5) mom = ta.sma(ta.mom(hl2,2),4) if close[1] > open[1] bw := close[1] - low[1] ret := (low - open) / bw * 100 if close[1] < open[1] bw := high[1] - close[1] ret := (open - high)/ bw * 100 ret := ret < -100 ? -100 : ret ret_red = close < open and close[1] > open[1] ret_grn = close > open and close[1] < open[1] ret_low = ret < -38.2 and ret > -61.7 ret_mid = ret < -61.8 and ret > -78.6 ret_col = ret < -78.7 and ret_red ? color.new(color.red, 20) : ret < -78.6 and ret_grn ? color.new(color.green,20) : ret_low ? color.new(color.yellow,20) : ret_mid ? color.new(color.orange,20) : color.new(color.silver,10) plot(ret, color = ret_col, style = plot.style_histogram, linewidth = 2) //color.silver plot(0, color = color.gray, display = display.pane) //color.new(color.gray, 20) p1 = plot(-38.2, color = na, display = display.pane) // color.new(color.yellow,50)) p2 = plot(-61.8, color = color.new(color.orange,100), display = display.pane) //color.new(color.orange,50)) p3 = plot(-78.6, color = color.new(color.red,100), display = display.pane) p4 = plot(-100, color = color.new(color.red,100), display = display.pane) fill(p1, p2, color.new(color.yellow,80)) fill(p2, p3, color.new(color.orange,80)) fill(p3, p4, color.new(color.red,80)) warn = ta.crossover(ret, -78.6) alertcondition(warn, "Large Retracement", "Prepare to exit.")
BB Support & Resistance
https://www.tradingview.com/script/QQ9opj40-BB-Support-Resistance/
grnghost
https://www.tradingview.com/u/grnghost/
52
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/ // © grnghost //@version=5 indicator("BB Support & Resitance", "BB S&R", overlay = true) //Input grp1 = "Bollinger Band Settings" bb_len = input.int(20, "Bollinger Band Length =", minval = 1, group = grp1) multi = input.int(2, "Multipler =", minval = 1, group = grp1) grp2 = "Time Frame Selection" TF1 = input.timeframe("60", "Time Frame 1", inline = "row1", group = grp2) // options=['15', '30','60', "120", "240", 'D', 'W', "M"]) show_tf1 = input.bool(true, "Show Time Frame 1", inline = "row1" , group = grp2) TF2 = input.timeframe("D", "Time Frame 2", inline = "row2" , group = grp2) //, options=['15', '30', '60', "120","240", 'D', 'W',"M"]) show_tf2 = input.bool(true, "Show Time Frame 2", inline = "row2" , group = grp2) TF3 = input.timeframe("W", "Time Frame 3", inline = "row3", group = grp2) // options=['30','60', "120", "240", 'D', 'W', "M"]) show_tf3 = input.bool(false, "Show Time Frame 3", inline = "row3" , group = grp2) grp3 = "Color Selection" cbtf = input.bool(false, "Color By Time Frame", group = grp3) tf1_col = input.color(color.new(color.yellow, 40), "Time Frame 1 Color", group = grp3) tf2_col = input.color(color.new(color.yellow, 20), "Time Frame 2 Color", group = grp3) tf3_col = input.color(color.new(color.yellow, 0), "Time Frame 3 Color", group = grp3) //Default Color Definition upper = color.new(color.red,50)//close < trend1 ? color.new(color.red,50) : color.new(color.green,50) //input.color(color.new(color.yellow,60), title = "Time Frame 1 Line Color") basis = color.new(color.yellow, 50) // close < trend1 ? color.new(color.red,50) : color.new(color.green,50)//input.color(color.new(color.yellow,60), title = "Time Frame 2 Line Color") lower = color.new(color.green, 50)// close < trend1 ? color.new(color.red,50) : color.new(color.green,50) //input.color(color.new(color.yellow,60), title = "Time Frame 3 Line Color") //Calculate Bollinger Bands [mid, up, lo] = ta.bb(close[1], bb_len, multi) [mid_tf1, up_tf1, lo_tf1] = request.security(syminfo.tickerid, TF1, [mid, up, lo] ) [mid_tf2, up_tf2, lo_tf2] = request.security(syminfo.tickerid, TF2, [mid, up, lo] ) [mid_tf3, up_tf3, lo_tf3] = request.security(syminfo.tickerid, TF3, [mid, up, lo] ) //Plot Support Resist Lines mid_ft1_ln = show_tf1 ? line.new(bar_index -1, mid_tf1, bar_index, mid_tf1, extend = extend.both, color = cbtf ? tf1_col : basis, width = 2, style = line.style_dotted) : na// color.new(color.yellow,50)) line.delete(mid_ft1_ln[1]) up_ft1_ln = show_tf1 ? line.new(bar_index -1, up_tf1, bar_index, up_tf1, extend = extend.both, color = cbtf ? tf1_col : upper, width = 2, style = line.style_dotted) : na// color.new(color.yellow,50)) line.delete(up_ft1_ln[1]) lo_ft1_ln = show_tf1 ? line.new(bar_index -1, lo_tf1, bar_index, lo_tf1, extend = extend.both, color = cbtf ? tf1_col : lower, width = 2, style = line.style_dotted) : na //color.new(color.yellow,50)) line.delete(lo_ft1_ln[1]) if show_tf2 mid_ft2_ln = show_tf2 ? line.new(bar_index -1, mid_tf2, bar_index, mid_tf2, extend = extend.both, color = cbtf ? tf2_col : basis, width = 2, style = line.style_dashed) :na// color.yellow) line.delete(mid_ft2_ln[1]) up_ft2_ln = show_tf2 ? line.new(bar_index -1, up_tf2, bar_index, up_tf2, extend = extend.both, color = cbtf ? tf2_col : upper, width = 2, style = line.style_dashed) : na// color.yellow) line.delete(up_ft2_ln[1]) lo_ft2_ln = show_tf2 ? line.new(bar_index -1, lo_tf2, bar_index, lo_tf2, extend = extend.both, color = cbtf ? tf2_col : lower, width = 2, style = line.style_dashed) : na// color.yellow) line.delete(lo_ft2_ln[1]) if show_tf3 mid_ft3_ln = show_tf3 ? line.new(bar_index -1, mid_tf3, bar_index, mid_tf3, extend = extend.both, color = cbtf ? tf3_col : basis, width = 3, style = line.style_solid) : na line.delete(mid_ft3_ln[1]) up_ft3_ln = show_tf3 ? line.new(bar_index -1, up_tf3, bar_index, up_tf3, extend = extend.both, color = cbtf ? tf3_col : upper, width = 3, style = line.style_solid) : na line.delete(up_ft3_ln[1]) lo_ft3_ln = show_tf3 ? line.new(bar_index -1, lo_tf3, bar_index, lo_tf3, extend = extend.both, color = cbtf ? tf3_col : lower, width = 3, style = line.style_solid) : na line.delete(lo_ft3_ln[1])
Sync Frame (MTF Charts) [Kioseff Trading]
https://www.tradingview.com/script/LbobwUkJ-Sync-Frame-MTF-Charts-Kioseff-Trading/
KioseffTrading
https://www.tradingview.com/u/KioseffTrading/
414
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/ // © KioseffTrading //@version=5 indicator("Sync Frame [Kioseff Trading]", overlay = true, max_boxes_count = 500, max_lines_count = 500) import RicardoSantos/MathOperator/2 import HeWhoMustNotBeNamed/arraymethods/1 HA = input.string(defval = "Traditional", title = "Candle Type", options = ["Traditional", "Heikin Ashi", "Baseline"]) autox = input.bool (defval = true, title = "Auto Scale X-Axis") lin = input.bool (defval = true, title = "Show Lin Reg") len = input.int (defval = 90, minval = 3, maxval = 90, title = "Intrabars") upcol = input.color (defval = #14D990, title = "Up Color", inline = "C") dncol = input.color (defval = #F24968, title = "Up Color", inline = "C") usert = input.bool (defval = false, title = "Use Custom Timeframes", group = "Custom Timeframes") usert1 = input.int (defval = 1, minval = 1, title = "TF 1", group = "Custom Timeframes") usert2 = input.int (defval = 2, minval = 1, title = "TF 2", group = "Custom Timeframes") usert3 = input.int (defval = 3, minval = 1, title = "TF 3", group = "Custom Timeframes") usert4 = input.int (defval = 4, minval = 1, title = "TF 4", group = "Custom Timeframes"), var shif = 25 usert5 = input.int (defval = 5, minval = 1, title = "TF 5", group = "Custom Timeframes"), var counter = 0 roundedCountRaw = int(counter * .01) roundedCount = switch autox true => math.max(math.min(roundedCountRaw, math.floor(475 / len)), 2) => 2 method float(int int) => float(int) strMax( float , userTime) => seconds = timeframe.in_seconds(timeframe.period) mult = seconds / 6 switch not usert => timeframe.from_seconds(seconds - mult * float) => str.tostring(userTime) req(autoTime, userTime) => modify = switch HA "Heikin Ashi" => ticker.heikinashi(syminfo.tickerid) => syminfo.tickerid [o, h, l, c] = request.security_lower_tf(modify, strMax(autoTime, userTime), [open, high, low, close], ignore_invalid_timeframe = true) [o1, h1, l1, c1] = req(1, usert1), [o2, h2, l2, c2] = req(2, usert2) [o3, h3, l3, c3] = req(3, usert3), [o4, h4, l4, c4] = req(4, usert4), [o5, h5, l5, c5] = req(5, usert5) type lowTFs matrix<float> lowTF1 matrix<float> lowTF2 matrix<float> lowTF3 matrix<float> lowTF4 matrix<float> lowTF5 box candles line HlWick var HlMat = matrix.new<float>(2, 1) switch barstate.isfirst => HlMat.set(0, 0, -1e8), HlMat.set(1, 0, 1e8) time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time => HlMat.set(0, 0, math.max(high, HlMat.get(0, 0))), HlMat.set(1, 0, math.min(low , HlMat.get(1, 0))) method matrixApp(matrix<float> id, Close, High, Low, Open, autoTime, userTime) => timeNeeded = math.ceil(len / (timeframe.in_seconds(timeframe.period) / timeframe.in_seconds(strMax(autoTime, userTime)))) if last_bar_index - bar_index <= timeNeeded * 4 // multiplied for non-24 hour markets for i = 0 to Close.size() - 1 id.add_col(0, array.from(Close.get(i), High.get(i), Low.get(i), Open.get(i))) id method sliceFun(matrix<float> id) => all = array.new_float() c = id.row(0).slice(0, len), h = id.row(1).slice(0, len) l = id.row(2).slice(0, len), o = id.row(3).slice(0, len) for i = 0 to c.size() - 1 all.push(c.get(i)), all.push(h.get(i)) all.push(l.get(i)), all.push(o.get(i)) [c, h, l, o, all] method normalize(array<float> id, i, newMin, newMax, idMax, idMin) => id.set(i, newMin + ((id.get(i) - idMin) * (newMax - newMin)) / (idMax - idMin)) method norm(matrix<float> id, int mult) => rang = (HlMat.get(0, 0) - HlMat.get(1, 0)) / 5 newMin = HlMat.get(1, 0) + rang * mult newMax = HlMat.get(1, 0) + rang * (mult + 1) [closes, highs, lows, opens, all] = id.sliceFun() allMax = all.max(), allMin = all.min() for i = 0 to closes.size() - 1 closes.normalize(i, newMin, newMax, allMax, allMin) opens .normalize(i, newMin, newMax, allMax, allMin) highs .normalize(i, newMin, newMax, allMax, allMin) lows .normalize(i, newMin, newMax, allMax, allMin) [closes, opens, highs, lows] var allSlopes = array.new_float(), var linRegLine = array.new_line(), var fillLine = array.new_line() method linReg(matrix<float> id, mult, mult2, userTime, autoTime) => if barstate.islast and lin and HA != "Baseline" [clo, ope, hi, lo] = id.norm(mult2 - 1) linReg = matrix.new<float>(4, clo.size()) for i = 0 to clo.size() - 1 linReg.set(0, i, i + 1), linReg.set(1, i, clo.get(i)) b = linReg.row(0) for i = 0 to clo.size() - 1 linReg.set(2, i, math.pow(b.get(i) - b.avg(), 2)) linReg.set(3, i, (b.get(i) - b.avg()) * (linReg.row(1).get(i) - linReg.row(1).avg())) bx = linReg.row(3).sum() / linReg.row(2).sum() mx = linReg.row(1).avg() - (bx * b.avg()) coord = switch bx.over_equal(0) true => hi.max() => lo.min() fillLine.push (line.new(bar_index + shif, coord, bar_index + shif + clo.size() * roundedCount + 5, coord, color = #00000000)) linRegLine.push(line.new(bar_index + shif, (bx * clo.size() + mx), bar_index + shif + clo.size() * roundedCount + 5, bx + mx, width = 1, style = line.style_solid)) allSlopes.push(bx * -1) method draw(matrix<float> id, mult, userTime) => if barstate.islast [clo, ope, hi, lo] = id.norm(mult - 1) baseline = math.avg(hi.max(), lo.min()), baseLine = array.new_line() candleDraw = matrix.new<lowTFs>(2, 0) trueClo = id.row(0).slice(0, len) val = switch hi.max().subtract(clo.first()).over_equal(clo.first().subtract(lo.min())) => text.align_bottom => text.align_top box.new(bar_index + shif, hi.max(), bar_index + len * roundedCount + shif + 5, lo.min(), bgcolor = HA == "Baseline" ? na : color.new(#000eff, 90), border_color = #363843, text = strMax(mult, userTime) + " (" + str.tostring((trueClo.first() / trueClo.last() - 1) * 100, format.percent) + ")", text_color = color.white, text_valign = val, text_halign = text.align_left, text_size = size.tiny) if HA == "Baseline" bl = line.new(bar_index + shif, baseline, bar_index + len * roundedCount + shif + 5, baseline, color = color.white, style = line.style_dashed) ul = line.new(bar_index + shif, hi.max(), bar_index + len * roundedCount + shif + 5, hi.max(), color = #00000000) ll = line.new(bar_index + shif, lo.min(), bar_index + len * roundedCount + shif + 5, lo.min(), color = #00000000) linefill.new(ul, bl, color.new(upcol, 90)) linefill.new(ll, bl, color.new(dncol, 90)) if HA != "Baseline" initialCol = switch id.get(0, 0).over_equal(id.get(3, 0)) true => upcol false => dncol candleDraw.add_col(candleDraw.columns(), array.from( lowTFs.new(candles = box.new(bar_index + shif + 2 + len * roundedCount, clo.first(), bar_index + shif + 4 + len * roundedCount, ope.first(), bgcolor = initialCol , border_color = na)), lowTFs.new(HlWick = line.new(bar_index + shif + 3 + len * roundedCount, hi.first(), bar_index + shif + 3 + len * roundedCount, lo.first (), color = initialCol)) )) for i = 1 to len - 1 col = switch id.get(0, i).over_equal(id.get(3, i)) true => upcol false => dncol getLeft = candleDraw.get(0, candleDraw.columns() - 1).candles.get_left() pAvg = math.round(math.avg(getLeft - roundedCount, getLeft)) candleDraw.add_col(candleDraw.columns(), array.from( lowTFs.new(candles = box.new(getLeft - roundedCount, clo.get(i), getLeft, ope.get(i), bgcolor = col , border_color = na)), lowTFs.new(HlWick = line.new(pAvg, hi.get(i), pAvg, lo.get(i), color = col)) )) if box.all.size() > 499 box.all.remove(1).delete() if line.all.size() > 490 count = 0. for x = 0 to line.all.size() - 1 if count.equal(2) break else if not linRegLine.includes(line.all.get(x)) if not fillLine.includes(line.all.get(x)) line.all.remove(x).delete() count += 1 else baseLine.push(line.new(bar_index + shif + 2 + len * roundedCount, clo.get(1), bar_index + shif + 4 + len * roundedCount, clo.first(), color = clo.first() > baseline ? upcol : dncol)) for i = 1 to len - 2 if clo.get(i).over(baseline) and clo.get(i + 1).under(baseline) or clo.get(i).under(baseline) and clo.get(i + 1).over(baseline) [col1, col2] = switch clo.get(i) >= baseline => [upcol, dncol] => [dncol, upcol] baseLine.push(line.new(baseLine.last().get_x1() - math.round(roundedCount / 2), baseline, baseLine.last().get_x1(), clo.get(i), color =col1)) baseLine.push(line.new(baseLine.last().get_x1() - math.round(roundedCount / 2), clo.get(i + 1), baseLine.last().get_x1(), baseline, color = col2)) else baseLine.push(line.new(baseLine.last().get_x1() - roundedCount, clo.get(i + 1), baseLine.last().get_x1(), clo.get(i), color = clo.get(i) >= baseline ? upcol : dncol)) id if last_bar_index - bar_index <= 500 box.all.flush(), label.all.flush(), line.all.flush() var ltf = lowTFs.new(matrix.new<float>(4, 0), matrix.new<float>(4, 0), matrix.new<float>(4, 0), matrix.new<float>(4, 0), matrix.new<float>(4, 0)) ltf.lowTF1.matrixApp(c1, h1, l1, o1, 1, usert1).draw(1, usert1).linReg(1, 1, usert1, 1) ltf.lowTF2.matrixApp(c2, h2, l2, o2, 2, usert2).draw(2, usert2).linReg(1, 2, usert2, 2) ltf.lowTF3.matrixApp(c3, h3, l3, o3, 3, usert3).draw(3, usert3).linReg(1, 3, usert3, 3) ltf.lowTF4.matrixApp(c4, h4, l4, o4, 4, usert4).draw(4, usert4).linReg(1, 4, usert4, 4) ltf.lowTF5.matrixApp(c5, h5, l5, o5, 5, usert5).draw(5, usert5).linReg(1, 5, usert5, 5) if lin if barstate.islast copySlope = allSlopes.copy() copySlope.sort(order.ascending) var float [] ups = na, var float [] dns = na if allSlopes.max().over_equal(0) ups := copySlope.slice(copySlope.binary_search_rightmost(0), copySlope.size()) for i = 0 to ups.size() - 1 col = color.from_gradient(ups.get(i), 0, ups.max(), color.white, upcol) linRegLine.get(allSlopes.indexof(ups.get(i))).set_color(col) linefill.new(linRegLine.get(allSlopes.indexof(ups.get(i))), fillLine.get(allSlopes.indexof(ups.get(i))), color.new(col, 75)) if allSlopes.min().under(0) dns := copySlope.slice(0, copySlope.binary_search_rightmost(0)) for i = 0 to dns.size() - 1 col = color.from_gradient(dns.get(i), dns.min(), 0, dncol, color.white) linRegLine.get(allSlopes.indexof(dns.get(i))).set_color(col) linefill.new(linRegLine.get(allSlopes.indexof(dns.get(i))), fillLine.get(allSlopes.indexof(dns.get(i))), color.new(col, 75)) if time >= chart.left_visible_bar_time counter += 1
User Defined Range Selector and Color Changing EMA Line
https://www.tradingview.com/script/IAWfDZmw-User-Defined-Range-Selector-and-Color-Changing-EMA-Line/
Crypto_Moses
https://www.tradingview.com/u/Crypto_Moses/
20
study
4
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/ // © Crypto_Moses //@version=4 study("User Defined Range Selector and Color Changing EMA Line", shorttitle="User EMA Range", overlay=true) // User Inputs len = input(69, title="EMA Length", minval=1) slopeLength = input(3, title="Slope Length", minval=1) src = input(low, title="Source") colorUp = input(color.blue, title="Color for Upward Slope") colorDown = input(color.red, title="Color for Downward Slope") colorSideways = input(color.gray, title="Color for Sideways") percentAway = input(1.5, title="Percentage Away for Mirrored Line", minval=0.1, step=0.1) // Calculate EMA and its Slope emaLine = ema(src, len) slope = emaLine - emaLine[slopeLength] emaColor = slope > 0 ? colorUp : slope < 0 ? colorDown : colorSideways // Calculate Mirrored Line mirroredLine = emaLine * (1 + percentAway / 100) // Plotting plot(emaLine, title="EMA", color=emaColor, linewidth=1) plot(mirroredLine, title="Mirrored EMA", color=color.gray, linewidth=1, style=plot.style_circles)
AMDX-XAMD
https://www.tradingview.com/script/tJcEhltJ/
minerlancer
https://www.tradingview.com/u/minerlancer/
14
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/ // © minerlancer //@version=5 indicator('AMDX-XAMD' , overlay = true , precision = 0 , max_boxes_count = 500 , max_labels_count = 500 , max_lines_count = 500 , max_bars_back = 5000) Timezone = 'America/New_York' DOM_240 = (timeframe.multiplier >= 240) DOM240 = (timeframe.multiplier <= 240) DOM60 = (timeframe.multiplier <= 60) DOM40 = (timeframe.multiplier <= 40) DOM30 = (timeframe.multiplier <= 30) DOM15 = (timeframe.multiplier <= 15) DOM5 = (timeframe.multiplier <= 5) //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// // AMDX / XDMA //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// //---Weekly show_Q_W = input.bool(defval = false , title = 'AMDX W' , inline = '0' , group = 'AMDX Weekly') color_Q_W= input.color(defval = color.rgb(54, 58, 69, 50) , title = '' , inline = '0' , group = 'AMDX Weekly') open_Q_W = input.bool(defval = false , title = 'Line Open True W', inline = '1' , group = 'AMDX Weekly') ln_cl_Q_W= input.color(defval = color.black , title = '' , inline = '1' , group = 'AMDX Weekly') show_txt_open_Q_W = input.bool(defval = false , title = 'Text Open' , inline = '1', group = 'AMDX Weekly') show_txt_Q_W = input.bool(defval = false , title = 'Text in Box  ' , inline = '2', group = 'AMDX Weekly') tran_txt_Q_W = input.int(defval = 70 , title = 'Trasparency Text' , maxval = 100 , inline = '2', group = 'AMDX Weekly') //---Dayly show_Q_D = input.bool(defval = true , title = 'AMDX D' , inline = '0' , group = 'AMDX Daily') open_Q_D = input.bool(defval = false , title = 'Line Open True D  ' , inline = '1' , group = 'AMDX Daily') show_txt_open_Q_D = input.bool(defval = false , title = 'Text Open' , inline = '1', group = 'AMDX Daily') show_txt_Q_D = input.bool(defval = false , title = 'Text in Box  ' , inline = '2' , group = 'AMDX Daily') tran_txt_Q_D = input.int(defval = 70 , title = 'Trasparency Text' , maxval = 100 , inline = '2' , group = 'AMDX Daily') //---Session show_Q_Sess = input.bool(defval = false , title = 'AMDX Session' , inline = '0' , group = 'AMDX Session') show_open_True_Sess_Q1 = input.bool(defval = true , title = 'Asian ' , inline = '1' , group = 'AMDX Session') show_open_True_Sess_Q2 = input.bool(defval = true , title = 'London ' , inline = '1' , group = 'AMDX Session') show_open_True_Sess_Q3 = input.bool(defval = true , title = 'NY ' , inline = '1' , group = 'AMDX Session') show_open_True_Sess_Q4 = input.bool(defval = true , title = 'PM ' , inline = '1' , group = 'AMDX Session') show_Q_BR_box = input.bool(defval = true , title = 'BG Box  ' , inline = '2' , group = 'AMDX Session') show_Q_txt_box = input.bool(defval = false , title = 'Text Box' , inline = '2' , group = 'AMDX Session') show_Q_txt_up = input.bool(defval = false , title = 'Text Session' , inline = '2' , group = 'AMDX Session' , tooltip = 'Show in TF 5m') show_open_True = input.bool(defval = true , title = 'Line Open True Session  ' , inline = '3' , group = 'AMDX Session') show_txt_open_True = input.bool(defval = true , title = 'Text Open' , inline = '3' , group = 'AMDX Session') [dailyTime, dailyOpen] = request.security(syminfo.tickerid, 'D', [time, open], lookahead=barmerge.lookahead_on) //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// // Open True //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// txt_True_W = 'Weekly' col_True_W = ln_cl_Q_W timing_True_W = dayofweek(time_close) == dayofweek.monday and (hour(time, Timezone) == 18) and (minute(time) == 00) txt_True_D = 'Daily' col_True_D = color.orange timing_True_D = (hour(time, Timezone) == 00) and (minute(time) == 00) txt_True_0 = 'Asian' col_True_0 = color.white timing_True_0 = (hour(time, Timezone) == 19) and (minute(time) == 30) txt_True_1 = 'London' col_True_1 = color.blue timing_True_1 = (hour(time, Timezone) == 01) and (minute(time) == 30) txt_True_2 = 'NY' col_True_2 = color.red timing_True_2 = (hour(time, Timezone) == 07) and (minute(time) == 30) txt_True_3 = 'PM' col_True_3 = color.purple timing_True_3 = (hour(time, Timezone) == 13) and (minute(time) == 30) //-----True open Weekly var line[] line_W = array.new_line(0) var label[] labl_W = array.new_label(0) if open_Q_W and DOM240 and not timeframe.ismonthly if timing_True_W and not timing_True_W[1] array.push(line_W , line.new(time , open , time + 80 * 3600000 , open , xloc = xloc.bar_time , color = col_True_W , width = 2)) array.push(labl_W , label.new(time + 80 * 3600000 , open , show_txt_open_Q_W ? txt_True_W : na , xloc = xloc.bar_time , style = label.style_none , size = size.small , textcolor = col_True_W)) //-----True open Daily var line[] line_D = array.new_line(0) var label[] labl_D = array.new_label(0) if open_Q_D and DOM240 if timing_True_D and not timing_True_D[1] array.push(line_D , line.new(time , open , time + 23 * 3600000 , open , xloc = xloc.bar_time , color = col_True_D , width = 2)) array.push(labl_D , label.new(time + 23 * 3600000 , open , show_txt_open_Q_D ? txt_True_D : na , xloc = xloc.bar_time , style = label.style_none , size = size.small , textcolor = col_True_D)) //-----True open Session var line[] l1 = array.new_line(0) var label[] la1 = array.new_label(0) var line[] l2 = array.new_line(0) var label[] la2 = array.new_label(0) var line[] l3 = array.new_line(0) var label[] la3 = array.new_label(0) var line[] l4 = array.new_line(0) var label[] la4 = array.new_label(0) _extend = 4 * 3600000 if show_open_True and DOM30 and not timeframe.ismonthly if timing_True_0 and not timing_True_0[1] and show_open_True_Sess_Q1 array.push(l1, line.new(time , open , time + _extend , open , xloc = xloc.bar_time , color = col_True_0 , width = 1)) array.push(la1 , label.new(time + _extend , open , show_txt_open_True ? txt_True_0 : na , xloc=xloc.bar_time , style=label.style_none , size=size.small , textcolor = col_True_0)) if timing_True_1 and not timing_True_1[1] and show_open_True_Sess_Q2 array.push(l2 , line.new(time , open , time + _extend , open , xloc=xloc.bar_time , color = col_True_1 , width = 1)) array.push(la2 , label.new(time + _extend, open, show_txt_open_True ? txt_True_1 : na , xloc = xloc.bar_time , style = label.style_none , size = size.small , textcolor = col_True_1)) if timing_True_2 and not timing_True_2[1] and show_open_True_Sess_Q3 array.push(l3 , line.new(time , open , time + _extend , open , xloc=xloc.bar_time, color = col_True_2 , width = 1)) array.push(la3 , label.new(time + _extend, open, show_txt_open_True ? txt_True_2 : na , xloc = xloc.bar_time , style = label.style_none , size = size.small, textcolor = col_True_2)) if timing_True_3 and not timing_True_3[1] and show_open_True_Sess_Q4 array.push(l4 , line.new(time , open , time + _extend , open , xloc = xloc.bar_time , color = col_True_3 , width = 1)) array.push(la4 , label.new(time + _extend , open , show_txt_open_True ? txt_True_3 : na , xloc = xloc.bar_time , style = label.style_none, size = size.small , textcolor = col_True_3)) // Delete lines if more than max if array.size(l1) > 10 line.delete(array.shift(l1)) label.delete(array.shift(la1)) if array.size(l1) > 10 line.delete(array.shift(l2)) label.delete(array.shift(la2)) if array.size(l3) > 10 line.delete(array.shift(l3)) label.delete(array.shift(la3)) if array.size(l4) > 10 line.delete(array.shift(l4)) label.delete(array.shift(la4)) //-------------------------------- //---Function //-------------------------------- drawing_VerticalLines(aBaseTime, aDrawTimeD, aLineStyle, aLineColor) => _iDrawTimeD = aDrawTimeD yy = year mm = month dd = dayofmonth hh = hour(aBaseTime) m2 = minute(aBaseTime) iDrawTime = timestamp(yy, mm, dd, hh, m2) hour_j = hour(iDrawTime, Timezone) dayofweek_j = dayofweek(iDrawTime, Timezone) iDsp = true if dayofweek_j == dayofweek.saturday and hour_j >= 6 iDsp := false else if dayofweek_j == dayofweek.sunday iDsp := false else if dayofweek_j == dayofweek.monday and hour_j < 7 iDsp := false // double drawing prevention if iDrawTime != aDrawTimeD and iDsp line.new(iDrawTime, dailyOpen, iDrawTime, dailyOpen + syminfo.mintick, xloc=xloc.bar_time, style=aLineStyle, extend=extend.both, color=aLineColor, width=1) _iDrawTimeD := iDrawTime _iDrawTimeD //-------------------------------------------- //-------------------------------------------- //--Functions in_session(sess) => not na(time(timeframe.period, sess, Timezone)) start_time(sess) => int startTime = na startTime := in_session(sess) and not in_session(sess)[1] ? time : startTime[1] startTime is_new_session(res, sess) => t = time(res, sess, Timezone) na(t[1]) and not na(t) or t[1] < t //-------------------------------------------- //------------------------------------------- //--Timing Session //---Q1 time_Q_ses_D = timeframe.period == '240' ? '0000-2200' : '0000-2300' Q_ses_D = time_Q_ses_D //--Timing Session //---Q1 Q_ses_AS = '1800-0000' Q_time_0 = '1800-1930' Q_time_1 = '1930-2100' Q_time_2 = '2100-2230' Q_time_3 = '2230-0000' //---Q2 Q_ses_LN = '0000-0600' Q_time_4 = '0000-0130' Q_time_5 = '0130-0300' Q_time_6 = '0300-0430' Q_time_7 = '0430-0600' //---Q3 Q_ses_NY = '0600-1200' Q_time_8 = '0600-0730' Q_time_9 = '0730-0900' Q_time_10 = '0900-1030' Q_time_11 = '1030-1200' //---Q4 Q_ses_PM = '1200-1800' Q_time_12 = '1200-1330' Q_time_13 = '1330-1500' Q_time_14 = '1500-1630' Q_time_15 = '1630-1800' //------------------------------------------- //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// // Box //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------// time_start = timestamp(Timezone , year , month , dayofmonth , 9, 30 , 00) // ======= Range + Box ======== ictbox(kz , bdcol , bgcol , txt, coltxt , x)=> sesh = is_new_session('1440', kz) float kzlow = na float kzhigh = na float kzbodlow = na float kzbodhigh = na kzbox = box(na) bline = line(na) bline2 = line(na) kzstart = start_time(kz) kzlow := sesh ? low : in_session(kz) ? math.min(low, kzlow[1]) : na kzhigh := sesh ? high : in_session(kz) ? math.max(high, kzhigh[1]) : na if in_session(kz) if in_session(kz)[1] box.delete(kzbox[1]) line.delete(bline[1]) line.delete(bline2[1]) if low < kzlow kzlow := low kzlow if high > kzhigh kzhigh := high kzhigh if x kzbox := box.new(kzstart , kzhigh , time , kzlow , bdcol , 1 , line.style_solid , extend.none , xloc.bar_time , bgcol , txt , size.auto , coltxt , text_wrap = text.wrap_auto , text_valign = text.align_top) kzbox if x bline := line.new(kzstart, kzhigh, time, kzhigh, xloc.bar_time, extend.none, bdcol, line.style_solid, 1) bline bline2 := line.new(kzstart, kzlow, time, kzlow, xloc.bar_time, extend.none, bdcol, line.style_solid, 1) bline2 tz = time - time[1] //--------------------- //---W = Day of Week bg_friday = DOM_240 and dayofweek(time_close) == dayofweek.friday ? color.new(color.gray , 60) : na bgcolor(color = bg_friday , title = 'Friday') txt_Q_W = dayofweek(time_close) == dayofweek.monday ? 'Q1 \nMonday' : dayofweek(time_close) == dayofweek.tuesday ? 'Q2 \nTuesday' : dayofweek(time_close) == dayofweek.wednesday ? 'Q3 \nWednesday' : dayofweek(time_close) == dayofweek.thursday ? 'Q4 \nThursday' : na col_Q_W = dayofweek(time_close) == dayofweek.friday ? color.rgb(255, 82, 82, 100) : color_Q_W col_txt_W_AMDX = show_txt_Q_W ? color.new(color.gray, tran_txt_Q_W) : na if DOM240 and not timeframe.ismonthly ictbox(Q_ses_D , col_Q_W , color.rgb(0, 187, 212, 100) , txt_Q_W , col_txt_W_AMDX , show_Q_W) //------------------------- //---D col_txt_D_AMDX = show_txt_Q_D ? color.new(color.gray , tran_txt_Q_D) : na if DOM60 and not timeframe.isdwm ictbox(Q_ses_AS , color.new(col_True_0 , 70) , color.rgb(0, 187, 212, 100) , 'Q1 \nAsia' , col_txt_D_AMDX , show_Q_D) ictbox(Q_ses_LN , color.new(col_True_1 , 70) , color.rgb(0, 187, 212, 100) , 'Q2 \nLondon' , col_txt_D_AMDX , show_Q_D) ictbox(Q_ses_NY , color.new(col_True_2 , 70) , color.rgb(0, 187, 212, 100) , 'Q3 \nNY' , col_txt_D_AMDX , show_Q_D) ictbox(Q_ses_PM , color.new(col_True_3 , 70) , color.rgb(0, 187, 212, 100) , 'Q4 \nPM' , col_txt_D_AMDX , show_Q_D) //------------------------- col_txt_session_AMDX = show_Q_txt_box ? color.new(color.gray, 80) : na if DOM30 and show_Q_Sess if show_open_True_Sess_Q1 and not timeframe.isdwm ictbox(Q_time_0 , color.new(col_True_0 , 50) , show_Q_BR_box ? color.new(col_True_0 , 90) : na , 'Q1' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_1 , color.new(col_True_0 , 50) , show_Q_BR_box ? color.new(col_True_0 , 90) : na , 'Q2' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_2 , color.new(col_True_0 , 50) , show_Q_BR_box ? color.new(col_True_0 , 90) : na , 'Q3' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_3 , color.new(col_True_0 , 50) , show_Q_BR_box ? color.new(col_True_0 , 90) : na , 'Q4' , col_txt_session_AMDX , show_Q_Sess) if show_open_True_Sess_Q2 ictbox(Q_time_4 , color.new(col_True_1 , 50) , show_Q_BR_box ? color.new(col_True_1 , 90) : na , 'Q1' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_5 , color.new(col_True_1 , 50) , show_Q_BR_box ? color.new(col_True_1 , 90) : na , 'Q2' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_6 , color.new(col_True_1 , 50) , show_Q_BR_box ? color.new(col_True_1 , 90) : na , 'Q3' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_7 , color.new(col_True_1 , 50) , show_Q_BR_box ? color.new(col_True_1 , 90) : na , 'Q4' , col_txt_session_AMDX , show_Q_Sess) if show_open_True_Sess_Q3 ictbox(Q_time_8 , color.new(col_True_2 , 50) , show_Q_BR_box ? color.new(col_True_2 , 90) : na , 'Q1' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_9 , color.new(col_True_2 , 50) , show_Q_BR_box ? color.new(col_True_2 , 90) : na , 'Q2' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_10, color.new(col_True_2 , 50) , show_Q_BR_box ? color.new(col_True_2 , 90) : na , 'Q3' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_11, color.new(col_True_2 , 50) , show_Q_BR_box ? color.new(col_True_2 , 90) : na , 'Q4' , col_txt_session_AMDX , show_Q_Sess) if show_open_True_Sess_Q4 ictbox(Q_time_12, color.new(col_True_3 , 50) , show_Q_BR_box ? color.new(col_True_3 , 90) : na , 'Q1' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_13, color.new(col_True_3 , 50) , show_Q_BR_box ? color.new(col_True_3 , 90) : na , 'Q2' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_14, color.new(col_True_3 , 50) , show_Q_BR_box ? color.new(col_True_3 , 90) : na , 'Q3' , col_txt_session_AMDX , show_Q_Sess) ictbox(Q_time_15, color.new(col_True_3 , 50) , show_Q_BR_box ? color.new(col_True_3 , 90) : na , 'Q4' , col_txt_session_AMDX , show_Q_Sess) //-------------------------------- //--Label session //-------------------------------- if DOM5 and not timeframe.isdwm var float top_bottom = 0 var color kz_color = na var bool in_kz = na var string kz_text = na if show_Q_txt_up if show_open_True_Sess_Q1 and time(timeframe.period , '1801-0000' , Timezone) in_kz := true , kz_color := color.new(col_True_0 , 80) , kz_text := txt_True_0 else if show_open_True_Sess_Q2 and time(timeframe.period , '0001-0600' , Timezone) in_kz := true , kz_color := color.new(col_True_1 , 80) , kz_text := txt_True_1 else if show_open_True_Sess_Q3 and time(timeframe.period , '0601-1200' , Timezone) in_kz := true , kz_color := color.new(col_True_2 , 80) , kz_text := txt_True_2 else if show_open_True_Sess_Q4 and time(timeframe.period , '1201-1800' , Timezone) in_kz := true , kz_color := color.new(col_True_3 , 80) , kz_text := txt_True_3 else in_kz := false else in_kz := true var box kz_box = na var line kz_start_line = na var line kz_end_line = na if show_Q_txt_up if in_kz and not in_kz[1] kz_box := box.new(bar_index, high, bar_index, low, border_color = color.new(color.red, 100), bgcolor = kz_color, text = kz_text , text_size = size.small) kz_start_line := line.new(bar_index, high, bar_index, box.get_top(kz_box), color = kz_color, style = line.style_dotted) top_bottom := 0 if in_kz[1] box.set_right(kz_box, bar_index) if high > box.get_bottom(kz_box) box.set_bottom(kz_box,1.0010* high) box.set_top(kz_box,1.0015*high) line.set_y2(kz_start_line, box.get_top(kz_box)) if in_kz[1] and not in_kz kz_end_line := line.new(bar_index, high, bar_index, box.get_top(kz_box), color = kz_color, style = line.style_dotted)
HTF MA's BG
https://www.tradingview.com/script/J2y52g4x-HTF-MA-s-BG/
MtnMarathoner
https://www.tradingview.com/u/MtnMarathoner/
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/ //@version=5 indicator('HTF MA\'s BG', overlay=true) InputTime = input.string("0730-1100:23456", "Time Input") t = time(timeframe.period, InputTime, "America/Denver") //denver time plus 2 hours //Set Red background color if outside of session time ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "Bollinger Bands" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) "HMA" => ta.wma(2*ta.wma(source, length/2)-ta.wma(source, length), math.floor(math.sqrt(length))) ShortSMMA = input.int(50, minval=1, title="Short MA") MedSMMA = input.int(50, minval=1, title="Medium MA") MinimumStopLossValue = input.float(1.0, minval=0.0, step=0.1, title="Minimum Stop Loss Value") maTypeInput = input.string("HMA", title="MA 3 Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group="MA Settings") src1 = input(close, title='Source') smma1 = 0.0 sma_1 = ma(src1, ShortSMMA, maTypeInput) HTF_sma_1 = request.security(syminfo.tickerid, '2', sma_1, barmerge.gaps_on, barmerge.lookahead_off) //plot(sma_1, title="Short MA", color=color.new(color.white, 0)) plot(HTF_sma_1, title="HTF Short MA", color=color.new(color.white, 0)) src2 = input(close, title='Source') smma2 = 0.0 sma_2 = ma(src2, MedSMMA, maTypeInput) HTF_sma_2 = request.security(syminfo.tickerid, '3', sma_2, barmerge.gaps_on, barmerge.lookahead_off) //plot(sma_2, title="Medium MA", color=color.new(color.green, 0)) plot(HTF_sma_2, title="HTF Medium MA", color=color.new(color.green, 0)) MAShort = HTF_sma_1 < HTF_sma_2 MALong = HTF_sma_1 > HTF_sma_2 sessioncolor = color.purple sessioncolor := not t ? color.purple : t and (close > HTF_sma_1 or close > HTF_sma_1[1]) ? color.green : t and (close < HTF_sma_1 or close < HTF_sma_1[1]) ? color.red : nz(sessioncolor[1]) bgcolor(color.new(sessioncolor, 75)) ////////////////////////////////////////////////////////////////////////// // Settings for 5min chart, BTCUSDC. For Other coin, change the parameters ////////////////////////////////////////////////////////////////////////// // Color variables upColor = color.green midColor = color.gray downColor = color.red // Source src_fastrangefilter = input(defval=hl2, title="Source") // Sampling Period // Settings for 5min chart, BTCUSDC. For Other coin, change the paremeters per_fastrangefilter = input.int(defval=24, minval=1, title="Sampling Period") // Range Multiplier mult_fastrangefilter = input.float(defval=2.7, minval=0.1, title="Range Multiplier") // Smooth Average Range smoothrng(x, t, m) => wper = t * 2 - 1 avrng = ta.ema(math.abs(x - x[1]), t) smoothrng = ta.ema(avrng, wper) * m smoothrng smrng = smoothrng(src_fastrangefilter, per_fastrangefilter, mult_fastrangefilter) // Range Filter rngfilt(x, r) => rngfilt = x rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r rngfilt filt = rngfilt(src_fastrangefilter, smrng) // Filter Direction upward = 0.0 upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1]) downward = 0.0 downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1]) // Colors filtcolor = upward > 0 ? upColor : downward > 0 ? downColor : midColor filtplot = plot(filt, color=filtcolor, linewidth=2, title="Fast Range Filter") barcolor = src_fastrangefilter > filt and src_fastrangefilter > src_fastrangefilter[1] and upward > 0 ? upColor : src_fastrangefilter > filt and src_fastrangefilter < src_fastrangefilter[1] and upward > 0 ? upColor : src_fastrangefilter < filt and src_fastrangefilter < src_fastrangefilter[1] and downward > 0 ? downColor : src_fastrangefilter < filt and src_fastrangefilter > src_fastrangefilter[1] and downward > 0 ? downColor : midColor // Bar Color barcolor(barcolor) shortSignal = (sessioncolor == color.red) and ((barcolor[1] == upColor and barcolor == midColor) or (barcolor[1] == midColor and barcolor == downColor) or (barcolor[1] == upColor and barcolor == downColor)) longSignal = (sessioncolor == color.green) and ((barcolor[1] == downColor and barcolor == midColor) or (barcolor[1] == midColor and barcolor == upColor) or (barcolor[1] == downColor and barcolor == upColor)) plotshape(longSignal and not longSignal[1], title="Buy Signal", style=shape.triangleup, size=size.tiny, location=location.belowbar, color=color.green) plotshape(shortSignal and not shortSignal[1], title="Sell Signal", style=shape.triangledown, size=size.tiny, location=location.abovebar, color=color.red) //write table var string GP2 = "Display" string tableYposInput = input.string("top", "Panel position", inline = "11", options = ["top", "middle", "bottom"], group = GP2) string tableXposInput = input.string("right", "", inline = "11", options = ["left", "center", "right"], group = GP2) color bullColorInput = input.color(color.new(color.green, 30), "Bull", inline = "12", group = GP2) color bearColorInput = input.color(color.new(color.red, 30), "Bear", inline = "12", group = GP2) color neutColorInput = input.color(color.new(color.gray, 30), "Neutral", inline = "12", group = GP2) var table panel = table.new(tableYposInput + "_" + tableXposInput, 4, 7) if barstate.islast // Table header. table.cell(panel, 0, 0, "SL Size", bgcolor = bearColorInput) SL = 0.0 SL := (sessioncolor == color.red) and close > open ? (math.max(MinimumStopLossValue,high[2]-close)) : (sessioncolor == color.red) and close < open ? (math.max(MinimumStopLossValue,high[1]-close)) : (sessioncolor == color.green) and close > open ? (math.max(1,close-low[1])) : (math.max(MinimumStopLossValue,close-low[2])) table.cell(panel, 0, 1, str.tostring(SL), bgcolor = neutColorInput)
LTF Candle Insights (Zeiierman)
https://www.tradingview.com/script/HsO1bxqX-LTF-Candle-Insights-Zeiierman/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
436
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("LTF Candle Insights (Zeiierman)",overlay = true,max_bars_back = 500, max_boxes_count = 500) // ~~ Inputs { tf = input.timeframe("1","Timeframe", group="Lower Timeframe Candles") numb = input.int(20,"Amount of Candles",minval=0, maxval=100, group="Lower Timeframe Candles") dn_col = input.color(color.new(color.red,10), title="Dn", inline="Candles", group="Lower Timeframe Candles") dn_wick = input.color(color.new(color.red,0), title="Wick", inline="Candles", group="Lower Timeframe Candles") up_col = input.color(color.new(color.lime,10), title="Up",inline="Candles", group="Lower Timeframe Candles") up_wick = input.color(color.new(color.lime,0), title="Wick", inline="Candles", group="Lower Timeframe Candles") Range = input.bool(true,"Range High/Low", inline="range", group="Range") Mid = input.bool(true,"Range Mid", inline="range", group="Range") high_col = input.color(color.red, title="High", inline="range 1", group="Range") low_col = input.color(color.lime, title="Low",inline="range 1", group="Range") mid_col = input.color(color.rgb(20, 69, 246), title="Mid",inline="range 1", group="Range") loc = input.int(1,"Location", group="Location Settings") // ~~ Table Inputs { showTable = input.bool(true,title="Show Table", inline="tbl", group="Table") TblSize = input.string(size.normal,title="",options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="tbl", group="Table") pos = input.string(position.top_right, title="",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],inline="tbl", group="Table") textcolor = input.color(color.white, title="Text",inline="tbl_col", group="Table") bgcolor = input.color(color.new(color.blue,30), title="Bg",inline="tbl_col", group="Table") //~~~} //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ LTF Error Message { tfs = str.tonumber(tf) if str.tostring(tf) == "1D" tfs := 1440 error = str.tonumber(timeframe.period)<tfs //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ UDT { type Candle array<box> candle array<line> wickH array<line> wickL array<float> hl type LTF array<float> o array<float> h array<float> l array<float> c //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Variables { b = bar_index var candle = Candle.new(array.new<box>(numb),array.new<line>(numb),array.new<line>(numb),array.new<float>(numb*2)) var ltfData = LTF.new(array.new<float>(numb),array.new<float>(numb),array.new<float>(numb),array.new<float>(numb)) ltfO = request.security_lower_tf(syminfo.tickerid, tf, open) ltfH = request.security_lower_tf(syminfo.tickerid, tf, high) ltfL = request.security_lower_tf(syminfo.tickerid, tf, low) ltfC = request.security_lower_tf(syminfo.tickerid, tf, close) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Code { //~~Save Previous Candle Data if timeframe.change(timeframe.period) if ltfData.o.size()>numb while ltfData.o.size()>numb ltfData.o.shift() ltfData.h.shift() ltfData.l.shift() ltfData.c.shift() ltfData.o.concat(ltfO) ltfData.h.concat(ltfH) ltfData.l.concat(ltfL) ltfData.c.concat(ltfC) //~~ Plot Candles if ltfData.o.size()>=numb d = loc for i=ltfData.o.size()-numb to ltfData.o.size()-1 candle.candle.shift().delete() candle.wickH.shift().delete() candle.wickL.shift().delete() candle.hl.shift() candle.hl.shift() o = ltfData.o.get(i) h = ltfData.h.get(i) l = ltfData.l.get(i) c = ltfData.c.get(i) candle.candle.push(box.new(b+d*2+loc,math.max(o,c),b+d*2+2+loc,math.min(o,c),color(na),bgcolor=o>c?dn_col:up_col)) candle.wickH.push(line.new(b+d*2+1+loc,math.max(o,c),b+d*2+1+loc,h,color=o>c?dn_col:up_col)) candle.wickL.push(line.new(b+d*2+1+loc,math.min(o,c),b+d*2+1+loc,l,color=o>c?dn_col:up_col)) candle.hl.push(h) candle.hl.push(l) d += 2 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Range { if Range RangeHigh = line.new(b,candle.hl.max(),b+numb*4+loc*3,candle.hl.max(),color=high_col,extend=extend.none) RangeLow = line.new(b,candle.hl.min(),b+numb*4+loc*3,candle.hl.min(),color=low_col,extend=extend.none) (RangeHigh[1]).delete() (RangeLow[1]).delete() if Mid RangeMid = line.new(b,math.avg(candle.hl.max(),candle.hl.min()),b+numb*4+loc*3,math.avg(candle.hl.max(),candle.hl.min()),color=mid_col,extend=extend.none) (RangeMid[1]).delete() //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Table { tbl = table.new(pos, 2, 11, frame_color=chart.bg_color, frame_width=2, border_width=2, border_color=chart.bg_color) if barstate.islast and showTable tbl.cell(0, 0, text=error?"Error":"TF", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize) tbl.cell(0, 1, text=error?"The chart's timeframe must be greater than the LTF '"+tf+"' timeframe. \n\nor please select a lower timeframe in the setting panel of the indicator.":str.tostring(timeframe.period), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize) tbl.cell(1, 0, text="LTF", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize) tbl.cell(1, 1, text=str.tostring(tf), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
Double Simple Moving Average
https://www.tradingview.com/script/so65bJAE-Double-Simple-Moving-Average/
OmegaTools
https://www.tradingview.com/u/OmegaTools/
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/ // © OmegaTools //@version=5 indicator("Double Simple Moving Average", overlay = true) lnt = input(21, "Length") mult = input(2.00, "Band width") a = ta.sma(high, lnt) b = ta.sma(low, lnt) c = ta.sma(close, lnt) d = ta.vwma(close, lnt) sp = a - b tool = d - c grad = color.from_gradient(tool, ta.lowest(tool, lnt*3), ta.highest(tool, lnt*3), #e91e63, #2962ff) p1 = plot(a, "High average", #2962ff) p2 = plot(b, "Low average", #e91e63) p3 = plot(c, "Close average", color.gray, 1, display = display.none, editable = false) fill(p1, p3, color.new(grad, 50)) fill(p2, p3, color.new(grad, 50)) p4 = plot(c + (sp * mult), "High band", color.gray, display = display.none) p5 = plot(c - (sp * mult), "Low band", color.gray, display = display.none) fill(p4, p5, color.new(color.gray, 85))
Hull Waves
https://www.tradingview.com/script/kQMP5CBq-Hull-Waves/
AleSaira
https://www.tradingview.com/u/AleSaira/
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/ // © AleSaira //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================{ // _____ .__ _________ .__ // / _ \ | | ____ / _____/____ |__|___________ /// /_\ \| | _/ __ \ \_____ \\__ \ | \_ __ \__ \ /// | \ |_\ ___/ / \/ __ \| || | \// __ \_ //\____|__ /____/\___ >_______ (____ /__||__| (____ / // \/ \/ \/ \/ \/ //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================{ //@version=5 indicator("Hull Waves", "Hull Waves", true, max_lines_count = 100, max_bars_back = 100) //==================////////////////////////================================/////////////////======================} // Input pfor the number of lines //==================////////////////////////================================/////////////////======================{ fiu_time = input.int (100, title="Number of Lines", minval=1) mira = input.int (15, title="Lenght of fan") //==================////////////////////////================================/////////////////======================} // Input for the fan colour //==================////////////////////////================================/////////////////======================{ lineColorUp = input (color.lime, title="Color for Lines Going Up") lineColorDown = input (color.rgb(248, 5, 5), title="Color for Lines Going Down") //==================////////////////////////================================/////////////////======================} // Input for the color of the fill areas //==================////////////////////////================================/////////////////======================{ fillColorUp = input (color.new(#0fb5d2, 66), title="Fill Color for Up Lines") fillColorDown = input (color.new(#de0ee2, 54), title="Fill Color for Down Lines") //==================////////////////////////================================/////////////////======================} // Input for moving average lengths //==================////////////////////////================================/////////////////======================{ sma1Length = input (8, title="Length for 5-period HMA") sma2Length = input (21, title="Length for 20-period HMA") //==================////////////////////////================================/////////////////======================} // Loop creating the fan of lines on each bar. //==================////////////////////////================================/////////////////======================{ fivehma = ta.hma(close, sma1Length) twentyhma = ta.hma(close, sma2Length) firstplot = plot(fivehma, title="8-period HMA", color=lineColorUp) secondplot = plot(twentyhma, title="21-period HMA", color=lineColorDown) fill(firstplot, secondplot, fivehma > twentyhma ? fillColorUp : fillColorDown) //==================////////////////////////================================/////////////////======================{ // Calculate the increment value for each line in the fan based on the price range over 'fiu_time' bars //==================////////////////////////================================/////////////////======================{ for i = 0 to fiu_time //==================////////////////////////================================/////////////////======================{ // Starting point of the fan in y //==================////////////////////////================================/////////////////======================{ lineUp = math.avg(close[1], open[1]) discover_01 = (close - open) / fiu_time //==================////////////////////////================================/////////////////======================{ // End point in y if line stopped at the current bar. //==================////////////////////////================================/////////////////======================{ giude_line = open + (discover_01 * i) // Extrapolate necessary y position to the next bar because we extend lines one bar in the future. //==================////////////////////////================================/////////////////======================{ giude_line := giude_line + (giude_line - lineUp) lineColor = giude_line > lineUp ? lineColorUp : lineColorDown line.new(bar_index - 1, lineUp, bar_index + mira, giude_line, color = lineColor) //==================////////////////////////================================/////////////////======================} // Define the condition for the alert //==================////////////////////////================================/////////////////======================{ alertcondition(condition = ta.crossover(fivehma, twentyhma), title = "Hull Waves Cross", message = "The Hull Waves have crossed!") //==================////////////////////////================================/////////////////======================} //==================////////////////////////================================/////////////////======================{
TrendSphere (Zeiierman)
https://www.tradingview.com/script/qSC6hZNa-TrendSphere-Zeiierman/
Zeiierman
https://www.tradingview.com/u/Zeiierman/
470
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("TrendSphere (Zeiierman)", overlay = true) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ ToolTips { t1="Selects the method used to measure volatility. 'Atr' uses Average True Range, 'Historical Volatility' uses the standard deviation of log returns, and 'Bollinger Band Width' uses the width between the Bollinger Bands. \n\nThe second value modifies the scale of the selected volatility measure. Increasing this value will result in wider bands, highlighting larger price trends, while decreasing it will narrow the bands, emphasizing smaller price movements." t2="The first value adjusts the influence of the volatility measure on the bands. A higher value increases the sensitivity of the bands to volatility, making them wider, while a lower value decreases sensitivity, making the bands narrower. \n\nThe second value defines the number of periods used in calculating the selected volatility measure. A higher value makes the bands more stable but less responsive to recent price changes, while a lower value makes them more responsive but also more prone to fluctuations." t3="Adjusts the sensitivity of the trend component. Increasing this value will make the trend component react more slowly to price changes, potentially smoothing out noise, while decreasing it will make it react more quickly, potentially highlighting shorter-term trends." t4="The 'Scaling' input adjusts the granularity and the resolution of the calculated values within the indicator. When you adjust this input, you're effectively changing the weight or emphasis of certain calculations, ensuring that they remain relevant and readable in different market contexts. \n\nIncreasing the value results in the magnification of the indicator's results, emphasizing even minor changes in price trends. Conversely, decreasing the value may smooth out minor fluctuations and emphasize more significant, long-term movements. \n\nAdjusting this value can be particularly necessary when you're dealing with assets with a broad range of prices, from those with very high values to those that are priced in fractions. By tailoring the scaling, you can ensure that the indicator remains responsive and relevant across various asset prices and market conditions." //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Inputs { vo = input.string("Atr", options = ["Atr","Historical Volatility","Bollinger Band Width"], title="Select Volatility   ", inline="vo", group="Volatility") volatilityScalingFactor = input.float(5.0, step=0.1, title="", minval = 0.1, inline="vo", group="Volatility", tooltip=t1) volatilityStrength = input.float(0.8, "volatility Strength", step=0.1, minval = 0, maxval = 1, inline="Volatility", group="Volatility") length = input.int(200, title="", step=2, minval=1,maxval=3000, inline="Volatility", group="Volatility", tooltip=t2) trendSensitivity = input.float(15, "Trend Sensitivity", minval = 0, inline="Trend", group="Trend", tooltip=t3) color_up = input.color(color.navy, title="Line   ", inline="Line", group="Style") color_dn = input.color(color.maroon, title="", inline="Line", group="Style") color_upper = input.color(color.new(#862458, 10), title="Cloud ", inline="Cloud", group="Style") color_lower = input.color(color.new(#493893, 10),title="", inline="Cloud", group="Style") scale = input.int(1, step=2, minval=1, title="Scaling", group="Scaling for Relevance", tooltip=t4) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Var { var float trend = 0.0 var int trendDirection = 0 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Function to determine the trend direction { trendDirectionFunction(dir) => dir - dir[1] > 0 ? 1 : (dir - dir[1] < 0 ? -1 : 0) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Function to calculate scaling factor getScalingFactor(_price) => scalingFactor = 1.0 if _price >= 10 scalingFactor := 1 else while (_price * scalingFactor < 100) scalingFactor := scalingFactor * 10 scalingFactor countLeftDigits(_price) => absPrice = math.abs(_price) count = 0 while absPrice >= 1 count := count + 1 absPrice := absPrice / 10 count scaling = getScalingFactor(close) digits = countLeftDigits(close) getScale2(digits) => switch digits 1 => 1 2 => 1 3 => 10 4 => 100 5 => 1000 scale2 = getScale2(digits) + scale //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Volatility Measures { // Historical Volatility logRet = math.log(close / close[1]) histVol = scaling==1?(ta.stdev(logRet, length) * math.sqrt(252))* scale2 : (ta.stdev(logRet, length) * math.sqrt(252)) / scaling * (10+scale) // Annualized based on 252 trading days // Bollinger Band Width basis = ta.sma(close, length) upperBand = basis + (volatilityScalingFactor * ta.stdev(close, length)) lowerBand = basis - (volatilityScalingFactor * ta.stdev(close, length)) bandWidth = scaling==1?(upperBand - lowerBand) / basis * scale2 :((upperBand - lowerBand) / basis) / scaling* (10+scale) scaledStdDev = switch vo "Atr" => (nz(ta.atr(length))*volatilityScalingFactor)*volatilityStrength "Historical Volatility" => (nz(histVol)*volatilityScalingFactor)*volatilityStrength "Bollinger Band Width" => (nz(bandWidth))*volatilityStrength //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Call Trend Direction { trendDirection := trendDirectionFunction(trend[1]) priceTrend = close - trend > 0 ? close - trend : trend - close //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Calculate the Trend { trendAdjustment = priceTrend>scaledStdDev?math.avg(close,trend):trendDirection * (scaledStdDev * (1/volatilityScalingFactor) * (1/trendSensitivity)) + trend trend := trendAdjustment //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Get Upper and Lower Bands { upper1 = trend + scaledStdDev lower1 = trend - scaledStdDev //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Plot { trueTrend = trendDirection == trendDirection[2] color_ = trendDirection == 1 ? color_up : color_dn trend_ = plot(trueTrend?trend:na, title="Trend Line", color=color_) upper_ = plot(trueTrend?upper1:na, title="Upper Line", color = color.new(color.black,100)) lower_ = plot(trueTrend?lower1:na, title="Lower Line", color = color.new(color.black,100)) fill(upper_, trend_, top_color = color_lower, bottom_color =color.new(na,100), top_value = upper1, bottom_value = trend, title="Bg Upper") fill(trend_, lower_, top_color = color.new(na,100), bottom_color = color_upper, top_value = trend, bottom_value = lower1, title="Bg Lower") //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Debug { //debug1 = label.new(x=bar_index, y=close, text="Scaling Factor: " + str.tostring(scaling), style=label.style_label_down, color=color.blue, size=size.small, textcolor=color.white, yloc=yloc.abovebar) //debug2 = label.new(x=bar_index, y=close, text="Scaling Factor: " + str.tostring(digits), style=label.style_label_up, color=color.blue, size=size.small, textcolor=color.white, yloc=yloc.belowbar) //label.delete(debug1[1]) //label.delete(debug2[1]) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
VAcc (Velocity & Acceleration)
https://www.tradingview.com/script/J0JW9FCX-VAcc-Velocity-Acceleration/
algotraderdev
https://www.tradingview.com/u/algotraderdev/
39
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/ // © algotraderdev & Scott Cong // Based on "Stocks & Commodities V. 41:09 (8–15): VAcc: A Momentum Indicator Based On Velocity And Acceleration by Scott Cong, PhD" //@version=5 indicator('VAcc', explicit_plot_zorder = true) import algotraderdev/vacc/1 as vacc float SOURCE = input.source(close, 'Source') int LENGTH = input.int(26, 'Length', minval = 2, step = 1) int SMOOTH = input.int(9, 'Smooth', minval = 1, step = 1) color VELOCITY_COLOR = input.color(color.blue, 'Velocity', group = 'Colors') color ABOVE_GROW_COLOR = input.color(#26a69a, 'Above Zero Grow', inline = 'Above', group = 'Colors') color ABOVE_FALL_COLOR = input.color(#b2dfdb, 'Fall', inline = 'Above', group = 'Colors') color BELOW_GROW_COLOR = input.color(#ffcdd2, 'Below Zero Grow', inline = 'Below', group = 'Colors') color BELOW_FALL_COLOR = input.color(#ff5252, 'Fall', inline = 'Below', group = 'Colors') [vel, acc] = vacc.get(SOURCE, LENGTH, SMOOTH) color accColor = if acc >= 0 acc[1] < acc ? ABOVE_GROW_COLOR : ABOVE_FALL_COLOR else acc[1] < acc ? BELOW_GROW_COLOR : BELOW_FALL_COLOR plot(acc * 100, 'Acc', color = accColor, style = plot.style_columns) plot(vel / LENGTH * 200, 'Vel', VELOCITY_COLOR)
TTP Big Whale Explorer
https://www.tradingview.com/script/QTqOhc57-TTP-Big-Whale-Explorer/
TheTradingParrot
https://www.tradingview.com/u/TheTradingParrot/
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/ // © TheTradingParrot //@version=5 indicator("TTP Big Whale Explorer", overlay = false) exp = request.security("INTOTHEBLOCK:BTC_LARGEHOLDERSINFLOWS-INTOTHEBLOCK:BTC_LARGEHOLDERSOUTFLOWS", "1D", close) ema50 = ta.ema(exp, 50) ema200 = ta.ema(exp, 200) ratio = ema50 / ema200 showEMA = input.bool(true, "Enable", group = "EMA") emaLength = input.int(20, "lenght", group = "EMA") emaratio = ta.ema(ratio, emaLength) plot(showEMA ? emaratio : na, color = color.new(color.yellow, 50)) c = color.from_gradient(ratio, 0, 2, color.rgb(0, 255, 0, 50), color.rgb(255, 0, 0)) plot(ratio, "ratio", color = c) hline(1,color = color.new(color.white, 30)) hline(1.5) hline(0.5) hline(2) hline(0)
BTC Supply in Profits and Losses (BTCSPL) [AlgoAlpha]
https://www.tradingview.com/script/BJXEjz0b-BTC-Supply-in-Profits-and-Losses-BTCSPL-AlgoAlpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
21
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("BTC Supply in Profits and Losses (BTCSPL) [AlgoAlpha]", precision = 2) ad = input.bool(title = 'Alpha Decay Adjusted', defval = true) ma = input.bool(title = 'Show Moving Average', defval = true) sh = input.bool(title = 'Show Short-Term Trend', defval = false) ch = input.bool(title = 'Show Rolling Change', defval = false) va = input.bool(title = 'Show BTCSPL Value Score (-1 to 1)', defval = false) malen = input.int(title = 'Moving Average Length', defval = 200, minval = 1) len = input.int(title = 'Rolling Change Length', defval = 90, minval = 1) valuerange = input.int(title = 'Value Range',defval = 1, minval = 1) aroonlength = input.int(title = 'AROON Length',defval = 20, minval = 1) bullcolor = #00ffbb bearcolor = #ff1100 p = request.security('BTC_PROFITADDRESSESPERCENTAGE', 'D', close) l = request.security('BTC_LOSSESADDRESSESPERCENTAGE', 'D', close) //plot(p, color = color.orange) //plot(l, color = color.blue) //c = ((bar_index/(6*365))*0.18) lowerbound = ta.lowest(p-l, 140*7) decayadjusted = ((p-l) - lowerbound)/(1 - lowerbound) lowerbound := request.security(syminfo.tickerid, "1D", lowerbound) decayadjusted := request.security(syminfo.tickerid, "1D", decayadjusted) upper = 100 * (ta.highestbars(ad ? decayadjusted : p-l, aroonlength) + aroonlength)/aroonlength lower = 100 * (ta.lowestbars(ad ? decayadjusted : p-l, aroonlength) + aroonlength)/aroonlength trendup = upper > lower trenduplong = (ad ? decayadjusted : p-l) > ta.ema((ad ? decayadjusted : p-l), malen) precondition = (sh ? trendup : trenduplong) osupper = plot(0, color = bullcolor, display = display.none) osmid = plot(0.1, color = bullcolor, display = display.none) oslower = plot(0.2, color = bullcolor, display = display.none) obupper = plot(0.8, color = bearcolor, display = display.none) obmid = plot(0.9, color = bullcolor, display = display.none) oblower = plot(1, color = bearcolor, display = display.none) hline(0.5, color = color.gray) plotshape(ta.crossover(decayadjusted,0.2) and trendup ? -0.1 : na, style = shape.triangleup, color = bullcolor, location = location.absolute, size = size.tiny) plotshape(ta.crossunder(decayadjusted,0.8) and not trendup ? 1.1 : na, style = shape.triangledown, color = bearcolor, location = location.absolute, size = size.tiny) plot(ad ? decayadjusted : na, color = precondition ? bullcolor : bearcolor, title = "Supply in Profits and Losses") plot(ad ? na : (p-l), color = precondition ? bullcolor : bearcolor, title = "Supply in Profits and Losses") plot(ma ? ta.ema((ad ? decayadjusted : p-l), malen) : na, color = color.gray) plot(ch ? ta.change(ad ? decayadjusted : p-l, len) : na, color = color.new(color.yellow, 70), title = "Change", style = plot.style_columns) plot( va ? valuerange-(ad ? decayadjusted : p-l)*2*valuerange : na, color = color.gray, title = "Value") 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)) barcolor(trenduplong ? bullcolor : bearcolor)
Entry Assistant by Ivan
https://www.tradingview.com/script/Sr5WRgpu-Entry-Assistant-by-Ivan/
ivanroyloewen
https://www.tradingview.com/u/ivanroyloewen/
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/ // © ivanroyloewen //@version=5 indicator("Entry Assistant", overlay = true) //-------------------------------------------------------------------------------------------------------------------------------( General Inputs / Variables ) --------------------------------------------- var direction = "Direction" // are you planning to go Long ( displays data to assist entering Long positions) var going_Long = input(title = "Long", defval = true, inline = direction, group = direction) // are you planning to go Short ( displays data to assist entering Short positions) var going_Short = input(title = "Short", defval = false, inline = direction, group = direction) var show = "Show" // display the stop loss line var show_Stop = input(title = "Stop", defval = true, inline = show, group = show) // display the BOC line var show_BOC = input(title = "BOC", defval = true, inline = show, group = show) // display the entry signal ( when current candle breaks previous candle ) var show_Entry_Signal = input(title = "Entry", defval = true, inline = show, group = show) // only display the last three digits of the price ( on the price label ) var show_Only_Last_Three_Digits = input(title = "Three Digits Only", defval = true, inline = show, group = show) //-------------------------------------------------------------------------------------------------------------------------------( Long Inputs ) ------------------------------------------------------------ var variables_Long = "Long Variables" // how much price below the current candle do you want to Stop line placed var pips_Below_Candle_Stop_Long = input.float(title = "Pips spacing below candle for stop loss", defval = 1.0, minval = 0, maxval = 1000, group = variables_Long) // how much price above the Long BOC line until Long entry signal is displayed var pips_Above_BOC_Entry_Long = input.float(title = "Pips spacing above BOC for entry signal", defval = 0.1, minval = 0, maxval = 1000, group = variables_Long) // how many candles ahead on the x axis is the Long price label placed var label_Distance_Long = input.int(title = "Label horizontal distance", defval = 20, minval = 0, maxval = 100, group = variables_Long) // Long Colors var colors_Long = "Long Colors" // the color of the Long Stop line var line_Color_Long = input.color(title = "Stop", defval = #5b9cf6, inline = colors_Long, group = "Long Colors") // the color of the Long BOC line var line_BOC_Color_Long = input.color(title = "BOC", defval = #ac774f, inline = colors_Long, group = "Long Colors") // the color of the Long entry signal var entry_Signal_Color_Long = input.color(title = "Entry", defval = color.green, inline = colors_Long, group = "Long Colors") // the color of the Long label var label_Color_Long = input(title = "Label", defval = #3179f5, inline = colors_Long, group = "Long Colors") // the color of the Long label text var labe_Text_Color_Long = input(title = "Text", defval = color.white, inline = colors_Long, group = "Long Colors") //-------------------------------------------------------------------------------------------------------------------------------( Short Inputs ) ----------------------------------------------------------- var variables_Short = "Short Variables" // how much price above the current candle do you want to Stop line placed var pips_Below_Candle_Stop_Short = input.float(title = "Pips spacing above candle for stop loss", defval = 1.0, minval = 0, maxval = 1000, group = variables_Short ) // how much price below the Short BOC line until Short entry signal is displayed var pips_Above_BOC_Entry_Short = input.float(title = "Pips spacing below BOC for entry signal", defval = 0.1, minval = 0, maxval = 1000, group = variables_Short ) // how many candles ahead on the x axis is the Short price label placed var label_Distance_Short = input.int(title = "Label horizontal distance", defval = 20, minval = 0, maxval = 100, group = variables_Short ) var colors_Short = "Short Colors" // the color of the Short Stop line var line_Color_Short = input.color(title = "Stop", defval = #5b9cf6, inline = colors_Short, group = "Short Colors") // the color of the Short BOC line var line_BOC_Color_Short = input.color(title = "BOC", defval = #ac774f, inline = colors_Short, group = "Short Colors") // the color of the Short entry signal var entry_Signal_Color_Short = input.color(title = "Entry", defval = color.green, inline = colors_Short, group = "Short Colors") // the color of the Short label var label_Color_Short = input(title = "Label", defval = #3179f5, inline = colors_Short, group = "Short Colors") // the color of the Short label text var label_Text_Color_Short = input(title = "Text", defval = color.white, inline = colors_Short, group = "Short Colors") //-------------------------------------------------------------------------------------------------------------------------------( Price Calculation ) ----------------------------------------------------------- var price_Digit_Count = str.length(str.tostring(syminfo.mintick)) // the time frame, calculated by the time between the current and previous candle time_Frame = time - time[1] // rounds numbers Truncate(number, decimals) => factor = math.pow(10, decimals) int(number * factor) / factor // get the price value from the given inputs pips_Price_Value_Stop_Long = syminfo.mintick * Truncate(pips_Below_Candle_Stop_Long, 1) * 10 pips_Price_Value_BOC_Long = syminfo.mintick * Truncate(pips_Above_BOC_Entry_Long, 1) * 10 // calculate the new line positions with the pips price value price_Stop_Long = low - pips_Price_Value_Stop_Long price_BOC_Entry_Long = high[1] + pips_Price_Value_BOC_Long // the position where the Long label will be initially placed long_Label_Point = chart.point.new(time = time, index = bar_index, price = price_Stop_Long) long_Label_Text = str.tostring(price_Stop_Long) // check if the current label text has less character than the instruments max digits price ( this means a "0" zero has been rounded off ) if str.length(long_Label_Text) < price_Digit_Count // get the amount of zeros that have been rounded off int amount_Of_Zeros_Rounded_Off = price_Digit_Count - str.length(long_Label_Text) // add as many zeros back on that have been rounded off for i = 1 to amount_Of_Zeros_Rounded_Off by 1 // add the zero back onto the label text long_Label_Text += "0" // get the price value from the given inputs pips_Price_Value_Stop_Short = syminfo.mintick * Truncate(pips_Below_Candle_Stop_Short, 1) * 10 pips_Price_Value_BOC_Short = syminfo.mintick * Truncate(pips_Above_BOC_Entry_Short, 1) * 10 // calculate the new line positions with the pips price value price_Stop_Short = high + pips_Price_Value_Stop_Short price_BOC_Entry_Short = low[1] - pips_Price_Value_BOC_Short // the position where the Short label will be initially placed short_Label_Point = chart.point.new(time = time, index = bar_index, price = price_Stop_Short) short_Label_Text = str.tostring(price_Stop_Short) // check if the current label text has less character than the instruments max digits price ( this means a "0" zero has been rounded off ) if str.length(short_Label_Text) < price_Digit_Count // get the amount of zeros that have been rounded off int amount_Of_Zeros_Rounded_Off = price_Digit_Count - str.length(short_Label_Text) // add as many zeros back on that have been rounded off for i = 1 to amount_Of_Zeros_Rounded_Off by 1 // add the zero back onto the label text short_Label_Text += "0" //-------------------------------------------------------------------------------------------------------------------------------( Handle Long Data / Drawings ) -------------------------------------------- // if you are going Long if going_Long // draw the Long Stop line below the current candle stop_Line_Long = line.new(bar_index[1], price_Stop_Long, bar_index, price_Stop_Long, xloc.bar_index, extend.right, line_Color_Long, line.style_solid, 2) // delete the previous Long Stop line line.delete(stop_Line_Long[1]) // if you are showing the Long BOC ( Break Of Candle ) line if show_BOC // draw the Long BOC line at the previous candles high line_Long_BOC = line.new(bar_index[1], high[1], bar_index, high[1], xloc.bar_index, extend.right, line_BOC_Color_Long, line.style_solid, 2) // delete the previous Long BOC line line.delete(line_Long_BOC[1]) // set the default value to ERR ( error ) last_Three_Characters = "ERR" // only show the last three digits of the stop loss price if show_Only_Last_Three_Digits // remove the decimal when only showing three digshow_Only long_Label_Text := str.replace( long_Label_Text , target = ".", replacement = "") // check for this condition to prevent compialation errors if str.length(long_Label_Text) - 3 < 0 == false // get the last 3 characters from the Long Stop line price last_Three_Characters := str.substring(long_Label_Text, str.length(long_Label_Text) - 3) // draw the Long label displaying the price of the Long line ( display only last 3 characters if specified ) label_Long = label.new(point = long_Label_Point, style = label.style_label_up, text = show_Only_Last_Three_Digits ? last_Three_Characters : long_Label_Text, color = label_Color_Long, textcolor = labe_Text_Color_Long, xloc = xloc.bar_time, size = size.huge) // adjust the Long label x position based off of input label_Long.set_x(time + label_Distance_Long * time_Frame) // delete the previous Long label label.delete(label_Long[1]) // draw a box when the current price has broken above the Long BOC line ( plus the additional pips from input) BOC_Signal = box.new(bar_index[1], high , bar_index, price_BOC_Entry_Long, border_color = na, bgcolor = entry_Signal_Color_Long, extend = extend.right) // delete the previous Long BOC signal box box.delete(BOC_Signal[1]) // if show entry signal is false or the current candles high is not above the previous candles high if show_Entry_Signal == false or high > price_BOC_Entry_Long == false // delete the current Long BOC signal box box.delete(BOC_Signal) //-------------------------------------------------------------------------------------------------------------------------------( Handle Short Data / Drawings ) ------------------------------------------- // if you are going Short if going_Short // draw the Short Stop line above the current candle stop_Line_Short = line.new(bar_index[1], price_Stop_Short, bar_index, price_Stop_Short, xloc.bar_index, extend.right, line_Color_Short, line.style_solid, 2) // delete the previous Short Stop line line.delete(stop_Line_Short[1]) // if you are showing the BOC ( Break Of Candle ) line if show_BOC // draw the Short BOC line at the previous candles low line_Short_BOC = line.new(bar_index[1], low[1], bar_index, low[1], xloc.bar_index, extend.right, line_BOC_Color_Short, line.style_solid, 2) // delete the previous Short BOC line line.delete(line_Short_BOC[1]) // set the default value to ERR ( error ) last_Three_Characters = "ERR" // only show the last three digits of the stop loss price if show_Only_Last_Three_Digits // remove the decimal when only showing three digshow_Only short_Label_Text := str.replace( short_Label_Text , target = ".", replacement = "") // check for this condition to prevent compialation errors if str.length(short_Label_Text) - 3 < 0 == false// or str.length(short_Label_Text) - 3 < str.length(short_Label_Text) - 1 // get the last 3 characters from the Short Stop line price last_Three_Characters := str.substring(short_Label_Text, str.length(short_Label_Text) - 3) // draw the Short label displaying the price of the Short line ( display only last 3 characters if specified ) label_Short = label.new(point = short_Label_Point, style = label.style_label_down, text = show_Only_Last_Three_Digits ? last_Three_Characters : short_Label_Text, color = label_Color_Short, textcolor = label_Text_Color_Short, xloc = xloc.bar_time, size = size.huge) // adjust the Short label x position based off of input label_Short.set_x(time + label_Distance_Short * time_Frame) // delete the previous Short label label.delete(label_Short[1]) // draw a box when the current price has broken below the Short BOC line ( minus the additional pips from input) BOC_Signal = box.new(bar_index[1], price_BOC_Entry_Short, bar_index, low, border_color = na, bgcolor = entry_Signal_Color_Short, extend = extend.right) // delete the previous Short BOC signal box box.delete(BOC_Signal[1]) // if show entry signal is false or the current candles low is not below the previous candles low if show_Entry_Signal == false or low < price_BOC_Entry_Short == false // delete the current Short BOC signal box box.delete(BOC_Signal) //------------------------------------------------------------------------------------------------------------------------------- ( Execute Functions) ----------------------------------------------------
Marubozu CANDLESTICK PATTERN
https://www.tradingview.com/script/dXXD4zta-Marubozu-CANDLESTICK-PATTERN/
pinescripter_maroc
https://www.tradingview.com/u/pinescripter_maroc/
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/ // © pinescripter_maroc //@version=5 indicator("Marubozu",overlay = true) condition = math.abs(open-close) > 3*math.avg(math.abs(open-close),15)/2 plotcandle(open,high,low,close,color=condition and open<close?color.green:na, wickcolor=condition and open<close ?color.blue:na) plotcandle(open,high,low,close,color=condition and open>close?color.orange:na, wickcolor=condition and open>close ?color.orange:na) plotshape(open<close?condition:na,style=shape.triangleup,color=color.green,text="Bullish",textcolor = color.green) plotshape(open>close?condition:na,style=shape.triangledown,color=color.orange,text="Bearish",textcolor = color.orange)
ADR % Ranges
https://www.tradingview.com/script/ew2fICBa-ADR-Ranges/
theGary
https://www.tradingview.com/u/theGary/
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/ // © theGary //@version=5 indicator("ADR % Ranges", overlay = true, max_lines_count=500) // @error catching if (timeframe.in_seconds() >= timeframe.in_seconds('D')) runtime.error('Timeframe cannot be greater than Daily') // @error catching end // @inputs auto_color = input.bool(true, title = 'Auto Color', group = 'General Settings', inline = '1') adr_days = input.int(5, title = 'Days', group = 'ADR Settings', inline = '1', maxval=20, minval = 1) show_hist = input.bool(false, title = 'Show Historical ADR Levels', group = 'ADR Settings', inline = '3') show_table = input.bool(true, title = 'Show Previous Daily Ranges Table', group = 'ADR Settings', inline = '4') table_size = input.string('Small', title = '', options = ['Small', 'Medium', 'Large'], group = 'ADR Settings', inline = '5') table_x = input.string('Center', title = '', options = ['Left', 'Center', 'Right'], group = 'ADR Settings', inline = '5') table_y = input.string('Bottom', title = '', options = ['Top', 'Middle', 'Bottom'], group = 'ADR Settings', inline = '5') show_text = input.bool(true, title = 'Show Text', group = 'Plot Settings', inline = '1') txt_size = input.string('Small', title = '', options = ['Small', 'Medium', 'Large'], group = 'Plot Settings', inline = '1') offset = input.int(50, title = 'Offset', group = 'Plot Settings', inline = '2', maxval = 100) adr_style = input.string('Solid', title = 'ADR​​​  ​ ', options = ['Solid', 'Dotted', 'Dashed'], group = 'Plot Settings', inline ='3') adr_css = input.color(color.new(#000000, 0), title = '', group = 'Plot Settings', inline ='3') adr_show = input.bool(false, title = 'Hide', group = 'Plot Settings', inline = '3') third_style = input.string('Dotted', title = '1/3 ADR', options = ['Solid', 'Dotted', 'Dashed'], group = 'Plot Settings', inline ='4') third_css = input.color(color.new(#000000, 0), title = '', group = 'Plot Settings', inline ='4') third_show = input.bool(false, title = 'Hide', group = 'Plot Settings', inline = '4') anchor_style = input.string('Dotted', title = 'Anchor ', options = ['Solid', 'Dotted', 'Dashed'], group = 'Plot Settings', inline ='5') anchor_css = input.color(color.new(#000000, 0), title = '', group = 'Plot Settings', inline ='5') anchor_show = input.bool(false, title = 'Hide', group = 'Plot Settings', inline = '5') // @inputs end // @function manage array f_array_add_pop(array, new_value) => array.unshift(array, new_value) array.pop(array) // @function line styler f_line_style(style) => style == 'Solid' ? line.style_solid : style == 'Dotted' ? line.style_dotted : style == 'Dashed' ? line.style_dashed : line.style_solid // @function line color f_line_color(_color) => auto_color ? chart.fg_color : _color // @calculate adr values // reset = dayofweek != dayofweek[1] reset = session.islastbar_regular[1] var float track_highs = 0.00 var float track_lows = 0.00 var float today_adr = 0.00 var adrs = array.new_float(adr_days, 0.00) var line adr_pos = na var line adr_third_pos = na var line adr_anchor = na var line adr_third_neg = na var line adr_neg = na var label adr_pos_lbl = na var label adr_third_pos_lbl = na var label adr_anchor_lbl = na var label adr_third_neg_lbl = na var label adr_neg_lbl = na track_highs := reset ? high : math.max(high, track_highs[1]) track_lows := reset ? low : math.min(low, track_lows[1]) lbl_size = txt_size == 'Small' ? size.tiny : txt_size == 'Medium' ? size.small : size.normal tablesize = table_size == 'Small' ? size.tiny : table_size == 'Medium' ? size.small : size.normal if reset // shift values f_array_add_pop(adrs, math.round_to_mintick(track_highs[1] - track_lows[1])) today_adr := math.round_to_mintick(array.avg(adrs)) // delete history if not show_hist line.delete(adr_pos[1]) line.delete(adr_third_pos[1]) line.delete(adr_anchor[1]) line.delete(adr_third_neg[1]) line.delete(adr_neg[1]) label.delete(adr_pos_lbl[1]) label.delete(adr_third_pos_lbl[1]) label.delete(adr_anchor_lbl[1]) label.delete(adr_third_neg_lbl[1]) label.delete(adr_neg_lbl[1]) else line.set_x2(adr_pos, bar_index) line.set_x2(adr_neg, bar_index) line.set_x2(adr_third_pos, bar_index) line.set_x2(adr_third_neg, bar_index) label.delete(adr_pos_lbl) label.delete(adr_neg_lbl) label.delete(adr_third_pos_lbl) label.delete(adr_third_neg_lbl) // draw new lines if not adr_show adr_pos := line.new(bar_index, open + today_adr, bar_index+offset, open + today_adr, xloc = xloc.bar_index, extend = extend.none, color = f_line_color(adr_css), style = f_line_style(adr_style)) adr_neg := line.new(bar_index, open - today_adr, bar_index+offset, open - today_adr, xloc = xloc.bar_index, extend = extend.none, color = f_line_color(adr_css), style = f_line_style(adr_style)) if show_text adr_pos_lbl := label.new(bar_index+offset, open + today_adr, text = str.tostring(adr_days) + 'ADR+', xloc = xloc.bar_index, size = lbl_size, textalign = text.align_left, textcolor = chart.fg_color, color = color.new(#000000,100), style = label.style_label_left) adr_neg_lbl := label.new(bar_index+offset, open - today_adr, text = str.tostring(adr_days) + 'ADR-', xloc = xloc.bar_index, size = lbl_size, textalign = text.align_left, textcolor = chart.fg_color, color = color.new(#000000,100), style = label.style_label_left) if not third_show adr_third_pos := line.new(bar_index, math.round_to_mintick(open + today_adr*.33), bar_index+offset, math.round_to_mintick(open + today_adr*.33), xloc = xloc.bar_index, extend = extend.none, color = f_line_color(third_css), style = f_line_style(third_style)) adr_third_neg := line.new(bar_index, math.round_to_mintick(open - today_adr*.33), bar_index+offset, math.round_to_mintick(open - today_adr*.33), xloc = xloc.bar_index, extend = extend.none, color = f_line_color(third_css), style = f_line_style(third_style)) if show_text adr_third_pos_lbl := label.new(bar_index+offset, math.round_to_mintick(open + today_adr*.33), text = '1/3ADR+', xloc = xloc.bar_index, size = lbl_size, textalign = text.align_left, textcolor = chart.fg_color, color = color.new(#000000,100), style = label.style_label_left) adr_third_neg_lbl := label.new(bar_index+offset, math.round_to_mintick(open - today_adr*.33), text = '1/3ADR-', xloc = xloc.bar_index, size = lbl_size, textalign = text.align_left, textcolor = chart.fg_color, color = color.new(#000000,100), style = label.style_label_left) if not anchor_show line.delete(adr_anchor) adr_anchor := line.new(bar_index, 1e20, bar_index, -1e20, xloc = xloc.bar_index, extend = extend.none, color = f_line_color(anchor_css), style = f_line_style(anchor_style)) else today_adr := today_adr[1] // update lines line.set_x2(adr_pos, bar_index+offset) line.set_x2(adr_neg, bar_index+offset) line.set_x2(adr_third_pos, bar_index+offset) line.set_x2(adr_third_neg, bar_index+offset) // update labels label.set_x(adr_pos_lbl, bar_index+offset) label.set_x(adr_neg_lbl, bar_index+offset) label.set_x(adr_third_pos_lbl, bar_index+offset) label.set_x(adr_third_neg_lbl, bar_index+offset) // @calculate adr values end // @table var table = table.new(position = position.bottom_center, columns = adr_days+1, rows = 1, bgcolor = chart.bg_color, frame_color = color.new(chart.fg_color,0), border_color = color.new(chart.fg_color,80), frame_width = 2, border_width = 1) if barstate.islast and show_table for i = 0 to adr_days - 1 table.cell(table, i, 0, text = str.tostring(array.get(adrs, i)), text_size = tablesize, text_color = chart.fg_color, bgcolor = chart.bg_color) table.cell(table, adr_days, 0, text = str.tostring(adr_days)+'ADR = ' + str.tostring(today_adr), text_size = tablesize, bgcolor = color.new(chart.fg_color, 00), text_color = chart.bg_color)
Scale Ability [TrendX_]
https://www.tradingview.com/script/nUrmKsUQ-Scale-Ability-TrendX/
TrendX_
https://www.tradingview.com/u/TrendX_/
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/ // © TrendX_ //@version=5 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxx // XXX.....X....X....X..XX:X...XX xx // X:XXX:..:X:...X:X.X:X:XX.XXXXX // XXXXX:XXX: .X:...X:XX..X:..XX xx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // indicator("Scale Ability [TrendX_]", overlay = false) //// ____ Scale ability setting ____ //// //Input bg_trans = input.int( defval = 90 , title = "Background Transparency" ) Type_period = input.string(defval = "FQ", title = "Type of Financial Period", options = ["FY", "FQ"]) var float EBITDA_current = na var float Equity_current = na var float CFIA_current = na var float TA_current = na var float TD_current = na var float NI_current = na //Get Financial data EBITDA_request = request.financial(syminfo.tickerid, "EBITDA" , Type_period) Equity_request = request.financial(syminfo.tickerid, "TOTAL_EQUITY" , Type_period) CFIA_request = request.financial(syminfo.tickerid, "CASH_F_INVESTING_ACTIVITIES", Type_period) TA_request = request.financial(syminfo.tickerid, "TOTAL_ASSETS" , Type_period) TD_request = request.financial(syminfo.tickerid, "TOTAL_DEBT" , Type_period) NI_request = request.financial(syminfo.tickerid, "DILUTED_NET_INCOME" , Type_period) //Define Financial data if (not na(EBITDA_request)) EBITDA_current := EBITDA_request if (not na(Equity_request)) Equity_current := Equity_request if (not na(CFIA_request)) CFIA_current := CFIA_request if (not na(TA_request)) TA_current := TA_request if (not na(TD_request)) TD_current := TD_request if (not na(NI_request)) NI_current := NI_request CFIATA = CFIA_current / TA_current NITD = NI_current / TD_current EBITDAE = EBITDA_current / Equity_current //Calculate Scaling index Scale_ability = math.avg(CFIATA, NITD, EBITDAE) * 100 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //// ____ Plotting ____ //// //Define Coloring functions ColorFunc(Scale_ability) => if Scale_ability >= 43 color.rgb(90, 0, 147) else if Scale_ability >= 40 and Scale_ability < 43 color.rgb(0, 4, 133) else if Scale_ability >= 36 and Scale_ability < 40 color.rgb(0, 25, 247) else if Scale_ability >= 31 and Scale_ability < 36 color.rgb(4, 83, 0) else if Scale_ability >= 26 and Scale_ability < 31 color.rgb(6, 123, 0) else if Scale_ability >= 21 and Scale_ability < 26 color.rgb(9, 163, 1) else if Scale_ability >= 16 and Scale_ability < 21 color.rgb(11, 224, 0) else if Scale_ability > 11 and Scale_ability < 16 color.rgb(13, 255, 0) else if Scale_ability == 11 color.rgb(111, 247, 0) else if Scale_ability < 11 and Scale_ability > 10 color.rgb(247, 194, 0) else if Scale_ability <= 10 and Scale_ability > 9 color.rgb(247, 161, 0) else if Scale_ability <= 9 and Scale_ability > 8 color.rgb(247, 124, 0) else if Scale_ability <= 8 and Scale_ability > 7 color.rgb(207, 117, 0) else if Scale_ability <= 7 and Scale_ability > 6 color.rgb(247, 99, 0) else if Scale_ability <= 6 and Scale_ability > 5 color.rgb(223, 68, 1) else if Scale_ability <= 4 color.rgb(100, 0, 0) bgFunc(Scale_ability) => if Scale_ability >= 43 color.rgb(90, 0, 147, bg_trans) else if Scale_ability >= 40 and Scale_ability < 43 color.rgb(0, 4, 133, bg_trans) else if Scale_ability >= 36 and Scale_ability < 40 color.rgb(0, 25, 247, bg_trans) else if Scale_ability >= 31 and Scale_ability < 36 color.rgb(4, 83, 0, bg_trans) else if Scale_ability >= 26 and Scale_ability < 31 color.rgb(6, 123, 0, bg_trans) else if Scale_ability >= 21 and Scale_ability < 26 color.rgb(9, 163, 1, bg_trans) else if Scale_ability >= 16 and Scale_ability < 21 color.rgb(11, 224, 0, bg_trans) else if Scale_ability > 11 and Scale_ability < 16 color.rgb(13, 255, 0, bg_trans) else if Scale_ability == 11 color.rgb(111, 247, 0, bg_trans) else if Scale_ability < 11 and Scale_ability > 10 color.rgb(247, 194, 0, bg_trans) else if Scale_ability <= 10 and Scale_ability > 9 color.rgb(247, 161, 0, bg_trans) else if Scale_ability <= 9 and Scale_ability > 8 color.rgb(247, 124, 0, bg_trans) else if Scale_ability <= 8 and Scale_ability > 7 color.rgb(207, 117, 0, bg_trans) else if Scale_ability <= 7 and Scale_ability > 6 color.rgb(247, 99, 0, bg_trans) else if Scale_ability <= 6 and Scale_ability > 5 color.rgb(223, 68, 1, bg_trans) else if Scale_ability <= 4 color.rgb(100, 0, 0, bg_trans) //Plotting Scaling index index_color = ColorFunc(Scale_ability) bg_color = bgFunc( Scale_ability) plot(Scale_ability, title = "Scale Ability index line", color = index_color, style = plot.style_stepline, linewidth = 3) bgcolor(color = bg_color) //Plotting average level hline(11, "Average level", color=color.yellow, linestyle = hline.style_dashed, linewidth = 1) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //// ____ Table ____ //// //Input var table scaleTable = na //Table display scaleTable := table.new(position.middle_right, 2, 6, color.rgb(15, 2, 16), frame_color = color.rgb(226, 251, 218), frame_width = 1, border_color = color.rgb(226, 251, 218), border_width = 1) table.cell(scaleTable, 0, 0, "Exellent" , text_color = color.white, text_size = size.auto) table.cell(scaleTable, 1, 0, str.tostring(math.round(Scale_ability)) + "%", text_color = (Scale_ability >= 43 ) ? color.rgb(90, 0, 147) : na, text_size = size.auto) table.cell(scaleTable, 0, 1, "Good" , text_color = color.white, text_size = size.auto) table.cell(scaleTable, 1, 1, str.tostring(math.round(Scale_ability)) + "%", text_color = (Scale_ability >= 31 and Scale_ability < 43) ? color.rgb(4, 83, 0) : na, text_size = size.auto) table.cell(scaleTable, 0, 2, "Above Average", text_color = color.white, text_size = size.auto) table.cell(scaleTable, 1, 2, str.tostring(math.round(Scale_ability)) + "%", text_color = (Scale_ability >= 11 and Scale_ability < 31) ? color.rgb(13, 255, 0) : na, text_size = size.auto) table.cell(scaleTable, 0, 3, "Below Average" , text_color = color.white, text_size = size.auto) table.cell(scaleTable, 1, 3, str.tostring(math.round(Scale_ability)) + "%", text_color = (Scale_ability > 7 and Scale_ability < 11) ? color.rgb(207, 117, 0) : na, text_size = size.auto) table.cell(scaleTable, 0, 4, "Poor" , text_color = color.white, text_size = size.auto) table.cell(scaleTable, 1, 4, str.tostring(math.round(Scale_ability)) + "%", text_color = (Scale_ability > 4 and Scale_ability <= 7) ? color.rgb(185, 0, 0) : na, text_size = size.auto) table.cell(scaleTable, 0, 5, "Very Poor" , text_color = color.white, text_size = size.auto) table.cell(scaleTable, 1, 5, str.tostring(math.round(Scale_ability)) + "%", text_color = (Scale_ability <= 4 ) ? color.rgb(185, 0, 0) : na, text_size = size.auto) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MTF Charting
https://www.tradingview.com/script/LuxF8wkD-MTF-Charting/
theGary
https://www.tradingview.com/u/theGary/
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/ // © theGary //@version=5 indicator("MTF Charting", overlay = true, max_boxes_count = 500, max_lines_count = 500) // visual Settings css_bull_body = input.color(color.green, title = 'Body  ', group = 'Visual Settings', inline = '1') css_bear_body = input.color(color.rgb(234, 21, 21), title = '', group = 'Visual Settings', inline = '1') css_bull_border = input.color(color.lime, title = 'Border ', group = 'Visual Settings', inline = '2') css_bear_border = input.color(color.red, title = '', group = 'Visual Settings', inline = '2') css_bull_wick = input.color(color.lime, title = 'Wick  ', group = 'Visual Settings', inline = '3') css_bear_wick = input.color(color.red, title = '', group = 'Visual Settings', inline = '3') use_label = input.bool(true, title = 'MTF Label', group = 'Visual Settings', inline = '4') css_label = input.color(color.new(#434651,0), title = '', group = 'Visual Settings', inline = '4') label_size = input.string('Medium', title = '', group = 'Visual Settings', inline = '4', options = ['Small', 'Medium', 'Large']) padding = input.int(10, title = 'Padding From Last Candle', minval = 3, maxval = 30, group = 'Visual Settings', inline = '5') padding_b = input.int(3, title = 'Padding Between MTF Candles', minval = 1, maxval = 10, group = 'Visual Settings', inline = '6') // timeframe settings use_tf1 = input.bool(true, title = 'HTF 1', group = 'Timeframe Settings', inline = '1') use_tf2 = input.bool(true, title = 'HTF 2', group = 'Timeframe Settings', inline = '2') use_tf3 = input.bool(true, title = 'HTF 3', group = 'Timeframe Settings', inline = '3') use_tf4 = input.bool(true, title = 'HTF 4', group = 'Timeframe Settings', inline = '4') use_tf5 = input.bool(true, title = 'HTF 5', group = 'Timeframe Settings', inline = '5') tf1 = input.timeframe('5', title = '', group = 'Timeframe Settings', inline = '1') tf2 = input.timeframe('15', title = '', group = 'Timeframe Settings', inline = '2') tf3 = input.timeframe('30', title = '', group = 'Timeframe Settings', inline = '3') tf4 = input.timeframe('60', title = '', group = 'Timeframe Settings', inline = '4') tf5 = input.timeframe('D', title = '', group = 'Timeframe Settings', inline = '5') tf1_bars= input.int(8, title = '', minval = 1, maxval = 50, group = 'Timeframe Settings', inline = '1') tf2_bars= input.int(8, title = '', minval = 1, maxval = 50, group = 'Timeframe Settings', inline = '2') tf3_bars= input.int(8, title = '', minval = 1, maxval = 50, group = 'Timeframe Settings', inline = '3') tf4_bars= input.int(8, title = '', minval = 1, maxval = 50, group = 'Timeframe Settings', inline = '4') tf5_bars= input.int(8, title = '', minval = 1, maxval = 50, group = 'Timeframe Settings', inline = '5') // functions f_bull_candle(o_src, c_src) => c_src >= o_src f_label_size() => ls = switch label_size "Small" => size.normal "Medium" => size.large "Large" => size.huge => size.normal f_array_htf(array, value_to_add, tf) => last_index = array.size(array)-1 if ta.change(time(tf)) array.shift(array) array.push(array, value_to_add) else array.set(array, last_index, value_to_add) f_array_ltf(array, array_add, max_array_size) => var joined_array = array.new_float(max_array_size, na) joined_array := array.concat(array,array_add) array_size = array.size(joined_array) number_to_delete = math.max(0, array_size-max_array_size) if number_to_delete != 0 for i = 0 to number_to_delete-1 array.shift(joined_array) joined_array f_array_boxdelete_pop(array) => box.delete(array.first(array)) array.shift(array) f_array_linedelete_pop(array) => line.delete(array.first(array)) array.shift(array) f_delete_all_boxes() => a_allBoxes = box.all if array.size(a_allBoxes) > 0 for i = 0 to array.size(a_allBoxes) - 1 box.delete(array.get(a_allBoxes, i)) f_delete_all_lines() => a_allLines = line.all if array.size(a_allLines) > 0 for i = 0 to array.size(a_allLines) - 1 line.delete(array.get(a_allLines, i)) f_delete_all_labels() => a_allLabels = label.all if array.size(a_allLabels) > 0 for i = 0 to array.size(a_allLabels) - 1 label.delete(array.get(a_allLabels, i)) f_delete_all() => f_delete_all_boxes() f_delete_all_lines() f_delete_all_labels() f_timeframe_text(_timeframe) => if timeframe.in_seconds(_timeframe) < 60 _timeframe + 's' else if timeframe.in_seconds(_timeframe) < 86400 _timeframe + 'm' else if timeframe.in_seconds(_timeframe) < 86400 _timeframe + 'D' else _timeframe f_draw_candles(o_array, h_array, l_array, c_array, box_array, line_array, label_array, start_spacing, end_spacing, label_y, timeframe) => array_size = array.size(o_array) for i = 0 to array_size - 1 new_x1 = bar_index + (start_spacing) + (3*i) new_x2 = new_x1 + 2 new_open = array.get(o_array, i) new_high = array.get(h_array, i) new_low = array.get(l_array, i) new_close = array.get(c_array, i) is_bull_candle = f_bull_candle(new_open, new_close) body_color = is_bull_candle ? css_bull_body : css_bear_body border_color = is_bull_candle ? css_bull_border : css_bear_border wick_color = is_bull_candle ? css_bull_wick : css_bear_wick array.push(box_array, box.new(left = new_x1, top = new_open, right = new_x2, bottom = new_close, xloc=xloc.bar_index, border_style=line.style_solid, bgcolor = body_color, border_color = border_color) ) mid_time = (new_x1 + new_x2) / 2 array.push(line_array, line.new(x1 = mid_time, y1 = new_high, x2 = mid_time, y2 = new_low, xloc=xloc.bar_index, style=line.style_solid, color = wick_color) ) middle_index = ((bar_index + start_spacing) + (bar_index + end_spacing)) / 2 if use_label array.push(label_array, label.new(middle_index, label_y, text = f_timeframe_text(timeframe), style = label.style_none, textcolor = css_label, size = f_label_size()) ) f_ltf_values(arr_o, arr_h, arr_l, arr_c, tf, max_array_size) => adjusted_timeframe = timeframe.in_seconds(tf) >= timeframe.in_seconds() ? '' : tf [o,h,l,c] = request.security_lower_tf(syminfo.tickerid, adjusted_timeframe, [open, high, low, close]) f_array_ltf(arr_o, o, max_array_size) f_array_ltf(arr_h, h, max_array_size) f_array_ltf(arr_l, l, max_array_size) f_array_ltf(arr_c, c, max_array_size) f_htf_values(arr_o, arr_h, arr_l, arr_c, tf) => [o,h,l,c] = request.security(syminfo.tickerid, tf, [open, high, low, close], lookahead = barmerge.lookahead_on) f_array_htf(arr_o, o, tf) f_array_htf(arr_h, h, tf) f_array_htf(arr_l, l, tf) f_array_htf(arr_c, c, tf) // define drawing object arrays var tf1_bodies = array.new_box(tf1_bars, na) var tf2_bodies = array.new_box(tf2_bars, na) var tf3_bodies = array.new_box(tf3_bars, na) var tf4_bodies = array.new_box(tf4_bars, na) var tf5_bodies = array.new_box(tf5_bars, na) var tf1_wicks = array.new_line(tf1_bars, na) var tf2_wicks = array.new_line(tf2_bars, na) var tf3_wicks = array.new_line(tf3_bars, na) var tf4_wicks = array.new_line(tf4_bars, na) var tf5_wicks = array.new_line(tf5_bars, na) var tf1_lbl = array.new_label(1, na) var tf2_lbl = array.new_label(1, na) var tf3_lbl = array.new_label(1, na) var tf4_lbl = array.new_label(1, na) var tf5_lbl = array.new_label(1, na) // define value arrays var tf1_o = array.new_float(tf1_bars, na) var tf2_o = array.new_float(tf2_bars, na) var tf3_o = array.new_float(tf3_bars, na) var tf4_o = array.new_float(tf4_bars, na) var tf5_o = array.new_float(tf5_bars, na) var tf1_h = array.new_float(tf1_bars, na) var tf2_h = array.new_float(tf2_bars, na) var tf3_h = array.new_float(tf3_bars, na) var tf4_h = array.new_float(tf4_bars, na) var tf5_h = array.new_float(tf5_bars, na) var tf1_l = array.new_float(tf1_bars, na) var tf2_l = array.new_float(tf2_bars, na) var tf3_l = array.new_float(tf3_bars, na) var tf4_l = array.new_float(tf4_bars, na) var tf5_l = array.new_float(tf5_bars, na) var tf1_c = array.new_float(tf1_bars, na) var tf2_c = array.new_float(tf2_bars, na) var tf3_c = array.new_float(tf3_bars, na) var tf4_c = array.new_float(tf4_bars, na) var tf5_c = array.new_float(tf5_bars, na) // store the values if use_tf1 if timeframe.in_seconds() > timeframe.in_seconds(tf1) f_ltf_values(tf1_o, tf1_h, tf1_l, tf1_c, tf1, tf1_bars) else f_htf_values(tf1_o, tf1_h, tf1_l, tf1_c, tf1) if use_tf2 if timeframe.in_seconds() > timeframe.in_seconds(tf2) f_ltf_values(tf2_o, tf2_h, tf2_l, tf2_c, tf2, tf2_bars) else f_htf_values(tf2_o, tf2_h, tf2_l, tf2_c, tf2) if use_tf3 if timeframe.in_seconds() > timeframe.in_seconds(tf3) f_ltf_values(tf3_o, tf3_h, tf3_l, tf3_c, tf3, tf3_bars) else f_htf_values(tf3_o, tf3_h, tf3_l, tf3_c, tf3) if use_tf4 if timeframe.in_seconds() > timeframe.in_seconds(tf4) f_ltf_values(tf4_o, tf4_h, tf4_l, tf4_c, tf4, tf4_bars) else f_htf_values(tf4_o, tf4_h, tf4_l, tf4_c, tf4) if use_tf5 if timeframe.in_seconds() > timeframe.in_seconds(tf5) f_ltf_values(tf5_o, tf5_h, tf5_l, tf5_c, tf5, tf5_bars) else f_htf_values(tf5_o, tf5_h, tf5_l, tf5_c, tf5) // calculate spacing var int tf1_start = na var int tf1_end = na var int tf2_start = na var int tf2_end = na var int tf3_start = na var int tf3_end = na var int tf4_start = na var int tf4_end = na var int tf5_start = na var int tf5_end = na var int last_end = na if (barstate.isfirst) last_end := padding if (use_tf1) tf1_start := padding tf1_end := tf1_start + 3 * tf1_bars last_end := tf1_end if (use_tf2) tf2_start := last_end + (padding_b*3) tf2_end := tf2_start + 3 * tf2_bars last_end := tf2_end if (use_tf3) tf3_start := last_end + (padding_b*3) tf3_end := tf3_start + 3 * tf3_bars last_end := tf3_end if (use_tf4) tf4_start := last_end + (padding_b*3) tf4_end := tf4_start + 3 * tf4_bars last_end := tf4_end if (use_tf5) tf5_start := last_end + (padding_b*3) tf5_end := tf5_start + 3 * tf5_bars tf1_max = nz(array.max(tf1_h), 0) tf2_max = nz(array.max(tf2_h), 0) tf3_max = nz(array.max(tf3_h), 0) tf4_max = nz(array.max(tf4_h), 0) tf5_max = nz(array.max(tf5_h), 0) y_value = math.max(tf1_max, tf2_max, tf3_max, tf4_max, tf5_max) if barstate.islast f_delete_all() if use_tf1 f_draw_candles(tf1_o, tf1_h, tf1_l, tf1_c, tf1_bodies, tf1_wicks, tf1_lbl, tf1_start, tf1_end, y_value, tf1) if use_tf2 f_draw_candles(tf2_o, tf2_h, tf2_l, tf2_c, tf2_bodies, tf2_wicks, tf2_lbl, tf2_start, tf2_end, y_value, tf2) if use_tf3 f_draw_candles(tf3_o, tf3_h, tf3_l, tf3_c, tf3_bodies, tf3_wicks, tf3_lbl, tf3_start, tf3_end, y_value, tf3) if use_tf4 f_draw_candles(tf4_o, tf4_h, tf4_l, tf4_c, tf4_bodies, tf4_wicks, tf4_lbl, tf4_start, tf4_end, y_value, tf4) if use_tf5 f_draw_candles(tf5_o, tf5_h, tf5_l, tf5_c, tf5_bodies, tf5_wicks, tf5_lbl, tf5_start, tf5_end, y_value, tf5) // label.new(bar_index+50, 30600, color = color.white, // text = str.tostring(tf4_c) // ) // TODO closing value is not updating because of ta.change, so need closing values to update
Trend Shift Pro
https://www.tradingview.com/script/6hEFyoAr-Trend-Shift-Pro/
federalTacos5392b
https://www.tradingview.com/u/federalTacos5392b/
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/ // © federalTacos5392b //@version=5 indicator("Trend Shift Pro", overlay = true) Threshold=input(0.8, title= "Practical Significance Threshold") // Calculate subgroup means for each block of 21 bars a = (hlc3[5] + hlc3[14] + hlc3[16]) / 3 b = (hlc3[8] + hlc3[15] + hlc3[1]) / 3 c = (hlc3[19] + hlc3[7] + hlc3[11]) / 3 d = (hlc3[10] + hlc3[6] + hlc3[18]) / 3 e = (hlc3[0] + hlc3[3] + hlc3[17]) / 3 f = (hlc3[9] + hlc3[20] + hlc3[13]) / 3 g = (hlc3[4] + hlc3[12] + hlc3[2]) / 3 // Create an array with the seven values for the current block of 21 bars var float[] values = array.new_float(7) var float MoM = na if bar_index % 21 == 0 // Reset the values array for a new block array.clear(values) // Push the subgroup means into the values array for the current block array.push(values, a) array.push(values, b) array.push(values, c) array.push(values, d) array.push(values, e) array.push(values, f) array.push(values, g) // Calculate the median of the seven values for the current block MoM := array.median(values) else // Set non-MoM values to na MoM := na // Calculate IQR for each block of 21 bars a1 = hlc3[0] b1 = hlc3[1] c1 = hlc3[2] d1 = hlc3[3] e1 = hlc3[4] f1 = hlc3[5] g1 = hlc3[6] h1 = hlc3[7] i1 = hlc3[8] j1 = hlc3[9] k1 = hlc3[10] l1 = hlc3[11] m1 = hlc3[12] n1 = hlc3[13] o1 = hlc3[14] p1 = hlc3[15] q1 = hlc3[16] r1 = hlc3[17] s1 = hlc3[18] t1 = hlc3[19] u1 = hlc3[20] // Create an array with the twenty-one values for the current block of 21 bars var float[] iqr_values = array.new_float(21) var float IQR = na if bar_index % 21 == 0 // Reset the values array for a new block array.clear(iqr_values) // Push the subgroup means into the values array for the current block array.push(iqr_values, a1) array.push(iqr_values, b1) array.push(iqr_values, c1) array.push(iqr_values, d1) array.push(iqr_values, e1) array.push(iqr_values, f1) array.push(iqr_values, g1) array.push(iqr_values, h1) array.push(iqr_values, i1) array.push(iqr_values, j1) array.push(iqr_values, k1) array.push(iqr_values, l1) array.push(iqr_values, m1) array.push(iqr_values, n1) array.push(iqr_values, o1) array.push(iqr_values, p1) array.push(iqr_values, q1) array.push(iqr_values, r1) array.push(iqr_values, s1) array.push(iqr_values, t1) array.push(iqr_values, u1) // Sort the values in ascending order array.sort(iqr_values) // Calculate Q1, Q3, and IQR var float Q1 = na var float Q3 = na if array.size(iqr_values) >= 4 Q1 := array.percentile_nearest_rank(iqr_values, 25) Q3 := array.percentile_nearest_rank(iqr_values, 75) IQR := 0.75*(Q3 - Q1) else // Set non-IQR values to na IQR := na // Non Parametric CohensD (practile significance) calculation var float CohensD = na if not na(MoM) and not na(IQR) and not na(MoM[21]) and not na(IQR[21]) CohensD := (MoM - MoM[21]) / math.sqrt((20 * math.pow(IQR, 2) + 20 * math.pow(IQR[21], 2)) / 40) else CohensD := na // Determine the color based on median of means direction color_change = MoM > MoM[21] ? color.green : (MoM < MoM[21] ? color.red : color.blue) // Detrmine Practical Significance Ps=math.abs(CohensD)< Threshold // Plot the MoM value with straight lines plot(MoM, title = "MoM Value", color = color.blue, linewidth = 1, style = plot.style_stepline) plot(MoM, title="MoM Value", color= color_change,style=plot.style_circles, linewidth = 5) //plot(CohensD, title = "Custom Calculation", color = color.purple, linewidth = 1, style = plot.style_line) plotshape(Ps,style =shape.triangleup, text= "NS",textcolor = color.rgb(224, 229, 241), size =size.small)
[KVA]K Stochastic Indicator
https://www.tradingview.com/script/ldddCgCC-KVA-K-Stochastic-Indicator/
Kamvia
https://www.tradingview.com/u/Kamvia/
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/ // © Kamvia //@version=5 indicator(title='[KVA]K Stochastic Indicator', shorttitle='KStochastic', overlay=false) // Input parameters length = input(14, 'Length') smoothK = input(1, 'Smooth K') smoothD = input(3, 'Smooth D') smoothF = input(21, 'Smooth F') _src = input.source(close,title="Source") sma_signal = input.string(title="Stochastic MA Type", defval="EMA", options=["SMA","WMA", "EMA","DEMA"]) // Calculate %K lowestLow = ta.lowest(_src, length) highestHigh = ta.highest(_src, length) k = 100 * (_src - lowestLow) / (highestHigh - lowestLow) dema(src, length)=> e1 = ta.ema(src, length) e2 = ta.ema(e1, length) ret = 2 * e1 - e2 ret ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "DEMA" => dema(source, length) "EMA" => ta.ema(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) // Smooth %K with simple moving average sk = ma(k, smoothK,sma_signal) // Smooth %K with simple moving average to calculate %D sd =ma(sk, smoothD,sma_signal) sf = ma(sk, smoothF,sma_signal) // Plotting plot(sk, color=color.new(color.blue, 0), title='%K') plot(sd, color=color.new(color.red, 0), title='%D') plot(sf, color=color.new(color.black, 0), title='%F') h0 = hline(80, "Upper Band", color=#787B86) hline(50, "Middle Band", color=color.new(#787B86, 50)) h1 = hline(20, "Lower Band", color=#787B86) fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background") stRD = sk ==100 stGD = sk == 0 stOBOS = true plot(stOBOS ? stRD ? sk : na:na, color=color.red, style=plot.style_circles, linewidth=3) plot(stOBOS ? stGD ? sk : na:na, color=color.green, style=plot.style_circles, linewidth=3)
VWAP Balance Zones
https://www.tradingview.com/script/LC5f30Lu-VWAP-Balance-Zones/
SamRecio
https://www.tradingview.com/u/SamRecio/
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/ // © SamRecio //@version=5 indicator("VWAP Balance Zones", shorttitle = "VBZ", overlay = true) d_tog = not input.bool(true, title = "", inline = "1") dc = input.color(color.rgb(93, 63, 211), title = "Daily                    ", inline = "1") dc_shade = input.color(color.rgb(93, 63, 211, 75), title = "", inline = "1") w_tog = not input.bool(true, title = "", inline = "2") wc = input.color(color.rgb(63, 211, 70), title = "Weekly                 ", inline = "2") wc_shade = input.color(color.rgb(63, 211, 70, 75), title = "", inline = "2") m_tog = not input.bool(true, title = "", inline = "3") mc = input.color(color.rgb(63, 189, 211), title = "Monthly                ", inline = "3") mc_shade = input.color(color.rgb(63, 189, 211, 75), title = "", inline = "3") dash() => (bar_index/2 - math.floor(bar_index/2)) > 0 get_st(_src,_func,_reset) => var _val = _src if _reset _val := _src condition = _func == ">"?_src>_val:_func == "<"?_src<_val:false if condition _val := _src _val no_show(_cond1,_cond2) => var output = true if _cond1 and _cond2 output := true if _cond2 and not _cond1 output := false output nd = timeframe.change("D") nw = timeframe.change("W") nm = timeframe.change("M") no_show_week = no_show(nw,nd) no_show_month = no_show(nm,nw) high_vwap = ta.vwap(high,nd) close_vwap = ta.vwap(close,nd) low_vwap = ta.vwap(low,nd) w_vwap = ta.vwap(hlc3,nw) m_vwap = ta.vwap(hlc3,nm) plot(nd or d_tog?na:high_vwap, style = plot.style_linebr, color = dc, title = "High VWAP") plot(nd or d_tog?na:close_vwap, style = plot.style_linebr, color = dash()?color.rgb(0,0,0,100):dc, title = "Close VWAP") plot(nd or d_tog?na:low_vwap, style = plot.style_linebr, color = dc, title = "Low VWAP") plot(nw or (no_show_week and not d_tog) or w_tog?na:w_vwap, style = plot.style_linebr, color =dash()?color.rgb(0,0,0,100):wc, linewidth = 2, title = "Weekly VWAP") plot(nm or (no_show_month and not w_tog) or m_tog?na:m_vwap, style = plot.style_linebr, color =dash()?color.rgb(0,0,0,100):mc, linewidth = 3, title = "Monthly VWAP") h_hi = get_st(high,">",nd) h_clo = get_st(close,">",nd) h_lo = get_st(low,">",nd) l_lo = get_st(low,"<",nd) l_clo = get_st(close,"<",nd) l_hi = get_st(high,"<",nd) w_lo = get_st(low,"<",nw) w_hi = get_st(high,">",nw) m_lo = get_st(low,"<",nm) m_hi = get_st(high,">",nm) low_50 = math.avg(close_vwap,l_clo) high_50 = math.avg(close_vwap,h_clo) h_vwap_h = math.avg(high_vwap,h_hi) h_vwap_l = math.avg(low_vwap,h_lo) l_vwap_h = math.avg(high_vwap,l_hi) l_vwap_l = math.avg(low_vwap,l_lo) w_low_50 = math.avg(w_vwap,w_lo) w_high_50 = math.avg(w_vwap,w_hi) m_low_50 = math.avg(m_vwap,m_lo) m_high_50 = math.avg(m_vwap,m_hi) l_50 = plot(nd or d_tog?na:low_50, style = plot.style_linebr, color = dc, title = "Lo-Close 50%") h_50 = plot(nd or d_tog?na:high_50, style = plot.style_linebr, color = dc, title = "Hi-Close 50%") hh_50 = plot(nd or d_tog?na:h_vwap_h, style = plot.style_linebr, color = dc, title = "Hi-High 50%") hl_50 = plot(nd or d_tog?na:h_vwap_l, style = plot.style_linebr, color = dc, title = "Hi-Low 50%") lh_50 = plot(nd or d_tog?na:l_vwap_h, style = plot.style_linebr, color = dc, title = "Lo-High 50%") ll_50 = plot(nd or d_tog?na:l_vwap_l, style = plot.style_linebr, color = dc, title = "Lo-Low 50%") fill(hh_50,hl_50,nd or d_tog?color.rgb(0,0,0,100):dc_shade, title = "Daily Hi 50% Zone") fill(lh_50,ll_50,nd or d_tog?color.rgb(0,0,0,100):dc_shade, title = "Daily Lo 50% Zone") plot(nw or (no_show_week and not d_tog) or w_tog?na:w_low_50, style = plot.style_linebr, color = wc, linewidth = 2, title = "Week High 50%") plot(nw or (no_show_week and not d_tog) or w_tog?na:w_high_50, style = plot.style_linebr, color = wc, linewidth = 2, title = "Week Low 50%") plot(nm or (no_show_month and not w_tog) or m_tog?na:m_low_50, style = plot.style_linebr, color = mc, linewidth = 3, title = "Month High 50%") plot(nm or (no_show_month and not w_tog) or m_tog?na:m_high_50, style = plot.style_linebr, color = mc, linewidth = 3, title = "Month Low 50%")
Linear Regression MTF + Bands
https://www.tradingview.com/script/Pr9hEmWf-Linear-Regression-MTF-Bands/
theGary
https://www.tradingview.com/u/theGary/
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/ // © theGary //@version=5 indicator("Linear Regression MTF + Bands", overlay=true) // CHOOSE ALERTS ALERTS_TF1 = input.bool(false, 'Alerts TF1', group = 'Choose Active Alerts') ALERTS_TF2 = input.bool(false, 'Alerts TF2', group = 'Choose Active Alerts') ALERTS_TF3 = input.bool(true, 'Alerts TF3', group = 'Choose Active Alerts') // TF1 use_tf1 = input.bool(false, title = 'Show TF1 ', inline='1', group='TF1 Settings') tf1_band = input.bool(true, title = 'History Band', inline='1', group='TF1 Settings') tf1_timeframe = input.int(5, title='Timeframe', inline='2', group='TF1 Settings', options = [1,5,15,30,60,240]) tf1_price = input.source(close, inline='2', title = ' ', group='TF1 Settings') tf1_linreg_length = input.int(title='Length ', defval=100, inline='3', maxval = 500, minval = 10, group='TF1 Settings') tf1_linreg_deviation = input.float(title='Deviation ', defval=2, step=0.25, minval=0.1, maxval=5.00, inline='3', group='TF1 Settings') tf1_color = input.color(color.new(#ffee58, 0), title='upper Color', inline='4', group='TF1 Settings') tf1_extend = input.string(defval = 'None', title = 'Extension', options = ['Both', 'Right', 'Left', 'None'], inline='5', group='TF1 Settings') tf1_width = input.int(1, title = 'Width', minval = 1, maxval = 5, inline='5', group='TF1 Settings') tf1_bg = input.int(90, minval = 0, maxval = 100, title = 'Background Transparency', inline='4', group='TF1 Settings') tf1_extendStyle = switch tf1_extend == "Both" => extend.both tf1_extend == "Left" => extend.left tf1_extend == "Right" => extend.right => extend.none // TF2 use_tf2 = input.bool(false, title = 'Show TF2 ', inline='1', group='TF2 Settings') tf2_band = input.bool(true, title = 'History Band', inline='1', group='TF2 Settings') tf2_timeframe = input.int(15, title='Timeframe', inline='2', group='TF2 Settings', options = [1,5,15,30,60,240]) tf2_price = input.source(close, inline='2', title = ' ', group='TF2 Settings') tf2_linreg_length = input.int(title='Length ', defval=100, inline='3', maxval = 500, minval = 10, group='TF2 Settings') tf2_linreg_deviation = input.float(title='Deviation ', defval=2, step=0.25, minval=0.1, maxval=5.00, inline='3', group='TF2 Settings') tf2_color = input.color(color.new(#ff9800, 0), title='upper Color', inline='4', group='TF2 Settings') tf2_extend = input.string(defval = 'None', title = 'Extension', options = ['Both', 'Right', 'Left', 'None'], inline='5', group='TF2 Settings') tf2_width = input.int(3, title = 'Width', minval = 1, maxval = 5, inline='5', group='TF2 Settings') tf2_bg = input.int(82, minval = 0, maxval = 100, title = 'Background Transparency', inline='6', group='TF2 Settings') tf2_extendStyle = switch tf2_extend == "Both" => extend.both tf2_extend == "Left" => extend.left tf2_extend == "Right" => extend.right => extend.none // TF3 use_tf3 = input.bool(true, title = 'Show TF3 ', inline='1', group='TF3 Settings') tf3_band = input.bool(true, title = 'History Band', inline='1', group='TF3 Settings') tf3_timeframe = input.int(60, title='Timeframe', inline='2', group='TF3 Settings', options = [1,5,15,30,60,240]) tf3_price = input.source(close, inline='2', title = ' ', group='TF3 Settings') tf3_linreg_length = input.int(title='Length ', defval=100, inline='3', maxval = 500, minval = 10, group='TF3 Settings') tf3_linreg_deviation = input.float(title='Deviation ', defval=2, step=0.25, minval=0.1, maxval=5.00, inline='3', group='TF3 Settings') tf3_color = input.color(color.new(#0086ff, 0), title='upper Color', inline='4', group='TF3 Settings') tf3_extend = input.string(defval = 'None', title = 'Extension', options = ['Both', 'Right', 'Left', 'None'], inline='5', group='TF3 Settings') tf3_width = input.int(5, title = 'Width', minval = 1, maxval = 5, inline='5', group='TF3 Settings') tf3_bg = input.int(75, minval = 0, maxval = 100, title = 'Background Transparency', inline='6', group='TF3 Settings') tf3_extendStyle = switch tf3_extend == "Both" => extend.both tf3_extend == "Left" => extend.left tf3_extend == "Right" => extend.right => extend.none calculate_linreg(source, length, deviation) => a = ta.wma(source, length) b = ta.sma(source, length) A = 4 * b - 3 * a B = 3 * a - 2 * b m = (A - B) / (length - 1) d = 0.00 for i = 0 to length - 1 by 1 l = B + m * i d += math.pow(source[i] - l, 2) d linreg_1 = math.sqrt(d / (length - 1)) * deviation y1_midvalue = A + 0 y2_midvalue = -m + (B + 0) y1_uppervalue = A + linreg_1 y2_uppervalue = -m + (B + linreg_1) y1_lowervalue = A - linreg_1 y2_lowervalue = -m + (B - linreg_1) x1_value = time[length] [x1_value, y1_midvalue, y2_midvalue, y1_lowervalue, y2_lowervalue, y1_uppervalue, y2_uppervalue] drawLinReg(color_input, extension_input, width_input, x1_value, y1_value, y2_value, linreg_length, tf_input, draw_label) => if draw_label label label_variable = label.new(bar_index + 5, y2_value, text=str.tostring(tf_input) + "min | " + str.tostring(math.round_to_mintick(y2_value)), style=label.style_label_left, textcolor = color.black, color = color_input, textalign = text.align_left) label.delete(label_variable[1]) label.set_tooltip(label_variable, 'testing123') line line_variable = line.new(x1_value, y1_value, time, y2_value, extend = extension_input, color = color_input, width = width_input, xloc = xloc.bar_time) line_variable [tf1_x1_value, tf1_y1_midvalue, tf1_y2_midvalue, tf1_y1_lowervalue, tf1_y2_lowervalue, tf1_y1_uppervalue, tf1_y2_uppervalue]= request.security(syminfo.tickerid, str.tostring(tf1_timeframe), calculate_linreg(tf1_price, tf1_linreg_length, tf1_linreg_deviation)) [tf2_x1_value, tf2_y1_midvalue, tf2_y2_midvalue, tf2_y1_lowervalue, tf2_y2_lowervalue, tf2_y1_uppervalue, tf2_y2_uppervalue]= request.security(syminfo.tickerid, str.tostring(tf2_timeframe), calculate_linreg(tf2_price, tf2_linreg_length, tf2_linreg_deviation)) [tf3_x1_value, tf3_y1_midvalue, tf3_y2_midvalue, tf3_y1_lowervalue, tf3_y2_lowervalue, tf3_y1_uppervalue, tf3_y2_uppervalue]= request.security(syminfo.tickerid, str.tostring(tf3_timeframe), calculate_linreg(tf3_price, tf3_linreg_length, tf3_linreg_deviation)) // plot Bands p_tf1_upper = plot(tf1_y2_uppervalue, title = 'TF1 Upper', color = tf1_color, style = plot.style_stepline, display = use_tf1 and tf1_band ? display.all:display.none, editable = false) p_tf1_lower = plot(tf1_y2_lowervalue, title = 'TF1 Lower', color = tf1_color, style = plot.style_stepline, display = use_tf1 and tf1_band ? display.all:display.none, editable = false) fill(p_tf1_lower, p_tf1_upper, title = 'TF1 Band Fill', color = color.new(tf1_color, 90), display = use_tf1 and tf1_band ? display.all:display.none, editable = false) p_tf2_upper = plot(tf2_y2_uppervalue, title = 'TF2 Upper', color = tf2_color, style = plot.style_stepline, display = use_tf2 and tf2_band ? display.all:display.none, editable = false) p_tf2_lower = plot(tf2_y2_lowervalue, title = 'TF2 Lower', color = tf2_color, style = plot.style_stepline, display = use_tf2 and tf2_band ? display.all:display.none, editable = false) fill(p_tf2_lower, p_tf2_upper, title = 'TF2 Band Fill', color = color.new(tf2_color, 90), display = use_tf2 and tf2_band? display.all:display.none, editable = false) p_tf3_upper = plot(tf3_y2_uppervalue, title = 'TF3 Upper', color = tf3_color, style = plot.style_stepline, display = use_tf3 and tf3_band ? display.all:display.none, editable = false) p_tf3_lower = plot(tf3_y2_lowervalue, title = 'TF3 Lower', color = tf3_color, style = plot.style_stepline, display = use_tf3 and tf3_band? display.all:display.none, editable = false) fill(p_tf3_lower, p_tf3_upper, title = 'TF3 Band Fill', color = color.new(tf3_color, 90), display = use_tf3 and tf3_band ? display.all:display.none, editable = false) var line tf3_mid = na var line tf2_mid = na var line tf1_mid = na var line tf3_upper = na var line tf2_upper = na var line tf1_upper = na var line tf3_lower = na var line tf2_lower = na var line tf1_lower = na if barstate.islast if use_tf3 tf3_mid := drawLinReg(color.new(tf3_color, 80), tf3_extendStyle, tf3_width, tf3_x1_value, tf3_y1_midvalue, tf3_y2_midvalue, tf3_linreg_length, tf3_timeframe, false) tf3_upper := drawLinReg(color.new(tf3_color, 0), tf3_extendStyle, tf3_width, tf3_x1_value, tf3_y1_uppervalue, tf3_y2_uppervalue, tf3_linreg_length, tf3_timeframe, true) tf3_lower := drawLinReg(color.new(tf3_color, 0), tf3_extendStyle, tf3_width, tf3_x1_value, tf3_y1_lowervalue, tf3_y2_lowervalue, tf3_linreg_length, tf3_timeframe,true) linefill tf3_fill = linefill.new(tf3_upper, tf3_lower, color.new(tf3_color,tf3_bg)) if not na(tf3_mid[1]) line.delete(tf3_mid[1]) line.delete(tf3_upper[1]) line.delete(tf3_lower[1]) linefill.delete(tf3_fill[1]) if use_tf2 tf2_mid := drawLinReg(color.new(tf2_color, 80), tf2_extendStyle, tf2_width, tf2_x1_value, tf2_y1_midvalue, tf2_y2_midvalue, tf2_linreg_length, tf2_timeframe, false) tf2_upper := drawLinReg(color.new(tf2_color, 0), tf2_extendStyle, tf2_width, tf2_x1_value, tf2_y1_uppervalue, tf2_y2_uppervalue, tf2_linreg_length, tf2_timeframe, true) tf2_lower := drawLinReg(color.new(tf2_color, 0), tf2_extendStyle, tf2_width, tf2_x1_value, tf2_y1_lowervalue, tf2_y2_lowervalue, tf2_linreg_length, tf2_timeframe,true) linefill tf2_fill = linefill.new(tf2_upper, tf2_lower, color.new(tf2_color,tf2_bg)) if not na(tf2_mid[1]) line.delete(tf2_mid[1]) line.delete(tf2_upper[1]) line.delete(tf2_lower[1]) linefill.delete(tf2_fill[1]) if use_tf1 tf1_mid := drawLinReg(color.new(tf1_color, 80), tf1_extendStyle, tf1_width, tf1_x1_value, tf1_y1_midvalue, tf1_y2_midvalue, tf1_linreg_length, tf1_timeframe, false) tf1_upper := drawLinReg(color.new(tf1_color, 0), tf1_extendStyle, tf1_width, tf1_x1_value, tf1_y1_uppervalue, tf1_y2_uppervalue, tf1_linreg_length, tf1_timeframe, true) tf1_lower := drawLinReg(color.new(tf1_color, 0), tf1_extendStyle, tf1_width, tf1_x1_value, tf1_y1_lowervalue, tf1_y2_lowervalue, tf1_linreg_length, tf1_timeframe,true) linefill tf1_fill = linefill.new(tf1_upper, tf1_lower, color.new(tf1_color,tf1_bg)) if not na(tf1_mid[1]) line.delete(tf1_mid[1]) line.delete(tf1_upper[1]) line.delete(tf1_lower[1]) linefill.delete(tf1_fill[1]) //ALERTS tf1_alert = high >= tf1_y2_uppervalue and ALERTS_TF1 ? 1 : low <= tf1_y2_lowervalue and ALERTS_TF1 ? -1 : 0 tf2_alert = high >= tf2_y2_uppervalue and ALERTS_TF2 ? 1 : low <= tf2_y2_lowervalue and ALERTS_TF2 ? -1 : 0 tf3_alert = high >= tf3_y2_uppervalue and ALERTS_TF3 ? 1 : low <= tf3_y2_lowervalue and ALERTS_TF3 ? -1 : 0 new_alert = ((tf1_alert != 0) or (tf2_alert != 0) or (tf3_alert != 0)) var new_alert_text = ' ' if new_alert if tf1_alert != 1 and tf2_alert != 1 and tf3_alert == 1 //ONLY 3 BULL new_alert_text := 'ABOVE: TF3 Channel' if tf1_alert != 1 and tf2_alert == 1 and tf3_alert != 1 //ONLY 2 BULL new_alert_text := 'ABOVE: TF2 Channel' if tf1_alert == 1 and tf2_alert != 1 and tf3_alert != 1 //ONLY 1 BULL new_alert_text := 'ABOVE: TF1 Channel' if tf1_alert != 1 and tf2_alert == 1 and tf3_alert == 1 //2 and 3 BULL new_alert_text := 'ABOVE: TF2 & TF3 Channel' if tf1_alert == 1 and tf2_alert != 1 and tf3_alert == 1 //1 and 3 BULL new_alert_text := 'ABOVE: TF1 & TF3 Channel' if tf1_alert == 1 and tf2_alert == 1 and tf3_alert != 1 //1 and 2 BULL new_alert_text := 'ABOVE: TF1 & TF2 Channel' if tf1_alert == 1 and tf2_alert == 1 and tf3_alert == 1 //1 and 2 and 3 BULL new_alert_text := 'ABOVE: TF1 & TF2 & TF3 Channel' ////////////////////////////////////////////////////////////////////// if tf1_alert != -1 and tf2_alert != -1 and tf3_alert == -1 //ONLY 3 BEAR new_alert_text := 'BELOW: TF3 Channel' if tf1_alert != -1 and tf2_alert == -1 and tf3_alert != -1 //ONLY 2 BEAR new_alert_text := 'BELOW: TF2 Channel' if tf1_alert == -1 and tf2_alert != -1 and tf3_alert != -1 //ONLY 1 BEAR new_alert_text := 'BELOW: TF1 Channel' if tf1_alert != -1 and tf2_alert == -1 and tf3_alert == -1 //2 and 3 BEAR new_alert_text := 'BELOW: TF2 & TF3 Channel' if tf1_alert == -1 and tf2_alert != -1 and tf3_alert == -1 //1 and 3 BEAR new_alert_text := 'BELOW: TF1 & TF3 Channel' if tf1_alert == -1 and tf2_alert == -1 and tf3_alert != -1 //1 and 2 BEAR new_alert_text := 'BELOW: TF1 & TF2 Channel' if tf1_alert == -1 and tf2_alert == -1 and tf3_alert == -1 //1 and 2 and 3 BEAR new_alert_text := 'BELOW: TF1 & TF2 & TF3 Channel' else new_alert_text := "" if new_alert == true alert(new_alert_text, alert.freq_once_per_bar_close)
Market Pivot Levels [Past & Live]
https://www.tradingview.com/script/X1njqKyf-Market-Pivot-Levels-Past-Live/
serkany88
https://www.tradingview.com/u/serkany88/
25
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(title="Market Levels [Past&Live]", max_labels_count=500, overlay=true, precision=2, max_lines_count=500) showDC = input.bool(true, title="Show Present Daily", group="Present", inline="dc") dcH_col = input.color(color.white, title="", group="Present", inline="dc") dcL_col = input.color(color.white, title="", group="Present", inline="dc") dcL_line = input.string(line.style_dashed, title="", options=[line.style_solid, line.style_dashed, line.style_dotted],group="Present", inline="dc") showYC = input.bool(true, title="Show Present Yesterday", group="Present", inline="yc") ycH_col = input.color(color.rgb(83,169,149,0), title="", group="Present", inline="yc") ycC_col = input.color(color.rgb(229, 193, 94), title="", group="Present", inline="yc") ycL_col = input.color(color.rgb(229,94,100,0), title="", group="Present", inline="yc") ycL_line = input.string(line.style_solid, title="", options=[line.style_solid, line.style_dashed, line.style_dotted],group="Present", inline="yc") showPreC = input.bool(false, title="Show Present Premarket", group="Present", inline="prec") PrecH_col = input.color(color.rgb(83,169,149,50), title="", group="Present", inline="prec") PrecL_col = input.color(color.rgb(229,94,100,50), title="", group="Present", inline="prec") precL_line = input.string(line.style_dotted, title="", options=[line.style_solid, line.style_dashed, line.style_dotted],group="Present", inline="prec") showD = input.bool(true, title="Show Past Daily", group="Past", inline="d") dH_col = input.color(color.white, title="", group="Past", inline="d") dL_col = input.color(color.white, title="", group="Past", inline="d") d_line = input.string(line.style_dashed, title="", options=[line.style_solid, line.style_dashed, line.style_dotted],group="Past", inline="d") showY = input.bool(true, title="Show Past Yesterday", group="Past", inline="y") yH_col = input.color(color.rgb(83,169,149,0), title="", group="Past", inline="y") yC_col = input.color(color.rgb(229, 193, 94), title="", group="Past", inline="y") yL_col = input.color(color.rgb(229,94,100,0), title="", group="Past", inline="y") y_line = input.string(line.style_solid, title="", options=[line.style_solid, line.style_dashed, line.style_dotted],group="Past", inline="y") showPre = input.bool(false, title="Show Past Premarket", group="Past", inline="pre") preH_col = input.color(color.rgb(83,169,149,50), title="", group="Past", inline="pre") preL_col = input.color(color.rgb(229,94,100,50), title="", group="Past", inline="pre") pre_line = input.string(line.style_dotted, title="", options=[line.style_solid, line.style_dashed, line.style_dotted],group="Past", inline="pre") // Create our custom type to hold values type valueHold float highVal = high float lowVal = low float pre_highVal = high float pre_clsVal = close float pre_lowVal = low int timeVal = time float preHigh = high float preLow = low f_arrayCheck(simple int size, arr) => if arr.size() > size arr.shift() arr // Let's get ticker extended no matter what the current chart is tc = ticker.new(syminfo.prefix, syminfo.ticker, session.extended) //Let's create our arrays for polylines for daily drawing var cpArrHigh = array.new<chart.point>(3, chart.point.from_time(time, close)) var cpArrLow = array.new<chart.point>(3, chart.point.from_time(time, close)) var prevArrh = array.new<chart.point>(3, chart.point.from_time(time, close)) var prevArrl = array.new<chart.point>(3, chart.point.from_time(time, close)) var prevArrc = array.new<chart.point>(3, chart.point.from_time(time, close)) var prevMarh = array.new<chart.point>(3, chart.point.from_time(time, close)) var prevMarl = array.new<chart.point>(3, chart.point.from_time(time, close)) var valHolder = array.new<valueHold>(3, valueHold.new(high, low, high, close, low, time, high, low)) // Let's find premarket high and low via function f_preFind() => _close = close var float pre_high = na var float pre_low = na if session.ispremarket pre_high := math.max(nz(pre_high, high), high) pre_low := math.min(nz(pre_low, low), low) else if session.ispostmarket pre_high := na pre_low := na [pre_high, pre_low] // Get the pre high and pre low as arrays and draw max and min of them [pre_high, pre_low] = request.security(tc, timeframe.period , f_preFind()) // Let's use polylines for previous market points with arrays highPoly = polyline.new(showD ? cpArrHigh : na, false, false, xloc.bar_time, dH_col, na, d_line, 1) lowPoly = polyline.new(showD ? cpArrLow : na, false, false, xloc.bar_time, dL_col, na, d_line, 1) // Let's use polylines for previous market points with arrays prevhighPoly = polyline.new(showY ? prevArrh : na, false, false, xloc.bar_time, yH_col, na, y_line, 1) prevlowPoly = polyline.new(showY ? prevArrl : na, false, false, xloc.bar_time, yL_col, na, y_line, 1) prevclsPoly = polyline.new(showY ? prevArrc : na, false, false, xloc.bar_time, yC_col, na, y_line, 1) preMarhPoly = polyline.new(showPre ? prevMarh : na, false, false, xloc.bar_time, preH_col, na, pre_line, 1) preMarlPoly = polyline.new(showPre ? prevMarl : na, false, false, xloc.bar_time, preL_col, na, pre_line, 1) // Daily change points changeD = timeframe.change("D") // How many bars since last time new day started changeLast = ta.barssince(changeD) // On the fly function to calculate daily highlows instead of tv inbuilt because tv's length cannot take series f_highlow(int last) => bardiff = last float _low = low, float _high = high for i = bardiff to 0 by 1 if high[i] > _high _high := high[i] if low[i] < _low _low := low[i] [_high, _low, close] // Calculate daily high's and lows [_high, _low, _close] = f_highlow(changeLast[1]) pr_h = fixnan(pre_high)[1] pr_l = fixnan(pre_low)[1] pr_c = fixnan(_close)[1] _ph = valHolder.get(0).pre_highVal[1] _pl = valHolder.get(0).pre_lowVal[1] _pc = valHolder.get(0).pre_clsVal[1] //Fill the array as a function just in case we will need to use later f_arrFill(chart.point[] highArr, chart.point[] lowArr, chart.point[] prevHigh, chart.point[] prevLow, chart.point[] prevCls, chart.point[] prevMarh, chart.point[] prevMarl) => _t = valHolder.get(0).timeVal // Yesterday Poly prevHigh.push(chart.point.from_time(_t, valHolder.get(1).pre_highVal)) prevHigh.push(chart.point.from_time(_t, _ph)) prevHigh.push(chart.point.from_time(time, _ph)) prevCls.push(chart.point.from_time(_t, valHolder.get(1).pre_clsVal)) prevCls.push(chart.point.from_time(_t, _pc)) prevCls.push(chart.point.from_time(time, _pc)) prevLow.push(chart.point.from_time(_t, valHolder.get(1).pre_lowVal)) prevLow.push(chart.point.from_time(_t, _pl)) prevLow.push(chart.point.from_time(time, _pl)) // Daily Poly highArr.push(chart.point.from_time(_t, valHolder.get(0).highVal)) highArr.push(chart.point.from_time(_t, _high)) highArr.push(chart.point.from_time(time, _high)) lowArr.push(chart.point.from_time(_t, valHolder.get(0).lowVal)) lowArr.push(chart.point.from_time(_t, _low)) lowArr.push(chart.point.from_time(time, _low)) // Prev Market Poly prevMarh.push(chart.point.from_time(_t, valHolder.get(0).preHigh)) prevMarh.push(chart.point.from_time(_t, pr_h)) prevMarh.push(chart.point.from_time(time, pr_h)) prevMarl.push(chart.point.from_time(_t, valHolder.get(0).preLow)) prevMarl.push(chart.point.from_time(_t, pr_l)) prevMarl.push(chart.point.from_time(time, pr_l)) 1 // When new day starts fill polyline arrays with previous day values for polylines to draw on chart // We also update prevtime values with current ones after we pushed to the arrays if changeD f_arrFill(cpArrHigh, cpArrLow, prevArrh, prevArrl, prevArrc, prevMarh, prevMarl) valHolder.unshift(valueHold.new(_high, _low, _high, _close, _low, time, pr_h, pr_l)) //Clear arrays after certain size so the script don't take forever to load int arrLimit = 300 if valHolder.size() > arrLimit valHolder.pop() f_arrayCheck(arrLimit, cpArrHigh) f_arrayCheck(arrLimit, cpArrLow) f_arrayCheck(arrLimit, prevArrh) f_arrayCheck(arrLimit, prevArrl) f_arrayCheck(arrLimit, prevArrc) f_arrayCheck(arrLimit, prevMarh) f_arrayCheck(arrLimit, prevMarl) // Current Daily high and low lines using normal lines and labels td = time - time[5] //time for text int prevTime = valHolder.get(0).timeVal float prevHigh = valHolder.get(1).pre_highVal float prevLow = valHolder.get(1).pre_lowVal float prevCls = valHolder.get(1).pre_clsVal // Daily Lines var line d_high_line = line.new(showDC ? prevTime : na, _high, time, _high, xloc=xloc.bar_time, color=dcH_col, style=dcL_line, width=1) var line p_high_line = line.new(showYC ? prevTime : na, prevHigh, time, prevHigh, xloc=xloc.bar_time, color=ycH_col, style=ycL_line, width=1) var line prem_high_line = line.new(showPreC ? prevTime : na, pr_h, time, pr_h, xloc=xloc.bar_time, color=PrecH_col, style=precL_line, width=1) var line d_low_line = line.new(showDC ? prevTime : na, _low, time, _low, xloc=xloc.bar_time, color=dcL_col, style=dcL_line, width=1) var line p_low_line = line.new(showYC ? prevTime : na, prevLow, time, prevLow, xloc=xloc.bar_time, color=ycL_col, style=ycL_line, width=1) var line p_cls_line = line.new(showYC ? prevTime : na, prevCls, time, prevCls, xloc=xloc.bar_time, color=ycC_col, style=ycL_line, width=1) var line prem_low_line = line.new(showPreC ? prevTime : na, pr_l, time, pr_l, xloc=xloc.bar_time, color=PrecL_col, style=precL_line, width=1) // Daily Labels var label dh = label.new(x=showDC ? time+td : na, y=_high, text="Daily High", xloc=xloc.bar_time, style=label.style_none, textcolor=dcH_col, size=size.normal, textalign=text.align_right) var label dl = label.new(x=showDC ? time+td : na, y=_low, text="Daily Low", xloc=xloc.bar_time, style=label.style_none, textcolor=dcL_col, size=size.normal, textalign=text.align_right) // Yesterday's Labels var label yh = label.new(x=showYC ? prevTime+td : na, y=prevHigh, text="Yesterday's High", xloc=xloc.bar_time, style=label.style_none, textcolor=ycH_col, size=size.normal, textalign=text.align_right) var label yl = label.new(x=showYC ? prevTime+td : na, y=prevLow, text="Yesterday's Low", xloc=xloc.bar_time, style=label.style_none, textcolor=ycL_col, size=size.normal, textalign=text.align_right) var label yc = label.new(x=showYC ? prevTime+td : na, y=prevCls, text="Yesterday's Close", xloc=xloc.bar_time, style=label.style_none, textcolor=ycC_col, size=size.normal, textalign=text.align_right) // Pre-market Labels var label prmh = label.new(x=showPreC ? prevTime+td : na, y=pr_h, text="Pre-market High", xloc=xloc.bar_time, style=label.style_none, textcolor=PrecH_col, size=size.normal, textalign=text.align_right) var label prml = label.new(x=showPreC ? prevTime+td : na, y=pr_l, text="Pre-market Low", xloc=xloc.bar_time, style=label.style_none, textcolor=PrecL_col, size=size.normal, textalign=text.align_right) //Adjust x/y locations accordingly in each bar if selected to show if showDC d_high_line.set_xy1(prevTime, _high) d_high_line.set_xy2(time, _high) d_low_line.set_xy1(prevTime, _low) d_low_line.set_xy2(time, _low) dh.set_xy(time+td, _high) dl.set_xy(time+td, _low) if showYC p_high_line.set_xy1(prevTime, prevHigh) p_high_line.set_xy2(time, prevHigh) p_cls_line.set_xy1(prevTime, prevCls) p_cls_line.set_xy2(time, prevCls) p_low_line.set_xy1(prevTime, prevLow) p_low_line.set_xy2(time, prevLow) yh.set_xy(time+td, prevHigh) yc.set_xy(time+td, prevCls) yl.set_xy(time+td, prevLow) if showPreC prem_high_line.set_xy1(prevTime, pr_h) prem_high_line.set_xy2(time, pr_h) prem_low_line.set_xy1(prevTime, pr_l) prem_low_line.set_xy2(time, pr_l) prmh.set_xy(time+td, pr_h) prml.set_xy(time+td, pr_l) //Vertical day end an finish line, can be disabled from style tab of indicator bgcolor(changeD ? color.new(color.aqua, 90) : na, title="New Day Line")
TSI Market Timer + Volatility Meter
https://www.tradingview.com/script/bdlvAuVw-TSI-Market-Timer-Volatility-Meter/
SpreadEagle71
https://www.tradingview.com/u/SpreadEagle71/
16
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/ // © SpreadEagle71 //@version=5 indicator("TSI Market Timer + Volatility Meter", shorttitle="TSI+VM", overlay=false) fast = input(5, title="TSI Fast") slow = input(15, title="TSI slow") //length = input.int(20, title="TTM SQZ length") compare = input.string("SPY", title="Comparison Index/ETF/Stock") v1 = close v3 = high v4 = low v2 = request.security(compare, timeframe.period, close) v14 = request.security('DXY', timeframe.period, close) dxy = ta.tsi(v14, fast, slow) spy = ta.tsi(v2, fast, slow) xxx = ta.tsi(v1, fast, slow) xxh = ta.tsi(v3, fast, slow) xxl = ta.tsi(v4, fast, slow) lookback = input(252, title="Lookback (252 approx 52 week high)") dxyfill = input(false, title="Fill lines between Stock and Trigger line, green up, red down?") spyfill = input(false, title="Fill lines between index and stock, green=up,red=down?") showx = input(true, title="Highlight stock/trigger crossover upqward?") showy = input(true, title="Highlight stock/trigger crossover downward?") up = xxx > 0 down = xxx < 0 newh = ta.highest(high, lookback) newhigh = high >= newh newl = ta.lowest(low, lookback) newlow = low<= newl mycolor = newhigh ? color.new(color.lime, 5) : newlow ? color.new(#d9dc24, 5) : up ? color.new(#118e15, 1) : down ? color.new(color.red, 0.95) : color.new(color.blue, 0.95) xplot=plot(xxx, color=mycolor, linewidth=2,transp=0) xxplot=plot(xxx,color= newhigh ? mycolor : na,linewidth=3) uplot= plot(dxy, color=color.new(color.rgb(243, 174, 14),transp=60), title='Trigger', linewidth=3) sp = plot(spy, color=color.new(color.purple, transp=10), title="INDEX", linewidth=2) transparency = dxyfill ? 80 : 100 fill(xplot, uplot, color = xxx > dxy ? color.new(color.green, transparency) : color.new(color.red, transparency)) spy_transparency = spyfill ? 80 :100 fill(xplot, sp, color = xxx > spy ? color.new(color.green, spy_transparency) : color.new(color.red, spy_transparency)) xover = ta.crossover(xxx, dxy) bgcolor(xover? showx ? color.rgb(8, 77, 10) : na : na, transp=75) xdown = ta.crossover(dxy,xxx) bgcolor(xdown? showy ? color.rgb(121, 40, 40) : na : na, transp=65) // Volatility Colors vlength = input.int(10, minval=1) annual = 365 per = timeframe.isintraday or timeframe.isdaily and timeframe.multiplier == 1 ? 1 : 7 hv = 100 * ta.stdev(math.log(close / close[1]), vlength) * math.sqrt(annual / per) cv= hv/ta.sma(close,vlength) ave = ta.sma(cv,30) low30=ta.lowest(cv,30) low100=ta.lowest(cv,100) high30=ta.highest(cv,30) high100=ta.highest(cv,100) mid_color= cv ==low100 ? color.blue :cv==low30? color.aqua : cv==high30 ? color.red : #ea9a04 plot(0, color=mid_color, style=plot.style_circles, linewidth=3) // Checking if the condition xxx > spy > dxy is met condition = xxx > dxy and xxx > spy and dxy < 0 plotshape(condition,"Stacked Condition", shape.triangleup, location.bottom, color=color.white, transp=0) hline(0.5) hline(-0.5)
Opening Range & Prior Day High/Low [Gorb]
https://www.tradingview.com/script/xNKGE5KR-Opening-Range-Prior-Day-High-Low-Gorb/
GorbAlgo
https://www.tradingview.com/u/GorbAlgo/
15
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/ // © GorbAlgo //@version=5 indicator("Opening Range & Prior Day High/Low [Gorb]", shorttitle="ORB & PDH/L [Gorb]", overlay=true) // Opening Range Break Configuration Settings // Group: Customize opening range and trading session time to users preferances _ORB = "Opening Range Break Settings" ORBrange = input.session(title='Opening Range', defval='0930-0945', group=_ORB) ORBextend = input.session(title='Extend Range Lines', defval='0930-1600', group=_ORB) // Opening Range Break Color Style Settings // Group: Customize opening range colors to meet users needs _ORBcolors = "Opening Range Colors" showORB = input(title='Enable Opening Range Box', defval=true, inline='ORB top', group=_ORBcolors) BorderColor = input(color.new(color.purple, 40), 'Border', inline='ORB bottom', group=_ORBcolors) ShadeColor = input(color.new(color.white, 90), 'Background', inline='ORB bottom', group=_ORBcolors) linesWidth = input.int(1, 'Width', minval=1, maxval=4, inline='ORB bottom', group=_ORBcolors) // Check if the current time is within the defined sessions inSession = not na(time(timeframe.period, ORBrange)) inExtend = not na(time(timeframe.period, ORBextend)) // Initialize variables to store indices and price levels for ORB var int orbRangeStartIndex = na var int orbExtendEndIndex = na var float orbExtendEndTime = na var orb_low = 0.0 var orb_high = 0.0 var box orbBox = na var bool isOrbBoxCreated = false // Calculate and draw the ORB box at session start if showORB and inSession and not inSession[1] orbRangeStartIndex := bar_index orb_low := low orb_high := high if inExtend orbExtendEndIndex := bar_index // Create the ORB box and set its properties if showORB and inSession and not inSession[1] orbBox := box.new(left=orbRangeStartIndex, top=orb_high, right=orbExtendEndIndex, bottom=orb_low, border_color=BorderColor, border_width=linesWidth) box.set_bgcolor(orbBox, ShadeColor) isOrbBoxCreated := true // Update ORB high and low within the session if inSession if high > orb_high orb_high := high if isOrbBoxCreated box.set_top(orbBox, orb_high) if low < orb_low orb_low := low if isOrbBoxCreated box.set_bottom(orbBox, orb_low) // Extend the ORB box to the end of the extend session if inExtend and isOrbBoxCreated // Find the bar index for the end of the ORBextend session if na(orbExtendEndIndex) or time > orbExtendEndIndex orbExtendEndIndex := bar_index if time[1] < orbExtendEndTime and time >= orbExtendEndTime orbExtendEndIndex := bar_index // Set the right edge of the box to the end index of the ORBextend session box.set_right(orbBox, orbExtendEndIndex) // End of Opening Range Break code /// Starting Previous Day's High/Low // Previous Day's High/Low Settings // Group: Allows users to customize how they want to display the high/low levels from the previous trading day. _PDHLGrp = "Previous Day High/lows" showPreviousDayHigh = input.bool(true, title='Enable PDH', inline='PD top', group= _PDHLGrp) showPreviousDayLow = input.bool(true, title='Enable PDL', inline='PD top', group= _PDHLGrp) colorPDH = input(color.new(color.green, 0), title='PDH Color', inline='PD bottom', group= _PDHLGrp) colorPDL = input(color.new(color.red, 0), title='PDL Color', inline='PD bottom', group= _PDHLGrp) // Initializing lines and variables to store previous day's high and low prices. var line highLinePreviousDay = na var line lowLinePreviousDay = na var float highPreviousDay = na var float lowPreviousDay = na // This block calculates the previous day's high and low by fetching data from the daily timeframe. highPreviousDay := request.security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_on) lowPreviousDay := request.security(syminfo.tickerid, 'D', low[1], lookahead=barmerge.lookahead_on) // Adjusting Line Extensions and Creating New Lines if session.isfirstbar line.set_extend(highLinePreviousDay, extend.none) line.set_extend(lowLinePreviousDay, extend.none) if timeframe.isintraday if showPreviousDayHigh highLinePreviousDay := line.new(bar_index, highPreviousDay, bar_index, highPreviousDay, color=colorPDH, style=line.style_solid, width=1) if showPreviousDayLow lowLinePreviousDay := line.new(bar_index, lowPreviousDay, bar_index, lowPreviousDay, color=colorPDL, style=line.style_solid, width=1) // Setting the End Point of the High and Low Lines line.set_x2(highLinePreviousDay, bar_index) line.set_x2(lowLinePreviousDay, bar_index) // End of indicator script
SMA SIGNALS
https://www.tradingview.com/script/lgs9kDUf-SMA-SIGNALS/
AbrahamAlgo
https://www.tradingview.com/u/AbrahamAlgo/
26
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/ // © AbrahamAlgo //@version=5 indicator("SMA Signals",overlay = true,timeframe = "") sma1_input = input(20,"SMA 1") sma2_input = input(40,"SMA 2") sma1= ta.sma(close,sma1_input) sma2= ta.sma(close,sma2_input) long = ta.crossunder(sma2, sma1) short = ta.crossover(sma2, sma1) plotshape(long , title = "long1" , text = 'LONG', style = shape.labelup, location = location.belowbar, color= color.rgb(0, 102, 3), textcolor = color.white, size = size.tiny) plotshape(short , title = "short1" , text = 'SHORT', style = shape.labeldown, location = location.abovebar, color= color.rgb(150, 0, 0), textcolor = color.white, size = size.tiny) alertcondition(long,title = "LONG", message = "OPEN LONG") alertcondition(short,title = "SHORT", message = "OPEN SHORT") // plot(sma1,color = color.rgb(82, 206, 255)) // plot(sma2,color = color.rgb(94, 82, 255))
Option Buying Pivot and SMA 3 Pivot crossover
https://www.tradingview.com/script/KyKZ5j8b-Option-Buying-Pivot-and-SMA-3-Pivot-crossover/
Sabarijegan
https://www.tradingview.com/u/Sabarijegan/
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/ // © Sabarijegan //@version=5 indicator("Option Buying Pivot and SMA 3 Pivot crossover", overlay=true) // Calculate Current candle Pivot point currentCandlePivot = (high[1] + low[1] + close[1]) / 3 // Calculate Current candle True Range prevHighLowDiff = high[1] - low[1] prevHighCloseDiff = high[1] - close[2] prevLowCloseDiff = low[1] - close[2] currentCandleTrueRange = math.max(prevHighLowDiff, math.max(prevHighCloseDiff, prevLowCloseDiff)) // Calculate Current candle Down Side stop-loss and Up Side stop-loss PutValue = currentCandlePivot + currentCandleTrueRange CallValue = currentCandlePivot - currentCandleTrueRange // Calculate Simple Moving Average of Pivot Point smaPivot = ta.sma(currentCandlePivot, 3) // Long Entry Logic longEntry = currentCandlePivot > smaPivot bgcolor(longEntry ? color.new(color.green, 90) : na, title="Long") // Short Entry Logic shortEntry = currentCandlePivot < smaPivot bgcolor(shortEntry ? color.new(color.red, 90) : na, title="Short") // Win Logic winLong = close > CallValue and longEntry winShort = close < PutValue and shortEntry bgcolor(winLong ? color.new(color.green, 90) : na, title="Win Long") bgcolor(winShort ? color.new(color.green, 90) : na, title="Win Short") // Loss Logic lossLong = close < CallValue and longEntry lossShort = close > PutValue and shortEntry bgcolor(lossLong ? color.new(color.red, 90) : na, title="Loss Long") bgcolor(lossShort ? color.new(color.red, 90) : na, title="Loss Short") // Plotting Entry Labels and Stop Loss Levels plotshape(series=longEntry, title="Buy Call", color=color.green, style=shape.labeldown, location=location.belowbar, text="Buy Call") plotshape(series=shortEntry, title="Buy Put", color=color.red, style=shape.labelup, location=location.abovebar, text="Buy Put") // Plotting Win and Loss Labels plotshape(series=winLong, title="Win Call", color=color.green, style=shape.labelup, location=location.abovebar, text="Win Call") plotshape(series=winShort, title="Win Put", color=color.green, style=shape.labeldown, location=location.belowbar, text="Win Put") plotshape(series=lossLong, title="Loss Call", color=color.red, style=shape.labelup, location=location.abovebar, text="Loss Call") plotshape(series=lossShort, title="Loss Put", color=color.red, style=shape.labeldown, location=location.belowbar, text="Loss Put") // Plotting Pivot Point, SMA, Call, and Put Values plot(currentCandlePivot, color=color.blue, title="Pivot Point") plot(smaPivot, color=color.orange, title="SMA of Pivot") plot(CallValue, color=color.green, title="Call Value") plot(PutValue, color=color.red, title="Put Value")
Z-Score
https://www.tradingview.com/script/K6UUM81t-Z-Score/
sosacur01
https://www.tradingview.com/u/sosacur01/
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/ // © sosacur01 //@version=5 indicator(title="Z-Score", overlay = true) //----------------------------------------- //Z-SCORE INPUTS z_score_signal = input.bool(title='ON/ Signal Z-Score at threshold (or OFF/ Signal Z-Score at Pullback from threshold)?', defval=false, group = "Z-Score Inputs") z_score_trigger = input.float(defval=1, group="Z-Score Inputs", title="Z-Score", minval=0, maxval=4, step=0.5, tooltip="Z-Score Signal") averageType_z = input.string(defval="SMA", group="Z-Score Inputs", title="MA Type", options=["SMA", "EMA", "WMA", "HMA", "RMA", "SWMA", "ALMA", "VWMA", "VWAP"]) averageLength_z = input.int(defval=20, group="Z-Score Inputs", title="Length", minval=0) averageSource_z = input(close, title="Source", group="Z-Score Inputs") //MA TYPE MovAvgType_z(averageType_z, averageSource_z, averageLength_z) => switch str.upper(averageType_z) "SMA" => ta.sma(averageSource_z, averageLength_z) "EMA" => ta.ema(averageSource_z, averageLength_z) "WMA" => ta.wma(averageSource_z, averageLength_z) "HMA" => ta.hma(averageSource_z, averageLength_z) "RMA" => ta.rma(averageSource_z, averageLength_z) "SWMA" => ta.swma(averageSource_z) "ALMA" => ta.alma(averageSource_z, averageLength_z, 0.85, 6) "VWMA" => ta.vwma(averageSource_z, averageLength_z) "VWAP" => ta.vwap(averageSource_z) => runtime.error("Moving average type '" + averageType_z + "' not found!"), na //Z-SCORE VALUES MA = MovAvgType_z(averageType_z, averageSource_z, averageLength_z) dev = ta.stdev(averageSource_z, averageLength_z) z_score = (close - MA)/dev //Z-SCORE CONDITIONS long_z = (z_score_signal ? z_score < - z_score_trigger : ta.crossover(z_score, - z_score_trigger)) short_z = (z_score_signal ? z_score > z_score_trigger : ta.crossunder(z_score, z_score_trigger)) //PLOT-Z-SCORE bgcolor(short_z ? color.new(color.red, 80) : long_z ? color.new(color.green, 80) : na, title="Z-Score Signal") //Z-Score Table var table myTable = table.new(position.bottom_right, 1, 8, border_width = 1) if barstate.islast text1 = "Moving Average Type\n" + str.tostring(averageType_z) text2 = "Moving Average Length\n" + str.tostring(averageLength_z) text3 = "Moving Average\n" + str.tostring(MA) text4 = "Standard Deviation\n" + str.tostring(dev) text5 = "Price\n" + str.tostring(close) text6 = "Z-score\n" + str.tostring(z_score) table.cell(myTable, 0, 1, text=text1, bgcolor = color.black, text_color = color.white) table.cell(myTable, 0, 2, text=text2, bgcolor = color.black, text_color = color.white) table.cell(myTable, 0, 3, text=text3, bgcolor = color.black, text_color = color.white) table.cell(myTable, 0, 4, text=text4, bgcolor = color.black, text_color = color.white) table.cell(myTable, 0, 5, text=text5, bgcolor = color.black, text_color = color.white) table.cell(myTable, 0, 6, text=text6, bgcolor = color.black, text_color = color.white)
Learning Understanding ta.change
https://www.tradingview.com/script/2oac2AZj-Learning-Understanding-ta-change/
TBAjustTBA
https://www.tradingview.com/u/TBAjustTBA/
15
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/ // © TBAjustTBA //First script I have published. Constructive criticism is welcome. // I hope this may be helpful to you. // Initially, I did this for myself as I was getting some odd results from the ta.change function. Turns out it was my error LOL. What a surprise! // Typical syntax: ta.change(source, value) // value doesn't need to be included. If it isn't, it will only calculate the change between the last and current value. // Conclusion. ta.change simply calculates the difference between a previous value/candle and the latest value/candle current value in that series. Positive number states that the recent is higher. // Bonus :-) Function on line 34 outputs the changes in a positive figure (so as to be able to sum the changes/volatility of the series of values) //@version=5 indicator("Learning ta.change") source = input(close) // input(close) is used to make it possible to change the value from the default 'close' // to another another value/series, e.g., high, low, or another indicator value) changeLength = input.int(1, 'The Length for the ta.change calculation. To see how the length math works.', tooltip = 'default is 1 so you can see the effect of looking back only one candle') changeLenthForManualCalculation = input.int(1, 'Length for the manually calculated change. In other workds, When doing the manual calculation, how many candles back should the change be calculated from?.') changeForNoLengthInFunctionSoOnlyComparingToLastCandle =ta.change(source) //This is Just to see that without a length, it will just assume you want to get the change between the last value and the current value in the series. changeWithLengthCalculation =ta.change(source, changeLength) // Manual calculation to compare to the ta.change function. Length variable is used. manualChangeCalculation = source - source[changeLength] // Test manual calculation of change to compare to ta.change. This outputs positive figures only. Good for getting a sum of the changes. float changeInPositiveFiguresOnly = if source[changeLenthForManualCalculation] < source == true source - source[changeLenthForManualCalculation] else source[changeLenthForManualCalculation] - source plot(changeForNoLengthInFunctionSoOnlyComparingToLastCandle, 'changeForNoLengthInFunctionSoOnlyComparingToLastCandle', color.teal) plot(changeWithLengthCalculation, 'changeWithLengthCalculation', color.green) plot(manualChangeCalculation, 'Plot of changes when calculated without using the ta.change function', color.blue, 3, plot.style_circles) // because this is in order of the expected syntax, it is not necessary to use title = and linewidth = . plot(changeInPositiveFiguresOnly, 'changeInPositiveFiguresOnly', color.fuchsia) hline(0, '0-Line for reference')
Market Sessions
https://www.tradingview.com/script/JlbS3Kah/
JVibez
https://www.tradingview.com/u/JVibez/
11
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/ // © JVibez //@version=5 indicator("Market Sessions)", overlay = true, max_bars_back = 400, max_boxes_count = 300, max_labels_count = 300, max_lines_count = 54) import PineCoders/Time/3 Yearnow = year(timenow) Monthnow = month(timenow) Daynow = dayofmonth(timenow) _timezone = "UTC" // Forex Sessions Asia_start = timestamp(_timezone, Yearnow, Monthnow,Daynow - 1, 23, 00, 00) Asia_end = timestamp(_timezone, Yearnow, Monthnow,Daynow, 8, 00, 00) Euro_start = timestamp(_timezone, Yearnow, Monthnow, Daynow, 08, 00, 00) Euro_end = timestamp(_timezone, Yearnow, Monthnow, Daynow, 17, 00, 00) USA_start = timestamp(_timezone, Yearnow, Monthnow, Daynow, 13, 00, 00) USA_end = timestamp(_timezone, Yearnow, Monthnow, Daynow, 22, 00, 00) // Stock Sessions _Asia_start = timestamp(_timezone, Yearnow, Monthnow,Daynow, 00, 00, 00) _Asia_end = timestamp(_timezone, Yearnow, Monthnow,Daynow, 8, 00, 00) _Euro_start = timestamp(_timezone, Yearnow, Monthnow,Daynow, 9, 00, 00) _Euro_end = timestamp(_timezone, Yearnow, Monthnow,Daynow, 17, 30, 00) _USA_start = timestamp(_timezone, Yearnow, Monthnow,Daynow, 15, 30, 00) _USA_end = timestamp(_timezone, Yearnow, Monthnow,Daynow, 22, 00, 00) start_day = timestamp(_timezone, Yearnow, Monthnow,Daynow, 00, 00, 00) end_day = timestamp(_timezone, Yearnow, Monthnow,Daynow, 23, 59, 59) // Get Diffrent Sessions Asia_sess = time >= Asia_start and time < Asia_end Euro_sess = time >= Euro_start and time < Euro_end USA_sess = time >= USA_start and time < USA_end EuUS_sess = time >= USA_start and time < Euro_end _Asia_sess = time >= _Asia_start and time < _Asia_end _Euro_sess = time >= _Euro_start and time < _Euro_end _USA_sess = time >= _USA_start and time < _USA_end UsAs_gap = time >= USA_end and time < Asia_start day_sess = time >= start_day and time < end_day t_mrktsess = "Market Session/Daily HiLO" t_DLHiLo = "Daily High/Low Inputs" // Plot Inputs p_sess = input.bool(true, "Sessions","","1",t_mrktsess) p_bckgr = input.bool(true, "Background","","1",t_mrktsess) bcktest = input.bool(false, "Shows Past", "Shows the Past Sessions for Backtest", "1", t_mrktsess) and day_sess == false // i_stok = input.string("No Text", "Dashboard Position", ["No Text", "Text"], "", "4", t_mrktsess) b_stok = input.bool(true, "Stock Open Close","","4",t_mrktsess) // Dashboard Inputs i_dashpos = input.string("Top Right", "Dashboard Position", ["Bottom Right", "Bottom Left", "Top Right", "Top Left"], "", "2", t_mrktsess) draw_testables = input.bool(true,"Dashboard","","2", t_mrktsess) // Daily HiLo Inputs i_textpos = input.string("Right", "Text Position", ["Right", "Middle", "Left"], "", "3", t_DLHiLo) p_DHLO = input.bool(true, "Last Day High/Low","","3",t_DLHiLo) colhigh = input.color(color.rgb(216, 216, 216), "Daily High", "", "3.1", t_DLHiLo) collow = input.color(color.rgb(216, 216, 216), "Daily Low", "", "3.1", t_DLHiLo) Dhigh = request.security(syminfo.tickerid, "D", high) Dlow = request.security(syminfo.tickerid, "D", low) ASST_EUFX = "0000-0800:123456" EUFX_EUST = "0800-0900:123456" EUST_USFX = "0900-1300:123456" USFX_USST = "1300-1530:123456" USST_EUST = "1530-1730:123456" EUST_USST = "1730-2200:123456" USAS_gap = "2200-2300:123456" fun_session(session) => sess_true = not na(time(timeframe.period, session, "UCT")) [sess_true] [_ASST_EUFX] = fun_session(ASST_EUFX) [_EUFX_EUST] = fun_session(EUFX_EUST) [_EUST_USFX] = fun_session(EUST_USFX) [_USFX_USST] = fun_session(USFX_USST) [_USST_EUST] = fun_session(USST_EUST) [_EUST_USST] = fun_session(EUST_USST) [_USAS_gap] = fun_session(USAS_gap) // Stock Open _open = time == _Asia_start or time == _Euro_start or time == _USA_start _close = time == _Asia_end or time == _Euro_end or time == _USA_end _20EMA = input.int(20, "1 EMA", inline = "1") _50EMA = input.int(50, "2 EMA", inline = "2") _200EMA = input.int(200, "3 EMA", inline = "3") _20col = input.color(color.rgb(150, 211, 135), "", inline = "1") _50col = input.color(color.rgb(221, 156, 119), "", inline = "2") _200col = input.color(color.rgb(108, 201, 224), "", inline = "3") b20EMA = input.bool(true, "", inline = "1") b50EMA = input.bool(true, "", inline = "2") b200EMA = input.bool(true, "", inline = "3") _20_EMA = ta.ema(close, _20EMA) _50_EMA = ta.ema(close, _50EMA) _200_EMA = ta.ema(close, _200EMA) frame_sess = timeframe.isminutes and timeframe.multiplier < 61 ? true : false frame_sess1 = timeframe.isminutes and timeframe.multiplier < 59 ? true : false daysinc = ta.barssince(day_sess[1] == false and day_sess) asiasinc = ta.barssince(Asia_sess[1] == false and Asia_sess) var label linetxt = na var label linetxt2 = na _opentrue = false _closetrue = false txtpos = switch i_textpos "Right" => bar_index "Middle" => bar_index - (asiasinc / 2) "Left" => bar_index - asiasinc s_stok = switch i_stok "Text" => true "No Text" => false if day_sess and barstate.islastconfirmedhistory and p_DHLO line.new(bar_index - asiasinc, Dhigh, bar_index + 1, Dhigh, color = colhigh) line.new(bar_index - asiasinc, Dlow, bar_index + 1, Dlow, color = collow) label.delete(linetxt) linetxt := label.new(txtpos, Dhigh, text = "Last Day High", textcolor = colhigh, style = label.style_none) label.delete(linetxt2) linetxt2 := label.new(txtpos, Dlow, text = "Last Day Low", textcolor = collow, style = label.style_none) if _open and b_stok and frame_sess1 and p_sess line.new(bar_index, high, bar_index, low, extend = extend.both, color = color.new(#ffffff, 15), style = line.style_dotted , width = 1) if _close and b_stok and frame_sess1 and p_sess line.new(bar_index, high, bar_index, low, extend = extend.both, color = color.new(#706f6f, 0), style = line.style_dotted , width = 1) if bcktest if _ASST_EUFX[1] == false and _ASST_EUFX or _EUST_USFX[1] == false and _EUST_USFX or _USST_EUST[1] == false and _USST_EUST and frame_sess1 line.new(bar_index, high, bar_index, low, extend = extend.both, color = color.new(#ffffff, 15), style = line.style_dotted , width = 1) _opentrue := true if _ASST_EUFX[1] and _ASST_EUFX == false or _USST_EUST[1] and _USST_EUST == false or _USAS_gap[1] == false and _USAS_gap and frame_sess1 line.new(bar_index, high, bar_index, low, extend = extend.both, color = color.new(#706f6f, 0), style = line.style_dotted , width = 1) _closetrue := true var int pl_hold = na var int svpl_hold = na if time == Asia_start pl_hold := 1 if not na(pl_hold) pl_hold := pl_hold + 1 if time == _Asia_start svpl_hold := pl_hold[1] / 2 pl_hold := na plotshape(_USAS_gap) plot(b20EMA ? _20_EMA : na, "1 EMA", _20col, display = display.pane) plot(b50EMA ? _50_EMA : na, "2 EMA", _50col, display = display.pane) plot(b200EMA ? _200_EMA : na, "3 EMA", _200col, display = display.pane) plot(Dhigh, color=color.new(#bc3a3a, 0), display = display.status_line) plot(Dlow, color=color.new(#5aa53f, 0), display = display.status_line) d_sess = p_sess ? display.pane : display.data_window plotshape(frame_sess ? time == Asia_start : na, "Sydney/Tokyo Sesssion", color = na, text = "Sydney/Tokyo" , location = location.bottom, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess ? time == Euro_start : na, "London Sesssion", color = na, text = "London", location = location.bottom, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess ? time == USA_start : na, "NewYork Sesssion", color = na, text = "NewYork", location = location.bottom, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and s_stok ? time == _Asia_start : na, "Open Stock Asia", color = na, offset = svpl_hold, text = "Open" , location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and s_stok ? time == _Euro_start : na, "Open Stock Euro", color = na, offset = svpl_hold, text = "Open", location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and s_stok ? time == _USA_start : na, "Open Stock USA", color = na, offset = svpl_hold, text = "Open", location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and s_stok ? time == _Asia_end : na, "Close Stock Asia", color = na, offset = -svpl_hold, text = "Close" , location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and s_stok ? time == _Euro_end : na, "Close Stock Euro", color = na, offset = -svpl_hold, text = "Close", location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and s_stok ? time == _USA_end : na, "Close Stock USA", color = na, offset = -svpl_hold, text = "Close", location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess ? time >= Asia_start and time < _Asia_start : na, "Asia Forex to Asia Stock", shape.square, location.bottom, color.rgb(156, 237, 35, 55), display = d_sess) plotshape(frame_sess ? time >= _Asia_start and time < Euro_start : na, "Asia Stock to Euro Forex", shape.square, location.bottom, color.rgb(244, 236, 0, 55), display = d_sess) plotshape(frame_sess ? time >= Euro_start and time < _Euro_start : na, "Euro Forex To Euro Stock", shape.square, location.bottom, color.rgb(255, 191, 0, 55), display = d_sess) plotshape(frame_sess ? time >= _Euro_start and time < USA_start : na, "Euro Stock to USA Forex", shape.square, location.bottom, color.rgb(255, 140, 0, 55), display = d_sess) plotshape(frame_sess ? time >= USA_start and time < _USA_start : na, "USA Forex to USA Stock", shape.square, location.bottom, color.rgb(230, 87, 4, 55), display = d_sess) plotshape(frame_sess ? time >= _USA_start and time < _Euro_end : na, "USA Forex to Euro Stock", shape.square, location.bottom, color.rgb(255, 0, 0, 55), display = d_sess) plotshape(frame_sess ? time >= _Euro_end and time < _USA_end : na, "Euro Stock to USA Stock", shape.square, location.bottom, color.rgb(236, 63, 5, 55), display = d_sess) plotshape(Asia_sess, "Asia Session", display = display.data_window) plotshape(Euro_sess, "Euro Session", display = display.data_window) plotshape(USA_sess, "USA Session", display = display.data_window) bgcolor(frame_sess and p_sess and _USAS_gap ? color.rgb(255, 255, 255, 95) : na) bgcolor(frame_sess and p_sess and p_bckgr and Asia_sess ? color.rgb(255, 255, 255, 98) : na) bgcolor(frame_sess and p_sess and p_bckgr and (Euro_sess or _Euro_sess) ? color.rgb(255, 255, 255, 97) : na) bgcolor(frame_sess and p_sess and p_bckgr and USA_sess ? color.rgb(255, 255, 255, 98) : na) plotshape(frame_sess1 and bcktest and _opentrue, "Open Stock Asia", color = na, offset = svpl_hold, text = "Open" , location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(frame_sess1 and bcktest and _closetrue, "Close Stock Asia", color = na, offset = -svpl_hold, text = "Close" , location = location.top, textcolor = color.rgb(255, 255, 255, 24), display = d_sess) plotshape(bcktest ? _ASST_EUFX[1] == false and _ASST_EUFX : na, "Sydney/Tokyo Sesssion", color = na, text = "Sydney/Tokyo" , location = location.bottom, textcolor = color.rgb(255, 255, 255, 24), display = display.pane, show_last = 900) plotshape(bcktest ? _EUFX_EUST[1] == false and _EUFX_EUST : na, "London Sesssion", color = na, text = "London", location = location.bottom, textcolor = color.rgb(255, 255, 255, 24), display = display.pane, show_last = 900) plotshape(bcktest ? _USST_EUST[1] == false and _USST_EUST : na, "NewYork Sesssion", color = na, text = "NewYork", location = location.bottom, textcolor = color.rgb(255, 255, 255, 24), display = display.pane, show_last = 900) plotshape(bcktest ? _ASST_EUFX : na, "Asia Stock to Euro Forex", shape.square, location.bottom, color.rgb(244, 236, 0, 55), display = display.pane, show_last = 900) plotshape(bcktest ?_EUFX_EUST : na, "Euro Forex To Euro Stock", shape.square, location.bottom, color.rgb(255, 191, 0, 55), display = display.pane, show_last = 900) plotshape(bcktest ? _EUST_USFX : na, "Euro Stock to USA Forex", shape.square, location.bottom, color.rgb(255, 140, 0, 55), display = display.pane, show_last = 900) plotshape(bcktest ? _USFX_USST : na, "USA Forex to USA Stock", shape.square, location.bottom, color.rgb(230, 87, 4, 55), display = display.pane, show_last = 900) plotshape(bcktest ? _USST_EUST : na, "USA Forex to Euro Stock", shape.square, location.bottom, color.rgb(255, 0, 0, 55), display = display.pane, show_last = 900) plotshape(bcktest ? _EUST_USST : na, "Euro Stock to USA Stock", shape.square, location.bottom, color.rgb(236, 63, 5, 55), display = display.pane, show_last = 900) bgcolor(bcktest and _USAS_gap ? color.rgb(255, 255, 255, 95) : na) fun_filltaCell(_table,_column,_row,_title,_value,_textpos,_bgcolor,_textcolor) => // Get Sell Function _celltext = _title + _value table.cell(_table,_column,_row,_celltext,text_halign=_textpos,bgcolor = _bgcolor,text_color = _textcolor) //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // prepare stats Tables tablespos = switch i_dashpos "Bottom Right" => position.bottom_right "Bottom Left" => position.bottom_left "Top Right" => position.top_right "Top Left" => position.top_left => position.top_right var tradetable = table.new(tablespos,2,15,color.new(#166aaf, 100),color.new(#49464d, 100),4,color.new(#49464d, 100),4) // Color Variables For Tables // raw Stats Tables if draw_testables if barstate.islastconfirmedhistory // Update Tables fun_filltaCell(tradetable,0,0, "Current Session","",text.align_center,color.new(#3497e8, 80),color.new(#f1f1f1, 0)) fun_filltaCell(tradetable,1,0, Asia_sess ? "Sydney/Tokyo" : time >= Euro_start and time < USA_start ? "London" : time >= USA_start and time < _Euro_end ? "London/NewYork" : time >= _Euro_end and time < _USA_end ? "NewYork" : _USAS_gap ? "Low Volume Zone" : na, "",text.align_center, Asia_sess or Euro_sess or USA_sess ? color.new(#20adc0, 80) : _USAS_gap ? color.rgb(195, 195, 195, 64) : color.new(#20adc0, 80) ,color.new(#f1f1f1, 0)) fun_filltaCell(tradetable,0,1,"Next Session","",text.align_center,color.new(#3497e8, 80),color.new(#f1f1f1, 0)) fun_filltaCell(tradetable,1,1, Asia_sess ? "London" : Euro_sess and not USA_sess ? "NewYork" : Euro_sess or _Euro_sess and USA_sess ? "Low Volume Zone" : USA_sess ? "Low Volume Zone" : _USAS_gap ? "Sydney/Tokyo" : na,"",text.align_center,color.new(#20adc0, 80),color.new(#f1f1f1, 0)) fun_filltaCell(tradetable,0,2,"Session Start in","",text.align_center,color.new(#3497e8, 80),color.new(#f1f1f1, 0)) fun_filltaCell(tradetable,1,2, str.format_time(Asia_sess ? Euro_start - timenow : Euro_sess and not USA_sess ? USA_start - timenow : Euro_sess and (USA_sess or _USA_sess) ? USA_end - timenow : _USAS_gap ? Asia_start - timenow : na, "HH:mm ", _timezone),"",text.align_center,color.new(#20adc0, 80),color.new(#f1f1f1, 0)) // fun_filltaCell(tradetable,1,3, str.format_time(week_sess, "dd:MM:yyyy", _timezone),"",text.align_center,color.new(#20adc0, 80),color.new(#f1f1f1, 0))
ES S/R Levels
https://www.tradingview.com/script/IVliYK4F-ES-S-R-Levels/
dclewis221
https://www.tradingview.com/u/dclewis221/
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/ // © daniel49193 //@version=5 indicator(title="ES SR Levels", overlay=true) // Define your price levels input supportLevels = input.string("4240-45 (major), 4224, 4220 (major), 4206 (major), 4195, 4185 (major), 4175",title="Support Levels") resistanceLevels = input.string("4260, 4267 (major), 4275, 4283, 4289, 4297-4300 (major), 4310-15, 4325-30", title="Resistance Levels") res_col = input(defval = color.new(color.red, 50), title = "Resistance Color", group = "Colors 🟡🟢🟣") sup_col = input(defval = color.new(color.lime, 50), title = "Support Color", group = "Colors 🟡🟢🟣") size_labels = input.string(title='Label font size', defval=size.normal, options=[size.large, size.normal, size.small]) color_labels = input(title='Label font color', defval=color.white) label_position = input.int(title='Label Position', defval=20, minval=0, maxval=50, tooltip='When increasing number, labels move right') IsHourlyTF() => timeframe.in_seconds() >= timeframe.in_seconds("60") // Function to check if a level is a range isRange(level) => str.contains(level, "-") // Function to extract the range values getRangeValues(level) => removeMajor = str.replace(level, "(major)", "") removeSpace = str.replace(removeMajor, " ", "") values = str.split(removeSpace, "-") if array.size(values) == 2 lowValStr = array.get(values, 0) highValStr = array.get(values, 1) if str.length(highValStr) == 2 lowValArray = str.split(lowValStr,'') highValPrice = array.get(lowValArray,0)+array.get(lowValArray,1)+highValStr lowVal = str.tonumber(lowValStr) highVal = str.tonumber(highValPrice) [lowVal, highVal] else if str.length(highValStr) == 4 lowVal = str.tonumber(lowValStr) highVal = str.tonumber(highValStr) [lowVal, highVal] else [0, 0] // Split the inputLevels string into individual levels var slevels_input = str.split(supportLevels, ", ") var rlevels_input = str.split(resistanceLevels, ", ") var s_boxes = array.new_box() var s_labels = array.new_label() var s_lines = array.new_line() var r_boxes = array.new_box() var r_labels = array.new_label() var r_lines = array.new_line() // Function to create lines from user-defined price levels f_setSLevels(_input_array,_input_boxes,_input_labels,_input_lines,_color) => for i = 0 to array.size(_input_array) - 1 price_level = str.replace(array.get(_input_array, i),"(major)","") isMajor = str.contains(array.get(_input_array, i), "(major)") if isRange(price_level) [lowVal, highVal] = getRangeValues(price_level) array.push(_input_boxes, box.new(left=bar_index, bottom=lowVal, right=bar_index + 1, top=highVal, bgcolor=_color, border_width=1, border_color=_color, extend=extend.both)) array.push(_input_labels, label.new(bar_index + label_position, highVal, isMajor ? str.tostring(lowVal)+"-"+str.tostring(highVal)+" (Major)" : str.tostring(lowVal)+"-"+str.tostring(highVal), style=label.style_none, textcolor=color_labels, size=size_labels)) else price = str.tonumber(price_level) array.push(_input_lines, line.new(x1=bar_index, y1=price, x2=bar_index+1, y2=price, color=_color, width=1, extend=extend.both)) array.push(_input_labels, label.new(bar_index + label_position, price, isMajor ? str.tostring(price)+" (Major)" : str.tostring(price), style=label.style_none, textcolor=color_labels, size=size_labels)) f_clearLabels(_array) => if array.size(_array) > 0 for i = 0 to array.size(_array) - 1 label.delete(array.shift(_array)) if barstate.islast f_clearLabels(s_labels) f_clearLabels(r_labels) f_setSLevels(slevels_input,s_boxes,s_labels,s_lines,sup_col) f_setSLevels(rlevels_input,r_boxes,r_labels,r_lines,res_col)
Pivottrend
https://www.tradingview.com/script/1f8eDF3n-Pivottrend/
mickes
https://www.tradingview.com/u/mickes/
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/ // © mickes //@version=5 indicator("Pivottrend", overlay = true, max_labels_count = 500) _timeframe = input.timeframe("", "Timeframe") _leftLength = input.int(10, "Left length") _rightLength = input.int(3, "Right length") _showLabels = input.bool(true, "Show labels") _showPivots = input.bool(false, "Show pivots") _showMarketStructureShift = input.bool(true, "Show MSS", tooltip = "Shows a line when pivot high/low is broken and trend changes. Almost the same as a Market Structure Shift (MSS).") type Pivot float Price int Time type Extreme float Price int BarIndex _atr = ta.atr(14) pivot(pivotExtreme) => Pivot pivot = na if not na(pivotExtreme) pivot := Pivot.new(pivotExtreme, time[_rightLength]) pivot trend() => var trend = 0 pivotHigh = request.security(syminfo.tickerid, _timeframe, pivot(ta.pivothigh(high, _leftLength, _rightLength)), lookahead = barmerge.lookahead_on) pivotLow = request.security(syminfo.tickerid, _timeframe, pivot(ta.pivotlow(low, _leftLength, _rightLength)), lookahead = barmerge.lookahead_on) var Pivot latestPivotHigh = na var Pivot latestPivotLow = na if not na(pivotHigh) latestPivotHigh := pivotHigh if _showPivots i = 0, extreme = Extreme.new(0) while true if time[i] < pivotHigh.Time break if high[i] > extreme.Price extreme.Price := high[i] extreme.BarIndex := bar_index - i i += 1 label.new(extreme.BarIndex, extreme.Price, "▲", color = color.new(color.green, 70)) if not na(pivotLow) latestPivotLow := pivotLow if _showPivots i = 0, extreme = Extreme.new(2147483647) while true if time[i] < pivotLow.Time break if low[i] < extreme.Price extreme.Price := low[i] extreme.BarIndex := bar_index - i i += 1 label.new(extreme.BarIndex, extreme.Price, "▼", style = label.style_label_up, color = color.new(color.red, 70)) if (trend == 0 or trend == 1) and not na(latestPivotLow) if high <= latestPivotLow.Price and high[1] > latestPivotLow.Price trend := -1 if _showMarketStructureShift line.new(latestPivotLow.Time, latestPivotLow.Price, time, latestPivotLow.Price, color = color.red, xloc = xloc.bar_time) if (trend == 0 or trend == -1) and not na(latestPivotHigh) if low >= latestPivotHigh.Price and low[1] < latestPivotHigh.Price trend := 1 if _showMarketStructureShift line.new(latestPivotHigh.Time, latestPivotHigh.Price, time, latestPivotHigh.Price, color = color.green, xloc = xloc.bar_time) trend trend = trend() bull = trend == 1 ? hl2 - (_atr * 2) : na bear = trend == -1 ? hl2 + (_atr * 2) : na bullStart = not na(bull) and na(bull[1]) bearStart = not na(bear) and na(bear[1]) middlePlot = plot(hl2, "Middle", na) bullPlot = plot(bull, "Bull", not na(bull) ? color.green : na, style = plot.style_linebr, linewidth = 2) bearPlot = plot(bear, "Bear", not na(bear) ? color.red : na, style = plot.style_linebr, linewidth = 2) fill(middlePlot, bullPlot, color.new(color.green, 90)) fill(middlePlot, bearPlot, color.new(color.red, 90)) plotshape(bullStart ? bull : na, title="Uptrend Begins", location = location.absolute, style = shape.circle, size = size.tiny, color = color.green) plotshape(bearStart ? bear : na, title="Downtrend Begins", location = location.absolute, style = shape.circle, size = size.tiny, color = color.red) if bullStart alert("Trend turned bullish", alert.freq_all) if _showLabels label.new(bar_index, bull, "Buy", style = label.style_label_up, textcolor = color.white, color = color.green) if bearStart alert("Trend turned bearish", alert.freq_all) if _showLabels label.new(bar_index, bear, "Sell", textcolor = color.white, color = color.red)
Watchlist Heatmap Plus
https://www.tradingview.com/script/pD7xfJck-Watchlist-Heatmap-Plus/
faiyaz7283
https://www.tradingview.com/u/faiyaz7283/
16
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/ // © faiyaz7283 //@version=5 indicator(title="Watchlist Heatmap Plus", shorttitle="WL-Plus", overlay=true) // ::Imports:: { import faiyaz7283/tools/10 as tools import faiyaz7283/printer/6 as prnt import faiyaz7283/multidata/7 as mltd // } // ::Inputs:: { var section00 = 'HEADER PREFIX' //---------------------: var headerPrefix = input.string(defval='', title='Header Prefix', tooltip='Customize this watchlist with a name prefix.', group=section00) var section01 = 'POSITION, SIZE & COLORS' //---------------------: var displayLoc = input.string(defval = position.top_right, title = 'Display Location', 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 = section01) var cellPad = input.int(defval = 1, title = 'Cell Spacing', minval = 0, maxval = 5, group = section01) var orientation = input.string(defval = 'horizontal', title = 'Orientation', options = ['horizontal', 'vertical'], group = section01) == 'vertical' ? false : true var grdUp = input.color(defval = #00FF00, title = '⬆ Max', inline = 'grdnt', group = section01) var grdNeutral = input.color(defval = #fff9c4, title = '⮕ Neutral', inline = 'grdnt', group = section01) var grdDown = input.color(defval = #FF0000, title = '⬇ Min', inline = 'grdnt', group = section01) var headerColor = input.color(defval = #ffcc80, title = 'Header:\tColor', inline = 'hdrCl', group = section01) var headerSize = input.string(defval=size.normal, title = 'Size', options = ['hide', size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline = 'hdrCl', group = section01) var headerAlign = input.string(defval=text.align_center, title = 'Align', options = [text.align_left, text.align_center, text.align_right], inline = 'hdrCl', group = section01) var pkSize = input.string(defval=size.auto, title = 'Primary Key:\tSize', options = [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline = 'pkCl', group = section01) var pkAlign = input.string(defval=text.align_center, title = 'Align', options = [text.align_left, text.align_center, text.align_right], inline = 'pkCl', group = section01) var pkOffset = input.string(defval='text', title = 'Primary Key:\tOffset Item', options = ['text', 'background'], inline = 'pkCl2', group = section01) == 'background' ? 'bg' : 'text' var pkOffsetColor = input.color(defval = #000000, title = 'Offset Color', inline = 'pkCl2', group = section01) var dkBgColor = input.color(defval = #666E8C1A, title = 'Data Key:\tBg', inline = 'dkCl', group = section01) var dkTextColor = input.color(defval = #ffffff, title = 'Text', inline = 'dkCl', group = section01) var dkSize = input.string(defval=size.auto, title = 'Size', options = [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline = 'dkCl', group = section01) var dkAlign = input.string(defval=text.align_center, title = 'Align', options = [text.align_left, text.align_center, text.align_right], inline = 'dkCl', group = section01) var dkOffset = input.string(defval='text', title = 'Data Key:\tOffset Item', options = ['text', 'background'], inline = 'dkCl2', group = section01) == 'background' ? 'bg' : 'text' var dkOffsetColor = input.color(defval = #000000, title = 'Offset Color', inline = 'dkCl2', group = section01) var textSize = input.string(defval=size.auto, title = 'Value:\tSize', options = [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], inline = 'valueCl', group = section01) var textAlign = input.string(defval=text.align_right, title = 'Align', options = [text.align_left, text.align_center, text.align_right], inline = 'valueCl', group = section01) var textOffset = input.string(defval='text', title = 'Value:\tOffset Item', options = ['text', 'background'], inline = 'valueCl2', group = section01) == 'background' ? 'bg' : 'text' var textOffsetColor = input.color(defval = #000000, title = 'Offset Color', inline = 'valueCl2', group = section01) var section02 = 'DATA DISPLAY' //----------------------------: var nthTip1 = 'N: nth candle\n\n- Nth 0 is current candle.\n- Nth 1 is previous candle.\n- Nth 2 is previous ' var nthTip = nthTip1 + '2nd candle in past.\n- Nth 3 is previous 3rd candle in past.\n ...' var nth = input.int(defval=0, title = 'History: Nth', minval=0, tooltip=nthTip, inline = 'tf', group = section02) var nthKey = nth > 0 ? (nth == 1 ? 'Previous ' : str.format('(Past {0}) ', tools.ordinal(nth))) : na var showOpen = input.bool(defval = true, title = 'Open', inline='dk', group = section02) var showHigh = input.bool(defval = true, title = 'High', inline='dk', group = section02) var showLow = input.bool(defval = true, title = 'Low', inline='dk', group = section02) var showClose = input.bool(defval = true, title = 'Close', inline='dk', group = section02) var showCloseP = input.bool(defval = true, title = 'Close%', inline='dk', group = section02) var showVol = input.bool(defval = true, title = 'Vol', inline='dk', group = section02) var showVolP = input.bool(defval = true, title = 'Vol%', inline='dk', group = section02) var dsplTip0 = 'Display Data Options:\n\n' var dsplTip1 = dsplTip0 + 'regular:\nReturns the standard value corresponding to the data key (e.g., open, high, low, close, volume).\n\n' var dsplTip2 = dsplTip1 + 'change:\nReturns the difference between two values.\n\n' var dsplTip3 = dsplTip2 + 'change percent:\nReturns the percentage difference between two values.\n\n' var dsplTip4 = dsplTip3 + 'equal to:\nReturns \'true\' if the two values are equal; otherwise, \'false\'.\n\n' var dsplTip5 = dsplTip4 + 'less than:\nReturns \'true\' if the first value is less than the second value; otherwise, \'false\'.\n\n' var dsplTip6 = dsplTip5 + 'less than or equal to:\nReturns \'true\' if the first value is less than or equal to the second value; otherwise, \'false\'.\n\n' var dsplTip7 = dsplTip6 + 'greater than:\nReturns \'true\' if the first value is greater than the second value; otherwise, \'false\'.\n\n' var dsplTip8 = dsplTip7 + 'greater than or equal to:\nReturns \'true\' if the first value is greater than or equal to the second value; otherwise, \'false\'.' var displayValues = input.string(defval ='regular', title = 'Display Data Type', options = ['regular', 'change', 'change percent', 'equal to', 'less than', 'less than or equal to', 'greater than', 'greater than or equal to'], inline='/', tooltip=dsplTip8, group = section02) var sortByKey = input.string(defval ='close', title = 'Sort By Key', options = ['open', 'high', 'low', 'close', 'volume'], inline = '-', group = section02) var sortByOrder = input.string(defval ='descending', title = 'Sort Order', options = ['descending', 'ascending'], inline = '-', group = section02) var asc = sortByOrder == 'ascending' ? true : false var section03 = 'CUSTOM TIMEFRAME' //--------------------------------: var tfNote0 = "M: Multiplier | U: Unit\n\nValid Multipliers per Unit:\n- Seconds, ONLY use 1, 5, 10, 15 or 30." var tfNote1 = tfNote0 + '\n- Minutes, 1 to 1439.\n- Days, 1 to 365.\n- Weeks, 1 to 52.\n- Months, 1 to 12.\n\n' var tfNote = tfNote1 + nthTip + '\n\nCheck box to display.' var tfMultiplier = input.int(defval = 1, title = 'M', minval = 1, maxval = 1439, inline = 'tf', group = section03) var tfUnits = input.timeframe(defval = 'Days', title = 'U', options = ['Seconds', 'Minutes', 'Days', 'Weeks', 'Months'], inline = 'tf', group = section03) var tfNth = input.int(defval=0, title = 'N', minval=0, inline = 'tf', group = section03) var customTf = input.bool(defval = false, title = 'Apply', tooltip = tfNote, inline = 'tf', group = section03) nthKey := customTf ? (tfNth > 0 ? (tfNth == 1 ? 'Previous ' : str.format('(Past {0}) ', tools.ordinal(tfNth))) : na) : nthKey var unit = switch tfUnits 'Seconds' => 'S' 'Minutes' => '' 'Days' => 'D' 'Weeks' => 'W' 'Months' => 'M' var tf = str.tostring(tfMultiplier) + unit var section04 = 'WATCHLIST SYMBOLS' //--------------------------------: var symbol01 = input.symbol(defval = '', title = '01. ', inline = 'r01', group = section04) var symbol02 = input.symbol(defval = '', title = '02. ', inline = 'r01', group = section04) var symbol03 = input.symbol(defval = '', title = '03. ', inline = 'r02', group = section04) var symbol04 = input.symbol(defval = '', title = '04. ', inline = 'r02', group = section04) var symbol05 = input.symbol(defval = '', title = '05. ', inline = 'r03', group = section04) var symbol06 = input.symbol(defval = '', title = '06. ', inline = 'r03', group = section04) var symbol07 = input.symbol(defval = '', title = '07. ', inline = 'r04', group = section04) var symbol08 = input.symbol(defval = '', title = '08. ', inline = 'r04', group = section04) var symbol09 = input.symbol(defval = '', title = '09. ', inline = 'r05', group = section04) var symbol10 = input.symbol(defval = '', title = '10. ', inline = 'r05', group = section04) var symbol11 = input.symbol(defval = '', title = '11. ', inline = 'r06', group = section04) var symbol12 = input.symbol(defval = '', title = '12. ', inline = 'r06', group = section04) var symbol13 = input.symbol(defval = '', title = '13. ', inline = 'r07', group = section04) var symbol14 = input.symbol(defval = '', title = '14. ', inline = 'r07', group = section04) var symbol15 = input.symbol(defval = '', title = '15. ', inline = 'r08', group = section04) var symbol16 = input.symbol(defval = '', title = '16. ', inline = 'r08', group = section04) var symbol17 = input.symbol(defval = '', title = '17. ', inline = 'r09', group = section04) var symbol18 = input.symbol(defval = '', title = '18. ', inline = 'r09', group = section04) var symbol19 = input.symbol(defval = '', title = '19. ', inline = 'r10', group = section04) var symbol20 = input.symbol(defval = '', title = '20. ', inline = 'r10', group = section04) var symbol21 = input.symbol(defval = '', title = '21. ', inline = 'r11', group = section04) var symbol22 = input.symbol(defval = '', title = '22. ', inline = 'r11', group = section04) var symbol23 = input.symbol(defval = '', title = '23. ', inline = 'r12', group = section04) var symbol24 = input.symbol(defval = '', title = '24. ', inline = 'r12', group = section04) var symbol25 = input.symbol(defval = '', title = '25. ', inline = 'r13', group = section04) var symbol26 = input.symbol(defval = '', title = '26. ', inline = 'r13', group = section04) var symbol27 = input.symbol(defval = '', title = '27. ', inline = 'r14', group = section04) var symbol28 = input.symbol(defval = '', title = '28. ', inline = 'r14', group = section04) var symbol29 = input.symbol(defval = '', title = '29. ', inline = 'r15', group = section04) var symbol30 = input.symbol(defval = '', title = '30. ', inline = 'r15', group = section04) var symbol31 = input.symbol(defval = '', title = '31. ', inline = 'r16', group = section04) var symbol32 = input.symbol(defval = '', title = '32. ', inline = 'r16', group = section04) var symbol33 = input.symbol(defval = '', title = '33. ', inline = 'r17', group = section04) var symbol34 = input.symbol(defval = '', title = '34. ', inline = 'r17', group = section04) var symbol35 = input.symbol(defval = '', title = '35. ', inline = 'r18', group = section04) var symbol36 = input.symbol(defval = '', title = '36. ', inline = 'r18', group = section04) var symbol37 = input.symbol(defval = '', title = '37. ', inline = 'r19', group = section04) var symbol38 = input.symbol(defval = '', title = '38. ', inline = 'r19', group = section04) var symbol39 = input.symbol(defval = '', title = '39. ', inline = 'r20', group = section04) var symbol40 = input.symbol(defval = '', title = '40. ', inline = 'r20', group = section04) var smblNote1 = 'Please note that once selected, symbols cannot be entirely removed from this form; ' var smblNote2 = smblNote1 + 'they can only be replaced with other symbols. To remove one or more symbols, you have two ' var smblNote3 = smblNote2 + 'options: either click \"reset settings\" or utilize this feature to exhibit the total ' var smblNote4 = smblNote3 + 'desired number of symbols, regardless of the existing count on the watchlist form.' var totSym = input.int(defval = 40, title = 'How many watchlist symbols to display?', minval = 0, maxval = 40, tooltip = smblNote4, group = section04) // } // ::Functions:: { sortByKey() => switch sortByKey 'open' => showOpen ? 'open' : na 'high' => showHigh ? 'high' : na 'low' => showLow ? 'low' : na 'close' => showClose ? 'close' : na 'volume' => showVol ? 'volume' : na displayTf() => mp = customTf ? tfMultiplier : timeframe.multiplier ut = customTf ? unit : timeframe.period _m = mp _u = switch str.endswith(ut, "S") => mp == 1 ? 'Second' : 'Seconds' str.endswith(ut, "D") => mp == 1 ? 'Day' : 'Days' str.endswith(ut, "W") => mp == 1 ? 'Week' : 'Weeks' str.endswith(ut, "M") => if mp == 1 'Month' else if mp == 12 _m := 1 'Year' else 'Months' => if mp == 1 'Minute' else if mp % 60 == 0 _m := mp / 60 _m == 1 ? 'Hour' : 'Hours' else 'Minutes' _m == 1 ? str.format('{0}{1}', nthKey, _u) : str.format('{0}{1} {2}', nthKey, _m, _u) displayValues() => switch displayValues 'regular' => na 'change' => 'change_format' 'change percent' => 'change_percent_format' 'equal to' => 'et' 'less than' => 'lt' 'less than or equal to' => 'lte' 'greater than' => 'gt' 'greater than or equal to' => 'gte' getPkv(simple string ticker) => t = customTf ? tf : '' p = customTf ? tfNth : nth pk = syminfo.ticker(ticker) tckr = ticker.new(syminfo.prefix(ticker), pk, syminfo.session) clp = (close[p] - close[p + 1]) / close[p + 1] * 100 vlp = (volume[p] - volume[p + 1]) / volume[p + 1] * 100 [o, o1, h, h1, l, l1, c, c1, v, v1, cp, vp] = request.security(tckr, t, [open[p], open[p + 1], high[p], high[p + 1], low[p], low[p + 1], close[p], close[p + 1], volume[p], volume[p + 1], clp, vlp], ignore_invalid_symbol = true) __kvs__ = array.new<mltd.kv>() if showOpen __kvs__.push(mltd.kv('open', o, o1, format='{0,number,currency}')) if showHigh __kvs__.push(mltd.kv('high', h, h1, format='{0,number,currency}')) if showLow __kvs__.push(mltd.kv('low', l, l1, format='{0,number,currency}')) if showClose __kvs__.push(mltd.kv('close', c, c1, format='{0,number,currency}')) if displayValues == 'regular' and showCloseP __kvs__.push(mltd.kv('close%', val=cp, format='{0,number,0.00}%')) if showVol __kvs__.push(mltd.kv('volume', v, v1, format=tools.numCompact(v), changeFormat=tools.numCompact(v-v1))) if displayValues == 'regular' and showVolP __kvs__.push(mltd.kv('volume%', val=vp, format='{0,number,0.00}%')) if __kvs__.size() == 0 runtime.error("Required: Atleast one data key must be selected for display.") mltd.pkv(pk, __kvs__) // } if barstate.islast // ::Data:: { symbols = array.new<mltd.pkv>() if tools._bool(symbol01) and totSym >= 1 symbols.push(getPkv(symbol01)) if tools._bool(symbol02) and totSym >= 2 symbols.push(getPkv(symbol02)) if tools._bool(symbol03) and totSym >= 3 symbols.push(getPkv(symbol03)) if tools._bool(symbol04) and totSym >= 4 symbols.push(getPkv(symbol04)) if tools._bool(symbol05) and totSym >= 5 symbols.push(getPkv(symbol05)) if tools._bool(symbol06) and totSym >= 6 symbols.push(getPkv(symbol06)) if tools._bool(symbol07) and totSym >= 7 symbols.push(getPkv(symbol07)) if tools._bool(symbol08) and totSym >= 8 symbols.push(getPkv(symbol08)) if tools._bool(symbol09) and totSym >= 9 symbols.push(getPkv(symbol09)) if tools._bool(symbol10) and totSym >= 10 symbols.push(getPkv(symbol10)) if tools._bool(symbol11) and totSym >= 11 symbols.push(getPkv(symbol11)) if tools._bool(symbol12) and totSym >= 12 symbols.push(getPkv(symbol12)) if tools._bool(symbol13) and totSym >= 13 symbols.push(getPkv(symbol13)) if tools._bool(symbol14) and totSym >= 14 symbols.push(getPkv(symbol14)) if tools._bool(symbol15) and totSym >= 15 symbols.push(getPkv(symbol15)) if tools._bool(symbol16) and totSym >= 16 symbols.push(getPkv(symbol16)) if tools._bool(symbol17) and totSym >= 17 symbols.push(getPkv(symbol17)) if tools._bool(symbol18) and totSym >= 18 symbols.push(getPkv(symbol18)) if tools._bool(symbol19) and totSym >= 19 symbols.push(getPkv(symbol19)) if tools._bool(symbol20) and totSym >= 20 symbols.push(getPkv(symbol20)) if tools._bool(symbol21) and totSym >= 21 symbols.push(getPkv(symbol21)) if tools._bool(symbol22) and totSym >= 22 symbols.push(getPkv(symbol22)) if tools._bool(symbol23) and totSym >= 23 symbols.push(getPkv(symbol23)) if tools._bool(symbol24) and totSym >= 24 symbols.push(getPkv(symbol24)) if tools._bool(symbol25) and totSym >= 25 symbols.push(getPkv(symbol25)) if tools._bool(symbol26) and totSym >= 26 symbols.push(getPkv(symbol26)) if tools._bool(symbol27) and totSym >= 27 symbols.push(getPkv(symbol27)) if tools._bool(symbol28) and totSym >= 28 symbols.push(getPkv(symbol28)) if tools._bool(symbol29) and totSym >= 29 symbols.push(getPkv(symbol29)) if tools._bool(symbol30) and totSym >= 30 symbols.push(getPkv(symbol30)) if tools._bool(symbol31) and totSym >= 31 symbols.push(getPkv(symbol31)) if tools._bool(symbol32) and totSym >= 32 symbols.push(getPkv(symbol32)) if tools._bool(symbol33) and totSym >= 33 symbols.push(getPkv(symbol33)) if tools._bool(symbol34) and totSym >= 34 symbols.push(getPkv(symbol34)) if tools._bool(symbol35) and totSym >= 35 symbols.push(getPkv(symbol35)) if tools._bool(symbol36) and totSym >= 36 symbols.push(getPkv(symbol36)) if tools._bool(symbol37) and totSym >= 37 symbols.push(getPkv(symbol37)) if tools._bool(symbol38) and totSym >= 38 symbols.push(getPkv(symbol38)) if tools._bool(symbol39) and totSym >= 39 symbols.push(getPkv(symbol39)) if tools._bool(symbol40) and totSym >= 40 symbols.push(getPkv(symbol40)) // } if symbols.size() > 0 tbs = prnt.tableStyle.new(bgColor=na, frameColor=na, borderWidth = cellPad) hs = prnt.headerStyle.new(bgColor=na, textHalign=headerAlign, textColor=headerColor, textSize=headerSize) cs = prnt.cellStyle.new(horizontal=orientation, textHalign=textAlign, textSize=textSize) // Initialize the printer. hd = headerPrefix + (asc ? ' ↑ ': ' ↓ ') + displayTf() header = headerSize != 'hide' ? hd : na printer = prnt.printer(header=header, tableStyle=tbs, headerStyle=hs, cellStyle=cs, stack=orientation, loc=displayLoc) // create the data3d object sortByKey := sortByKey() d3d = mltd.data3d(symbols, sort=(not na(sortByKey) ? true : false), asc=asc, sortByKey=sortByKey, sortByChange=true) // Dynamic values array<float> _closeDv = na prnt.dvs _closeDvs = na float _closeDvMax = na float _closeDvMin = na array<float> _volumeDv = na prnt.dvs _volumeDvs = na float _volumeDvMax = na float _volumeDvMin = na float _sortedDvMax = na float _sortedDvMin = na d3dDv = map.new<string, prnt.dvs>() d3d_styles = map.new<string, prnt.cellStyle>() dc_val_color = prnt.dynamicColor.new(up=grdUp, neutral=grdNeutral, down=grdDown, offsetItem='bg') dc_sorted_val_color = prnt.dynamicColor.new(up=grdUp, neutral=grdNeutral, down=grdDown, offsetItem=textOffset, offsetColor=textOffsetColor) // Data keys: // open - if showOpen _openDv = d3d.dkChangeValues('open', true) _openDvMax = _openDv.max() _openDvMin = _openDv.min() _sortedDvMax := sortByKey == 'open' ? _openDvMax : _sortedDvMax _sortedDvMin := sortByKey == 'open' ? _openDvMin : _sortedDvMin d3dDv.put('open', _openDv.dvs()) styleOpen = prnt.cellStyle.copy(cs) styleOpen.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'open' ? dc_sorted_val_color : dc_val_color) styleOpen.dynamicColor.numberUp := _openDvMax styleOpen.dynamicColor.numberDown := _openDvMin styleOpen.gradient := true d3d_styles.put('open', styleOpen) // high - if showHigh _highDv = d3d.dkChangeValues('high', true) _highDvMax = _highDv.max() _highDvMin = _highDv.min() _sortedDvMax := sortByKey == 'high' ? _highDvMax : _sortedDvMax _sortedDvMin := sortByKey == 'high' ? _highDvMin : _sortedDvMin d3dDv.put('high', _highDv.dvs()) styleHigh = prnt.cellStyle.copy(cs) styleHigh.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'high' ? dc_sorted_val_color : dc_val_color) styleHigh.dynamicColor.numberUp := _highDv.max() styleHigh.dynamicColor.numberDown := _highDv.min() styleHigh.gradient := true d3d_styles.put('high', styleHigh) // low - if showLow _lowDv = d3d.dkChangeValues('low', true) _lowDvMax = _lowDv.max() _lowDvMin = _lowDv.min() _sortedDvMax := sortByKey == 'low' ? _lowDvMax : _sortedDvMax _sortedDvMin := sortByKey == 'low' ? _lowDvMin : _sortedDvMin d3dDv.put('low', _lowDv.dvs()) styleLow = prnt.cellStyle.copy(cs) styleLow.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'low' ? dc_sorted_val_color : dc_val_color) styleLow.dynamicColor.numberUp := _lowDv.max() styleLow.dynamicColor.numberDown := _lowDv.min() styleLow.gradient := true d3d_styles.put('low', styleLow) // close - if showClose _closeDv := d3d.dkChangeValues('close', true) _closeDvs := _closeDv.dvs() _closeDvMax := _closeDv.max() _closeDvMin := _closeDv.min() _sortedDvMax := sortByKey == 'close' ? _closeDvMax : _sortedDvMax _sortedDvMin := sortByKey == 'close' ? _closeDvMin : _sortedDvMin d3dDv.put('close', _closeDvs) styleClose = prnt.cellStyle.copy(cs) styleClose.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'close' ? dc_sorted_val_color : dc_val_color) styleClose.dynamicColor.numberUp := _closeDvMax styleClose.dynamicColor.numberDown := _closeDvMin styleClose.gradient := true d3d_styles.put('close', styleClose) // close% - if displayValues == 'regular' and showCloseP if not showClose _closeDv := d3d.dkFloatValues('close%') _closeDvs := _closeDv.dvs() _closeDvMax := _closeDv.max() _closeDvMin := _closeDv.min() d3dDv.put('close%', _closeDvs) styleCloseP = prnt.cellStyle.copy(cs) styleCloseP.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'close' ? dc_sorted_val_color : dc_val_color) styleCloseP.dynamicColor.numberUp := _closeDvMax styleCloseP.dynamicColor.numberDown := _closeDvMin styleCloseP.gradient := true d3d_styles.put('close%', styleCloseP) // volume - if showVol _volumeDv := d3d.dkChangeValues('volume', true) _volumeDvs := _volumeDv.dvs() _volumeDvMax := _volumeDv.max() _volumeDvMin := _volumeDv.min() _sortedDvMax := sortByKey == 'volume' ? _volumeDvMax : _sortedDvMax _sortedDvMin := sortByKey == 'volume' ? _volumeDvMin : _sortedDvMin d3dDv.put('volume', _volumeDvs) styleVol = prnt.cellStyle.copy(cs) styleVol.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'volume' ? dc_sorted_val_color : dc_val_color) styleVol.dynamicColor.numberUp := _volumeDvMax styleVol.dynamicColor.numberDown := _volumeDvMin styleVol.gradient := true d3d_styles.put('volume', styleVol) // volume% - if displayValues == 'regular' and showVolP if not showVol _volumeDv := d3d.dkFloatValues('volume%') _volumeDvs := _volumeDv.dvs() _volumeDvMax := _volumeDv.max() _volumeDvMin := _volumeDv.min() d3dDv.put('volume%', _volumeDvs) styleVolP = prnt.cellStyle.copy(cs) styleVolP.dynamicColor := prnt.dynamicColor.copy(sortByKey == 'volume' ? dc_sorted_val_color : dc_val_color) styleVolP.dynamicColor.numberUp := _volumeDvMax styleVolP.dynamicColor.numberDown := _volumeDvMin styleVolP.gradient := true d3d_styles.put('volume%', styleVolP) // Primary keys - stylePk = prnt.cellStyle.new(textHalign=pkAlign, textSize=pkSize) if not na(sortByKey) stylePk.dynamicColor := prnt.dynamicColor.new(up=grdUp, neutral=grdNeutral, down=grdDown, offsetItem=pkOffset, offsetColor=pkOffsetColor, numberUp=_sortedDvMax, numberDown=_sortedDvMin) stylePk.gradient := true else stylePk.textColor := dkTextColor stylePk.bgColor := dkBgColor d3d_styles.put('pk', stylePk) // Data keys - styleDk = prnt.cellStyle.new(textHalign=dkAlign, textColor=dkTextColor, textSize=dkSize, bgColor=dkBgColor) d3d_styles.put('dk', styleDk) printer.print(d3d, styles=d3d_styles, displayValues=displayValues(), dynamicValues=d3dDv, dynamicKey=sortByKey)
Advanced Divergence Oscillator
https://www.tradingview.com/script/Y6oPpAfx-Advanced-Divergence-Oscillator/
DraftVenture
https://www.tradingview.com/u/DraftVenture/
16
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/ // Credit to Larry Williams and TradingView //@version=5 indicator(title="Advanced Divergence Oscillator", shorttitle="ADO", format=format.price, precision=2, timeframe="", timeframe_gaps=true) // Welcome to the Advanced Divergence Oscillator // This tool is an enhancement of the Ultimate Oscillator, offering traders // more control and deeper insight into price action. // User Input Section // ------------------- // These inputs allow users to fine-tune the oscillator to their specific trading strategy. length1 = input.int(3, minval = 1, title = "Primary Length") length2 = input.int(8, minval = 1, title = "Secondary Length") length3 = input.int(13, minval = 1, title = "Tertiary Length") length4 = input.int(10, minval = 1, title = "Gaussian Smoothing") // Calculation of price averages based on different lengths average(bp, tr_, length) => math.sum(bp, length) / math.sum(tr_, length) high_ = math.max(high, close[1]) low_ = math.min(low, close[1]) bp = close - low_ tr_ = high_ - low_ avg7 = average(bp, tr_, length1) avg14 = average(bp, tr_, length2) avg28 = average(bp, tr_, length3) // Divergence Detection and Plotting // ---------------------------------- // Enhanced logic for detecting and plotting divergences in market price movements. lbR = input(title="Pivot Right", defval = 2) lbL = input(title="Pivot Left", defval = 2) rangeUpper = input(title="Max Lookback", defval = 30) rangeLower = input(title="Min Lookback", defval = 2) plotBull = input(title="Plot Bullish", defval = true) plotHiddenBull = input(title = "Plot Hidden Bullish", defval = true) plotBear = input(title = "Plot Bearish", defval = true) plotHiddenBear = input(title="Plot Hidden Bearish", defval = true) bearColor = color.new(color.red, 25) bullColor = color.new(color.green, 25) hiddenBullColor = color.new(color.green, 50) hiddenBearColor = color.new(color.red, 50) textColor = color.white noneColor = color.new(color.white, 100) // Final Configuration oscAvg = 100 * (4*avg7 + 2*avg14 + avg28)/7 osc = ta.alma(oscAvg, length4, 0.85, 6) plot(osc, color=#d8f436, title="Oscillator") // Divergence Detection and Plotting // ---------------------------------- // Enhanced logic for detecting and plotting divergences in market price movements. // Utilized from TradingView Divergence RSI plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true _inRange(cond) => bars = ta.barssince(cond == true) rangeLower <= bars and bars <= rangeUpper //------------------------------------------------------------------------------ // Regular Bullish // Osc: Higher Low oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1]) // Price: Lower Low priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1) bullCondAlert = priceLL and oscHL and plFound bullCond = plotBull and bullCondAlert plot( plFound ? osc[lbR] : na, offset=-lbR, title="Regular Bullish", linewidth=2, color=(bullCond ? bullColor : noneColor) ) //------------------------------------------------------------------------------ // Hidden Bullish // Osc: Lower Low oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1]) // Price: Higher Low priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1) hiddenBullCondAlert = priceHL and oscLL and plFound hiddenBullCond = plotHiddenBull and hiddenBullCondAlert plot( plFound ? osc[lbR] : na, offset=-lbR, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond ? hiddenBullColor : noneColor) ) //------------------------------------------------------------------------------ // Regular Bearish // Osc: Lower High oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1]) // Price: Higher High priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1) bearCondAlert = priceHH and oscLH and phFound bearCond = plotBear and bearCondAlert plot( phFound ? osc[lbR] : na, offset=-lbR, title="Regular Bearish", linewidth=2, color=(bearCond ? bearColor : noneColor) ) //------------------------------------------------------------------------------ // Hidden Bearish // Osc: Higher High oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1]) // Price: Lower High priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1) hiddenBearCondAlert = priceLH and oscHH and phFound hiddenBearCond = plotHiddenBear and hiddenBearCondAlert plot( phFound ? osc[lbR] : na, offset=-lbR, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond ? hiddenBearColor : noneColor) ) // Additional Alert Configurations // ------------------------------- // Users can customize alert conditions to match their trading strategies. alertcondition(bullCondAlert, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar") alertcondition(hiddenBullCondAlert, title='Hidden Bullish Divergence', message='Found a new Hidden Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar') alertcondition(bearCondAlert, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar') alertcondition(hiddenBearCondAlert, title='Hidden Bearisn Divergence', message='Found a new Hidden Bearisn Divergence, `Pivot Lookback Right` number of bars to the left of the current bar') // Script Summary // -------------- // This section provides a brief overview of what the script does, // serving as a quick reference for users. // The ADO is a versatile tool for identifying potential price reversals // through divergence analysis. It combines multiple average calculations // to create a smoothed oscillator, which is then used to detect bullish and bearish divergences.
Candle volume analysis
https://www.tradingview.com/script/tLUmW2dG-Candle-volume-analysis/
AlexeyWolf
https://www.tradingview.com/u/AlexeyWolf/
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/ // © AlexeyWolf // @version=5 funvolcalc(_i) => bool f = true int i=_i while i>0 if volume <= volume[i] f := false break i:=i-1 f indicator(title = "Advanced VSA:Candle volume analysis ", shorttitle="Volume analysis [AlexeyWolf v2]", format = format.volume, precision = 0,max_bars_back=5000) i_sw1 = input.int(2, "First number of candles ago", 1,4000,1, inline = '1') effort1 = input.color(color.rgb(100, 101, 104), "Color 1", "Use this color when the volume of one candle is individually larger than the previous 'Number of candles ago First'", inline = '1') i_sw2 = input.int(2, "Second number of candles ago", 1,5000,1, inline = '2') effort2 = input.color(color.rgb(17, 70, 230), "Color 2", "Use this color when the volume of one candle is individually larger than the previous 'Number of candles ago Second'", inline = '2') i_sw3 = input.bool(false, "Use the total volumes of the previous candles for the 'Second number of candles ago'","Compare the volume with the volume of each candle separately or with the sum of the volumes of previous candles") color basic = color.rgb(178, 181, 190, 0) color volumeColor = na volumeColor := funvolcalc(i_sw1)? effort1 : basic if i_sw2>i_sw1 and not i_sw3 volumeColor := funvolcalc(i_sw2)? effort2 : volumeColor else if i_sw3 volumeColor := math.sum(volume,i_sw2+1)<2*volume? effort2 : volumeColor plot(volume, style = plot.style_columns, color = volumeColor)
% Chg Lines
https://www.tradingview.com/script/WDeBZYOd-Chg-Lines/
theGary
https://www.tradingview.com/u/theGary/
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/ // ©atraderstoolbox //@version=5 indicator("% Chg Lines", overlay = true) // inputs todayonly = input.bool(false, "Show Today Only") pct1 = input.float(0.50, "% 1") pct2 = input.float(1.00, "% 2") pct3 = input.float(1.50, "% 3") pct4 = input.float(2.00, "% 4") pct5 = input.float(2.50, "% 5") label_color = input.color(color.new(color.white,30), title = "Label Color") label_offset = input.int(10, title = "Label Offset", minval = 5, maxval = 50) // calculate level values prevclose = request.security(syminfo.tickerid, "D", close[1], barmerge.gaps_off, barmerge.lookahead_on) pos_pctchg1 = prevclose + (pct1 / 100 * prevclose) pos_pctchg2 = prevclose + (pct2 / 100 * prevclose) pos_pctchg3 = prevclose + (pct3 / 100 * prevclose) pos_pctchg4 = prevclose + (pct4 / 100 * prevclose) pos_pctchg5 = prevclose + (pct5 / 100 * prevclose) neg_pctchg1 = + prevclose - (pct1 / 100 * prevclose) neg_pctchg2 = + prevclose - (pct2 / 100 * prevclose) neg_pctchg3 = + prevclose - (pct3 / 100 * prevclose) neg_pctchg4 = + prevclose - (pct4 / 100 * prevclose) neg_pctchg5 = + prevclose - (pct5 / 100 * prevclose) // calculate plot times var bool isToday = false timeadj = syminfo.type == "stock" ? 1 : syminfo.type == "crypto" ? 0 : 1 isToday := year(timenow) == year(time_tradingday) and month(timenow) == month(time_tradingday) and dayofmonth(timenow) == (dayofmonth(time_tradingday) + timeadj) oktoplot = (isToday and todayonly) or not todayonly // plot lines pclose = plot(oktoplot ? prevclose : na, title = "Previous Close", style = plot.style_cross, color = color.new(color.gray,70)) upper1 = plot(oktoplot ? pos_pctchg1 : na, title = "+ Chg 1", style = plot.style_cross, color = color.new(color.gray,80)) upper2 = plot(oktoplot ? pos_pctchg2 : na, title = "+ Chg 2", style = plot.style_cross, color = color.new(color.gray,80)) upper3 = plot(oktoplot ? pos_pctchg3 : na, title = "+ Chg 3", style = plot.style_cross, color = color.new(color.gray,80)) upper4 = plot(oktoplot ? pos_pctchg4 : na, title = "+ Chg 4", style = plot.style_cross, color = color.new(color.gray,80)) upper5 = plot(oktoplot ? pos_pctchg5 : na, title = "+ Chg 5", style = plot.style_cross, color = color.new(color.gray,80)) lower1 = plot(oktoplot ? neg_pctchg1 : na, title = "- Chg 1", style = plot.style_cross, color = color.new(color.gray,80)) lower2 = plot(oktoplot ? neg_pctchg2 : na, title = "- Chg 2", style = plot.style_cross, color = color.new(color.gray,80)) lower3 = plot(oktoplot ? neg_pctchg3 : na, title = "- Chg 3", style = plot.style_cross, color = color.new(color.gray,80)) lower4 = plot(oktoplot ? neg_pctchg4 : na, title = "- Chg 4", style = plot.style_cross, color = color.new(color.gray,80)) lower5 = plot(oktoplot ? neg_pctchg5 : na, title = "- Chg 5", style = plot.style_cross, color = color.new(color.gray,80)) fill(pclose, upper5, color = color.new(color.green,90), title = "Upper % Fill") fill(pclose, lower5, color = color.new(color.red,90), title = "Lower % Fill") // labels var label pclose_label = na var label upper1_label = na var label upper2_label = na var label upper3_label = na var label upper4_label = na var label upper5_label = na var label lower1_label = na var label lower2_label = na var label lower3_label = na var label lower4_label = na var label lower5_label = na if barstate.islast pclose_label := label.new(bar_index + label_offset, prevclose, text = "pClose", textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) upper1_label := label.new(bar_index + label_offset, pos_pctchg1, text = str.tostring(pct1), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) upper2_label := label.new(bar_index + label_offset, pos_pctchg2, text = str.tostring(pct2), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) upper3_label := label.new(bar_index + label_offset, pos_pctchg3, text = str.tostring(pct3), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) upper4_label := label.new(bar_index + label_offset, pos_pctchg4, text = str.tostring(pct4), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) upper5_label := label.new(bar_index + label_offset, pos_pctchg5, text = str.tostring(pct5), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) lower1_label := label.new(bar_index + label_offset, neg_pctchg1, text = str.tostring(-pct1), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) lower2_label := label.new(bar_index + label_offset, neg_pctchg2, text = str.tostring(-pct2), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) lower3_label := label.new(bar_index + label_offset, neg_pctchg3, text = str.tostring(-pct3), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) lower4_label := label.new(bar_index + label_offset, neg_pctchg4, text = str.tostring(-pct4), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) lower5_label := label.new(bar_index + label_offset, neg_pctchg5, text = str.tostring(-pct5), textcolor = label_color, style = label.style_label_center, textalign = text.align_right, color = color.new(label_color, 100)) if not na(pclose_label[1]) label.delete(pclose_label[1]) label.delete(upper1_label[1]) label.delete(upper2_label[1]) label.delete(upper3_label[1]) label.delete(upper4_label[1]) label.delete(upper5_label[1]) label.delete(lower1_label[1]) label.delete(lower2_label[1]) label.delete(lower3_label[1]) label.delete(lower4_label[1]) label.delete(lower5_label[1])
Optimal Length BackTester [YinYangAlgorithms]
https://www.tradingview.com/script/PtSznKiX-Optimal-Length-BackTester-YinYangAlgorithms/
YinYangAlgorithms
https://www.tradingview.com/u/YinYangAlgorithms/
16
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/ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@ @ // @@@@@@@@@@@@@@@@@@@@@@@@@ @@ // @@@@@@@@@@@@@@@@@@@@@@@ @@ // @@@@@@@@@@@@@@@@@@@@@@ @@@ // @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // © YinYangAlgorithms //@version=5 indicator("Optimal Length BackTester [YinYangAlgorithms]", overlay=true, max_bars_back=5000) // ~~~~~~~~~~~~ INPUTS ~~~~~~~~~~~~ // //Optimal Length outputType = input.string("All", "Output Type", options=["Neutral", "Fast", "Slow", "Fast + Slow", "Fast + Neutral", "Slow + Neutral", "All"]) lengthSource = input.source(close, "Neutral Length") lengthSource_fast = input.source(close, "Fast Length") lengthSource_slow = input.source(close, "Slow Length") maType = input.string("SMA", "MA Type", options=["SMA", "EMA", "VWMA"]) displayType = input.string("MA", "Display Type", options=["MA", "Bollinger Bands", "Donchian Channels", "Envelope", "Envelope Adjusted"]) // ~~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~~ // src = close showNeutral = outputType == "Neutral" or outputType == "Fast + Neutral" or outputType == "Slow + Neutral" or outputType == "All" showFast = outputType == "Fast" or outputType == "Fast + Neutral" or outputType == "Fast + Slow" or outputType == "All" showSlow = outputType == "Slow" or outputType == "Slow + Neutral" or outputType == "Fast + Slow" or outputType == "All" neutralColor = color.blue slowColor = color.red fastColor = color.green // ~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~ // pine_ema(src, series int length) => alpha = 2 / (length + 1) sum = 0.0 sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1]) getMA(_src, _len) => switch maType "SMA" => ta.sma(_src, _len) "EMA" => pine_ema(_src, _len) "VWMA" => ta.vwma(_src, _len) // ~~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~~ // //Determining the Optimal Length with 'Failsafe's' to ensure there aren't errors optimalLength = 14 optimalMA = getMA(src, optimalLength) optimalLength_fast = 14 optimalMA_fast = getMA(src, optimalLength_fast) optimalLength_slow = 14 optimalMA_slow = getMA(src, optimalLength_slow) if showNeutral optimalLength := math.min(math.max(math.round(lengthSource), 1), 1000) optimalMA := getMA(src, optimalLength) if showFast optimalLength_fast := math.min(math.max(math.round(lengthSource_fast), 1), 1000) optimalMA_fast := getMA(src, optimalLength_fast) if showSlow optimalLength_slow := math.min(math.max(math.round(lengthSource_slow), 1), 1000) optimalMA_slow := getMA(src, optimalLength_slow) // ~~ Bollinger Bands ~~ // mult = 2.0 //Neutral Bollinger Bands dev = mult * ta.stdev(src, math.round(optimalLength)) upper = optimalMA + dev lower = optimalMA - dev plot(displayType == "Bollinger Bands" and showNeutral ? optimalMA : na, "Basis", color=color.new(neutralColor, 0)) p1 = plot(displayType == "Bollinger Bands" and showNeutral ? upper : na, "Upper", color=color.new(neutralColor, 50)) p2 = plot(displayType == "Bollinger Bands" and showNeutral ? lower : na, "Lower", color=color.new(neutralColor, 50)) fill(p1, p2, title = "Background", color=color.new(neutralColor, 96)) //Slow Bollinger Bands dev_slow = mult * ta.stdev(src, math.round(optimalLength_slow)) upper_slow = optimalMA_slow + dev_slow lower_slow = optimalMA_slow - dev_slow plot(displayType == "Bollinger Bands" and showSlow ? optimalMA_slow : na, "Basis", color=color.new(slowColor, 0)) p1_slow = plot(displayType == "Bollinger Bands" and showSlow ? upper_slow : na, "Upper", color=color.new(slowColor, 50)) p2_slow = plot(displayType == "Bollinger Bands" and showSlow ? lower_slow : na, "Lower", color=color.new(slowColor, 50)) fill(p1_slow, p2_slow, title = "Background", color=color.new(slowColor, 96)) //Fast Bollinger Bands dev_fast = mult * ta.stdev(src, math.round(optimalLength_fast)) upper_fast = optimalMA_fast + dev_fast lower_fast = optimalMA_fast - dev_fast plot(displayType == "Bollinger Bands" and showFast ? optimalMA_fast : na, "Basis", color=color.new(fastColor, 0)) p1_fast = plot(displayType == "Bollinger Bands" and showFast ? upper_fast : na, "Upper", color=color.new(fastColor, 50)) p2_fast = plot(displayType == "Bollinger Bands" and showFast ? lower_fast : na, "Lower", color=color.new(fastColor, 50)) fill(p1_fast, p2_fast, title = "Background", color=color.new(fastColor, 96)) // ~~ Donchian Channels ~~ // //Neutral Donchian Channels lower_dc = ta.lowest(optimalLength) upper_dc = ta.highest(optimalLength) basis_dc = math.avg(upper_dc, lower_dc) plot(displayType == "Donchian Channels" and showNeutral ? basis_dc : na, "Donchain Channel - Neutral Basis", color=color.new(neutralColor, 0)) u = plot(displayType == "Donchian Channels" and showNeutral ? upper_dc : na, "Donchain Channel - Neutral Upper", color=color.new(neutralColor, 50)) l = plot(displayType == "Donchian Channels" and showNeutral ? lower_dc : na, "Donchain Channel - Neutral Lower", color=color.new(neutralColor, 50)) fill(u, l, color=color.new(neutralColor, 96), title = "Donchain Channel - Neutral Background") //Fast Donchian Channels lower_dc_fast = ta.lowest(optimalLength_fast) upper_dc_fast = ta.highest(optimalLength_fast) basis_dc_fast = math.avg(upper_dc_fast, lower_dc_fast) plot(displayType == "Donchian Channels" and showFast ? basis_dc_fast : na, "Donchain Channel - Fast Neutral Basis", color=color.new(fastColor, 0)) u_fast = plot(displayType == "Donchian Channels" and showFast ? upper_dc_fast : na, "Donchain Channel - Fast Upper", color=color.new(fastColor, 50)) l_fast = plot(displayType == "Donchian Channels" and showFast ? lower_dc_fast : na, "Donchain Channel - Fast Lower", color=color.new(fastColor, 50)) fill(u_fast, l_fast, color=color.new(fastColor, 96), title = "Donchain Channel - Fast Background") //Slow Donchian Channels lower_dc_slow = ta.lowest(optimalLength_slow) upper_dc_slow = ta.highest(optimalLength_slow) basis_dc_slow = math.avg(upper_dc_slow, lower_dc_slow) plot(displayType == "Donchian Channels" and showSlow ? basis_dc_slow : na, "Donchain Channel - Slow Neutral Basis", color=color.new(slowColor, 0)) u_slow = plot(displayType == "Donchian Channels" and showSlow ? upper_dc_slow : na, "Donchain Channel - Slow Upper", color=color.new(slowColor, 50)) l_slow = plot(displayType == "Donchian Channels" and showSlow ? lower_dc_slow : na, "Donchain Channel - Slow Lower", color=color.new(slowColor, 50)) fill(u_slow, l_slow, color=color.new(slowColor, 96), title = "Donchain Channel - Slow Background") // ~~ Moving Average ~~ // plot(displayType == "MA" and showNeutral ? optimalMA : na, color=neutralColor) plot(displayType == "MA" and showFast ? optimalMA_fast : na, color=fastColor) plot(displayType == "MA" and showSlow ? optimalMA_slow : na, color=slowColor) // ~~ Envelopes ~~ // percent = 10.0 maxAmount = math.max(optimalLength, optimalLength_fast, optimalLength_slow) //Neutral k = displayType == "Envelope" ? percent/100.0 : (percent/100.0) / (optimalLength / maxAmount) upper_env = optimalMA * (1 + k) lower_env = optimalMA * (1 - k) plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? optimalMA : na, "Envelope - Neutral Basis", color=color.new(neutralColor, 0)) u_env = plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? upper_env : na, "Envelope - Neutral Upper", color=color.new(neutralColor, 50)) l_env = plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? lower_env : na, "Envelope - Neutral Lower", color=color.new(neutralColor, 50)) fill(u_env, l_env, color=color.new(neutralColor, 96), title = "Envelope - Neutral Background") //Fast k_fast = displayType == "Envelope" ? percent/100.0 : (percent/100.0) / (optimalLength_fast / maxAmount) upper_env_fast = optimalMA_fast * (1 + k_fast) lower_env_fast = optimalMA_fast * (1 - k_fast) plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? optimalMA_fast : na, "Envelope - Fast Basis", color=color.new(fastColor, 0)) u_env_fast = plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? upper_env_fast : na, "Envelope - Fast Upper", color=color.new(fastColor, 50)) l_env_fast = plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? lower_env_fast : na, "Envelope - Fast Lower", color=color.new(fastColor, 50)) fill(u_env_fast, l_env_fast, color=color.new(fastColor, 96), title = "Envelope - Fast Background") //Slow k_slow = displayType == "Envelope" ? percent/100.0 : (percent/100.0) / (optimalLength_slow / maxAmount) upper_env_slow = optimalMA_slow * (1 + k_slow) lower_env_slow = optimalMA_slow * (1 - k_slow) plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? optimalMA_slow : na, "Envelope - Slow Basis", color=color.new(slowColor, 0)) u_env_slow = plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? upper_env_slow : na, "Envelope - Slow Upper", color=color.new(slowColor, 50)) l_env_slow = plot(displayType == "Envelope" or displayType == "Envelope Adjusted" ? lower_env_slow : na, "Envelope - Slow Lower", color=color.new(slowColor, 50)) fill(u_env_slow, l_env_slow, color=color.new(slowColor, 96), title = "Envelope - Slow Background") // ~~~~~~~~~~~~ END ~~~~~~~~~~~~ //
MTF Volumetric Order Blocks [ A V Z I ]
https://www.tradingview.com/script/gB5JVhBT-MTF-Volumetric-Order-Blocks-A-V-Z-I/
avziofficial
https://www.tradingview.com/u/avziofficial/
16
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/ // © avziofficial //@version=5 indicator("MTF Volumetric Order Blocks [ A V Z I ]",overlay = true, max_bars_back = 5000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500) //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------- Input Settings //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //----------------------------------------} //Order Blocks //----------------------------------------{ show_order_blocks=input.bool(true,"Order Blocks",group = 'Order Blocks', inline = "ob1") ibull_ob_css = input.color(#5d606b19, '', inline = 'ob1', group = 'Order Blocks') ibear_ob_css = input.color(#5d606b19, '', inline = 'ob1', group = 'Order Blocks') ob_type__= input.string('All', '',options = ['All','Internal','External'], group = 'Order Blocks',inline = 'ob1') i_tf_ob = input.timeframe("", "Timeframe", group = 'Order Blocks', inline = "ob2") mittigation_filt= input.string('Wicks', "Mitigation Method",options = ['Touch','Wicks','Close','Average'], group = 'Order Blocks',inline = 'ob3') overlapping_filt= input(true, 'Hide Overlap', inline = 'ob3', group = 'Order Blocks') max_obs = input.int(4, 'Max OBs', minval = 3, group = 'Order Blocks', inline = 'ob4') length_extend_ob = input.int(defval = 20,title = "Length", minval = 0, maxval = 500 ,group = 'Order Blocks', inline = "ob4") ob_extend = input.bool(false,"Extend",group = 'Order Blocks', inline = "ob4") text_size_ob =input.string("Large", options=["Small", "Medium","Large"], title="Text Size",inline="ob1_t", group="Order Blocks") text_size_ob_ = text_size_ob == "Small" ? size.tiny : text_size_ob == "Medium" ? size.small : text_size_ob == "Large" ? size.normal : text_size_ob == "Medium2" ? size.normal : text_size_ob == "Large2" ? size.large : size.huge ob_text_color_1 = input.color(#787b86 , '', inline = 'ob1_t', group = 'Order Blocks') volume_text = input.bool(true, 'Volume', group='Order Blocks',inline = 'ob1_t') percent_text = input.bool(true, 'Percentage', group='Order Blocks',inline = 'ob1_t') show_line_ob = input.string("On", title = "Mid Line", options=["On", "Off"], group='Order Blocks',inline='ob1_l') show_line_ob_1=show_line_ob=="On"?true:false line_style_ob = input.string("Solid", title = "Line Style", options=["Solid", "Dashed", "Dotted"], group='Order Blocks',inline='ob1_l') line_style_ob_1 = line_style_ob=="Solid" ? line.style_solid : line_style_ob=="Dashed" ? line.style_dashed : line.style_dotted //----------------------------------------} // MTF Order Blocks //----------------------------------------{ show_order_blocks_mtf=input.bool(false,"MTF Order Blocks",group = 'Order Blocks', inline = "m_ob1") ibull_ob_css_2 = input.color(#5d606b19, '', inline = 'm_ob1', group = 'Order Blocks') ibear_ob_css_2 = input.color(#5d606b19, '', inline = 'm_ob1', group = 'Order Blocks') ob_type__mtf= input.string('All', '',options = ['All','Internal','External'], group = 'Order Blocks',inline = 'm_ob1') i_tf_ob_mtf = input.timeframe("240", "Timeframe", group = 'Order Blocks', inline = "mob2") mittigation_filt_mtf= input.string('Wicks', "Mitigation Method",options = ['Touch','Wicks','Close','Average'], group = 'Order Blocks',inline = 'mob3') overlapping_filt_mtf= input(true, 'Hide Overlap', inline = 'mob3', group = 'Order Blocks') max_obs_mtf = input.int(4, 'Max OBs', minval = 3, group = 'Order Blocks', inline = "mob4") length_extend_ob_mtf = input.int(defval = 20,title = "Length", minval = 0, maxval = 500 ,group = 'Order Blocks', inline = "mob4") ob_extend_mtf = input.bool(false,"Extend",group = 'Order Blocks', inline = "mob4") //v_filter = input.bool(true, 'Internal Bull/Bear Activity', group='Order Blocks',inline = 'volume') text_size_ob2 =input.string("Medium", options=["Small", "Medium","Large"], title="Text Size",inline="ob2_t", group="Order Blocks") text_size_ob_2 = text_size_ob2 == "Small" ? size.tiny : text_size_ob2 == "Medium" ? size.small : text_size_ob2== "Large" ? size.normal : text_size_ob2 == "Medium2" ? size.normal : text_size_ob2 == "Large2" ? size.large : size.huge ob_text_color_2 = input.color(#787b86 , '', inline = 'ob2_t', group = 'Order Blocks') volume_text_2 = input.bool(true, 'Volume', group='Order Blocks',inline = 'ob2_t') percent_text_2 = input.bool(true, 'Percentage', group='Order Blocks',inline = 'ob2_t') show_line_ob2 = input.string("On", title = "Mid Line", options=["On", "Off"], group='Order Blocks',inline='ob2_l') show_line_ob_2=show_line_ob2=="On"?true:false line_style_ob2 = input.string("Solid", title = "Line Style", options=["Solid", "Dashed", "Dotted"], group='Order Blocks',inline='ob2_l') line_style_ob_2 = line_style_ob2=="Solid" ? line.style_solid : line_style_ob2=="Dashed" ? line.style_dashed : line.style_dotted v_buy = #00dbff4d v_sell = #e91e634d tf_s1=i_tf_ob_mtf==''?timeframe.period:i_tf_ob_mtf timeframe_st=not(str.contains(tf_s1,'S')) and not(str.contains(tf_s1,'D')) and not(str.contains(tf_s1,'W')) and not(str.contains(tf_s1,'M')) ? str.tonumber(tf_s1)>=60? str.tostring(str.tonumber(tf_s1)/60) +"H": tf_s1 +"M" : tf_s1 timeframe1=timeframe_st + ' : ' show_iob = ob_type__=='All' or ob_type__=='Internal' //input(true, 'Internal', inline = 'ob', group = 'Order Blocks') show_ob = ob_type__=='All' or ob_type__=='External' //input(false, 'External', inline = 'ob', group = 'Order Blocks') show_iob_mtf = ob_type__mtf=='All' or ob_type__mtf=='Internal' //input(true, 'Internal', inline = 'ob', group = 'Order Blocks') show_ob_mtf = ob_type__mtf=='All' or ob_type__mtf=='External' //input(false, 'External', inline = 'ob', group = 'Order Blocks') ob_showlast = 5//input.int(10, 'LookBack', minval = 1, inline = 'ob', group = 'Order Blocks') iob_showlast = 5//input.int(5, 'LookBack', minval = 1, inline = 'iob', group = 'Order Blocks') max_width_ob = 3//input.float(3, 'Max OB Width', minval = 0.1,maxval = 3, inline = 'close', group = 'Order Blocks') max_width_ob:=max_width_ob==3?20:max_width_ob style = 'Colored' v_lookback= 10 ob_loockback=10 timediff=(time[1]-time[101])/100 //-----------------------------------------------------------------------------} //Global variables //-----------------------------------------------------------------------------{ color transparent = #ffffff00 length = 50 is_newbar(res) => t = time(res) not na(t) and (na(t[1]) or t > t[1]) //Swings detection/measurements calculate_swing_points(length)=> var prev = 0 prev := high[length] > ta.highest(length) ? 0 : low[length] < ta.lowest(length) ? 1 : prev[1] t = prev == 0 and prev[1] != 0 ? high[length] : 0 b = prev == 1 and prev[1] != 1 ? low[length] : 0 [t, b] var t_MS = 0, var int_t_MS = 0 var internal_y_up = 0., var internal_x_up = 0, var internal_y_dn = 0., var internal_x_dn = 0 var y_up = 0., var x_up = 0 , var y_dn = 0., var x_dn = 0 var crossed_up = true, var crossed_down = true var internal_up_broke = true, var internal_dn_broke = true var up_trailing = high, var down_trailing = low var up_trailing_x = 0, var down_trailing_x = 0 var high_text = '', var low_text = '' bullish_OB_Break = false bearish_OB_Break = false //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // } // ———————————————————— Global data { //Using current bar data for HTF highs and lows instead of security to prevent future leaking var htfH = open var htfL = open if close > htfH htfH:= close if close < htfL htfL := close // } //-----------------------------------------------------------------------------} //Order Blocks //-----------------------------------------------------------------------------{ first_nonzero_digit(n) => s = str.tostring(n) int r=int (str.tonumber(s[0])) for c=0 to str.length(s)-1 if s[c] != '0' r:=int (str.tonumber(s[c])) r //Order block coordinates function ob_found(loc,b_index,show_ob,show_iob)=> type_obs="none" valid=false H=high L=low O=open C=close V=volume idx=1 volume_=0.0 b_volume=0 s_volume=0 use_max=false min = 99999999. max = 0. if open[5]>close[5] and close[4]>=open[5] and low[1]>high[5] and low>high[5] and show_iob if low[5]>low[4] type_obs:="Internal Bearish" H:=math.min(high[4],high[5]) L:=low[4] O:=open[4] C:=close[4] V:=volume[4] idx:=time[4] valid:=true use_max:=false else type_obs:="Internal Bearish" H:=high[5] L:=low[5] O:=open[5] C:=close[5] V:=volume[5] idx:=time[5] valid:=true use_max:=false else if open[5]<close[5] and close[4]<=open[5] and high[1]<low[5] and high<low[5] and show_iob if high[4]>high[5] type_obs:="Internal Bullish" H:=high[4] L:=math.max(low[4],low[5]) O:=open[4] C:=close[4] V:=volume[4] idx:=time[4] valid:=true use_max:=true else type_obs:="Internal Bullish" H:=high[5] L:=low[5] O:=open[5] C:=close[5] V:=volume[5] idx:=time[5] valid:=true use_max:=true else if open[5]>close[5] and close[4]>close[5] and close[3]>=open[5] and low>high[5] and show_iob if low[5]>low[4] type_obs:="Internal Bearish" H:=math.min(high[4],high[5]) L:=low[4] O:=open[4] C:=close[4] V:=volume[4] idx:=time[4] valid:=true use_max:=false else type_obs:="Internal Bearish" H:=high[5] L:=low[5] O:=open[5] C:=close[5] V:=volume[5] idx:=time[5] valid:=true use_max:=false else if open[5]<close[5] and close[4]<close[5] and close[3]<=open[5] and high<low[5] and show_iob if high[4]>high[5] type_obs:="Internal Bullish" H:=high[4] L:=math.max(low[4],low[5]) O:=open[4] C:=close[4] V:=volume[4] idx:=time[4] valid:=true use_max:=true else type_obs:="Internal Bullish" H:=high[5] L:=low[5] O:=open[5] C:=close[5] V:=volume[5] idx:=time[5] valid:=true use_max:=true else valid:=false if valid ind=0 thold_ = (ta.highest(300) - ta.lowest(300)) * (max_width_ob/2.) / 100. buyingVolume = math.round(V * (C - L) / (H - L)) sellingVolume = math.round(V * (H - C) / (H - L)) t_volume = (buyingVolume+sellingVolume)/2. b_volume:=int ((buyingVolume/ta.highest(t_volume,300))*100) s_volume:=int ((sellingVolume/ta.highest(t_volume,300))*100) volume_:=V //Search for highest/lowest high within the structure interval and get range if use_max max:=H//[idx] min_1=L//[idx]//H[1]-math.min(open[1],close[1])>ob_threshold min:=math.max(min_1,max-thold_) else max_1=H//[idx]//math.max(open[idx],close[idx]) min:=L//[idx] max:=math.min(max_1,min+thold_) [valid,volume_,b_volume,s_volume,max,min,idx,use_max ? -1 : 1,type_obs] //Set order blocks show_orderblock(boxes,lines, target_top, target_btm, target_left, target_type, show_last, swing, size,vol,col_1,col_2,length_extend_ob,ob_extend,tf_text,tf_text_2,ob_text_size,vol_text,perct_text,text_color_ob,show_line_obs,line_style_obs)=> for x = 0 to show_last-1 get_box = array.get(boxes, x) box.set_lefttop(get_box, na, na) box.set_rightbottom(get_box, na , na) box.set_border_color(get_box, na) box.set_bgcolor(get_box, na) get_line = array.get(lines, x) line.set_color(get_line,na) line.set_xy1(get_line,na,na) line.set_xy2(get_line,na,na) for i = 0 to size-1 get_box = array.get(boxes, i) get_line = array.get(lines, i) max_left=bar_index-750 volume_sum=array.sum(vol) volume_=array.get(vol, i)>100000000 ? array.get(vol, i)/100000000.: array.get(vol, i)>1000000 ? array.get(vol, i)/1000000. : array.get(vol, i)/1000. volume_per=(array.get(vol, i)/volume_sum)*100 unit=array.get(vol, i)>100000000 ?' B': array.get(vol, i)>1000000 ?' M' : ' K' text_vol=vol_text and perct_text ? tf_text + str.tostring(volume_,'#.##')+ unit + ' ('+ str.tostring(volume_per,'#.##')+'%)' : vol_text and not(perct_text) ? tf_text + str.tostring(volume_,'#.##')+ unit : not(vol_text) and perct_text ? tf_text + ' '+ str.tostring(volume_per,'#.##')+'%' : tf_text_2+ '' if true//max_left<array.get(target_left, i) box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top, i)) box.set_rightbottom(get_box,timenow+((timediff)*length_extend_ob) , array.get(target_btm, i)) box.set_text(get_box,text_vol) box.set_text_color(get_box,text_color_ob) box.set_border_color(get_box,color.gray) box.set_border_width(get_box,2) box.set_text_halign(get_box,text.align_right) box.set_text_valign(get_box,text.align_center) box.set_text_size(get_box,ob_text_size) fully_extend=not(vol_text) and not(perct_text) and ob_extend? extend.right : extend.none len_ext=not(vol_text) and not(perct_text)?length_extend_ob : length_extend_ob/2 line.set_extend(get_line,fully_extend) line.set_style(get_line,line_style_obs) line.set_xy1(get_line,array.get(target_left, i),array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/2) line.set_xy2(get_line,time+((timediff)*(len_ext)),array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/2) if show_line_obs line.set_color(get_line,color.gray) if ob_extend box.set_extend(get_box, extend.right) color css = na css := array.get(target_type, i) == 1 ? col_1 : col_2 box.set_border_color(get_box, css) box.set_bgcolor(get_box, css) box.set_border_color(get_box, css) // //Set order blocks // display_sub_ob_sell(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size,right)=> // for x = 0 to show_last-1 // get_box = array.get(boxes, x) // box.set_lefttop(get_box, na, na) // box.set_rightbottom(get_box, na , na) // box.set_border_color(get_box, na) // box.set_bgcolor(get_box, na) // for i = 0 to math.min(show_last-1, size-1) // get_box = array.get(boxes, i) // x=1000000000000 // max_left=bar_index-750 // max_right=array.get(target_left, i)+(((timediff)*(array.get(right, i)+5))) //> time+((timediff)*20) ? time+((time[1]-time[2])*20) : array.get(target_left, i)+(time+((time[1]-time[2])*(array.get(right, i)+10))) // if true//max_left<array.get(target_left, i) // box.set_lefttop(get_box,array.get(target_left, i), array.get(target_top, i)) // box.set_rightbottom(get_box, math.min(max_right,timenow+((timediff)*20)), array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/2) // //box.set_extend(get_box, extend.right) // color css = na // if true//max_left<array.get(target_left, i) // css := array.get(target_type, i) == 1 ? v_buy : v_buy // box.set_border_color(get_box, color.new(css,100)) // box.set_bgcolor(get_box, css) // // if overlapping_filt // // for i = math.min(show_last-1, size-1) to 0 // // get_box = array.get(boxes, i) // // valid=true // // index=0 // // //label.new(array.get(target_left,i),array.get(target_top,i),str.tostring(i)) // // if i>0 // // for x=i-1 to 0 // // if array.get(target_top,i)>=array.get(target_btm,x) and array.get(target_top,i)<=array.get(target_top,x) // // valid:=false // // if array.get(target_btm,i)>=array.get(target_btm,x) and array.get(target_btm,i)<=array.get(target_top,x) // // valid:=false // // if array.get(target_btm,i)==array.get(target_btm,x) and array.get(target_top,i)==array.get(target_top,x) // // valid:=false // // if array.get(target_btm,i)<=array.get(target_btm,x) and array.get(target_top,i)>=array.get(target_top,x) // // valid:=false // // if not(valid) // // box.set_border_color(get_box, na) // // box.set_bgcolor(get_box, na) display_sub_ob_buy(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size,right1,right2)=> for x = 0 to show_last-1 get_box = array.get(boxes, x) box.set_lefttop(get_box, na, na) box.set_rightbottom(get_box, na , na) box.set_border_color(get_box, na) box.set_bgcolor(get_box, na) for i = 0 to math.min(show_last-1, size-1) get_box = array.get(boxes, i) x=1000000000000 max_left=bar_index-750 right=math.max(array.get(right1, i),array.get(right2, i)) max_right=array.get(target_left, i)+(((timediff)*right+10)) //> time+((time[1]-time[2])*20 ? time+((time[1]-time[2])*20) : array.get(target_left, i)+(time+((time[1]-time[2])*(array.get(right, i)+10)))) if true//max_left<array.get(target_left, i) box.set_lefttop(get_box, math.max(array.get(target_left, i),max_left), array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/10) box.set_rightbottom(get_box, math.min(max_right,timenow+((timediff)*20)), array.get(target_btm, i)+(array.get(target_top, i) - array.get(target_btm, i))/10) //box.set_right(get_box, array.get(target_left, i)+100) //box.set_extend(get_box, extend.right) color css = na if true//max_left<array.get(target_left, i) css := array.get(right1, i)>array.get(right2, i)? v_sell : v_buy box.set_border_color(get_box, color.new(css,100)) box.set_bgcolor(get_box, css) remove_ob(target_top, target_btm, target_left, target_type, show_last, swing, size)=> del_index=0 deleted=false for i = 0 to size-1 if i>0 for x=i-1 to 0 if array.get(target_top,i)>=array.get(target_btm,x) and array.get(target_top,i)<=array.get(target_top,x) deleted:=true del_index:=i if array.get(target_btm,i)>=array.get(target_btm,x) and array.get(target_btm,i)<=array.get(target_top,x) deleted:=true del_index:=i if array.get(target_btm,i)==array.get(target_btm,x) and array.get(target_top,i)==array.get(target_top,x) deleted:=true del_index:=i if array.get(target_btm,i)<=array.get(target_btm,x) and array.get(target_top,i)>=array.get(target_top,x) deleted:=true del_index:=i [deleted,del_index] time_diff()=>((time[1]-time[101])/100) // var iob_h_top = array.new_float(0) // var iob_l_btm = array.new_float(0) // var iob_h_left = array.new_int(0) // var iob_l_left = array.new_int(0) // var iob_type = array.new_int(0) // if ta.pivothigh(high,3,1) // array.unshift(iob_h_top,high[1]) // array.unshift(iob_h_left,time) // if ta.pivotlow(low,3,1) // array.unshift(iob_l_btm,low[1]) // array.unshift(iob_l_left,time) // if array.size(iob_h_top)>3 // array.shift(iob_h_top) // array.shift(iob_h_left) // if array.size(iob_l_btm)>3 // array.shift(iob_l_btm) // array.shift(iob_l_left) // if array.size(iob_h_top)>0 // for i=0 to array.size(iob_h_top)-1 // x=array.get(iob_h_left,i) // y=array.get(iob_h_top,i) // if close>y // label.new(int(math.avg(x, time)), y, 'BOS', color = color.gray, textcolor = color.white,style= label.style_label_down, size = size.small,xloc =xloc.bar_time ) // line.new(x, y, time, y, color = color.gray, style =line.style_dashed,xloc = xloc.bar_time ) // array.remove(iob_h_top,i) // array.remove(iob_h_left,i) // break //-----------------------------------------------------------------------------} //Order Blocks Arrays //-----------------------------------------------------------------------------{ var ob_top = array.new_float(0) var ob_btm = array.new_float(0) var ob_left = array.new_int(0) var ob_type = array.new_int(0) var ob_sell_vol = array.new_int(0) var ob_buy_vol = array.new_int(0) var ob_vol = array.new_float(0) var ob_top_mtf = array.new_float(0) var ob_btm_mtf = array.new_float(0) var ob_left_mtf = array.new_int(0) var ob_type_mtf = array.new_int(0) var ob_sell_vol_mtf = array.new_int(0) var ob_buy_vol_mtf = array.new_int(0) var ob_vol_mtf = array.new_float(0) bar_merge=barmerge.gaps_off look_bars=barmerge.lookahead_on [valid_ob,volume_,b_volume,s_volume,top_ob,btm_ob,left_ob,type_ob,_type]=request.security(ticker.standard(syminfo.tickerid), i_tf_ob, ob_found(x_up,bar_index,show_ob,show_iob), bar_merge,look_bars) [valid_ob_mtf,volume__mtf,b_volume_mtf,s_volume_mtf,top_ob_mtf,btm_ob_mtf,left_ob_mtf,type_ob_mtf,_type_mtf]=request.security(ticker.standard(syminfo.tickerid), i_tf_ob_mtf, ob_found(x_up,bar_index,show_ob_mtf,show_iob_mtf), bar_merge,look_bars) tf1_time=request.security(ticker.standard(syminfo.tickerid),i_tf_ob,time_diff(), bar_merge,look_bars) tf2_time=request.security(ticker.standard(syminfo.tickerid),i_tf_ob_mtf,time_diff(), bar_merge,look_bars) if valid_ob and not(valid_ob[1]) and barstate.isconfirmed array.unshift(ob_vol, volume_) array.unshift(ob_buy_vol, b_volume) array.unshift(ob_sell_vol, s_volume) array.unshift(ob_top, top_ob) array.unshift(ob_btm, btm_ob) array.unshift(ob_left, left_ob) array.unshift(ob_type, type_ob) if valid_ob_mtf and not(valid_ob_mtf[1]) and barstate.isconfirmed array.unshift(ob_vol_mtf, volume__mtf) array.unshift(ob_buy_vol_mtf, b_volume_mtf) array.unshift(ob_sell_vol_mtf, s_volume_mtf) array.unshift(ob_top_mtf, top_ob_mtf) array.unshift(ob_btm_mtf, btm_ob_mtf) array.unshift(ob_left_mtf, time-((tf2_time)*5)) array.unshift(ob_type_mtf, type_ob_mtf) // if barstate.islast // label.new(bar_index,high,str.tostring(array.size(ob_top))) alertcondition(_type=="External Bearish",'Bearish External OB','Bearish External OB Found MTF Volumetric Order Blocks [ A V Z I ]') alertcondition(_type=="External Bullish",'Bullish External OB','Bullish External OB Found MTF Volumetric Order Blocks [ A V Z I ]') alertcondition(_type=="Internal Bearish",'Bearish Internal OB','Bearish Internal OB Found MTF Volumetric Order Blocks [ A V Z I ]') alertcondition(_type=="Internal Bullish",'Bullish Internal OB','Bullish Internal OB Found MTF Volumetric Order Blocks [ A V Z I ]') //Set order blocks var iob_boxes = array.new_box(0) var ob_boxes = array.new_box(0) var ob_volume = array.new_line(0) var ob_volume_labels = array.new_label(0) var iob_boxes_buy = array.new_box(0) var ob_boxes_buy = array.new_box(0) var iob_boxes_sell = array.new_box(0) var ob_boxes_sell = array.new_box(0) var iob_boxes_mtf = array.new_box(0) var ob_boxes_mtf = array.new_box(0) var ob_volume_mtf = array.new_line(0) var ob_volume_labels_mtf = array.new_label(0) var iob_boxes_buy_mtf = array.new_box(0) var ob_boxes_buy_mtf = array.new_box(0) var iob_boxes_sell_mtf = array.new_box(0) var ob_boxes_sell_mtf = array.new_box(0) if array.size(ob_top_mtf)>max_obs_mtf// or array.get(ob_left_mtf,array.size(ob_left_mtf)-1)>bar_index-400 array.pop(ob_top_mtf) array.pop(ob_btm_mtf) array.pop(ob_left_mtf) array.pop(ob_type_mtf) array.pop(ob_buy_vol_mtf) array.pop(ob_sell_vol_mtf) array.pop(ob_vol_mtf) // if array.get(ob_left_mtf,array.size(ob_left_mtf)-1)>bar_index-400 // array.pop(ob_top_mtf) // array.pop(ob_btm_mtf) // array.pop(ob_left_mtf) // array.pop(ob_type_mtf) // array.pop(ob_buy_vol_mtf) // array.pop(ob_sell_vol_mtf) // array.pop(ob_vol_mtf) if array.size(ob_top)>max_obs// or array.get(ob_left,array.size(ob_left)-1)>bar_index-400 array.pop(ob_top) array.pop(ob_btm) array.pop(ob_left) array.pop(ob_type) array.pop(ob_buy_vol) array.pop(ob_sell_vol) array.pop(ob_vol) // //Delete internal order blocks box coordinates if high_ms/bottom is broken if array.size(ob_top_mtf)>1 for index=0 to array.size(ob_top_mtf)-1 src1=mittigation_filt_mtf=='Wicks' or mittigation_filt_mtf=='Touch'? low : mittigation_filt_mtf=='Close'? close : low src2=mittigation_filt_mtf=='Wicks' or mittigation_filt_mtf=='Touch'? high : mittigation_filt_mtf=='Close'? close : high up= mittigation_filt_mtf=='Touch' ? array.get(ob_top_mtf, index) : mittigation_filt_mtf=='Average'? array.get(ob_top_mtf, index)-(array.get(ob_top_mtf, index) - array.get(ob_btm_mtf, index))/2 : array.get(ob_btm_mtf, index) dn= mittigation_filt_mtf=='Touch' ? array.get(ob_btm_mtf, index) : mittigation_filt_mtf=='Average'? array.get(ob_top_mtf, index)-(array.get(ob_top_mtf, index) - array.get(ob_btm_mtf, index))/2 : array.get(ob_top_mtf, index) if (src1 < up or src1[1] < up or (mittigation_filt_mtf!='Touch' and src1[1] < up)) and array.get(ob_type_mtf, index) == 1// and bullish_OB_Break==false array.remove(ob_top_mtf, index) array.remove(ob_btm_mtf, index) array.remove(ob_left_mtf, index) array.remove(ob_type_mtf, index) array.remove(ob_buy_vol_mtf, index) array.remove(ob_sell_vol_mtf, index) array.remove(ob_vol_mtf, index) bullish_OB_Break := true break else if (src2 > dn or src2[1] > dn or (mittigation_filt_mtf!='Touch' and src2[1] > dn)) and array.get(ob_type_mtf, index) == -1// and bearish_OB_Break==false array.remove(ob_top_mtf, index) array.remove(ob_btm_mtf, index) array.remove(ob_left_mtf, index) array.remove(ob_type_mtf, index) array.remove(ob_buy_vol_mtf, index) array.remove(ob_sell_vol_mtf, index) array.remove(ob_vol_mtf, index) bearish_OB_Break := true break if array.size(ob_top)>1 for index=0 to array.size(ob_top)-1 src1=mittigation_filt=='Wicks' or mittigation_filt=='Touch'? low : mittigation_filt=='Close'? close : low src2=mittigation_filt=='Wicks' or mittigation_filt=='Touch'? high : mittigation_filt=='Close'? close : high up= mittigation_filt=='Touch' ? array.get(ob_top, index) : mittigation_filt=='Average'? array.get(ob_top, index)-(array.get(ob_top, index) - array.get(ob_btm, index))/2 : array.get(ob_btm, index) dn= mittigation_filt=='Touch' ? array.get(ob_btm, index) : mittigation_filt=='Average'? array.get(ob_top, index)-(array.get(ob_top, index) - array.get(ob_btm, index))/2 : array.get(ob_top, index) if (src1 < up or src1[1] < up or (mittigation_filt!='Touch' and src1[2] < up)) and array.get(ob_type, index) == 1// and bullish_OB_Break==false array.remove(ob_top, index) array.remove(ob_btm, index) array.remove(ob_left, index) array.remove(ob_type, index) array.remove(ob_buy_vol, index) array.remove(ob_sell_vol, index) array.remove(ob_vol, index) bullish_OB_Break := true break else if (src2 > dn or src2[1] > dn or (mittigation_filt!='Touch' and src2[2] > dn)) and array.get(ob_type, index) == -1// and bearish_OB_Break==false array.remove(ob_top, index) array.remove(ob_btm, index) array.remove(ob_left, index) array.remove(ob_type, index) array.remove(ob_buy_vol, index) array.remove(ob_sell_vol, index) array.remove(ob_vol, index) bearish_OB_Break := true break alertcondition(bullish_OB_Break,'Bullish OB Break','Bullish OB Broken MTF Volumetric Order Blocks [ A V Z I ]') alertcondition(bearish_OB_Break,'Bearish OB Break','Bearish OB Broken MTF Volumetric Order Blocks [ A V Z I ]') ob_size_mtf = array.size(ob_type_mtf) // iob_size = array.size(iob_type) ob_size = array.size(ob_type) if barstate.islast if true for i = 0 to max_obs-1 array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(ob_boxes_buy, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(ob_boxes_sell, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(ob_volume, line.new(na,na,na,na,xloc = xloc.bar_time,color=color.gray,style=line.style_solid,width = 1)) if true for i = 0 to max_obs_mtf-1 array.push(ob_boxes_mtf, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(ob_boxes_buy_mtf, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(ob_boxes_sell_mtf, box.new(na,na,na,na, xloc = xloc.bar_time)) array.push(ob_volume_mtf, line.new(na,na,na,na,xloc = xloc.bar_time,color=color.gray,style=line.style_solid,width = 1)) // array.push(ob_volume, line.new(na,na,na,na,xloc = xloc.bar_index,color=color.yellow,style=line.style_dashed,width = 3)) // array.push(ob_volume_labels, label.new(na,na,xloc =xloc.bar_index,color=color.yellow,size=size.small )) if ob_size > 1 and (overlapping_filt) [deleted_ob,del_index]=remove_ob(ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size) if deleted_ob array.remove(ob_top, del_index) array.remove(ob_btm, del_index) array.remove(ob_left, del_index) array.remove(ob_type, del_index) array.remove(ob_buy_vol, del_index) array.remove(ob_sell_vol, del_index) array.remove(ob_vol, del_index) if ob_size_mtf > 1 and (overlapping_filt_mtf) [deleted_ob,del_index]=remove_ob(ob_top_mtf, ob_btm_mtf, ob_left_mtf, ob_type_mtf, max_obs_mtf, false, ob_size_mtf) if deleted_ob array.remove(ob_top_mtf, del_index) array.remove(ob_btm_mtf, del_index) array.remove(ob_left_mtf, del_index) array.remove(ob_type_mtf, del_index) array.remove(ob_buy_vol_mtf, del_index) array.remove(ob_sell_vol_mtf, del_index) array.remove(ob_vol_mtf, del_index) ob_size_mtf := array.size(ob_type_mtf) // iob_size := array.size(iob_type) ob_size := array.size(ob_type) if ob_size > 0 and barstate.islast if show_order_blocks show_orderblock(ob_boxes,ob_volume, ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size,ob_vol,ibull_ob_css,ibear_ob_css,length_extend_ob,ob_extend,'','',text_size_ob_,volume_text,percent_text,ob_text_color_1,show_line_ob_1,line_style_ob_1) // if v_filter // display_sub_ob_buy(ob_boxes_buy, ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size,ob_buy_vol,ob_sell_vol) // display_sub_ob_sell(ob_boxes_sell, ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size,ob_sell_vol) if ob_size_mtf > 0 and barstate.islast if show_order_blocks_mtf show_orderblock(ob_boxes_mtf,ob_volume_mtf , ob_top_mtf , ob_btm_mtf , ob_left_mtf , ob_type_mtf , max_obs_mtf , false, ob_size_mtf ,ob_vol_mtf ,ibull_ob_css_2,ibear_ob_css_2,length_extend_ob_mtf,ob_extend_mtf,timeframe1,timeframe_st,text_size_ob_2,volume_text_2,percent_text_2,ob_text_color_2,show_line_ob_2,line_style_ob_2) // if v_filter // display_sub_ob_buy(ob_boxes_buy_mtf , ob_top_mtf , ob_btm_mtf , ob_left_mtf , ob_type_mtf , max_obs_mtf , false, ob_size_mtf ,ob_buy_vol_mtf ,ob_sell_vol_mtf) // display_sub_ob_sell(ob_boxes_sell_mtf , ob_top_mtf , ob_btm_mtf , ob_left_mtf , ob_type_mtf , max_obs_mtf , false, ob_size_mtf ,ob_sell_vol_mtf ) //-----------------------------------------------------------------------------}
Backtest Strategy Optimizer Adapter - Supertrend Example
https://www.tradingview.com/script/l30UMAOu-Backtest-Strategy-Optimizer-Adapter-Supertrend-Example/
DinGrogu
https://www.tradingview.com/u/DinGrogu/
4
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/ // © DinGrogu //@version=5 indicator('Backtest Strategy Optimizer Adapter - Supertrend Example', overlay=false) import DinGrogu/backtest/1 as backtest // ################################################################# // # Supertrend Sample function // ################################################################# f_true_range(_high=high, _low=low, _close=close) => _previous_high = _high[1] _previous_close = _close[1] true_range = na(_previous_high) ? _high - _low : math.max(math.max(_high - _low, math.abs(_high - _previous_close)), math.abs(_low - _previous_close)) f_supertrend(_length=10, _multiplier=3, _src=hl2, _close=close, _high=high, _low=low) => true_range = f_true_range(_high, _low, _close) atr = ta.rma(true_range, _length) upper_band = _src + _multiplier * atr lower_band = _src - _multiplier * atr lower_band_previous = nz(lower_band[1]) upper_band_previous = nz(upper_band[1]) lower_band := lower_band > lower_band_previous or _close[1] < lower_band_previous ? lower_band : lower_band_previous upper_band := upper_band < upper_band_previous or _close[1] > upper_band_previous ? upper_band : upper_band_previous int direction = na float signal = na prev_signal = signal[1] if (na(atr[1])) direction := 1 else if (prev_signal == upper_band_previous) direction := _close > upper_band ? -1 : 1 else direction := _close < lower_band ? 1 : -1 signal := direction == -1 ? lower_band : upper_band bool uptrend = direction < 0 bool downtrend = direction > 0 bool uptrend_start = uptrend and downtrend[1] bool downtrend_start = downtrend and uptrend[1] [signal, uptrend, downtrend, uptrend_start, downtrend_start] // ################################################################# // # MAIN VARIABLES // ################################################################# // You can either use a date or the amount of bars back. // In this example its using the amount of bars. // ################################################################# training_bars = input.int(defval=5000, minval=1, title='Training Bars', group='Backtest') date_start = training_bars date_end = date_start var best_value = 0.0 var best_pnl = 0.0 // ################################################################# // # ENTRIES AND EXITS // ################################################################# // See my library "indicators" for more indicators to use here // https://www.tradingview.com/u/DinGrogu/ // Your code for the desired number of entries / exits. // You can use ChatGPT to auto-generate the below code // ################################################################# [_, _, _, entry_001, exit_001] = f_supertrend(10, 1) [_, _, _, entry_002, exit_002] = f_supertrend(10, 2) [_, _, _, entry_003, exit_003] = f_supertrend(10, 3) [_, _, _, entry_004, exit_004] = f_supertrend(10, 4) // 005 etc... // ################################################################# // Your code for the desired number of backtests. // You can use ChatGPT to auto-generate the below code // ################################################################# // AUTO GENERATED CODE [BEGIN] // ▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼ var results_list = array.new_string(5) pnl_001 = backtest.profit(date_start, date_end, entry_001, exit_001) pnl_002 = backtest.profit(date_start, date_end, entry_002, exit_002) pnl_003 = backtest.profit(date_start, date_end, entry_003, exit_003) pnl_004 = backtest.profit(date_start, date_end, entry_004, exit_004) plot(pnl_001, title='0.1', color=backtest.color(001)) plot(pnl_002, title='0.2', color=backtest.color(002)) plot(pnl_003, title='0.3', color=backtest.color(003)) plot(pnl_004, title='0.4', color=backtest.color(004)) if (ta.change(pnl_001)) array.set(results_list, 0, str.tostring(pnl_001) + '|1') if (ta.change(pnl_002)) array.set(results_list, 1, str.tostring(pnl_002) + '|2') if (ta.change(pnl_003)) array.set(results_list, 2, str.tostring(pnl_003) + '|3') if (ta.change(pnl_004)) array.set(results_list, 3, str.tostring(pnl_004) + '|4') // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ // AUTO GENERATED CODE [END] // ################################################################# // ################################################################# // # SET THE VALUES CREATED BY THE CODE ABOVE // ################################################################# // At each new bar reset the best pnl and value. if (barstate.islast) best_pnl := 0 best_value := 0 // Then run the results array again afterwards to set the new best_pnl and value. if (array.size(results_list) > 0) for i = 0 to array.size(results_list) - 1 by 1 result_string = array.get(results_list, i) if (str.contains(result_string, '|')) result_values = str.split(result_string, '|') result = str.tonumber(array.first(result_values)) if (not na (result) and result > best_pnl) best_value := str.tonumber(array.last(result_values)) best_pnl := result plot(best_value, title='🔌 Value', display=display.none) plot(best_pnl, title='🔌 Profit (%)', color=color.green)
Lingga Trader Scalper
https://www.tradingview.com/script/UdkeVdGI/
linggatrader
https://www.tradingview.com/u/linggatrader/
16
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/ // © nicks1008 //@version=5 indicator(title='Lingga Trader', shorttitle='Lingga Scalper |3 Min', precision=2, overlay=true) Rsi_value = input.int(14, title='RSI Length', step=1) hl = input.int(80, title='Higher Value of RSI', step=1) ll = input.int(20, title='Lower value of RSI', step=1) rs = ta.rsi(close, Rsi_value) sma_value = input.int(70, title='SMA Length', step=1) sma1 = ta.sma(close, sma_value) dist_SMA = 1 candle_length = 1 iff_1 = high < sma1 ? color.new(color.red,30) : color.new(color.yellow,30) iff_2 = low > sma1 ? color.new(color.lime,30) : iff_1 mycolor = rs >= hl or rs <= ll ? color.new(color.yellow,30) : iff_2 gaps = sma1 + dist_SMA //Gap between price and SMA for Sell gapb = sma1 - dist_SMA //Gap between price and SMA for Buy chartgap = gaps or gapb //for both below or above the SMA gap1 = sma1 + 5 gapvalue = open / 100 * candle_length //setting % with its Share price gapp = high - low > gapvalue //or rs<50 // Condition for Min candle size to be eligible for giving signal - Buy Calls gapp2 = high - low > gapvalue //or rs>55 // Condition for Min candle size to be eligible for giving signal - Sell Calls bull = open < close and high - low > 2 * gapvalue and close > (high + open) / 2 bear = open > close and high - low > 2 * gapvalue and close < (low + open) / 2 rev1 = rs > 68 and open > close and open > gaps and high - low > gapvalue + 0.5 and low != close //over red candles "S" - uptrend rev1a = rs > 90 and open < close and close > gaps and high != close and open != low // over green candles"S" - uptrend sellrev = rev1 or rev1a rev2 = rs < 50 and open < close and open < gapb and open == low //over green candles"B" rev3 = rs < 30 and open > close and high > gapb and open != high and barstate.isconfirmed != bear //over red candles"B" rev4 = rs < 85 and close == high and high - low > gapvalue and open < close //over green candle in both trends hlrev_s = ta.crossunder(rs, hl) llrev_b = ta.crossover(rs, ll) and open < close buycall = open < close and open > sma1 and ta.cross(close[1], sma1) and close > sma1 sellcall = ta.cross(close, sma1) and open > close BUY = ta.crossover(close[1], sma1) and close[1] > open[1] and high[0] > high[1] and close[0] > open[0] SELL = ta.crossunder(low[1], sma1) and close[1] < open[1] and low[0] < low[1] and close[0] < open[0] plotshape(SELL, title='SELL', style=shape.labeldown, color=color.new(color.red, 30), text='S', textcolor=color.new(color.black, 30)) plotshape(BUY, title='BUY', style=shape.labelup, color=color.new(color.aqua, 30), text='B', textcolor=color.new(color.black, 30), location=location.belowbar) plotshape(hlrev_s, title='Reversal1', style=shape.labeldown, color=color.new(color.yellow, 20), text='!', textcolor=color.new(color.black, 20)) plotshape(llrev_b, title='Reversal2', style=shape.labelup, color=color.new(color.yellow, 20), text='!', textcolor=color.new(color.black, 20), location=location.belowbar) barcolor(BUY ? color.new(color.green, 0) : SELL ? color.new(color.maroon, 30) : hlrev_s or llrev_b ? color.new(color.yellow, 0) : na) plot(sma1, title='SMA', color=mycolor, linewidth=1) alertcondition(hlrev_s or llrev_b, title='Both Reversal Signal', message='Reversal Alert') alertcondition(SELL or BUY, title='Buy & Sell Signal Both', message='Buy/Sell Alert') alertcondition(BUY, title='Only Buy Signal', message='Buy Alert') alertcondition(SELL, title='Only Sell Signal', message='Sell Alert') alertcondition(hlrev_s , title='Reversal from Top', message='Down Reversal Alert') alertcondition(llrev_b, title='Reversal from Down', message='Up Reversal Alert') //@version=5 bool msb_sv = input.bool (true, title='Plot MSB lines') bool box_sv = input.bool (true, title='Plot Orderblocks') bool m_sv = input.bool (true, title='Plot Breakerblocks') bool range_sv = input.bool (true, title='Plot Range') bool range_eq_sv = input.bool (true, title='Plot Range 0.5 Line') bool range_q_sv = input.bool (true, title='Plot Range 0.25 and 0.75 Lines') color u_s = input.color (color.new(#089981, 80), title='Untested Supply Color') color t_s = input.color (color.new(#b2b5be, 80), title='Tested Supply Color') color u_d = input.color (color.new(#f23645, 80), title='Untested Demand Color') color t_d = input.color (color.new(#b2b5be, 80), title='Tested Demand Color') color u_b = input.color (color.new(#ff9800, 80), title='Untested Breaker Color') color t_b = input.color (color.new(#b2b5be, 80), title='Tested Breaker Color') var float[] pvh1_price = array.new_float (30, na) // high var int[] pvh1_time = array.new_int (30, na) var float[] pvl1_price = array.new_float (30, na) // low var int[] pvl1_time = array.new_int (30, na) var float[] pvh2_price = array.new_float (10, na) // higher high var int[] pvh2_time = array.new_int (10, na) var float[] pvl2_price = array.new_float (10, na) // lower low var int[] pvl2_time = array.new_int (10, na) var float htcmrll_price = na // high that created most recent ll var int htcmrll_time = na var float ltcmrhh_price = na // low that created most recent hh var int ltcmrhh_time = na var box[] long_boxes = array.new_box() // orderblocks var box[] short_boxes = array.new_box() var box[] m_long_boxes = array.new_box() // breakerblocks var box[] m_short_boxes = array.new_box() var line[] bull_bos_lines = array.new_line() // MSB lines var line[] bear_bos_lines = array.new_line() var line[] range_h_lines = array.new_line() // Range lines var line[] range_25_lines = array.new_line() var line[] range_m_lines = array.new_line() var line[] range_75_lines = array.new_line() var line[] range_l_lines = array.new_line() var label[] la_ph2 = array.new_label() // 2nd order pivots var label[] la_pl2 = array.new_label() var float temp_pv_0 = na var float temp_pv_1 = na var float temp_pv_2 = na var int temp_time = na var float last_range_h = na var float last_range_l = na var line range_m = na var line range_25 = na var line range_75 = na var float box_top = na var float box_bottom = na bool pvh = high < high[1] and high[1] > high[2] bool pvl = low > low[1] and low[1] < low[2] int pv1_time = bar_index[1] float pv1_high = high[1] float pv1_low = low[1] bool new_ph_2nd = false bool new_pl_2nd = false string alert = na //weekendicator multiplier = input.float(3, minval=0, maxval=10, step=0.1, group = "Weekend") day_clr = dayofweek < 2 or dayofweek > 6 ? color.new(#9598a1, 80) : color.new(#9598a1, 100) plot(((high / low) * ohlc4) * (1 + multiplier / 100), style=plot.style_line, color=day_clr) plot(((low / high) * ohlc4) * (1 - multiplier / 100), style=plot.style_area, color=day_clr) // range blocks etc if barstate.isconfirmed if pvh array.pop(pvh1_price) array.pop(pvh1_time) array.unshift(pvh1_price, pv1_high) array.unshift(pvh1_time, pv1_time) if array.size(pvh1_price) > 2 temp_pv_0 := array.get(pvh1_price, 0) temp_pv_1 := array.get(pvh1_price, 1) temp_pv_2 := array.get(pvh1_price, 2) if temp_pv_0 < temp_pv_1 and temp_pv_1 > temp_pv_2 array.pop(pvh2_price) array.pop(pvh2_time) array.unshift(pvh2_price, temp_pv_1) array.unshift(pvh2_time, array.get(pvh1_time, 1)) new_ph_2nd := true if temp_pv_1 > array.get(pvh2_price, 1) for i = 0 to array.size(pvl2_time) - 1 by 1 temp_ltcmrhh_time = array.get(pvl2_time, i) if temp_ltcmrhh_time < array.get(pvh2_time, 0) ltcmrhh_price := array.get(pvl2_price, i) ltcmrhh_time := temp_ltcmrhh_time break if temp_pv_0 < ltcmrhh_price if msb_sv array.push(bear_bos_lines, line.new(x1=ltcmrhh_time, y1=ltcmrhh_price, x2=bar_index, y2=ltcmrhh_price, color=color.fuchsia, width=2)) box_top := array.get(pvh2_price, 0) box_bottom := math.max(low[bar_index - array.get(pvh2_time, 0)], low[bar_index - array.get(pvh2_time, 0) + 1]) array.push(short_boxes, box.new(left=array.get(pvh2_time, 0), top=box_top, right=bar_index, bottom=box_bottom, bgcolor= box_sv ? u_s : na , border_color=na, extend=extend.right)) ltcmrhh_price := na if pvl array.pop(pvl1_price) array.pop(pvl1_time) array.unshift(pvl1_price, pv1_low) array.unshift(pvl1_time, pv1_time) if array.size(pvl1_price) > 2 temp_pv_0 := array.get(pvl1_price, 0) temp_pv_1 := array.get(pvl1_price, 1) temp_pv_2 := array.get(pvl1_price, 2) if temp_pv_0 > temp_pv_1 and temp_pv_1 < temp_pv_2 array.pop(pvl2_price) array.pop(pvl2_time) array.unshift(pvl2_price, temp_pv_1) array.unshift(pvl2_time, array.get(pvl1_time, 1)) new_pl_2nd := true if temp_pv_1 < array.get(pvl2_price, 1) for i = 0 to array.size(pvh2_time) - 1 by 1 temp_htcmrll_time = array.get(pvh2_time, i) if temp_htcmrll_time < array.get(pvl2_time, 0) htcmrll_price := array.get(pvh2_price, i) htcmrll_time := temp_htcmrll_time break if temp_pv_0 > htcmrll_price if msb_sv array.push(bull_bos_lines, line.new(x1=htcmrll_time, y1=htcmrll_price, x2=bar_index, y2=htcmrll_price, color=color.olive, width=2)) box_top := math.min(high[bar_index - array.get(pvl2_time, 0)], high[bar_index - array.get(pvl2_time, 0) + 1]) box_bottom := array.get(pvl2_price, 0) array.push(long_boxes, box.new(left=array.get(pvl2_time, 0), top=box_top, right=bar_index, bottom=box_bottom, bgcolor= box_sv ? u_d : na, border_color=na, extend=extend.right)) htcmrll_price := na if array.size(short_boxes) > 0 for i = array.size(short_boxes) - 1 to 0 by 1 tbox = array.get(short_boxes, i) top = box.get_top(tbox) bottom = box.get_bottom(tbox) ago = box.get_left(tbox) if array.get(pvh1_price, 0) > bottom if box_sv box.set_bgcolor(tbox, t_s) if array.get(pvl1_price, 0) > top if m_sv box.set_bgcolor(tbox, u_b) array.push(m_long_boxes, tbox) else box.delete(tbox) array.remove(short_boxes, i) if msb_sv line.delete(array.get(bear_bos_lines, i)) array.remove(bear_bos_lines, i) if array.size(long_boxes) > 0 for i = array.size(long_boxes) - 1 to 0 by 1 lbox = array.get(long_boxes, i) top = box.get_top(lbox) bottom = box.get_bottom(lbox) ago = box.get_left(lbox) if array.get(pvl1_price, 0) < top if box_sv box.set_bgcolor(lbox, t_d) if array.get(pvh1_price, 0) < bottom if m_sv box.set_bgcolor(lbox, u_b) array.push(m_short_boxes, lbox) else box.delete(lbox) array.remove(long_boxes, i) if msb_sv line.delete(array.get(bull_bos_lines, i)) array.remove(bull_bos_lines, i) if array.size(m_short_boxes) > 0 for i = array.size(m_short_boxes) - 1 to 0 by 1 tbox = array.get(m_short_boxes, i) top = box.get_top(tbox) bottom = box.get_bottom(tbox) ago = box.get_left(tbox) if array.get(pvh1_price, 0) > bottom box.set_bgcolor(tbox, t_b) if array.get(pvl1_price, 0) > top box.delete(tbox) array.remove(m_short_boxes, i) if array.size(m_long_boxes) > 0 for i = array.size(m_long_boxes) - 1 to 0 by 1 lbox = array.get(m_long_boxes, i) top = box.get_top(lbox) bottom = box.get_bottom(lbox) ago = box.get_left(lbox) if array.get(pvl1_price, 0) < top box.set_bgcolor(lbox, t_b) if array.get(pvh1_price, 0) < bottom box.delete(lbox) array.remove(m_long_boxes, i) if range_sv and (new_ph_2nd or new_pl_2nd) and (array.get(pvh2_price, 0) < array.get(pvh2_price, 1) and array.get(pvl2_price, 0) > array.get(pvl2_price, 1) and array.get(pvh2_price, 0) > array.get(pvl2_price, 1) and array.get(pvl2_price, 0) < array.get(pvh2_price, 1)) and (array.get(pvl2_price, 1) > nz(last_range_h) or na(last_range_l)? true : (array.get(pvh2_price, 1) < last_range_l)) temp_time := math.min(array.get(pvh2_time, 1), array.get(pvl2_time, 1)) last_range_h := array.get(pvh2_price, 1) last_range_l := array.get(pvl2_price, 1) temp_pv_0 := (last_range_h + last_range_l)/2 temp_pv_1 := (last_range_h + temp_pv_0)/2 temp_pv_2 := (last_range_l + temp_pv_0)/2 array.push(range_h_lines, line.new(x1=temp_time, y1=last_range_h, x2=bar_index, y2=last_range_h, color=color.black, width=2, extend=extend.right)) array.push(range_l_lines, line.new(x1=temp_time, y1=last_range_l, x2=bar_index, y2=last_range_l, color=color.black, width=2, extend=extend.right)) if range_eq_sv array.push(range_m_lines, line.new(x1=temp_time, y1=temp_pv_0, x2=bar_index, y2=temp_pv_0, color=color.gray, width=2, extend=extend.right)) if range_q_sv array.push(range_25_lines, line.new(x1=temp_time, y1=temp_pv_1, x2=bar_index, y2=temp_pv_1, style=line.style_dashed, color=color.gray, width=1, extend=extend.right)) array.push(range_75_lines, line.new(x1=temp_time, y1=temp_pv_2, x2=bar_index, y2=temp_pv_2, style=line.style_dashed, color=color.gray, width=1, extend=extend.right)) if array.size(range_h_lines) > 0 for i = array.size(range_h_lines) - 1 to 0 by 1 range_h = array.get(range_h_lines, i) top = line.get_y1(range_h) range_l = array.get(range_l_lines, i) bottom = line.get_y1(range_l) temp_time := line.get_x1(range_h) if range_eq_sv range_m := array.get(range_m_lines, i) if range_q_sv range_25 := array.get(range_25_lines, i) range_75 := array.get(range_75_lines, i) if array.get(pvh1_price, 0) < bottom or array.get(pvl1_price, 0) > top line.delete(range_h) array.remove(range_h_lines, i) line.delete(range_l) array.remove(range_l_lines, i) if range_eq_sv line.delete(range_m) array.remove(range_m_lines, i) if range_q_sv line.delete(range_25) array.remove(range_25_lines, i) line.delete(range_75) array.remove(range_75_lines, i) last_range_h := na last_range_l := na //////////////////////////////////////////////////////////////////////////////// //new york open etc iMDisplay = input.bool (true, "Display", group="New York Midnight Open") iMTime = input.session ('0400-0405:1234567', "Session", group="New York Midnight Open") iMStyle = input.string ("Dashed", "Line Style", options=["Solid", "Dotted", "Dashed"], group="New York Midnight Open") iMColor = input.color (#58A2B0, "Color", group="New York Midnight Open") iMHistory = input.bool (false, "History", group="New York Midnight Open") iMLabel = input.bool (true, "Show Label", group="New York Midnight Open") i8Display = input.bool (true, "Display", group="New York 8:30 Open") i8Time = input.session ('1230-1235:1234567', "Session", group="New York 8:30 Open") i8Style = input.string ("Dotted", "Line Style", options=["Solid", "Dotted", "Dashed"], group="New York 8:30 Open") i8Color = input.color (#58A2B0, "Color", group="New York 8:30 Open") i8History = input.bool (false, "History", group="New York 8:30 Open") i8Label = input.bool (true, "Show Label", group="New York 8:30 Open") tMidnight = time ("1", iMTime) t830 = time ("1", i8Time) _MStyle = iMStyle == "Solid" ? line.style_solid : iMStyle == "Dotted" ? line.style_dotted : line.style_dashed _8Style = i8Style == "Solid" ? line.style_solid : i8Style == "Dotted" ? line.style_dotted : line.style_dashed //==== Midnight Open ==== if iMDisplay var openMidnight = 0.0 if tMidnight if not tMidnight[1] openMidnight := open else openMidnight := math.max(open, openMidnight) var label lb = na var line lne = na if openMidnight != openMidnight[1] if barstate.isconfirmed line.set_x2(lne, tMidnight) lne := line.new(tMidnight, openMidnight, last_bar_time + 14400000/2, openMidnight, xloc.bar_time, extend.none, iMColor, _MStyle, 1) if iMLabel lb := label.new(last_bar_time + 14400000/2, openMidnight, "Midnight", xloc.bar_time, yloc.price, na, label.style_none, iMColor, size.normal, text.align_right) label.delete(lb[1]) if not iMHistory line.delete(lne[1]) //=========================== //==== 8:30 Open ==== if i8Display var open830 = 0.0 if t830 if not t830[1] open830 := open else open830 := math.max(open, open830) var label lb2 = na var line lne2 = na if open830 != open830[1] if barstate.isconfirmed line.set_x2(lne2, t830 - 30600000) lne2 := line.new(t830, open830, last_bar_time + 14400000/2, open830, xloc.bar_time, extend.none, i8Color, _8Style, 1) if i8Label lb2 := label.new(last_bar_time + 14400000/2, open830, "8:30", xloc.bar_time, yloc.price, na, label.style_none, i8Color, size.normal, text.align_right) label.delete(lb2[1]) if not i8History line.delete(lne2[1]) //=========================== // Balanced Price Range bpr_threshold = input.float(0, step = 0.25, title = "BPR Threshold", tooltip = "Valid BPR's must have a range greater than this number") bars_since = input(15, "Bars to Look Back for BPR", tooltip = "Only look for BPR's when a sequence of bearish and bullish FVG's are within this many bars of each other") only_clean_bpr = input(false, "Only Clean BPR", tooltip = "Only show BPR's when price does not interfere with the range prior to its completion") delete_old_bpr = input(true, "Delete Old BPR", tooltip = "Delete all BPR's that have been invalidated or overwritten. Only show current/active BPR's") bearish_bpr_color = input.color(color.new(color.green, 70)) bullish_bpr_color = input.color(color.new(color.green, 70)) float box_high = na float box_low = na int box_left = 0 int box_right = 0 var box box_bearish = na var box box_bullish = na new_fvg_bearish = low[2] - high > 0 new_fvg_bullish = low - high[2] > 0 valid_high = high[1] > high[2] and high[1] > high[0] valid_low = low[1] < low[2] and low[1] < low[0] midline = (high - low) / 2 + low valid_hammer = open > midline and close > midline valid_shooter = open < midline and close < midline // Bullish BPR bull_num_since = ta.barssince(new_fvg_bearish) bull_bpr_cond_1 = new_fvg_bullish and bull_num_since <= bars_since bull_bpr_cond_2 = bull_bpr_cond_1 ? high[bull_num_since] + low[bull_num_since + 2] + high[2] + low > math.max(low[bull_num_since + 2], low) - math.min(high[bull_num_since], high[2]) : na bull_combined_low = bull_bpr_cond_2 ? math.max(high[bull_num_since], high[2]) : na bull_combined_high = bull_bpr_cond_2 ? math.min(low[bull_num_since + 2], low) : na bull_bpr_cond_3 = true if only_clean_bpr for h = 2 to (bull_num_since) if high[h] > bull_combined_low bull_bpr_cond_3 := false bull_result = bull_bpr_cond_1 and bull_bpr_cond_2 and bull_bpr_cond_3 and (bull_combined_high - bull_combined_low >= bpr_threshold) if bull_result[1] if delete_old_bpr and not na(box_bullish) box.delete(box_bullish) box_bullish := box.new(bar_index - bull_num_since - 1, bull_combined_high[1], bar_index + 1, bull_combined_low[1], border_color = bullish_bpr_color, border_width = 1, bgcolor = bullish_bpr_color) alertcondition(bull_result[1], "Bullish Alert", "New Bullish BPR") if not na(box_bullish) and low > box.get_bottom(box_bullish) box.set_right(box_bullish, bar_index + 1) else if not na(box_bullish) and low < box.get_bottom(box_bullish) if delete_old_bpr box.delete(box_bullish) else box_bullish := na // Bearish BPR bear_num_since = ta.barssince(new_fvg_bullish) bear_bpr_cond_1 = new_fvg_bearish and bear_num_since <= bars_since bear_bpr_cond_2 = bear_bpr_cond_1 ? high[bear_num_since] + low[bear_num_since + 2] + high[2] + low > math.max(low[bear_num_since + 2], low) - math.min(high[bear_num_since], high[2]) : na bear_combined_low = bear_bpr_cond_2 ? math.max(high[bear_num_since + 2], high) : na bear_combined_high = bear_bpr_cond_2 ? math.min(low[bear_num_since], low[2]) : na bear_bpr_cond_3 = true if only_clean_bpr for h = 2 to (bear_num_since) if low[h] < bear_combined_high bear_bpr_cond_3 := false bear_result = bear_bpr_cond_1 and bear_bpr_cond_2 and bear_bpr_cond_3 and (bear_combined_high - bear_combined_low >= bpr_threshold) if bear_result[1] if delete_old_bpr and not na(box_bearish) box.delete(box_bearish) box_bearish := box.new(bar_index - bear_num_since - 1, bear_combined_high[1], bar_index + 1, bear_combined_low[1], border_color = bearish_bpr_color, border_width = 1, bgcolor = bearish_bpr_color) alertcondition(bear_result[1], "Bearish Alert", "New Bearish BPR") if not na(box_bearish) and high < box.get_top(box_bearish) box.set_right(box_bearish, bar_index + 1) else if not na(box_bearish) and high > box.get_top(box_bearish) if delete_old_bpr box.delete(box_bearish) else box_bearish := na //////////////////////////////////////////////////////////////////////////////// //CME gap show and fill mode = input.string( defval="1 - Close from current symbol", title="Mode", options=["1 - Close from current symbol", "2 - CME original close crice", "3 - CME settlement price"], tooltip="In Mode 1 the closing price is determined in the current symbol but with the tradinghours from the CME futures contract. Mode 2 and 3 obtain the price directly from the CME futures contract and paint it in the chart of the current symbol. But note, that modes 2 and 3 may not give you the expected result, due to price differences in futures and spot prices.") cme = request.security("CME:BTC1!", "60", close) cmeSettlement = request.security("CME:BTC1!", "D", close, lookahead=barmerge.lookahead_on) //Function to get friday closing price according to CME trading hours getCloseCME() => cmeClose = 0.0 cmeClosePrev = nz(cmeClose[1], cmeClose) showLine = 0 showLine := nz(showLine[1], showLine) if mode == "1 - Close from current symbol" cmeClose := dayofweek == 6 and time == timestamp('GMT-5', year, month, dayofmonth, 16, 0, 0) ? close[1] : cmeClosePrev else if mode == "2 - CME original close crice" cmeClose := dayofweek == 6 and time == timestamp('GMT-5', year, month, dayofmonth, 16, 0, 0) ? cme : cmeClosePrev else if mode == "3 - CME settlement price" cmeClose := dayofweek == 6 and time == timestamp('GMT-5', year, month, dayofmonth, 16, 0, 0) ? cmeSettlement : cmeClosePrev showLine := showLine == 0 and time >= timestamp('GMT-5', year, month, dayofmonth, 16, 0, 0) and dayofweek >= 6 ? 1 : showLine == 1 and dayofweek <= 1 and time >= timestamp('GMT-5', year, month, dayofmonth, 17, 0, 0) ? 0 : showLine [cmeClose, showLine] [cmeClose, showLine] = getCloseCME() //Plotting plot1 = plot(showLine == 1 ? cmeClose : na, 'CME Friday Close', style=plot.style_linebr, linewidth=2, color=color.new(color.blue, 0)) plot2 = plot(close, 'Dummy plot for background', color=na) fill(plot1, plot2, title='Background', color=close > cmeClose ? color.new(color.green, 80) : close < cmeClose ? color.new(color.red, 80) : na)
MTF ATR Reversal Levels (Open Source)
https://www.tradingview.com/script/CSm56daB-MTF-ATR-Reversal-Levels-Open-Source/
DeuceDavis
https://www.tradingview.com/u/DeuceDavis/
96
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/ // Some code has been borowed from multiple open sources but the heart of the code is from the Blackflag FTS Indicator // provided by https://www.tradingview.com/u/vsnfnd/ // @DeuceDavis aka JustDeuce //@version=5 indicator('MTF ATR Reversal Levels', overlay=true) // inputs // //{ trailType = input.string('modified', 'Trailtype', options=['modified', 'unmodified']) ATRPeriod = input(28, 'ATR Period') ATRFactor = input.float(3.0, 'ATR Factor', step=0.1) ATRAlertThreshold = input.float(1, 'ATR Alert Threshold', step=0.1) showCurrentReversalLevel = input(true, 'Show Current Bar Reversal Levels (Horizontal Line') offsetLabels = input(title='Offset Labels', defval=false) showReversalLevel = input(false, 'Plot Historical Reversal Levels') showTrendChangeAlert = input(title='Show Trend Change Buy/Sell Alert', defval=true) conservativeAlert = input(title='Alert After Pullback', defval=false) //Inputs res1Start = input(title='------------Primary Resolution Settings----------', defval=false) res1 = input.timeframe(title='Resolution 1', defval='Chart TF', options=['Chart TF', '1m', '3m', '5m', '15m', '30m', '45m', '1H', '2H', '3H', '4H', 'Daily', 'Weekly', 'Monthly']) showRes1Fibs = input(title='Show Fibonacci Reversal Cloud', defval=false) fibLevel1 = input(title='Fibonacci Level 1', defval=50.0) fibLevel2 = input(title='Fibonacci Level 2', defval=61.8) fibLevel3 = input(title='Fibonacci Level 3', defval=78.6) extraResolutions = input(title='------------Other Resolution Settings----------', defval=false) res2 = input.timeframe(title='Resolution 2', defval='15m', options=['Chart TF', '1m', '3m', '5m', '15m', '30m', '45m', '1H', '2H', '3H', '4H', 'Daily', 'Weekly', 'Monthly']) res3 = input.timeframe(title='Resolution 3', defval='30m', options=['Chart TF', '1m', '3m', '5m', '15m', '30m', '45m', '1H', '2H', '3H', '4H', 'Daily', 'Weekly', 'Monthly']) res4 = input.timeframe(title='Resolution 4', defval='1H', options=['Chart TF', '1m', '3m', '5m', '15m', '30m', '45m', '1H', '2H', '3H', '4H', 'Daily', 'Weekly', 'Monthly']) res5 = input.timeframe(title='Resolution 5', defval='Daily', options=['Chart TF', '1m', '3m', '5m', '15m', '30m', '45m', '1H', '2H', '3H', '4H', 'Daily', 'Weekly', 'Monthly']) //inputs for to choose timeframe resolution of calculations resLookUp(Resolution) => if Resolution == 'Chart TF' timeframe.period else if Resolution == '1m' '1' else if Resolution == '3m' '3' else if Resolution == '5m' '5' else if Resolution == '15m' '15' else if Resolution == '30m' '30' else if Resolution == '45m' '45' else if Resolution == '1H' '60' else if Resolution == '2H' '120' else if Resolution == '3H' '180' else if Resolution == '4H' '240' else if Resolution == 'Daily' '1D' else if Resolution == 'Weekly' '1W' else if Resolution == 'Monthly' '1M' plotTransp = showReversalLevel ? 50 : 100 plotCurrentTransp = showCurrentReversalLevel ? 50 : 100 supportColor = color.new(color.lime, plotTransp) resistanceColor = color.new(color.red, plotTransp) currentSupportColor = color.new(color.lime, plotCurrentTransp) currentResistanceColor = color.new(color.red, plotCurrentTransp) //} //////// FUNCTIONS ////////////// //{ // Wilders ma // Wild_ma(_src, _malength) => _wild = 0.0 _wild := nz(_wild[1]) + (_src - nz(_wild[1])) / _malength _wild // RoundToTickUp() rounds the given value up to the next tick, // using the tick size of the chart's instrument. RoundToTick(value) => math.floor(value / syminfo.mintick) * syminfo.mintick /////////// TRUE RANGE CALCULATIONS ///////////////// trueRanges(res) => norm_o = request.security(syminfo.tickerid, res, open) norm_h = request.security(syminfo.tickerid, res, high) norm_l = request.security(syminfo.tickerid, res, low) norm_c = request.security(syminfo.tickerid, res, close) HiLo = request.security(syminfo.tickerid, res, math.min(norm_h - norm_l, 1.5 * nz(ta.sma(norm_h - norm_l, ATRPeriod)))) // HiLo = min(norm_h - norm_l, 1.5 * nz(sma((norm_h - norm_l), ATRPeriod))) HRef = request.security(syminfo.tickerid, res, norm_l <= norm_h[1] ? norm_h - norm_c[1] : norm_h - norm_c[1] - 0.5 * (norm_l - norm_h[1])) LRef = request.security(syminfo.tickerid, res, norm_h >= norm_l[1] ? norm_c[1] - norm_l : norm_c[1] - norm_l - 0.5 * (norm_l[1] - norm_h)) trueRange = request.security(syminfo.tickerid, res, trailType == 'modified' ? math.max(HiLo, HRef, LRef) : math.max(norm_h - norm_l, math.abs(norm_h - norm_c[1]), math.abs(norm_l - norm_c[1]))) //} /////////// TRADE LOGIC //////////////////////// //{ loss = ATRFactor * request.security(syminfo.tickerid, res, Wild_ma(trueRange, ATRPeriod)) Up = norm_c - loss Dn = norm_c + loss TrendUp = Up TrendDown = Dn Trend = 1 var float trail = na TrendUp := norm_c[1] > TrendUp[1] ? math.max(Up, TrendUp[1]) : Up TrendDown := norm_c[1] < TrendDown[1] ? math.min(Dn, TrendDown[1]) : Dn Trend := norm_c > TrendDown[1] ? 1 : norm_c < TrendUp[1] ? -1 : nz(Trend[1], 1) trail := Trend == 1 ? TrendUp : TrendDown trail := RoundToTick(trail) //trail := Trend == na ? trail[1] : // Trend == 1 ? TrendUp : TrendDown ex = 0.0 ex := ta.crossover(Trend, 0) ? norm_h : ta.crossunder(Trend, 0) ? norm_l : Trend == 1 ? math.max(ex[1], norm_h) : Trend == -1 ? math.min(ex[1], norm_l) : ex[1] fib1Level = fibLevel1 fib2Level = fibLevel2 fib3Level = fibLevel3 f1 = RoundToTick(ex + (trail - ex) * fib1Level / 100) f2 = RoundToTick(ex + (trail - ex) * fib2Level / 100) f3 = RoundToTick(ex + (trail - ex) * fib3Level / 100) atrValue = Wild_ma(trueRange, ATRPeriod) trueRangeRatio = trueRange / atrValue[1] [trail, Trend, ex, f1, f2, f3, trueRangeRatio] //{ [trail1, Trend1, ex1, f1_1, f2_1, f3_1, atrRatio1] = trueRanges(resLookUp(res1)) [trail2, Trend2, ex2, f1_2, f2_2, f3_2, atrRatio2] = trueRanges(resLookUp(res2)) [trail3, Trend3, ex3, f1_3, f2_3, f3_3, atrRatio3] = trueRanges(resLookUp(res3)) [trail4, Trend4, ex4, f1_4, f2_4, f3_4, atrRatio4] = trueRanges(resLookUp(res4)) [trail5, Trend5, ex5, f1_5, f2_5, f3_5, atrRatio5] = trueRanges(resLookUp(res5)) t1 = plot(trail1, 'Reversal Res 1', style=plot.style_line, color=Trend1 == 1 ? supportColor : Trend1 == -1 ? resistanceColor : na) t2 = plot(trail2, 'Reversal Res 2', style=plot.style_line, color=Trend2 == 1 ? supportColor : Trend2 == -1 ? resistanceColor : na) t3 = plot(trail3, 'Reversal Res 3', style=plot.style_line, color=Trend3 == 1 ? supportColor : Trend3 == -1 ? resistanceColor : na) t4 = plot(trail4, 'Reversal Res 4', style=plot.style_line, color=Trend4 == 1 ? supportColor : Trend4 == -1 ? resistanceColor : na) t5 = plot(trail5, 'Reversal Res 5', style=plot.style_line, color=Trend5 == 1 ? supportColor : Trend5 == -1 ? resistanceColor : na) t1_fib1 = plot(f1_1, title='f1_1', color=color.new(color.black, 100)) t1_fib2 = plot(f2_1, title='f2_1', color=color.new(color.black, 100)) t1_fib3 = plot(f3_1, title='f3_1', color=color.new(color.black, 100)) t2_fib1 = plot(f1_2, title='f1_2', color=color.new(color.black, 100)) t2_fib2 = plot(f2_2, title='f2_2', color=color.new(color.black, 100)) t2_fib3 = plot(f3_2, title='f3_2', color=color.new(color.black, 100)) t3_fib1 = plot(f1_3, title='f1_3', color=color.new(color.black, 100)) t3_fib2 = plot(f2_3, title='f2_3', color=color.new(color.black, 100)) t3_fib3 = plot(f3_3, title='f3_3', color=color.new(color.black, 100)) t4_fib1 = plot(f1_4, title='f1_4', color=color.new(color.black, 100)) t4_fib2 = plot(f2_4, title='f2_4', color=color.new(color.black, 100)) t4_fib3 = plot(f3_4, title='f3_4', color=color.new(color.black, 100)) t5_fib1 = plot(f1_5, title='f1_5', color=color.new(color.black, 100)) t5_fib2 = plot(f2_5, title='f2_5', color=color.new(color.black, 100)) t5_fib3 = plot(f3_5, title='f3_5', color=color.new(color.black, 100)) //Color Logic l1Color = Trend1 == 1 ? currentSupportColor : Trend1 == -1 ? currentResistanceColor : na l2Color = Trend2 == 1 ? currentSupportColor : Trend2 == -1 ? currentResistanceColor : na l3Color = Trend3 == 1 ? currentSupportColor : Trend3 == -1 ? currentResistanceColor : na l4Color = Trend4 == 1 ? currentSupportColor : Trend4 == -1 ? currentResistanceColor : na l5Color = Trend5 == 1 ? currentSupportColor : Trend5 == -1 ? currentResistanceColor : na //Lines and Labels if barstate.islast l1 = line.new(x1=bar_index[1], y1=trail1, x2=bar_index, y2=trail1, extend=extend.right, width=3, color=l1Color) l2 = line.new(x1=bar_index[1], y1=trail2, x2=bar_index, y2=trail2, extend=extend.right, width=3, color=l2Color) l3 = line.new(x1=bar_index[1], y1=trail3, x2=bar_index, y2=trail3, extend=extend.right, width=3, color=l3Color) l4 = line.new(x1=bar_index[1], y1=trail4, x2=bar_index, y2=trail4, extend=extend.right, width=3, color=l4Color) l5 = line.new(x1=bar_index[1], y1=trail5, x2=bar_index, y2=trail5, extend=extend.right, width=3, color=l5Color) line.delete(l1[1]) line.delete(l2[1]) line.delete(l3[1]) line.delete(l4[1]) line.delete(l5[1]) label1Text = str.tostring(res1) + ': ' + str.tostring(trail1, '0.00') + '|TR:ATR:' + str.tostring(atrRatio1, '0.00') label1 = label.new(x=bar_index, y=trail1, color=l1Color, textcolor=color.white, style=label.style_label_lower_left) label.set_text(id=label1, text=label1Text) label.set_xy(label1, offsetLabels ? bar_index + 5 : bar_index + 2, trail1) label.delete(label1[1]) label2Text = str.tostring(res2) + ': ' + str.tostring(trail2, '0.00') + '|TR:ATR:' + str.tostring(atrRatio2, '0.00') label2 = label.new(x=bar_index, y=trail2, color=l2Color, textcolor=color.white, style=label.style_label_lower_left) label.set_text(id=label2, text=label2Text) label.set_xy(label2, offsetLabels ? bar_index + 15 : bar_index + 2, trail2) label.delete(label2[1]) label3Text = str.tostring(res3) + ': ' + str.tostring(trail3, '0.00') + '|TR:ATR:' + str.tostring(atrRatio3, '0.00') label3 = label.new(x=bar_index, y=trail3, color=l3Color, textcolor=color.white, style=label.style_label_lower_left) label.set_text(id=label3, text=label3Text) label.set_xy(label3, offsetLabels ? bar_index + 20 : bar_index + 2, trail3) label.delete(label3[1]) label4Text = str.tostring(res4) + ': ' + str.tostring(trail4, '0.00') + '|TR:ATR:' + str.tostring(atrRatio4, '0.00') label4 = label.new(x=bar_index, y=trail4, color=l4Color, textcolor=color.white, style=label.style_label_lower_left) label.set_text(id=label4, text=label4Text) label.set_xy(label4, offsetLabels ? bar_index + 25 : bar_index + 2, trail4) label.delete(label4[1]) label5Text = str.tostring(res5) + ': ' + str.tostring(trail5, '0.00') + '|TR:ATR:' + str.tostring(atrRatio5, '0.00') label5 = label.new(x=bar_index, y=trail5, color=l5Color, textcolor=color.white, style=label.style_label_lower_left) label.set_text(id=label5, text=label5Text) label.set_xy(label5, offsetLabels ? bar_index + 30 : bar_index + 2, trail5) label.delete(label5[1]) //Paint Reversal Clouds fib1Color = showRes1Fibs ? color.new(l1Color, 90) : na fill(t1, t1_fib1, fib1Color) fill(t1, t1_fib2, fib1Color) fill(t1, t1_fib3, fib1Color) //Trade Trigger (Crossover of Any Reversal Leval) ATRTrendIndex = Trend1 + Trend2 + Trend3 + Trend4 + Trend5 labelText = Trend1 != Trend1[1] ? res1 : Trend2 != Trend2[1] ? res2 : Trend3 != Trend3[1] ? res3 : Trend4 != Trend4[1] ? res4 : Trend5 != Trend5[1] ? res5 : na TRRatioThresholdMet = (atrRatio1 >= ATRAlertThreshold and Trend1 != Trend1[1]) or (atrRatio2 >= ATRAlertThreshold and Trend2 != Trend2[1]) or (atrRatio3 >= ATRAlertThreshold and Trend3 != Trend3[1]) or (atrRatio4 >= ATRAlertThreshold and Trend4 != Trend4[1]) or (atrRatio5 >= ATRAlertThreshold and Trend5 != Trend5[1]) tradeTrigger = ATRTrendIndex != ATRTrendIndex[1] buySignal = tradeTrigger and ATRTrendIndex > ATRTrendIndex[1] and TRRatioThresholdMet sellSignal = tradeTrigger and ATRTrendIndex < ATRTrendIndex[1] and TRRatioThresholdMet if buySignal and showTrendChangeAlert buyLabel = label.new(x=bar_index, y=low - 5, color=color.green, textcolor=color.white, style=label.style_label_up, text=labelText + '\nBuy') alert('ALERT: ATR Bullish Cross:' + labelText, alert.freq_once_per_bar) if sellSignal and showTrendChangeAlert sellLabel = label.new(x=bar_index, y=high + 5, color=color.red, textcolor=color.white, style=label.style_label_down, text=labelText + '\nSell') alert('ALERT: ATR Bearish Cross:' + labelText, alert.freq_once_per_bar)
Volume-Weighted RSI [wbburgin]
https://www.tradingview.com/script/cM6CWwGG-Volume-Weighted-RSI-wbburgin/
wbburgin
https://www.tradingview.com/u/wbburgin/
138
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/ // © wbburgin //@version=5 indicator("Volume-Weighted RSI [wbburgin]",overlay=false) // ===================================================================================================================== // INPUTS // ===================================================================================================================== length = input(14, "Length",group="Base Inputs") src = input.source(close,"Source",group="Base Inputs") plotBase = input.bool(true,"Plot Volume-weighted RSI",group="Base Inputs") usema = input.bool(true,"Use Signal",inline="Sig",group="Signal") pvrsi_ma_length = input.int(25," | Signal Length",inline="Sig",group="Signal") useabn = input.bool(true,"Plot Abnormal Activity",inline="Abn",group="Abnormal Activity") abn_mult = input.float(2.5," | SD Multiple",tooltip="Use a higher multiple for more"+ " stringent filtering of abnormal activity (only affects crosses/circles on plot, not RSI calculation)",inline="Abn" ,group="Abnormal Activity") stylesheet = input.string("Dark Style",title="Color Style",options=["Dark Style","Light Style"],group="Style") overbought_level = input.float(70, 'Overbought', inline = 'ob', group = 'Style') overbought_linecolor = input(#089981, '', inline = 'ob', group = 'Style') overbought_areacolor = input(color.new(#089981, 80), '', inline = 'ob', group = 'Style') oversold_level = input.float(30, 'Oversold', inline = 'os', group = 'Style') oversold_linecolor = input(#f23645, '', inline = 'os', group = 'Style') oversold_areacolor = input(color.new(#f23645, 80), '', inline = 'os', group = 'Style') barcolors = input.bool(true,"Bar Colors",group="Style") // ===================================================================================================================== // CORE LOGIC // ===================================================================================================================== pricevolume_rsi(x, y) => u_x = math.max(x - x[1], 0) * math.max(volume - volume[1],0) d_x = math.max(x[1] - x, 0) * math.max(volume[1] - volume,0) u = u_x > 0 ? math.sqrt(u_x) : -math.sqrt(u_x) d = d_x > 0 ? math.sqrt(d_x) : -math.sqrt(d_x) rs = ta.rma(u, y) / ta.rma(d, y) res = 100 - 100 / (1 + rs) res pvrsi = pricevolume_rsi(src,length) pvrsi_ma = ta.rma(pvrsi,pvrsi_ma_length) // Abnormal Volume Calculations obv = ta.cum(math.sign(ta.change(src)) * volume) volume_difference = math.abs(volume - volume[1]) / volume[1] abnormal_volume = volume_difference >= ta.sma(volume_difference,length) + (abn_mult*ta.stdev(volume_difference,length)) abv_pos = abnormal_volume and obv > obv[1] abv_neg = abnormal_volume and obv < obv[1] vd_placement = abv_neg ? 100 : abv_pos ? 0 : na // Abnormal Price Calculations obp = ta.cum(math.sign(ta.change(volume)) * src) price_difference = math.abs(src - src[1]) / src[1] abnormal_price= price_difference >= ta.sma(price_difference,length) + (abn_mult*ta.stdev(price_difference,length)) abp_pos = abnormal_price and obp > obp[1] abp_neg = abnormal_price and obp < obp[1] pd_placement = abp_neg ? 100 : abp_pos ? 0 : na // ===================================================================================================================== // STYLE & DESIGN // ===================================================================================================================== // RSI Design ---------- | pvrsiColor = switch stylesheet == "Dark Style" => (color.white) stylesheet == "Light Style" => (color.black) plot_rsi = plot(plotBase?pvrsi:na,color= pvrsi > overbought_level or pvrsi < oversold_level ? color.new(pvrsiColor,90) : pvrsiColor, title="Volume RSI") // Adding gradients on top of the PVRSI plot ---------- | pvrsi_up = pvrsi > 50 ? pvrsi : na pvrsi_dn = pvrsi < 50 ? pvrsi : na pvrsi_up_color = color.from_gradient(pvrsi,50,100,pvrsiColor,color.new(color.lime,75)) pvrsi_dn_color = color.from_gradient(pvrsi,0,50,color.new(color.red,75),pvrsiColor) plot(not plotBase ? na : pvrsi_up,color=pvrsi_up_color,editable = false,style=plot.style_linebr) plot(not plotBase ? na : pvrsi_dn,color=pvrsi_dn_color,editable = false,style=plot.style_linebr) // Signal and Bar Color ---------- | barcolor = color.from_gradient(pvrsi,oversold_level,overbought_level,oversold_linecolor,overbought_linecolor) plot(usema ? pvrsi_ma : na, "Signal", color= barcolor, linewidth = 2) barcolor(not barcolors ? na : barcolor) // Overbought / Oversold ---------- | obColor = color.from_gradient(pvrsi,oversold_level,overbought_level,overbought_linecolor, color.new(overbought_linecolor,90)) osColor = color.from_gradient(pvrsi,oversold_level,overbought_level,color.new(oversold_linecolor,90),oversold_linecolor) plot_up = plot(overbought_level, color = obColor, editable = false) plot_avg = plot(50, color = na, editable = false) plot_dn = plot(oversold_level, color = osColor, editable = false) fill(plot_rsi, plot_up, pvrsi > overbought_level ? overbought_areacolor : na) fill(plot_dn, plot_rsi, pvrsi < oversold_level ? oversold_areacolor : na) fill(plot_rsi, plot_avg, overbought_level, 50, overbought_areacolor, color.new(chart.bg_color, 100)) fill(plot_avg, plot_rsi, 50, oversold_level, color.new(chart.bg_color, 100), oversold_areacolor) // Abnormal Activity ---------- | pvs = switch abv_pos and abp_pos => color.new(overbought_linecolor,50) abv_neg and abp_pos => color.new(oversold_linecolor,50) bgcolor(not useabn ? na : pvs) plotshape(useabn?vd_placement:na, title="Abnormal Volume",style=shape.circle,location=location.absolute, color= obv < obv[1] ? color.new(color.red,50) : color.new(color.lime,50),size=size.tiny) plotshape(useabn?pd_placement:na, title="Abnormal Price",style=shape.cross,location=location.absolute, color= obp < obp[1] ? color.new(color.red,50) : color.new(color.lime,50),size=size.tiny) // ===================================================================================================================== // ALERTS // ===================================================================================================================== alertcondition(abv_pos,"Abnormal Positive Volume") alertcondition(abv_neg,"Abnormal Negative Volume") alertcondition(abp_pos,"Abnormal Price - Up") alertcondition(abp_neg,"Abnormal Price - Down") alertcondition( ta.crossover(pvrsi,oversold_level),"RSI Crossing over Oversold" ) alertcondition( ta.crossunder(pvrsi,overbought_level),"RSI Crossing under Overbought" )
MACD_RSI_trend_following
https://www.tradingview.com/script/7z28gXMN-MACD-RSI-trend-following/
vpirinski
https://www.tradingview.com/u/vpirinski/
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/ // © vpirinski //@version=5 //#region *********** DESCRIPTION *********** // ================================================== INFO ================================================== // This indicator can be used to build-up a strategy for trading of assets which are currently in trending phase. // My preference is to use it on slowly moving assets like GOLD and on higher timeframes, but practice may show that we find more usefull cases. // This script uses two indicators - MACD and RSI, as the timeframe that those are extracted for is configurable (defaults with the Chart TF, but can be any other selected by the user). // The strategy has the following simple idea: // - Buy if any if the conditions below is true: // - The selected TF MACD line crosses above the signal line and the TF RSI is above the user selected trigger value // - The selected TF MACD line is above the signal line and the TF RSI crosses above the user selected trigger value // - Once we're in position we wait for the selected TF MACD line to cross below the signal line, and then we set a SL at the low of thet bar // ================================================== DETAILS and USAGE ================================================== // In the current implementation I find two possible use cases for the indicator: // - as a stand-alone indicator on the chart which can also fire alerts that can help to determine if we want to manually enter/exit trades based on them // - can be used to connect to the Signal input of the TTS (TempalteTradingStrategy) by jason5480 in order to backtest it, thus effectively turning it into a strategy (instructions below in TTS CONNECTIVITY section) // Trading period can be selected from the indicator itself to limit to more interesting periods. // Arrow indications are drawn on the chart to indicate the trading conditions met in the script - green arrow for a buy signal indication and orange for LTF crossunder to indicate setting of SL. // ================================================== SETTINGS ================================================== // Leaving all of the settings as in vanilla use case, as both the MACD and RSI indicator's settings follow the default ones for the stand-alone indicators themselves. // The start-end date is a time filter that can be extermely usefull when backtesting different time periods. // Pesonal preference is using the script on a D/W timeframe, while the indicator is configured to use Monthly chart. // The default value of the RSI filter is left to 50, which can be changed. I.e. if the RSI is above 50 we have a regime filter based on the MACD criteria. // ================================================== EXTERNAL LIBS ================================================== // The script uses a couple of external libraries: // - HeWhoMustNotBeNamed/enhanced_ta/14 - collection of TA indicators // - jason5480/tts_convention/3 - more details about the Template Trading Strategy below // I would like to highly appreciate and credit the work of both HeWhoMustNotBeNamed and jason5480 for providing them to the community. // ================================================== TTS SETTINGS (NEEDED IF USED TO BACKTEST WITH TTS) ================================================== // The TempalteTradingStrategy is a strategy script developed in Pine by jason5480, which I recommend for quick turn-around of testing different ideas on a proven and tested framework // I cannot give enough credit to the developer for the efforts put in building of the infrastructure, so I advice everyone that wants to use it first to get familiar with the concept and by checking // by checking jason5480's profile https://www.tradingview.com/u/jason5480/#published-scripts // The TTS itself is extremely functional and have a lot of properties, so its functionality is beyond the scope of the current script - // Again, I strongly recommend to be thoroughly epxlored by everyone that plans on using it. // In the nutshell it is a script that can be feed with buy/sell signals from an external indicator script and based on many configuration options it can determine how to execute the trades. // The TTS has many settings that can be applied, so below I will cover only the ones that differ from the default ones, at least according to my testing - do your own research, you may find something even better :) // The current/latest version that I've been using as of writing and testing this script is TTSv48 // Settings which differ from the default ones: // - from - False (time filter is from the indicator script itself) // - Deal Conditions Mode - External (take enter/exit conditions from an external script) // - 🔌Signal 🛈➡ - MACD_RSI_trend_following: 🔌Signal to TTSv48 (this is the output from the indicator script, according to the TTS convention) // - Sat/Sun - true (for crypto, in order to trade 24/7) // - Order Type​​ - STOP (perform stop order) // - Distance Method​​ - HHLL (HigherHighLowerLow - in order to set the SL according to the strategy definition from above) // // The next are just personal preferenes, you can feel free to experiment according to your trading style // - Take Profit Targets - 0 (either 100% in or out, no incremental stepping in or out of positions) //   - Dist Mul|Len Long/Short- 10 (make sure that we don't close on profitable trades by any reason) // - Quantity Method - EQUITY (personal backtesting preference is to consider each backtest as a separate portfolio, so determine the position size by 100% of the allocated equity size) // - Equity %         - 100 (note above) //#region *********** STRATEGY_SETUP *********** indicator(title = 'MACD_RSI_trend_following', shorttitle = 'MACD_RSI_trend_following', overlay = true, explicit_plot_zorder = true ) //#endregion ======================================================================================================== //#region *********** LIBRARIES *********** import HeWhoMustNotBeNamed/enhanced_ta/14 as eta import jason5480/tts_convention/3 as tts_conv //#endregion ======================================================================================================== //#region *********** USER_INPUT *********** var string COMMON_GROUP_STR = "Common" i_timeframe = input.timeframe(title = "Timeframe", defval = "", group = COMMON_GROUP_STR) i_repaint_en = true //input.bool (title = "Repainting On/Off", defval = true, group = COMMON_GROUP_STR, tooltip="Off for use as an Indicator to avoid repainting. On for use in Strategies so that trades can respond to realtime data.") var string MACD_GROUP_STR = "MACD" i_macd_ma_source = input.source (title = "Source", defval = close, group = MACD_GROUP_STR) i_macd_osc_ma_type = input.string (title = "Osc MA type", defval = "ema", group = MACD_GROUP_STR, options = ["ema", "sma", "rma", "hma", "wma", "vwma", "swma"]) i_macd_signal_line_ma_type = input.string (title = "Signal MA type", defval = "ema", group = MACD_GROUP_STR, options = ["ema", "sma", "rma", "hma", "wma", "vwma", "swma"]) i_macd_fast_ma_length = input.int (title = "Fast MA Length", defval = 12, group = MACD_GROUP_STR) i_macd_slow_ma_length = input.int (title = "Slow MA Length", defval = 26, group = MACD_GROUP_STR) i_macd_signal_length = input.int (title = "Low MACD Hist", defval = 9, group = MACD_GROUP_STR) var string RSI_GROUP_STR = "RSI" i_rsi_source = input.source (title = "Source", defval = close, group = RSI_GROUP_STR) i_rsi_length = input.int (title = "Length", defval = 14, group = RSI_GROUP_STR) i_rsi_trigger_value = input.int (title = "RSI trigger value", defval = 50, group = RSI_GROUP_STR) var string TIME_GROUP_STR = "Start and End Time" i_start_time = input.time (title="Start Date", defval=timestamp("01 Jan 2000 13:30 +0000"), group=TIME_GROUP_STR) i_end_time = input.time (title="End Date", defval=timestamp("1 Jan 2099 19:30 +0000"), group=TIME_GROUP_STR) //#endregion ======================================================================================================== //#region *********** COMMON_FUNCTIONS *********** // Function offering a repainting/no-repainting version of the HTF data (but does not work on tuples). // It has the advantage of using only one `security()` call for both. // The built-in MACD function behaves identically to Repainting On in the custom function below. In other words _repaint = TRUE. // https://www.tradingview.com/script/cyPWY96u-How-to-avoid-repainting-when-using-security-PineCoders-FAQ/ f_security(_symbol, _tf, _src, _repaint) => request.security(_symbol, _tf, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1] //#endregion ======================================================================================================== //#region *********** LOGIC *********** // Get the current TF MACD and RSI and then interpolate them for the user TF fast_ma = eta.ma(source = i_macd_ma_source, maType = i_macd_osc_ma_type, length = i_macd_fast_ma_length) slow_ma = eta.ma(source = i_macd_ma_source, maType = i_macd_osc_ma_type, length = i_macd_slow_ma_length) ctf_macd_line = fast_ma - slow_ma ctf_signal_line = eta.ma(source = ctf_macd_line, maType = i_macd_signal_line_ma_type, length = i_macd_signal_length) ctf_hist_line = ctf_macd_line - ctf_signal_line ctf_rsi = ta.rsi(i_rsi_source, i_rsi_length) macd_line = f_security(syminfo.tickerid, i_timeframe, ctf_macd_line, i_repaint_en) signal_line = f_security(syminfo.tickerid, i_timeframe, ctf_signal_line, i_repaint_en) hist_line = f_security(syminfo.tickerid, i_timeframe, ctf_hist_line, i_repaint_en) rsi = f_security(syminfo.tickerid, i_timeframe, ctf_rsi, i_repaint_en) // Determine the strategy trading conditions macd_crossover = ta.crossover (macd_line, signal_line) macd_crossunder = ta.crossunder(macd_line, signal_line) rsi_crossover = ta.crossover (rsi, i_rsi_trigger_value) // Filters time_and_bar_filter = barstate.isconfirmed and ((time >= i_start_time) and (time <= i_end_time)) macd_crossover_filter = macd_crossover and (rsi > i_rsi_trigger_value) rsi_crossover_filter = (macd_line > signal_line) and rsi_crossover strategy_buy_fiter = macd_crossover_filter or rsi_crossover_filter strategy_set_sl_filter = macd_crossunder // Strategy buy/set SL buy_signal = time_and_bar_filter and strategy_buy_fiter set_sl_signal = time_and_bar_filter and strategy_set_sl_filter //#endregion ======================================================================================================== //#region *********** BUY_&_SELL_SIGNALS TO TTS *********** tts_deal_conditions = tts_conv.DealConditions.new( startLongDeal = buy_signal, startShortDeal = false, endLongDeal = set_sl_signal, endShortDeal = false, cnlStartLongDeal = false, cnlStartShortDeal = false, cnlEndLongDeal = false, cnlEndShortDeal = false) plot(series = tts_conv.getSignal(tts_deal_conditions), title = '🔌Signal to TTS', color = color.olive, display = display.data_window + display.status_line) //#endregion ======================================================================================================== //#region *********** DEBUG_&_PLOTS *********** plotshape(buy_signal, style=shape.triangleup, location=location.bottom, size = size.tiny, color=buy_signal ? color.rgb(19, 231, 26) : na) plotshape(set_sl_signal, style=shape.triangledown, location=location.top, size = size.tiny, color=set_sl_signal ? color.rgb(216, 129, 71) : na) //#endregion ======================================================================================================== //#region *********** ALERTS *********** alertcondition(buy_signal, "BuySignal", "MACD and RSI conditions satisfied for {{ticker}} - buy at price {{close}}") alertcondition(set_sl_signal, "SetSLSignal", "MACD crossunder - set SL for {{ticker}} at price {{close}}") //#endregion ========================================================================================================
Volume-Trend Sentiment (VTS) [AlgoAlpha]
https://www.tradingview.com/script/AK0TDO0D-Volume-Trend-Sentiment-VTS-AlgoAlpha/
AlgoAlpha
https://www.tradingview.com/u/AlgoAlpha/
15
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("⨇⨈ Volume-Trend Sentiment [AlgoAlpha]") //VTS Inputs showhis = input.bool(false, "Show Histogram?", group = "Settings") l = input.int(7, minval = 2, title = "VTS length", group = "Volume Trend Sentiment") l1 = input.int(7, minval = 2, title = "Standard Deviation length", group = "Volume Trend Sentiment") l2 = input.int(7, minval = 2, title = "VTS SMA length", group = "Volume Trend Sentiment") //VTS Calculation vts = ta.ema((close-open)/volume, l)-ta.ema(ta.ema((close-open)/volume, l), l) stdev = ta.stdev(vts, l1) * 1 vtsX = ta.sma(vts/(stdev+stdev), l2) //Sentiment Background Colors co(vtsX) => if vtsX>0.95 color.new(color.blue,0) else if vtsX>0.90 color.new(color.blue,10) else if vtsX>0.80 color.new(color.blue,20) else if vtsX>0.70 color.new(color.blue,30) else if vtsX>0.60 color.new(color.blue,40) else if vtsX>0.50 color.new(color.blue,50) else if vtsX>0.40 color.new(color.blue,60) else if vtsX>0.30 color.new(color.blue,70) else if vtsX>0.20 color.new(color.blue,80) else if vtsX>0.10 color.new(color.blue,90) else if vtsX==0.00 (color.rgb(239, 0, 0,90)) else if vtsX>-0.10 color.rgb(239, 0, 0,80) else if vtsX>-0.20 color.rgb(239, 0, 0,70) else if vtsX>-0.30 color.rgb(239, 0, 0,60) else if vtsX>-0.40 color.rgb(239, 0, 0,50) else if vtsX>-0.50 color.rgb(239, 0, 0,40) else if vtsX>-0.60 color.rgb(239, 0, 0,30) else if vtsX>-0.70 color.rgb(239, 0, 0,20) else if vtsX>-0.80 color.rgb(239, 0, 0,10) else if vtsX>-0.95 color.rgb(239, 0, 0,0) else color.rgb(239, 0, 0,0) bgcolor(co(vtsX)) //Plots plot(showhis ? (vts/(stdev+stdev)): na, color = vts > 0 ? color.rgb(0, 0, 0) : color.rgb(0, 0, 0), style = plot.style_columns, linewidth = 3) vtsplot = plot(vtsX, color = color.white, linewidth = 2) mid = plot(0, color = color.gray, style = plot.style_circles) fill(vtsplot, mid, color = vtsX > 0 ? color.navy : color.maroon) //OB/OS Zones (Removed but feel free to add back) // r = plot(2, color = color.rgb(255, 82, 82, 70)) // r1 = plot(1, color = color.rgb(255, 82, 82, 70)) // s = plot(-2, color = color.rgb(76, 175, 79, 70)) // s1 = plot(-1, color = color.rgb(76, 175, 79, 70)) // fill(s,s1, color = color.rgb(76, 175, 79, 70)) // fill(r,r1, color = color.rgb(255, 82, 82, 70))
BUY/SELL RSI FLIUX v1.0
https://www.tradingview.com/script/MKe4c2mg-buy-sell-rsi-fliux-v1-0/
vladimir5738
https://www.tradingview.com/u/vladimir5738/
15
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/ // © vladimir5738 //@version=5 indicator("BUY/SELL RSI FLIUX v0.1", shorttitle="BSRSIFLUX", overlay=true) // Уровни поддержки и сопротивления lengthSR = 14 // Количество баров для определения уровней highestHigh = ta.highest(high, lengthSR) lowestLow = ta.lowest(low, lengthSR) // RSI lengthRSI = 9 // Количество баров для расчета RSI rsiValue = ta.rsi(close, lengthRSI) rsiOverbought = 70 rsiOversold = 30 // Построение уровней поддержки и сопротивления plot(highestHigh, "Resistance", color=color.red) plot(lowestLow, "Support", color=color.green) // Условия для сигналов на основе RSI longCondition = rsiValue < rsiOversold and close > lowestLow shortCondition = rsiValue > rsiOverbought and close < highestHigh // Отображение меток купли/продажи plotshape(series=longCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY") plotshape(series=shortCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL") plot(close)
MaxAl - Multiple MTF Moving Averages, ATR Trend & More (v0.1)
https://www.tradingview.com/script/kKm8My4K-MaxAl-Multiple-MTF-Moving-Averages-ATR-Trend-More-v0-1/
Maximus_Algorithmus
https://www.tradingview.com/u/Maximus_Algorithmus/
12
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/ // © Maximus_Algorithmus //@version=5 indicator(title="MaxAl - MTF Multiple Moving Averages & More Indicators (v0.1)", shorttitle="MaxAl-MultMTFMA", overlay=true) group_00 = "🟢 Hide / Display " bool display_01 = input.bool(true, "Hide/Display MA #1", group = group_00) bool display_02 = input.bool(false, "Hide/Display MA #2", group = group_00) bool display_03 = input.bool(false, "Hide/Display MA #3", group = group_00) bool display_04 = input.bool(true, "Hide/Display MA #4", group = group_00) bool display_05 = input.bool(true, "Hide/Display MA #5", group = group_00) bool display_06 = input.bool(true, "Hide/Display MA #6", group = group_00) bool display_bb = input.bool(true, "Hide/Display Bollinger Bands", group = group_00) bool display_atr = input.bool(false, "Hide/Display ATR Trailing Stop", group = group_00) bool display_tbl = input.bool(true, "Hide/Display MTF RSI & Z-Score Table", group = group_00) group_01 = "🟢 Moving Average #1" // Assigning Inputs var float htf_ma_01 = na string res_01 = input.timeframe("", "Timeframe", group = group_01) string avg_type_01 = input.string("EMA", "Average Type", group = group_01 , options = ["SMA", "EMA", "WMA", "VWMA", "HMA"]) int len_01 = input.int(5, "Length", group = group_01) float src_01 = input.source(close, "Price Source", group = group_01) int offset_01 = input.int(0, "Offset", group = group_01) int width_01 = input.int(1, "Line Width", group = group_01) color color_01 = input.color(color.rgb(0, 255, 0), "Color", group = group_01) // Defining Moving Average Calculations Based on User Selection if avg_type_01 == "SMA" htf_ma_01 := ta.sma(src_01, len_01) if avg_type_01 == "EMA" htf_ma_01 := ta.ema(src_01, len_01) if avg_type_01 == "WMA" htf_ma_01 := ta.wma(src_01, len_01) if avg_type_01 == "VWMA" htf_ma_01 := ta.vwma(src_01, len_01) if avg_type_01 == "HMA" htf_ma_01 := ta.hma(src_01, len_01) // Calculate Timeframe Based Moving Average output_01 = request.security(syminfo.tickerid, res_01, htf_ma_01[2], lookahead = barmerge.lookahead_on) plot_01 = display_01 ? display.all : display.none plot(output_01, "Moving Average #1", color = color_01, display = plot_01) group_02 = "🟢 Moving Average #2" // Assigning Inputs var float htf_ma_02 = na string res_02 = input.timeframe("", "Timeframe", group = group_02) string avg_type_02 = input.string("EMA", "Average Type", group = group_02 , options = ["SMA", "EMA", "WMA", "VWMA", "HMA"]) int len_02 = input.int(10, "Length", group = group_02) float src_02 = input.source(close, "Price Source", group = group_02) int offset_02 = input.int(0, "Offset", group = group_02) int width_02 = input.int(1, "Line Width", group = group_02) color color_02 = input.color(color.rgb(255, 145, 0), "Color", group = group_02) // Defining Moving Average Calculations Based on User Selection if avg_type_02 == "SMA" htf_ma_02 := ta.sma(src_02, len_02) if avg_type_02 == "EMA" htf_ma_02 := ta.ema(src_02, len_02) if avg_type_02 == "WMA" htf_ma_02 := ta.wma(src_02, len_02) if avg_type_02 == "VWMA" htf_ma_02 := ta.vwma(src_02, len_02) if avg_type_02 == "HMA" htf_ma_02 := ta.hma(src_02, len_02) // Calculate Timeframe Based Moving Average output_02 = request.security(syminfo.tickerid, res_02, htf_ma_02[2], lookahead = barmerge.lookahead_on) plot_02 = display_02 ? display.all : display.none plot(output_02, "Moving Average #2", color = color_02, display = plot_02) group_03 = "🟢 Moving Average #3" // Assigning Inputs var float htf_ma_03 = na string res_03 = input.timeframe("", "Timeframe", group = group_03) string avg_type_03 = input.string("EMA", "Average Type", group = group_03 , options = ["SMA", "EMA", "WMA", "VWMA", "HMA"]) int len_03 = input.int(20, "Length", group = group_03) float src_03 = input.source(close, "Price Source", group = group_03) int offset_03 = input.int(0, "Offset", group = group_03) int width_03 = input.int(1, "Line Width", group = group_03) color color_03 = input.color(color.rgb(256, 256, 256), "Color", group = group_03) // Defining Moving Average Calculations Based on User Selection if avg_type_03 == "SMA" htf_ma_03 := ta.sma(src_03, len_03) if avg_type_03 == "EMA" htf_ma_03 := ta.ema(src_03, len_03) if avg_type_03 == "WMA" htf_ma_03 := ta.wma(src_03, len_03) if avg_type_03 == "VWMA" htf_ma_03 := ta.vwma(src_03, len_03) if avg_type_03 == "HMA" htf_ma_03 := ta.hma(src_03, len_03) // Calculate Timeframe Based Moving Average output_03 = request.security(syminfo.tickerid, res_03, htf_ma_03[2], lookahead = barmerge.lookahead_on) plot_03 = display_03 ? display.all : display.none plot(output_03, "Moving Average #3", color = color_03, display = plot_03) group_04 = "🟢 Moving Average #4" // Assigning Inputs var float htf_ma_04 = na string res_04 = input.timeframe("", "Timeframe", group = group_04) string avg_type_04 = input.string("EMA", "Average Type", group = group_04 , options = ["SMA", "EMA", "WMA", "VWMA", "HMA"]) int len_04 = input.int(50, "Length", group = group_04) float src_04 = input.source(close, "Price Source", group = group_04) int offset_04 = input.int(0, "Offset", group = group_04) int width_04 = input.int(1, "Line Width", group = group_04) color color_04 = input.color(color.rgb(256, 0, 0), "Color", group = group_04) // Defining Moving Average Calculations Based on User Selection if avg_type_04 == "SMA" htf_ma_04 := ta.sma(src_04, len_04) if avg_type_04 == "EMA" htf_ma_04 := ta.ema(src_04, len_04) if avg_type_04 == "WMA" htf_ma_04 := ta.wma(src_04, len_04) if avg_type_04 == "VWMA" htf_ma_04 := ta.vwma(src_04, len_04) if avg_type_04 == "HMA" htf_ma_04 := ta.hma(src_04, len_04) // Calculate Timeframe Based Moving Average output_04 = request.security(syminfo.tickerid, res_04, htf_ma_04[2], lookahead = barmerge.lookahead_on) plot_04 = display_04 ? display.all : display.none plot(output_04, "Moving Average #4", color = color_04, display = plot_04) group_05 = "🟢 Moving Average #5" // Assigning Inputs var float htf_ma_05 = na string res_05 = input.timeframe("", "Timeframe", group = group_05) string avg_type_05 = input.string("EMA", "Average Type", group = group_05 , options = ["SMA", "EMA", "WMA", "VWMA", "HMA"]) int len_05 = input.int(100, "Length", group = group_05) float src_05 = input.source(close, "Price Source", group = group_05) int offset_05 = input.int(0, "Offset", group = group_05) int width_05 = input.int(1, "Line Width", group = group_05) color color_05 = input.color(color.rgb(161, 1, 167), "Color", group = group_05) // Defining Moving Average Calculations Based on User Selection if avg_type_05 == "SMA" htf_ma_05 := ta.sma(src_05, len_05) if avg_type_05 == "EMA" htf_ma_05 := ta.ema(src_05, len_05) if avg_type_05 == "WMA" htf_ma_05 := ta.wma(src_05, len_05) if avg_type_05 == "VWMA" htf_ma_05 := ta.vwma(src_05, len_05) if avg_type_05 == "HMA" htf_ma_05 := ta.hma(src_05, len_05) // Calculate Timeframe Based Moving Average output_05 = request.security(syminfo.tickerid, res_05, htf_ma_05[2], lookahead = barmerge.lookahead_on) plot_05 = display_05 ? display.all : display.none plot(output_05, "Moving Average #5", color = color_05, display = plot_05) group_06 = "🟢 Moving Average #6" // Assigning Inputs var float htf_ma_06 = na string res_06 = input.timeframe("", "Timeframe", group = group_06) string avg_type_06 = input.string("EMA", "Average Type", group = group_06 , options = ["SMA", "EMA", "WMA", "VWMA", "HMA"]) int len_06 = input.int(200, "Length", group = group_06) float src_06 = input.source(close, "Price Source", group = group_06) int offset_06 = input.int(0, "Offset", group = group_06) int width_06 = input.int(1, "Line Width", group = group_06) color color_06 = input.color(color.rgb(232, 56, 147), "Color", group = group_06) // Defining Moving Average Calculations Based on User Selection if avg_type_06 == "SMA" htf_ma_06 := ta.sma(src_06, len_06) if avg_type_06 == "EMA" htf_ma_06 := ta.ema(src_06, len_06) if avg_type_06 == "WMA" htf_ma_06 := ta.wma(src_06, len_06) if avg_type_06 == "VWMA" htf_ma_06 := ta.vwma(src_06, len_06) if avg_type_06 == "HMA" htf_ma_06 := ta.hma(src_06, len_06) // Calculate Timeframe Based Moving Average output_06 = request.security(syminfo.tickerid, res_06, htf_ma_06[2], lookahead = barmerge.lookahead_on) plot_06 = display_06 ? display.all : display.none plot(output_06, "Moving Average #6", color = color_06, display = plot_06) group_bb = "🟢 Bollinger Band Settings" var float htf_ma_bb = na string res_bb = input.timeframe("", "Timeframe", group = group_bb) string avg_type_bb = input.string("SMA", "Basis MA Type", group = group_bb, options = ["SMA", "EMA", "WMA", "VWMA", "HMA", "SMMA (RMA)"]) int len_bb = input.int(20, "Basis MA Length", group = group_bb) float src_bb = input.source(close, "Basis MA Source", group = group_bb) float mult_bb = input.float(2.0, "Bands Standard Deviation", group = group_bb, minval=0.001, maxval=50) int width_basis_bb = input.int(1, "Basis Line Width", group = group_bb) color color_basis_bb = input.color(color.rgb(125, 125, 125), "Basis Color", group = group_bb) int width_stdev_bb = input.int(1, "Bands Line Width", group = group_bb) color color_stdev_bb = input.color(color.rgb(0, 0, 256), "Bands Color", group = group_bb) color color_fill_bb = input.color(color.rgb(0, 0, 256, 95), "Fill Color", group = group_bb) // Defining Moving Average Calculations Based on User Selection if avg_type_bb == "SMA" htf_ma_bb := ta.sma(src_bb, len_bb) if avg_type_bb == "EMA" htf_ma_bb := ta.ema(src_bb, len_bb) if avg_type_bb == "WMA" htf_ma_bb := ta.wma(src_bb, len_bb) if avg_type_bb == "VWMA" htf_ma_bb := ta.vwma(src_bb, len_bb) if avg_type_bb == "HMA" htf_ma_bb := ta.hma(src_bb, len_bb) if avg_type_bb == "SMMA (RMA)" htf_ma_bb := ta.rma(src_bb, len_bb) deviation = ta.stdev(src_bb, len_bb) basis = request.security(syminfo.tickerid, res_bb, htf_ma_bb, lookahead = barmerge.lookahead_on) dev = request.security(syminfo.tickerid, res_bb, deviation, lookahead = barmerge.lookahead_on) upper = basis + mult_bb * dev lower = basis - mult_bb * dev plot_bb = display_bb ? display.all : display.none p1 = plot(upper, "Upper", color = color_stdev_bb, display = plot_bb) plot(basis, "Basis", color = color_basis_bb, display = plot_bb) p2 = plot(lower, "Lower", color = color_stdev_bb, display = plot_bb) fill(p1, p2, title = "Background", color = color_fill_bb, display = plot_bb) // Begin - ATR Stop group_ATR = "🟢 ATR Trailing Stop Settings" // Begin - ATR Stop var float atr_trailing_stop = na var float pos = na var bool atr_entry_signal = false atr_tooltip = "ATR Trailing Stop indicator is specific to timeframe and ticker. Must set parameters to specific ticker and timeframe." atr_period_bull = input.int(6, "Bull Trend - ATR Period", minval = 1, step = 1, group = group_ATR, tooltip = atr_tooltip) atr_multi_bull = input.float(2, "Bull Trend - ATR Multiplier", minval = 0, step = 0.1, group = group_ATR, tooltip = atr_tooltip) color_bull_atr = input.color(color.rgb(0, 256, 0), "ATR Trail Stop Color", group = group_ATR) atr_period_bear = input.int(17, "Bear Trend - ATR Period", minval = 1, step = 1, group = group_ATR, tooltip = atr_tooltip) atr_multi_bear = input.float(2.7, "Bear Trend - ATR Multiplier", minval = 0, step = 0.1, group = group_ATR, tooltip = atr_tooltip) color_bear_atr = input.color(color.rgb(256, 0, 0), "ATR Trail Stop Color", group = group_ATR) atr_bull = ta.atr(atr_period_bull) loss_bull = atr_multi_bull * atr_bull atr_bear = ta.atr(atr_period_bear) loss_bear = atr_multi_bear * atr_bear atr_trailing_stop := close > nz(atr_trailing_stop[1], 0) and close[1] > nz(atr_trailing_stop[1], 0) ? math.max(nz(atr_trailing_stop[1]), close - loss_bull) : close < nz(atr_trailing_stop[1], 0) and close[1] < nz(atr_trailing_stop[1], 0) ? math.min(nz(atr_trailing_stop[1]), close + loss_bear) : close > nz(atr_trailing_stop[1], 0) ? close - loss_bull : close + loss_bear pos := close[1] < nz(atr_trailing_stop[1], 0) and close > nz(atr_trailing_stop[1], 0) ? 1 : close[1] > nz(atr_trailing_stop[1], 0) and close < nz(atr_trailing_stop[1], 0) ? -1 : nz(pos[1], 0) color_atr = pos > 0 ? color_bull_atr : color_bear_atr plot_atr = display_atr ? display.all : display.none plot(display_atr ? atr_trailing_stop : na, color = color_atr, title="ATR Trailing Stop", display = plot_atr) // Position group_tbl_01 = "🟢 MTF RSI & Z-Score Settings" tablePos = input.string("Bottom Right", "Location", ["Top Right" , "Middle Right" , "Bottom Right" , "Top Center", "Middle Center" , "Bottom Center", "Top Left" , "Middle Left" , "Bottom Left" ], group = group_tbl_01, inline = "1") // Size tableSiz = input.string("Small", " Size", ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], group = group_tbl_01, inline = "1") //tabColr = input.color(color.new(color.white, 50), "", group = "Table Location & Size", inline = "1") tabColr = color.new(color.white, 50) // RSI in Different Timeframes d_rsi_1 = input.bool(true, "Display RSI 1", group = "RSI 1 Settings") rsiSrc1 = input.source(close, "RSI 1 Source", group = "RSI 1 Settings") rsiLen1 = input.int(2, "RSI 1 Length", 1, group = "RSI 1 Settings") rsi_os_1 = input.int(5, "Oversold Level", group = "RSI 1 Settings") rsi_ob_1 = input.int(95, "Overbought Level", group = "RSI 1 Settings") d_rsi_2 = input.bool(false, "Display RSI 2", group = "RSI 2 Settings") rsiSrc2 = input.source(close, "RSI 2 Source", group = "RSI 2 Settings") rsiLen2 = input.int(3, "RSI 2 Length", 1, group = "RSI 2 Settings") rsi_os_2 = input.int(5, "Oversold Level", group = "RSI 2 Settings") rsi_ob_2 = input.int(95, "Overbought Level", group = "RSI 2 Settings") d_rsi_3 = input.bool(true, "Display RSI 3", group = "RSI 3 Settings") rsiSrc3 = input.source(close, "RSI 3 Source", group = "RSI 3 Settings") rsiLen3 = input.int(14, "RSI 3 Length", 1, group = "RSI 3 Settings") rsi_os_3 = input.int(30, "Oversold Level", group = "RSI 3 Settings") rsi_ob_3 = input.int(70, "Overbought Level", group = "RSI 3 Settings") d_z_1 = input.bool(true, "Display Z-Score 1", group = "Z-Score 1 Settings") zLen1 = input.int(20, "Z-Score 1 Length", 1, group = "Z-Score 1 Settings") zSrc1 = input.source(close, "Z-Score 1 Source", group = "Z-Score 1 Settings") z_os_1 = input.float(-2.0, "Oversold Level", group = "Z-Score 1 Settings") z_ob_1 = input.float(2.0, "Overbought Level", group = "Z-Score 1 Settings") d_z_2 = input.bool(true, "Display Z-Score 2", group = "Z-Score 2 Settings") zLen2 = input.int(100, "Z-Score 2 Length", 1, group = "Z-Score 2 Settings") zSrc2 = input.source(close, "Z-Score 2 Source", group = "Z-Score 2 Settings") z_os_2 = input.float(-2.0, "Oversold Level", group = "Z-Score 2 Settings") z_ob_2 = input.float(2.0, "Overbought Level", group = "Z-Score 2 Settings") d_z_3 = input.bool(true, "Display Z-Score 3", group = "Z-Score 3 Settings") zLen3 = input.int(200, "Z-Score 3 Length", 1, group = "Z-Score 3 Settings") zSrc3 = input.source(close, "Z-Score 3 Source", group = "Z-Score 3 Settings") z_os_3 = input.float(-2.0, "Oversold Level", group = "Z-Score 3 Settings") z_ob_3 = input.float(2.0, "Overbought Level", group = "Z-Score 3 Settings") // Timeframes flg01 = input.bool(true, "TF[01]", inline = "01") tim01 = input.timeframe("5", "", inline = "01") flg02 = input.bool(true, "TF[02]", inline = "02") tim02 = input.timeframe("30", "", inline = "02") flg03 = input.bool(true, "TF[03]", inline = "03") tim03 = input.timeframe("60", "", inline = "03") flg04 = input.bool(true, "TF[04]", inline = "04") tim04 = input.timeframe("240", "", inline = "04") flg05 = input.bool(true, "TF[05]", inline = "05") tim05 = input.timeframe("1D", "", inline = "05") flg06 = input.bool(true, "TF[06]", inline = "06") tim06 = input.timeframe("1W", "", inline = "06") flg07 = input.bool(true, "TF[07]", inline = "07") tim07 = input.timeframe("1M", "", inline = "07") // Complete Calculations symbol = ticker.modify(syminfo.tickerid, syminfo.session) // RSI & MA timArr = array.new<string>(na) rsi1Arr = array.new<float>(na) rsi2Arr = array.new<float>(na) rsi3Arr = array.new<float>(na) z1Arr = array.new<float>(na) z2Arr = array.new<float>(na) z3Arr = array.new<float>(na) // Functions zscore(source, length) => mean = ta.sma(source,length) stdev = ta.stdev(source,length) z = (source - mean) / stdev // RSI & MA Function rsiNmaFun(tf, flg) => [rsi1, rsi2, rsi3, z1, z2, z3] = request.security(symbol, tf, [ta.rsi(rsiSrc1, rsiLen1), ta.rsi(rsiSrc2, rsiLen2), ta.rsi(rsiSrc3, rsiLen3), zscore(zSrc1, zLen1), zscore(zSrc2, zLen2), zscore(zSrc3, zLen3)]) if flg and (barstate.isrealtime ? true : timeframe.in_seconds(timeframe.period) <= timeframe.in_seconds(tf)) array.push(timArr, na(tf) ? timeframe.period : tf) array.push(rsi1Arr, rsi1) array.push(rsi2Arr, rsi2) array.push(rsi3Arr, rsi3) array.push(z1Arr , z1) array.push(z2Arr , z2) array.push(z3Arr , z3) rsiNmaFun(tim01, flg01), rsiNmaFun(tim02, flg02), rsiNmaFun(tim03, flg03), rsiNmaFun(tim04, flg04), rsiNmaFun(tim05, flg05), rsiNmaFun(tim06, flg06), rsiNmaFun(tim07, flg07) // Build The Table // Get Table 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 // Define Table var tbl = table.new(locNsze(tablePos), 9, 10, frame_width = 3, frame_color = tabColr, border_width = 1, border_color = tabColr) // Cell Function cell(col, row, txt, color, x, y, z) => th = z == -1 ? text.align_left : z == 1 ? text.align_right : text.align_center table.cell(tbl, col, row, txt, text_color = color.new(color, x), text_halign = th, bgcolor = color.new(color, y), text_size = locNsze(tableSiz)) // Post Timeframe in format tfTxt(x)=> out = x if not str.contains(x, "S") and not str.contains(x, "M") and not str.contains(x, "W") and not str.contains(x, "D") if str.tonumber(x)%60 == 0 out := str.tostring(str.tonumber(x)/60)+"H" else out := x + "m" out // Coloring Cell Function cellColor(x, o_b, o_s) => BL3 = o_b //BULL Red BL2 = (o_b + o_s) * 0.5 + (o_b - (o_b + o_s) * 0.5) * 0.9 //BULL Orange to Red BL1 = (o_b + o_s) * 0.5 + (o_b - (o_b + o_s) * 0.5) * 0.85 //BULL Green to Orange NL0 = (o_b + o_s) * 0.5 //NEUTRAL BR1 = (o_b + o_s) * 0.5 - (o_b - (o_b + o_s) * 0.5) * 0.85 //BEAR Red to Orange BR2 = (o_b + o_s) * 0.5 - (o_b - (o_b + o_s) * 0.5) * 0.9 //BEAR Orange to Green BR3 = o_s //BEAR Green x >= BL3 ? color.red : x <= BL3 and x >= BL2 ? color.from_gradient(x, BL2, BL3, color.orange, color.red ) : x <= BL2 and x >= BL1 ? color.from_gradient(x, BL1, BL2, color.green, color.orange) : x <= BL1 and x >= NL0 ? color.from_gradient(x, NL0, BL1, color.white, color.green ) : x <= BR3 ? color.green : x >= BR3 and x <= BR2 ? color.from_gradient(x, BR3, BR2, color.green, color.orange) : x >= BR2 and x <= BR1 ? color.from_gradient(x, BR2, BR1, color.orange, color.red ) : x >= BR1 and x <= NL0 ? color.from_gradient(x, BR1, NL0, color.red, color.white ) : color.white if barstate.islast and display_tbl table.clear(tbl, 0, 0, 8, 9) // Build Table // Table Header cell(0, 0, "TF", color.white, 10, 70, 0) if d_rsi_1 cell(1, 0, "RSI(" + str.tostring(rsiLen1) +")", color.white, 10, 70, 0) if d_rsi_2 cell(2, 0, "RSI(" + str.tostring(rsiLen2) +")", color.white, 10, 70, 0) if d_rsi_3 cell(3, 0, "RSI(" + str.tostring(rsiLen3) +")", color.white, 10, 70, 0) if d_z_1 cell(4, 0, "Z("+ str.tostring(zLen1) + ")", color.white, 10, 70, 0) if d_z_2 cell(5, 0, "Z("+ str.tostring(zLen2) + ")", color.white, 10, 70, 0) if d_z_3 cell(6, 0, "Z("+ str.tostring(zLen3) + ")", color.white, 10, 70, 0) // Create Info Table Cells j = 1 if array.size(rsi1Arr) > 0 for i = 0 to array.size(rsi1Arr) - 1 if not na(array.get(rsi1Arr, i)) cell(0, j, tfTxt(array.get(timArr, i)), color.white, 0, 70, 0) if d_rsi_1 cell(1, j, str.tostring(array.get(rsi1Arr, i), "#.##") + (array.get(rsi1Arr, i) >= 50 ? " ▲" : array.get(rsi1Arr, i) < 50 ? " ▼" : ""), cellColor(array.get(rsi1Arr, i), rsi_ob_1, rsi_os_1), 0, 60, 1) if d_rsi_2 cell(2, j, str.tostring(array.get(rsi2Arr, i), "#.##") + (array.get(rsi2Arr, i) >= 50 ? " ▲" : array.get(rsi2Arr, i) < 50 ? " ▼" : ""), cellColor(array.get(rsi2Arr, i), rsi_ob_2, rsi_os_2), 0, 60, 1) if d_rsi_3 cell(3, j, str.tostring(array.get(rsi3Arr, i), "#.##") + (array.get(rsi3Arr, i) >= 50 ? " ▲" : array.get(rsi3Arr, i) < 50 ? " ▼" : ""), cellColor(array.get(rsi3Arr, i), rsi_ob_3, rsi_os_3), 0, 60, 1) if d_z_1 cell(4, j, str.tostring(array.get(z1Arr, i), "#.##") + (array.get(z1Arr, i) > 0 ? " ▲" : array.get(z1Arr, i) < 0 ? " ▼" : ""), cellColor(array.get(z1Arr, i), z_ob_1, z_os_1), 0, 60, na(array.get(z1Arr, i)) ? 0 : 1) if d_z_2 cell(5, j, str.tostring(array.get(z2Arr, i), "#.##") + (array.get(z2Arr, i) > 0 ? " ▲" : array.get(z2Arr, i) < 0 ? " ▼" : ""), cellColor(array.get(z2Arr, i), z_ob_2, z_os_2), 0, 60, na(array.get(z2Arr, i)) ? 0 : 1) if d_z_3 cell(6, j, str.tostring(array.get(z3Arr, i), "#.##") + (array.get(z3Arr, i) > 0 ? " ▲" : array.get(z3Arr, i) < 0 ? " ▼" : ""), cellColor(array.get(z3Arr, i), z_ob_3, z_os_3), 0, 60, na(array.get(z3Arr, i)) ? 0 : 1) j += 1
Volume Forecast
https://www.tradingview.com/script/AgWBRvOc-Volume-Forecast/
gigi_duru
https://www.tradingview.com/u/gigi_duru/
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/ // © gigi_duru //@version=5 indicator("VolumeForecast", overlay = false, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500) measureMode = input.string("High/low", options = ["Open/close", "High/low", "Push", "Volume"]) startDate = input.time(timestamp("2023-01-01 00:00+03:00")) enableSession1 = input.bool(true, "", inline = "session1") session1 = input.session("0200-0659", inline = "session1") var sessionFrom1 = str.split(session1, "-").get(0) var sessionTo1 = str.split(session1, "-").get(1) enableSession2 = input.bool(true, "", inline = "session2") session2 = input.session("0900-1159", inline = "session2") var sessionFrom2 = str.split(session2, "-").get(0) var sessionTo2 = str.split(session2, "-").get(1) enableSession3 = input.bool(true, "", inline = "session3") session3 = input.session("1400-1859", inline = "session3") var sessionFrom3 = str.split(session3, "-").get(0) var sessionTo3 = str.split(session3, "-").get(1) enableSession4 = input.bool(true, "", inline = "session4") session4 = input.session("2000-2259", inline = "session4") var sessionFrom4 = str.split(session4, "-").get(0) var sessionTo4 = str.split(session4, "-").get(1) timezone = input.string("GMT+2") forecastBars = input.int(100, minval = 0, inline = "forecast") accountforDayOfWeek = input(false, inline = "forecast") deviationLookback = input(100, inline = "deviation") deviationMin = input(0.5, title = "Min", inline = "deviation") deviationMax = input(2.0, title = "Max", inline = "deviation") showMinValues = input.bool(false, inline = "display") showMaxValues = input.bool(false, inline = "display") showRealTimeVolume = input(false) showAverageVolume = input(true) measurementMultiplier = input(0.1) statsGroupByFormat = accountforDayOfWeek ? "E-HH:mm" : "HH:mm" var int timeframeMs = time_close - time var tbl = table.new(position.bottom_right, 2, 10) tbl.cell(0, 0, "Stats group size:", text_color = color.white) tbl.cell(0, 1, "Deviation (last " + str.tostring(deviationLookback) + " bars):", text_color = color.white) openInSession(sess) => na(time(timeframe.period, sess + ":1234567", timezone)) == false toHourString(timestamp) => str.format_time(timestamp, "HHmm", timezone) var int openTimeSession1 = na var int openTimeSession2 = na var int openTimeSession3 = na var int openTimeSession4 = na var int closeTimeSession1 = na var int closeTimeSession2 = na var int closeTimeSession3 = na var int closeTimeSession4 = na openInSession1 = openInSession(session1) and enableSession1 openInSession2 = openInSession(session2) and enableSession2 openInSession3 = openInSession(session3) and enableSession3 openInSession4 = openInSession(session4) and enableSession4 isOpenInSession = openInSession1 or openInSession2 or openInSession3 or openInSession4 type Volumes array<float> Volumes var deviations = array.new_float() while(deviations.size() > deviationLookback) deviations.remove(0) avgDeviation = deviations.size() > 0 ? deviations.avg() : 1.0 tbl.cell(1, 1, str.tostring(avgDeviation, "0.00"), text_color = color.white) var float sessionOpen1 = na var float sessionOpen2 = na var float sessionOpen3 = na var float sessionOpen4 = na var float push = na if(openInSession1) if(str.tonumber(toHourString(time_close)) < str.tonumber(sessionTo1)) if(na(sessionOpen1)) sessionOpen1 := open openTimeSession1 := time closeTimeSession1 := na else push := close - sessionOpen1 closeTimeSession1 := time_close else sessionOpen1 := na openTimeSession1 := na closeTimeSession1 := na if(not isOpenInSession) push := na if(openInSession2) if(str.tonumber(toHourString(time_close)) < str.tonumber(sessionTo2)) if(na(sessionOpen2)) sessionOpen2 := open openTimeSession2 := time closeTimeSession2 := na else push := close - sessionOpen2 closeTimeSession2 := time_close else sessionOpen2 := na openTimeSession2 := na closeTimeSession2 := na if(not isOpenInSession) push := na if(openInSession3) if(str.tonumber(toHourString(time_close)) < str.tonumber(sessionTo3)) if(na(sessionOpen3)) sessionOpen3 := open openTimeSession3 := time closeTimeSession3 := na else push := close - sessionOpen3 closeTimeSession3 := time_close else sessionOpen3 := na openTimeSession3 := na closeTimeSession3 := na if(not isOpenInSession) push := na if(openInSession4) if(str.tonumber(toHourString(time_close)) < str.tonumber(sessionTo4)) if(na(sessionOpen4)) sessionOpen4 := open openTimeSession4 := time closeTimeSession4 := na else push := close - sessionOpen4 closeTimeSession4 := time_close else sessionOpen4 := na openTimeSession4 := na closeTimeSession4 := na if(not isOpenInSession) push := na push := math.abs(push) / syminfo.mintick var float maxMeasurement = na measurement = measureMode == "" ? na : measureMode == "High/low" ? (high - low) / syminfo.mintick : measureMode == "Open/close" ? math.abs(close - open) / syminfo.mintick : measureMode == "Volume" ? volume : measureMode == "Push" ? push : na measurement := math.round(measurement * measurementMultiplier, 1) if(openTimeSession1 and closeTimeSession1) box.new(openTimeSession1, measurement, closeTimeSession1, 0, bgcolor = color.rgb(33, 149, 243, 81), xloc = xloc.bar_time, border_color = na) if(openTimeSession2 and closeTimeSession2) box.new(openTimeSession2, measurement, closeTimeSession2, 0, bgcolor = color.rgb(33, 249, 243, 82), xloc = xloc.bar_time, border_color = na) if(openTimeSession3 and closeTimeSession3) box.new(openTimeSession3, measurement, closeTimeSession3, 0, bgcolor = color.rgb(255, 33, 162, 83), xloc = xloc.bar_time, border_color = na) if(openTimeSession4 and closeTimeSession4) box.new(openTimeSession4, measurement, closeTimeSession4, 0, bgcolor = color.rgb(255, 233, 33, 84), xloc = xloc.bar_time, border_color = na) var volumes = map.new<string, Volumes>() currentTime = str.format_time(time, statsGroupByFormat) var futureBars = array.new_box() if(futureBars.size() == 0 and forecastBars > 0) for i = 1 to forecastBars futureBars.push(box.new(time, 0, time_close, 0, border_color = color.black, border_width = 1, bgcolor = color.rgb(255, 255, 255, 77), xloc = xloc.bar_time)) timeVolumes = volumes.get(currentTime) avgVol = 0.0 var volumeLine = line.new(0, measurement, 0, measurement, extend = extend.right, color = open <= close ? color.green : color.red, xloc = xloc.bar_time, style = line.style_dotted) volumeLine.set_y1(measurement) volumeLine.set_y2(measurement) if(time > startDate) if(isOpenInSession) if(showAverageVolume) if(na(timeVolumes)) timeVolumes := Volumes.new(array.new_float()) volumes.put(currentTime, timeVolumes) timeVolumes.Volumes.push(measurement) avgVol := timeVolumes.Volumes.avg() if(barstate.isconfirmed and deviationLookback > 0) deviations.push(math.max(deviationMin, math.min(deviationMax, avgVol / measurement))) tbl.cell(1, 0, str.tostring(timeVolumes.Volumes.size()), text_color = color.white) avgVol := avgVol / avgDeviation if(showRealTimeVolume and showAverageVolume) line.new(time, 0, time, measurement, xloc = xloc.bar_time, color = open <= close ? color.rgb(76, 175, 79, 60) : color.rgb(255, 82, 82, 52), width = 6) plotcandle(isOpenInSession ? (showMinValues ? timeVolumes.Volumes.min() : 0) : 0, isOpenInSession ? (showMaxValues ? timeVolumes.Volumes.max() : (showAverageVolume ? avgVol : measurement)) : na, 0, isOpenInSession ? (showAverageVolume ? avgVol : measurement) : na, color = color.rgb(24, 86, 138), title = "Average Volume", wickcolor = color.rgb(24, 86, 138), bordercolor = color.rgb(24, 86, 138), display = display.pane) if(forecastBars > 0) for i = 1 to forecastBars futureBar = futureBars.get(i - 1) futureBar.set_left(time + timeframeMs * i) futureBar.set_right(time_close + timeframeMs * i) futureTime = str.format_time(time + timeframeMs * i, statsGroupByFormat) futureTimeVolumes = volumes.get(futureTime) if(na(futureTimeVolumes)) break else averageVol = futureTimeVolumes.Volumes.avg() / avgDeviation if(showMinValues) futureBar.set_bottom(futureTimeVolumes.Volumes.min()) if(showMaxValues) line.new(time + timeframeMs * i, 0, time + timeframeMs * i, futureTimeVolumes.Volumes.max(), xloc = xloc.bar_time, color = color.rgb(255, 255, 255, 95), style = line.style_dotted, width = 1) futureBar.set_top(averageVol)
Crypto Market Overview
https://www.tradingview.com/script/pw05nnBK-Crypto-Market-Overview/
kikfraben
https://www.tradingview.com/u/kikfraben/
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/ // © kikfraben // Updated last on: Nov 6 2023 //@version=5 indicator("Crypto Market Overview", "CMO", true) // Define Lookback Period of % Change period = input(1, "Lookback Period") // Define Currency of Table cur = input.string("USD", "Currency", options = ["USD", "EUR", "CNY", "JPY", "AUD", "RUB", "INR", "AED"]) // Get Major Market Cap Data btc_cap = request.security("CRYPTOCAP:BTC", "D", close, currency = cur) // BTC eth_cap = request.security("CRYPTOCAP:ETH", "D", close, currency = cur) // ETH total_cap = request.security("CRYPTOCAP:TOTAL", "D", close, currency = cur) // TOTAL // Get Stablecoin Market Cap Data usdt_cap = request.security("CRYPTOCAP:USDT", "D", close, currency = cur) // USDT usdc_cap = request.security("CRYPTOCAP:USDC", "D", close, currency = cur) // USDC dai_cap = request.security("CRYPTOCAP:DAI", "D", close, currency = cur) // DAI tusd_cap = request.security("CRYPTOCAP:TUSD", "D", close, currency = cur) // TUSD busd_cap = request.security("CRYPTOCAP:BUSD", "D", close, currency = cur) // BUSD stable_cap = usdt_cap + usdc_cap + dai_cap + tusd_cap + busd_cap // Get Shitcoin Market Cap Data shit_cap = total_cap - btc_cap - eth_cap - stable_cap // Get Major Dominance Data btc_dom = request.security("CRYPTOCAP:BTC.D", "D", close, currency = cur) // BTC.D eth_dom = request.security("CRYPTOCAP:ETH.D", "D", close, currency = cur) // ETH.D total_dom = "100%" // Get Stablecoin Dominance Data usdt_dom = request.security("CRYPTOCAP:USDT.D", "D", close, currency = cur) // USDT.D usdc_dom = request.security("CRYPTOCAP:USDC.D", "D", close, currency = cur) // USDC.D dai_dom = request.security("CRYPTOCAP:DAI.D", "D", close, currency = cur) // DAI.D tusd_dom = request.security("CRYPTOCAP:TUSD.D", "D", close, currency = cur) // TUSD.D busd_dom = request.security("CRYPTOCAP:BUSD.D", "D", close, currency = cur) // BUSD.D stable_dom = usdt_dom + usdc_dom + dai_dom + tusd_dom + busd_dom // Get Shitcoin Dominance Data shit_dom = 100 - btc_dom - eth_dom - stable_dom // Format Market Cap Data & Get Market Cap Rate of Change f_btc_cap = str.tostring(btc_cap / 1000000000, ".00") + "B" f_eth_cap = str.tostring(eth_cap / 1000000000, ".00") + "B" f_total_cap = str.tostring(total_cap / 1000000000, ".00") + "B" f_stable_cap = str.tostring(stable_cap / 1000000000, ".00") + "B" f_shit_cap = str.tostring(shit_cap / 1000000000, ".00") + "B" roc_btc_cap = ta.roc(btc_cap, period) roc_eth_cap = ta.roc(eth_cap, period) roc_total_cap = ta.roc(total_cap, period) roc_stable_cap = ta.roc(stable_cap, period) roc_shit_cap = ta.roc(shit_cap, period) f_btc_cap_roc = str.tostring(roc_btc_cap, format.percent) f_eth_cap_roc = str.tostring(roc_eth_cap, format.percent) f_stable_cap_roc = str.tostring(roc_stable_cap, format.percent) f_shit_cap_roc = str.tostring(roc_shit_cap, format.percent) f_total_cap_roc = str.tostring(roc_total_cap, format.percent) // Format Dominance & Get Dominance Rate of Change roc_btc_dom = ta.roc(btc_dom, period) roc_eth_dom = ta.roc(eth_dom, period) roc_stable_dom = ta.roc(stable_dom, period) roc_shit_dom = ta.roc(shit_dom, period) f_btc_dom = str.tostring(btc_dom, format.percent) f_eth_dom = str.tostring(eth_dom, format.percent) f_stable_dom = str.tostring(stable_dom, format.percent) f_shit_dom = str.tostring(shit_dom, format.percent) f_btc_dom_roc = str.tostring(roc_btc_dom, format.percent) f_eth_dom_roc = str.tostring(roc_eth_dom, format.percent) f_stable_dom_roc = str.tostring(roc_stable_dom, format.percent) f_shit_dom_roc = str.tostring(roc_shit_dom, format.percent) // Color Conditions up_col = #3fa8c9 down_col = #c93f3f bg_col = color.new(color.white, 95) txt_col = color.white txt_col1 = color.new(color.white, 25) txt_col2 = color.new(color.green, 35) table_col = color.new(color.white, 70) // Get Table main = table.new(position = position.middle_center, columns = 6,rows = 8, frame_color = table_col, border_color = table_col, frame_width = 2, border_width = 2) // Merge Cells table.merge_cells(main, 0, 0, 4, 0) // Layout table.cell(main, 0, 0, "Crypto Market Overview", text_color = color.yellow, bgcolor = bg_col) table.cell(main, 0, 1, "Asset", text_color = txt_col, bgcolor = bg_col) table.cell(main, 1, 1, "Market Cap", text_color = txt_col, bgcolor = bg_col) table.cell(main, 2, 1, "Cap RoC", text_color = txt_col, bgcolor = bg_col) table.cell(main, 3, 1, "Dominance", text_color = txt_col, bgcolor = bg_col) table.cell(main, 4, 1, "Dom RoC", text_color = txt_col, bgcolor = bg_col) table.cell(main, 0, 2, "Bitcoin", text_color = txt_col1, bgcolor = bg_col) table.cell(main, 0, 3, "Ethereum", text_color = txt_col1, bgcolor = bg_col) table.cell(main, 0, 4, "Stablecoins", text_color = txt_col1, bgcolor = bg_col) table.cell(main, 0, 5, "Shitcoins", text_color = txt_col1, bgcolor = bg_col) table.cell(main, 0, 6, "Total", text_color = txt_col, bgcolor = bg_col) // BTC table.cell(main, 1, 2, f_btc_cap, text_color = roc_btc_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 2, 2, f_btc_cap_roc, text_color = roc_btc_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 3, 2, f_btc_dom, text_color = roc_btc_dom > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 4, 2, f_btc_dom_roc, text_color = roc_btc_dom > 0 ? up_col : down_col, bgcolor = bg_col) // ETH table.cell(main, 1, 3, f_eth_cap, text_color = roc_eth_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 2, 3, f_eth_cap_roc, text_color = roc_eth_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 3, 3, f_eth_dom, text_color = roc_eth_dom > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 4, 3, f_eth_dom_roc, text_color = roc_eth_dom > 0 ? up_col : down_col, bgcolor = bg_col) // Stablecoins table.cell(main, 1, 4, f_stable_cap, text_color = roc_stable_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 2, 4, f_stable_cap_roc, text_color = roc_stable_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 3, 4, f_stable_dom, text_color = roc_stable_dom > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 4, 4, f_stable_dom_roc, text_color = roc_stable_dom > 0 ? up_col : down_col, bgcolor = bg_col) // Shitcoins table.cell(main, 1, 5, f_shit_cap, text_color = roc_shit_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 2, 5, f_shit_cap_roc, text_color = roc_shit_cap > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 3, 5, f_shit_dom, text_color = roc_shit_dom > 0 ? up_col : down_col, bgcolor = bg_col) table.cell(main, 4, 5, f_shit_dom_roc, text_color = roc_shit_dom > 0 ? up_col : down_col, bgcolor = bg_col) // Total table.cell(main, 1, 6, f_total_cap, text_color = txt_col, bgcolor = bg_col) table.cell(main, 2, 6, f_total_cap_roc, text_color = txt_col, bgcolor = bg_col) table.cell(main, 3, 6, total_dom, text_color = txt_col, bgcolor = bg_col) table.cell(main, 4, 6, text = "na", text_color = txt_col, bgcolor = bg_col)
Klinger Oscillator Advanced
https://www.tradingview.com/script/RTu2Vp9g/
GreyGoliath
https://www.tradingview.com/u/GreyGoliath/
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/ // © schmidtkemanfred1956 // The Klinger Oscillator is not fully implemented in Tradeview. While the description at // https://de.tradingview.com/chart/?solution=43000589157 is complete, the implementation is limited to the // pure current volume movement. This results in no difference compared to the On Balance Volume indicator. //However, Klinger's goal was to incorporate the trend as volume force in its strength and duration into the //calculation. The expression ((V x [2 x ((dm/cm) - 1)] x T x 100)) for volume force only makes sense as an //absolute value, which should probably be expressed as //((V x abs(2 x ((dm/cm) - 1)) x T x 100)). Additionally, there is a need to handle the theoretical possibility //of cm == 0. //Since, in general, significantly more trading volume occurs at the closing price than during the day, an //additional parameter for weighting the closing price is implemented. In intraday charts, considering the //closing price, in my opinion, does not make sense. //@version=5 indicator( title = "Klinger Oscillator Advanced", shorttitle = "KOA", overlay = false) fastper = input.int( title = "Fast Period" , tooltip = "Fast period for volumeforce" , inline = "PERIOD" , defval = 34 , minval = 1 ) slowper = input.int( title = "Slow" , tooltip = "Slow period for volumeforce" , inline = "PERIOD" , defval = 55 , minval = 2 ) signalper = input.int( title = "Signal Period" , tooltip = "Period for signal line" , defval = 13 , minval = 1 ) closeweight = input.int( title = "Close weight" , tooltip = "Weighting of closing price. 0 = hl2, 1 = hlc3, 2 = hlcc4, >2 feel free." , defval = 1 , minval = 0 , maxval = 10 ) //Function for Klinger Oscillator KlingerOsc (simple int fastper = 34, simple int slowper = 55, simple int signalper = 13, simple int closeweight = 1) => series int trend = na series float cm = na series float dm = na series float ko = na series float signal = na series float price = na if bar_index > slowper - 1 dm := high - low price := switch closeweight 0 => hl2 1 => hlc3 2 => hlcc4 //hlccx => (high+low+close*closeweight) / (2+closeweight) trend := price > price[1] ? 1 : -1 cm := trend > 0 and trend[1] > 0 ? cm[1] + dm : dm + dm[1] vf = volume * trend * 100 * cm > 0 ? math.abs (2 * dm / cm - 1) : 0 kofast = ta.ema (vf, fastper) koslow = ta.ema (vf, slowper) ko := kofast - koslow //Signalline signal := ta.ema (ko, signalper) [ko, signal] [ko, signal] = KlingerOsc (fastper, slowper, signalper,closeweight) plot(ko, color = #2962FF, title="Klinger Oscillator") plot(signal, color = #43A047, title="Signal") plot(0, color=color.gray)
unconscious line
https://www.tradingview.com/script/xpJM8K4i/
Unjuno
https://www.tradingview.com/u/Unjuno/
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/ // © Unjuno //に皆が相場の動く向きを予想するが相場は、買いたい人が買いたいところで買って売りたい人が売りたいときに売ってということをし続けるとこれは、希望価格の生存時間は、短いと考えるのでこれは移動圧力がその方向に移 //動するので、最終的には、一番意識されていない領域に収束する。 //意識されていない領域を見分けることによって、相場の収束する点がわかるということになる。 //問題は意識されていない領域をどう定義するかである。ここでは、その領域を高値と高値安値と安値を結んだ領域ではない場所と考える。 //@version=5 indicator("unconscious line") arrybaf = input(10000,title = "arybuf") var array<float> a = array.new<float>(arrybaf,0) var array<float> aa = array.new<float>(arrybaf,0) int count = 0 array.set(a,count,close[1]-close[2]) //傾きを見て現在の位置における延長した価格帯を見て、線が通っていないところに、しるしをつける。 for int i = 0 to count getval = array.get(a,i) //この微分値により、現在の価格を求格納する。 setval = close[count]+(getval*(count-i)) array.set(aa,i,setval) /// array.sort(aa) var float Biggest_difference = 0 var float tempval = 0 tempval := 0 var float tempval2 = 0 tempval2 := 0 Biggest_difference := 0 for int i = 0 to count tempval := (array.get(aa,i) - array.get(aa,i+1)) < 0 ? (-1)*(array.get(aa,i) - array.get(aa,i+1)) : (array.get(aa,i) - array.get(aa,i+1)) if(Biggest_difference < tempval) Biggest_difference := tempval var float plotprice1 = 0 var float plotprice2 = 0 for int i = 0 to count tempval := (array.get(aa,i) - array.get(aa,i+1)) < 0 ? (-1)*(array.get(aa,i) - array.get(aa,i+1)) : (array.get(aa,i) - array.get(aa,i+1)) if(tempval == Biggest_difference) plotprice1 := array.get(aa,i) plotprice2 := array.get(aa,i+1) /// count += 1 ///plot plot(array.get(aa,0),title = "1",color = color.blue,linewidth = 2) plot(array.get(aa,count),title = "2",color = color.white,linewidth = 2) plot(plotprice1,title = "3",color = color.yellow,linewidth = 2) plot(plotprice2,title = "4",color = color.green,linewidth = 2) //収束なので、時間がかかるほど、近付く可能性が高くなるので、バーごとにカウントして、値が下抜け又は上抜けした場合に、0に初期化する変数を定義し、数値のみ見れる形で、描画する。 //収束していないバーの数の変数 var int countbarnonconvergence = 0 countbarnonconvergence += 1 if(ta.crossover(high,plotprice1 > plotprice2 ? plotprice2 : plotprice1) or ta.crossunder(low,plotprice1 > plotprice2 ? plotprice1 : plotprice2)) countbarnonconvergence := 0 plot(countbarnonconvergence,title = "period of nonconcentration",color = color.white,display = display.status_line)
Logarithmic Bollinger Bands [MisterMoTA]
https://www.tradingview.com/script/v8zcuVql-Logarithmic-Bollinger-Bands-MisterMoTA/
MisterMoTA
https://www.tradingview.com/u/MisterMoTA/
14
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 = MisterMoTA // © MisterMoTA //@version=5 indicator(title="Logarithmic Bollinger Bands [MisterMoTA]", shorttitle = "LBBMO", overlay=true) hideLabels = input.bool(false, title="Hide Labels", group = "Indicator Settings") styleOption = input.string("small", title="Label Size", options=["normal", "large", "small"], group = "Indicator Settings") labelSize = styleOption == "normal" ? size.normal : styleOption == "large" ? size.large : styleOption == "small" ? size.small : size.normal std = input.float(2, "Standard deviation", group = "Indicator Settings") src = input.source(close,"Source", group = "Indicator Settings") decimals = input.int(2, "Decimals for price displayed in Labels", maxval = 8, group = "Indicator Settings") labelDistance = input.int(10, "Labels Distance From Price", group = "Indicator Settings") mainPivotColor = input.color(#3288bd, "SMA 20 Color", group = "Indicator Settings") line0382Color = input.color(#66c2a5, "0.382 Color", group = "Indicator Settings") line0618Color = input.color(#abdda4, "0.618 Color", group = "Indicator Settings") lineT1Color = input.color(#e6f598, " MAIN BB BANDS Color", group = "Indicator Settings") lineee0382Color = input.color(#fee08b, "0.382 Expansion Color", group = "Indicator Settings") lineee0618Color = input.color(#fdae61, "0.618 Expansion Color", group = "Indicator Settings") lineee1Color = input.color(#f46d43, "1 Expansion Color", group = "Indicator Settings") lineee1618Color = input.color(#d53e4f, "1.618 Color", group = "Indicator Settings") var string decs =na if decimals == 0 decs := "#" else if decimals == 1 decs :="#.#" else if decimals == 2 decs := "#.##" else if decimals == 3 decs :="#.###" else if decimals == 4 decs :="#.####" else if decimals == 5 decs :="#.#####" else if decimals == 6 decs :="#.######" else if decimals == 7 decs :="#.#######" else if decimals == 8 decs :="#.########" var lm = label (na) var l1 = label (na) var l2 = label (na) var l3 = label (na) var l4 = label (na) var l5 = label (na) var l6 = label (na) var l7 = label (na) var r11 = label (na) var r22 = label (na) var r33 = label (na) var r44 = label (na) var r55 = label (na) var r66 = label (na) var r77 = label (na) float p0382 = na float p0618 = na float Top1 = na float pp0382 = na float pp0618 = na float pp1 = na float pp1618 = na float m0382 = na float m0618 = na float Bottom1 = na float mm0382 = na float mm0618 = na float mm1 = na float mm1618 = na smma = ta.sma(src, 20) dev = std * ta.stdev(src, 20) upper = smma + dev lower = smma - dev p0382 := smma * math.pow(smma/lower, 0.382) p0618 := smma * math.pow(smma/lower, 0.618) Top1 :=upper pp0382 := upper * math.pow(upper/smma, 0.382) pp0618 := upper * math.pow(upper/smma, 0.618) pp1 := upper * math.pow(upper/smma, 1) pp1618 := upper * math.pow(upper/smma, 1.618) m0382 := smma * math.pow(smma/upper, 0.382) m0618 := smma * math.pow(smma/upper, 0.618) Bottom1 := lower mm0382 := lower * math.pow(lower/smma, 0.382) mm0618 := lower * math.pow(lower/smma, 0.618) mm1 := lower * math.pow(lower/smma, 1) mm1618 := lower * math.pow(lower/smma, 1.618) plot( smma, color = mainPivotColor, linewidth = 2, style = plot.style_line, title="SMA 20", display = display.pane) plot( p0382, color = line0382Color, linewidth = 1, style = plot.style_line , title="+ 0.382 Pivot", display = display.pane) plot( p0618, color = line0618Color, linewidth = 1, style = plot.style_line, title="+ 0.618 Pivot", display = display.pane) topBB = plot( Top1, color = lineT1Color, linewidth = 2, style = plot.style_line, title="Main Top Bollinger Band", display = display.pane) plot( pp0382, color = lineee0382Color, linewidth = 1, style = plot.style_line, title="+ 0.382 Expansion Pivot", display = display.pane) plot( pp0618, color = lineee0618Color, linewidth = 1, style = plot.style_line, title="+ 0.618 Expansion Pivot", display = display.pane) plot( pp1, color = lineee1Color, linewidth = 1, style = plot.style_line, title="+ 1 Expansion Pivot", display = display.pane) plot( pp1618, color = lineee1618Color, linewidth = 1, style = plot.style_line, title="+ 1.618 Expansion Pivot", display = display.pane) plot( m0382, color = line0382Color, linewidth = 1, style = plot.style_line, title="- 0.382 Pivot", display = display.pane) plot( m0618, color = line0618Color, linewidth = 1, style = plot.style_line, title="- 0.618 Pivot", display = display.pane) bottomBB = plot( Bottom1, color = lineT1Color, linewidth = 2, style = plot.style_line, title="Main Bottom Bollinger Band", display = display.pane) plot( mm0382, color = lineee0382Color, linewidth = 1, style = plot.style_line, title="- 0.382 Expansion Pivot", display = display.pane) plot( mm0618, color = lineee0618Color, linewidth = 1, style = plot.style_line, title="- 0.618 Expansion Pivot", display = display.pane) plot( mm1, color = lineee1Color, linewidth = 1, style = plot.style_line, title=" - 1 Expansion Pivot", display = display.pane) plot( mm1618, color = lineee1618Color, linewidth = 1, style = plot.style_line, title="- 1.618 Expansion Pivot", display = display.pane) fill(topBB, bottomBB, title = "Background", color=color.rgb(33, 100, 243, 95)) if hideLabels == false lm := label.new(bar_index+labelDistance, smma, str.tostring(smma, decs) + ' is 20 SMA', color=#00000000, textcolor=mainPivotColor, style=label.style_label_left, size=labelSize) l1 := label.new(bar_index+labelDistance, p0382, str.tostring(p0382, decs), color=#00000000, textcolor=line0382Color, style=label.style_label_left, size=labelSize) l2 := label.new(bar_index+labelDistance, p0618, str.tostring(p0618, decs), color=#00000000, textcolor=line0618Color, style=label.style_label_left, size=labelSize) l3 := label.new(bar_index+labelDistance, Top1, str.tostring(Top1, decs) + " is Top Bollindger Band", color=#00000000, textcolor=lineT1Color, style=label.style_label_left, size=labelSize) l4 := label.new(bar_index+labelDistance, pp0382, str.tostring(pp0382, decs), color=#00000000, textcolor=lineee0382Color, style=label.style_label_left, size=labelSize) l5 := label.new(bar_index+labelDistance, pp0618, str.tostring(pp0618, decs), color=#00000000, textcolor=lineee0618Color, style=label.style_label_left, size=labelSize) l6 := label.new(bar_index+labelDistance, pp1, str.tostring(pp1, decs), color=#00000000, textcolor=lineee1Color, style=label.style_label_left, size=labelSize) l7 := label.new(bar_index+labelDistance, pp1618, str.tostring(pp1618, decs), color=#00000000, textcolor=lineee1618Color, style=label.style_label_left, size=labelSize) r11 := label.new(bar_index+labelDistance, m0382, str.tostring(m0382, decs), color=#00000000, textcolor=line0382Color, style=label.style_label_left,size=labelSize) r22 := label.new(bar_index+labelDistance, m0618, str.tostring(m0618, decs), color=#00000000, textcolor=line0618Color, style=label.style_label_left, size=labelSize) r33 := label.new(bar_index+labelDistance, Bottom1, str.tostring(Bottom1, decs) + " is Bottom Bollindger Band", color=#00000000, textcolor=lineT1Color, style=label.style_label_left, size=labelSize) r44 := label.new(bar_index+labelDistance, mm0382, str.tostring(mm0382, decs) , color=#00000000, textcolor=lineee0382Color, style=label.style_label_left, size=labelSize) r55 := label.new(bar_index+labelDistance, mm0618, str.tostring(mm0618, decs), color=#00000000, textcolor=lineee0618Color, style=label.style_label_left, size=labelSize) r66 := label.new(bar_index+labelDistance, mm1, str.tostring(mm1, decs), color=#00000000, textcolor=lineee1Color, style=label.style_label_left, size=labelSize) r77 := label.new(bar_index+labelDistance, mm1618, str.tostring(mm1618, decs), color=#00000000, textcolor=lineee1618Color, style=label.style_label_left, size=labelSize) label.delete(lm[1]) label.delete(l1[1]) label.delete(l2[1]) label.delete(l3[1]) label.delete(l4[1]) label.delete(l5[1]) label.delete(l6[1]) label.delete(l7[1]) label.delete(r11[1]) label.delete(r22[1]) label.delete(r33[1]) label.delete(r44[1]) label.delete(r55[1]) label.delete(r66[1]) label.delete(r77[1])
Daily Score
https://www.tradingview.com/script/mumrQFi5-Daily-Score/
JuicyTeets
https://www.tradingview.com/u/JuicyTeets/
14
study
4
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/ // © JuicyTeets //@version=4 study("Daily Score", overlay=true) // Input parameters smaLength = input(50, title="SMA Length") smaLengthTwoHundred = input(200, title="SMA Length 200") rsiLength = input(13, title="RSI Length") rsiThreshold = input(40.99, title="RSI Threshold") // Calculate the SMA smaValue = sma(close, smaLength) smaValueTwoHundred = sma(close, smaLengthTwoHundred) // Compare current price to the SMA isAboveSMA = close > smaValue isAboveSMATwoHundred = close > smaValueTwoHundred // Assign a score based on the comparison OverFiftyScore = isAboveSMA ? 2 : 0 OverTwoHundredScore = isAboveSMATwoHundred ? 1 : 0 // Calculate the previous SMA value prevSmaValue = sma(close, smaLength)[1] prevSmaTwoHundredValue = sma(close, smaLengthTwoHundred)[1] // Assess the trend isUpTrend = smaValue > prevSmaValue isDownTrend = smaValue < prevSmaValue FiftyTrendScore = isUpTrend ? 2 : isDownTrend ? -2 :0 isUpTrendTwoHundred = smaValueTwoHundred > prevSmaTwoHundredValue isDownTrendTwoHundred = smaValueTwoHundred < prevSmaTwoHundredValue TwoHundredTrendScore = isUpTrendTwoHundred ? 2 : isDownTrendTwoHundred ? -2 :0 // Assess if 50 is above the 200 is50above200 = smaValue > smaValueTwoHundred is50above200score = is50above200 ? 3 : 0 // Score for comparison of current price at trigger to price at end of previous bull zone rsiValue = rsi(close, rsiLength) rsiBelowThreshold = crossover(rsiValue, rsiThreshold) var float priceAtRSILow = na if (rsiBelowThreshold) priceAtRSILow := close priceAboveRSILow = close > priceAtRSILow LastPeriodScore = priceAboveRSILow ? 3 : 0 //Scoring for whether a local min or max has recently occurred lookbackPeriod = 30 recentPeriod = 5 // Function to get the highest high and lowest low over a specified period getExtremePrices(srcHigh, srcLow, length) => highPrice = highest(srcHigh, length) lowPrice = lowest(srcLow, length) [highPrice, lowPrice] // Get the highest high and lowest low over the last 100 days [highestHigh100Day, lowestLow100Day] = getExtremePrices(high, low, lookbackPeriod) // Assess how recently the extreme prices were achieved daysSinceHigh = barssince(high == highestHigh100Day) daysSinceLow = barssince(low == lowestLow100Day) // Check if either the highest high or lowest low was achieved within the last 5 days and assign a score Extremescore = (daysSinceHigh <= recentPeriod or daysSinceLow <= recentPeriod) ? -3 : 0 //Check if a golden cross has occurred within 5 days // Input parameters sma50 = sma(close, 50) sma200 = sma(close, 200) // Assess whether the 50-day SMA has crossed over the 200-day SMA in the last 5 days PositivecrossoverOccurred = crossover(sma50, sma200) and barssince(crossover(sma50, sma200)) < 5 NegativecrossoverOccurred = crossover(sma200, sma50) and barssince(crossover(sma200, sma50)) < 5 // Score calculation PosXscore = PositivecrossoverOccurred ? 2 : 0 NegXscore = NegativecrossoverOccurred ? -2 : 0 // Update the score based on all assessments combinedScore1 = OverFiftyScore + FiftyTrendScore + OverTwoHundredScore + TwoHundredTrendScore + is50above200score + LastPeriodScore + Extremescore + PosXscore + NegXscore // Create final Score score = combinedScore1 // Plot the score on the chart// plot(score, color=color.rgb(131,255,82), style=plot.style_stepline, title="Score")
New Tradability by haji
https://www.tradingview.com/script/SKKOx2a7-New-Tradability-by-haji/
elicruz2380
https://www.tradingview.com/u/elicruz2380/
31
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/ // © hajjiplays // This code is now available to the public. People may now copy and reuse the code in bigger projects. // However this script property of NoGoodLuck LLC, // and may not be copied or redistributed without credit to Elhadji Ouedrago or NoGoodLuck. //@version=5 indicator("New Tradability by haji", overlay = false) ha_t = ticker.heikinashi(syminfo.tickerid) normal = ticker.new(syminfo.prefix, syminfo.tickerid) tradabilitybar = "On" fearbar = "On" forceshow = "Greed" areanumber = input.int(2, "True Area Lookback", group = "Settings", minval = 0) backtracknumber = input.int(1999, "Backtest Bars", group = "Settings", minval = 0) testingnumberMicro = input.int(1, "Micro Testing Number", group = "Settings Pattern", minval = 1) testingnumberNormal = input.int(3, "Normal Testing Number", group = "Settings Pattern", minval = 1) testingnumberMacro = input.int(8, "Macro Testing Number", group = "Settings Pattern", minval = 1) testingshort = input.bool(true, "Use Short Time Frame") testingnormal = input.bool(true, "Use Normal Time Frame") testinglong = input.bool(true, "Use Long Time Frame") abovebelow = input.string("Above", "Above or Below", ["Above", "Below"], group = "Main Alerts") alertmewhen = input.string("None", "Alert Me When", ["None", "Pre-Active", "Active", "Mean Reversion"], group = "Main Alerts") trendarea = input.int(0, title = "Trend Area Score Alert Value", group = "Main Alerts") tradabilityvalue = input.int(0, title = "Tradability Score Alert Value", group = "Main Alerts") microqualityalert = input.int(0, title = "Micro Quality Alert Value", group = "Specific Alerts") qualityalert = input.int(0, title = "Quality Alert Value", group = "Specific Alerts") macroqualityalert = input.int(0, title = "Macro Quality Alert Value", group = "Specific Alerts") microtrendalert = input.int(0, title = "Micro Trend Alert Value", group = "Specific Alerts") trendalert = input.int(0, title = "Trend Value", group = "Specific Alerts") macrotrendalert = input.int(0, title = "Macro Trend Alert Value", group = "Specific Alerts") andor = input.string("AND", "AND / OR", ["AND", "OR"], group = "Pattern Alerts") consistencymicroScoreAlert = input.int(0, title = "Consistency Micro Score", group = "Pattern Alerts") consistencynormalScoreAlert = input.int(0, title = "Consistency Normal Score", group = "Pattern Alerts") consistencymacroScoreAlert = input.int(0, title = "Consistency Macro Score", group = "Pattern Alerts") arrownumber = 4 patterns_short = '30' patterns_normal = '60' patterns_long = '240' overlay = false showdirection = true useoldcal = true timingg1 = false useV4 = true timingg = false if timingg1 == true timingg := true if overlay == false fearbar := "Off" showdirection := false williamsalligator = " Williams Alligator is Mixed" resshort = patterns_short ha_openshort = request.security(ha_t, resshort, open) ha_closeshort = request.security(ha_t, resshort, close) ha_difshort = ha_openshort - ha_closeshort iff_short = ha_difshort < 0 ? 2 : 3 ha_diffshort = ha_difshort > 0 ? 1 : iff_short resnormal = patterns_normal ha_opennormal = request.security(ha_t, resnormal, open) ha_closenormal = request.security(ha_t, resnormal, close) ha_difnormal = ha_opennormal - ha_closenormal iff_normal = ha_difnormal < 0 ? 2 : 3 ha_diffnormal = ha_difnormal > 0 ? 1 : iff_normal reslong = patterns_long ha_openlong = request.security(ha_t, reslong, open) ha_closelong = request.security(ha_t, reslong, close) ha_diflong = ha_openlong - ha_closelong iff_long = ha_diflong < 0 ? 2 : 3 ha_difflong = ha_diflong > 0 ? 1 : iff_long res15 = '15' ha_open15 = request.security(ha_t, res15, open) ha_close15 = request.security(ha_t, res15, close) ha_dif15 = ha_open15 - ha_close15 iff_15 = ha_dif15 < 0 ? 2 : 3 ha_diff15 = ha_dif15 > 0 ? 1 : iff_15 res60 = '60' ha_open60 = request.security(ha_t, res60, open) ha_close60 = request.security(ha_t, res60, close) ha_dif60 = ha_open60 - ha_close60 iff_60 = ha_dif60 < 0 ? 2 : 3 ha_diff60 = ha_dif60 > 0 ? 1 : iff_60 res240 = '240' ha_open240 = request.security(ha_t, res240, open) ha_close240 = request.security(ha_t, res240, close) ha_dif240 = ha_open240 - ha_close240 iff_240 = ha_dif240 < 0 ? 2 : 3 ha_diff240 = ha_dif240 > 0 ? 1 : iff_240 colorr = color.gray oneclose200 = (request.security(syminfo.tickerid, "1", ta.sma(request.security(syminfo.tickerid, "1", close), 200))) oneclose50 = (request.security(syminfo.tickerid, "1", ta.sma(request.security(syminfo.tickerid, "1", close), 50))) oneclose9 = (request.security(syminfo.tickerid, "1", ta.sma(request.security(syminfo.tickerid, "1", close), 9))) fifteenclose200 = (request.security(syminfo.tickerid, "15", ta.sma(request.security(syminfo.tickerid, "15", close), 200))) fifteenclose50 = (request.security(syminfo.tickerid, "15", ta.sma(request.security(syminfo.tickerid, "15", close), 50))) fifteenclose9 = (request.security(syminfo.tickerid, "15", ta.sma(request.security(syminfo.tickerid, "15", close), 9))) thirtyclose200 = (request.security(syminfo.tickerid, "30", ta.sma(request.security(syminfo.tickerid, "30", close), 200))) thirtyclose50 = (request.security(syminfo.tickerid, "30", ta.sma(request.security(syminfo.tickerid, "30", close), 50))) thirtyclose9 = (request.security(syminfo.tickerid, "30", ta.sma(request.security(syminfo.tickerid, "30", close), 9))) onehourclose200 = (request.security(syminfo.tickerid, "60", ta.sma(request.security(syminfo.tickerid, "60", close), 200))) onehourclose50 = (request.security(syminfo.tickerid, "60", ta.sma(request.security(syminfo.tickerid, "60", close), 50))) onehourclose9 = (request.security(syminfo.tickerid, "60", ta.sma(request.security(syminfo.tickerid, "60", close), 9))) microquality = (((math.abs(close - oneclose200) * 8) + (math.abs(close - oneclose50) * 4) + (math.abs(close - oneclose9) * 2)) * 2) quality = (((math.abs(close - fifteenclose200) * 8) + (math.abs(close - fifteenclose50) * 4) + (math.abs(close - fifteenclose9) * 2))) macroquality = (((math.abs(close - thirtyclose200) * 8) + (math.abs(close - thirtyclose50) * 4) + (math.abs(close - thirtyclose9) * 2)) * 2) + (((math.abs(close - onehourclose200) * 8) + (math.abs(close - onehourclose50) * 4) + (math.abs(close - onehourclose9) * 2)) * 1) currentmicroquality = microquality[0] rankedmicroquality = 1 for i = 1 to 1000 if microquality[i] > currentmicroquality rankedmicroquality := rankedmicroquality + 1 percentilemicro = ((rankedmicroquality - 1) * 100) / 1000 currentquality = quality[0] rankedquality = 1 for i = 1 to 1000 if quality[i] > currentquality rankedquality := rankedquality + 1 percentile = ((rankedquality - 1) * 100) / 1000 currentmacroquality = macroquality[0] rankedmacroquality = 1 for i = 1 to 1000 if macroquality[i] > currentmacroquality rankedmacroquality := rankedmacroquality + 1 percentilemacro = ((rankedmacroquality - 1) * 100) / 1000 currentAtr = ta.atr(2)[0] rankedAtr = 1 if tradabilitybar == "On" for i = 1 to 1000 if ta.atr(2)[i] > currentAtr rankedAtr := rankedAtr + 1 Volatility = 'Average' ATRpercentile = (100 - ((rankedAtr * 100)/1000)) lengthh = 15 mult = 2.0 lengthhKC = 20 multKC = 1.5 useTrueRange = true // Calculate BB source = close basis = ta.sma(source, lengthh) dev = multKC * ta.stdev(source, lengthh) upperBB = basis + dev lowerBB = basis - dev // Calculate KC maa = ta.sma(source, lengthhKC) range_1 = useTrueRange ? ta.tr : high - low rangemaa = ta.sma(range_1, lengthhKC) upperKC = maa + rangemaa * multKC lowerKC = maa - rangemaa * multKC sqzOn = lowerBB > lowerKC and upperBB < upperKC sqzOff = lowerBB < lowerKC and upperBB > upperKC noSqz = not sqzOn and not sqzOff val = ta.linreg(source - math.avg(math.avg(ta.highest(high, lengthhKC), ta.lowest(low, lengthhKC)), ta.sma(close, lengthhKC)), lengthhKC, 0) max = 70 min = 1 overbought = 70 oversold = 30 src2 = close N = max-min+1 diff = nz(src2 - src2[1]) var num = array.new_float(N,0) var den = array.new_float(N,0) k = 0 overbuy = 0 oversell = 0 avgg = 0. for i = min to max alpha = 1/i num_rma = alpha*diff + (1-alpha)*array.get(num,k) den_rma = alpha*math.abs(diff) + (1-alpha)*array.get(den,k) rsi = 50*num_rma/den_rma + 50 avgg += rsi overbuy := rsi > overbought ? overbuy + 1 : overbuy oversell := rsi < oversold ? oversell + 1 : oversell array.set(num,k,num_rma) array.set(den,k,den_rma) k += 1 //---- avg_rsi = avgg/N buy_rsi_ma = 0. sell_rsi_ma = 0. buy_rsi_ma := nz(buy_rsi_ma[1] + overbuy/N*(avg_rsi - buy_rsi_ma[1]),avg_rsi) sell_rsi_ma := nz(sell_rsi_ma[1] + oversell/N*(avg_rsi - sell_rsi_ma[1]),avg_rsi) mfivariable = 0.0 if ha_diff60 == 2 if overbuy > 10 mfivariable := -5 if ha_diff60 == 1 if oversell > 10 mfivariable := -5 if ha_diff60 == 2 if oversell > 10 mfivariable := 10 if ha_diff60 == 1 if overbuy > 10 mfivariable := 10 squeezevariable = 1.0 len = 34 src = close ref = 13 sqzLen = 5 ma = ta.ema(src, len) closema = close - ma refma = ta.ema(src, ref)-ma sqzma = ta.ema(src, sqzLen)-ma if noSqz squeezevariable := 10 if sqzOn squeezevariable := -5 tradability = (((percentile * 2 ) + ATRpercentile) / 3) + (mfivariable + squeezevariable) percentiletradability = tradability lengthce = 4 multce = 2.0 showLabels = true useClose = true highlightState = true atr = multce * ta.atr(lengthce) longStop = (useClose ? ta.highest(close, lengthce) : ta.highest(lengthce)) - atr longStopPrev = nz(longStop[1], longStop) longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop shortStop = (useClose ? ta.lowest(close, lengthce) : ta.lowest(lengthce)) + atr shortStopPrev = nz(shortStop[1], shortStop) shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop var int dir = 1 dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir lasttime = 0 lasttime2 = 0 if tradabilitybar == "On" if dir == 2 for i = 1 to 100 if dir[i] == 2 lasttime += 5 else break if dir == 1 for i = 1 to 100 if dir[i] == 1 lasttime += 5 else break if ha_diff60 == 2 for i = 1 to 100 if ha_diff60 == 1 lasttime2 += 5 else break if ha_diff60 == 1 for i = 1 to 100 if ha_diff60 == 2 lasttime2 += 5 else break extra = (dir == 1 ? (math.abs(close - longStop)) : (math.abs(close - shortStop))) madridvariable = 0.0 if closema>= sqzma and closema>=0 and dir == 1 madridvariable := 10 if closema>= sqzma and closema>=0 and dir == -1 madridvariable := -10 if closema<= sqzma and closema<=0 and dir == -1 madridvariable := 10 if closema<= sqzma and closema<=0 and dir == 1 madridvariable := -10 if closema>= sqzma and closema<=0 and dir == 1 madridvariable := 5 if closema>= sqzma and closema<=0 and dir == -1 madridvariable := -5 if closema<= sqzma and closema>=0 and dir == -1 madridvariable := 5 if closema<= sqzma and closema>=0 and dir == 1 madridvariable := -5 currentextra = extra[0] rankedextra = 1 if tradabilitybar == "On" for i = 1 to 60 if extra[i] > currentextra rankedextra := rankedextra + 1 percentileextra = (((rankedextra - 1) * 100) / 60) percentiletradabilityy = (macroquality * 8) + (percentile * 4) + (microquality * 2) / 14 tradabilitybarn = ((percentilemacro * 5) + (percentile * 3) + (percentilemicro * 2)) / 10 currenttradabilitybarn = tradabilitybarn[0] rankedtradabilitybarn = 1 for i = 1 to 1000 if tradabilitybarn[i] > currenttradabilitybarn rankedtradabilitybarn := rankedtradabilitybarn + 1 percentiletradabilitybarn = ((rankedtradabilitybarn - 1) * 100) / 1000 yellowthing = (tradabilitybarn) + ((mfivariable + squeezevariable + madridvariable) / 3) yellowcolor = color.rgb(255, 235, 59, 60) if yellowthing[1] > yellowthing yellowcolor := color.rgb(59, 59, 255, 60) stoploss = (dir == 1 ? longStop : shortStop) [macd, signal, histob] = request.security(syminfo.tickerid, '240', ta.macd(close, 12, 26, 9)) bigtime = '' mediumtime = '' smalltime = '' if histob > 0 bigtime := '⬆' if histob < 0 bigtime := '⬇' [macdm, signalm, histom] = ta.macd(close, 12, 26, 9) if histom > 0 mediumtime := '⬆' if histom < 0 mediumtime := '⬇' [macds, signals, histos] = request.security(syminfo.tickerid, '15', ta.macd(close, 12, 26, 9)) if histos > 0 smalltime := '⬆' if histos < 0 smalltime := '⬇' fifteen_minute_MFI = request.security(syminfo.tickerid, '15', ta.mfi(hlc3, 14)) one_hour_MFI = request.security(syminfo.tickerid, '240', ta.mfi(hlc3, 14)) if fifteen_minute_MFI > 80 mediumtime := '⬇' if fifteen_minute_MFI < 20 mediumtime := '⬆' if one_hour_MFI > 80 bigtime := '⬇' if one_hour_MFI < 20 bigtime := '⬆' defaultcolor = color.rgb(255, 255, 255, 100) barinndercolor = color.gray baroutercolor = color.white tradenowcolor = color.rgb(120, 123, 134, 90) if ha_diff60 == 2 and dir == 1 and williamsalligator == "Williams Alligator is Bullish ↑" tradenowcolor := color.rgb(20, 255, 48, 75) if ha_diff60 == 1 and dir == -1 and williamsalligator == "Williams Alligator is Bearish ↓" tradenowcolor := color.rgb(255, 20, 20, 75) if showdirection == false tradenowcolor := color.rgb(146, 146, 146, 75) going = color.rgb(120, 123, 134, 70) if ha_diff15 == 1 going := color.rgb(255, 82, 82, 70) if ha_diff15 == 2 going := color.rgb(76, 175, 79, 70) going15 = color.rgb(120, 123, 134, 70) if ha_diff15 == 1 going15 := color.rgb(255, 82, 82, 70) if ha_diff15 == 2 going15 := color.rgb(76, 175, 79, 70) if showdirection == false going := color.rgb(76, 175, 79, 100) going15 := color.rgb(76, 175, 79, 100) hii = 6 whyy = 10 var stop = table.new(position.middle_center,51, 51, border_width = 0, border_color = color.rgb(255, 255, 255, 100), frame_color = color.rgb(255, 255, 255, 100), frame_width = 2) if overlay == false table.set_position(stop, position.top_center) if tradabilitybar == "On" and overlay == true for i = 1 to 29 table.cell(stop, 2, i, '', bgcolor=color.rgb(55, 55, 56, 100), text_color = color.gray, height=hii, width=whyy) table.cell(stop, 2, 30, 'Tradability Score = '+ str.tostring(yellowthing, '#') + ' % - Stop Loss: ' + str.tostring(stoploss) + ' - ' + williamsalligator, bgcolor=tradenowcolor, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 1, 30, ' ', bgcolor=going, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 3, 30, ' ', bgcolor=going15, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) if tradabilitybar == "On" and overlay == false hii := 9 table.cell(stop, 2, 30, 'Tradability Score = '+ str.tostring(yellowthing, '#') + ' % - Stop Loss: ' + str.tostring(stoploss), bgcolor=tradenowcolor, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 1, 30, ' ', bgcolor=going, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 3, 30, ' ', bgcolor=going15, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) fgtimeframe = '45' MACDTRADEBUY = smalltime == '⬆' and bigtime == '⬆' and mediumtime == '⬆' MACDTRADESELL = smalltime == '⬇' and bigtime == '⬇' and mediumtime == '⬇' fourhourHeikinAshibuy = ha_diff240 == 2 fourhourHeikinAshisell = ha_diff240 == 1 WilliamsAlligatorBuy = williamsalligator == "Williams Alligator is Bullish ↑" WilliamsAlligatorSell = williamsalligator == "Williams Alligator is Bearish ↓" ChandelierBuy = dir == 1 ChandelierSell = dir == -1 onehourHeikinAshiBuy = ha_diff60 == 2 onehourHeikinAshiSell = ha_diff60 == 1 MFIbuy = ta.mfi(close, 14)[2] <= 30 MFIsell = ta.mfi(close, 14)[2] >= 70 shortHeikinAshibuy = ha_diff15 == 2 shortHeikinAshisell = ha_diff15 == 1 shortMFIbuy = fifteen_minute_MFI < 30 shortMFIsell = fifteen_minute_MFI > 70 shortMACDbuy = histos > 0 shortMACDsell = histos < 0 shortpivotbuy = request.security(syminfo.tickerid, '15', ta.pivotlow(4, 2)) shortpivotsell = request.security(syminfo.tickerid, '15', ta.pivothigh(4, 2)) shortsarbuy = request.security(syminfo.tickerid, '15', ta.sar(0.02, 0.02,0.2)) < close shortsarsell = request.security(syminfo.tickerid, '15', ta.sar(0.02, 0.02,0.2)) > close normalHeikinAshibuy = ha_diff60 == 2 normalHeikinAshisell = ha_diff60 == 1 normalMFIbuy = ta.mfi(close, 14) < 30 normalMFIsell = ta.mfi(close, 14) > 70 normalMACDbuy = histom > 0 normalMACDsell = histom < 0 normalpivotbuy = ta.pivotlow(4, 2) or ta.pivotlow(4, 3) normalpivotsell = ta.pivothigh(4, 2) or ta.pivothigh(4, 3) normalsarbuy = ta.sar(0.02, 0.02,0.2) < close normalsarsell = ta.sar(0.02, 0.02,0.2) > close longHeikinAshibuy = ha_diff240 == 2 longHeikinAshisell = ha_diff240 == 1 longMFIbuy = one_hour_MFI < 30 longMFIsell = one_hour_MFI > 70 longMACDbuy = histob > 0 longMACDsell = histob < 0 longpivotbuy = request.security(syminfo.tickerid, '240', ta.pivotlow(4, 2)) or request.security(syminfo.tickerid, '240', ta.pivotlow(4, 3)) longpivotsell = request.security(syminfo.tickerid, '240', ta.pivothigh(4, 2)) or request.security(syminfo.tickerid, '240', ta.pivothigh(4, 3)) longsarbuy = request.security(syminfo.tickerid, '240', ta.sar(0.02, 0.02,0.2)) < close longsarsell = request.security(syminfo.tickerid, '240', ta.sar(0.02, 0.02,0.2)) > close shortbuyarea = 0 normalbuyarea = 0 longbuyarea = 0 shortsellarea = 0 normalsellarea = 0 longsellarea = 0 for i = 0 to areanumber if shortHeikinAshibuy[i] shortbuyarea += 1 if shortMFIbuy[i] shortbuyarea += 1 if shortMACDbuy[i] shortbuyarea += 1 if shortpivotbuy[i] shortbuyarea += 1 if shortsarbuy[i] shortbuyarea += 1 if shortHeikinAshisell[i] shortsellarea += 1 if shortMFIsell[i] shortsellarea += 1 if shortMACDsell[i] shortsellarea += 1 if shortpivotsell[i] shortsellarea += 1 if shortsarsell[i] shortsellarea += 1 if normalHeikinAshibuy[i] normalbuyarea += 1 if normalMFIbuy[i] normalbuyarea += 1 if normalMACDbuy[i] normalbuyarea += 1 if normalpivotbuy[i] normalbuyarea += 1 if normalsarbuy[i] normalbuyarea += 1 if normalHeikinAshisell[i] normalsellarea += 1 if normalMFIsell[i] normalsellarea += 1 if normalMACDsell[i] normalsellarea += 1 if normalpivotsell[i] normalsellarea += 1 if normalsarsell[i] normalsellarea += 1 if longHeikinAshibuy[i] longbuyarea += 1 if longMFIbuy[i] longbuyarea += 1 if longMACDbuy[i] longbuyarea += 1 if longpivotbuy[i] longbuyarea += 1 if longsarbuy[i] longbuyarea += 1 if longHeikinAshisell[i] longsellarea += 1 if longMFIsell[i] longsellarea += 1 if longMACDsell[i] longsellarea += 1 if longpivotsell[i] longsellarea += 1 if longsarsell[i] longsellarea += 1 shortrendarea = 0 shortrendareacolor = color.gray if shortbuyarea > shortsellarea shortrendarea := (shortbuyarea / (shortbuyarea + shortsellarea)) * 100 shortrendareacolor := color.green if shortsellarea > shortbuyarea shortrendarea := (shortsellarea / (shortbuyarea + shortsellarea)) * 100 shortrendareacolor := color.red shortcolor = color.rgb(120, 123, 134, 70) if shortbuyarea / (shortbuyarea + shortsellarea) > 0.6 shortcolor := color.rgb(76, 175, 79, 70) if shortsellarea / (shortbuyarea + shortsellarea) > 0.6 shortcolor := color.rgb(175, 76, 76, 70) line1 = hline(15, '15', color.rgb(255, 255, 255, 100)) line2 = hline(11, '11', color.rgb(255, 255, 255, 100)) fill(line1, line2, color = shortcolor) normalrendarea = 0 normalrendareacolor = color.gray if normalbuyarea > normalsellarea normalrendarea := (normalbuyarea / (normalbuyarea + normalsellarea)) * 100 normalrendareacolor := color.green if normalsellarea > normalbuyarea normalrendarea := (normalsellarea / (normalbuyarea + normalsellarea)) * 100 normalrendareacolor := color.red normalcolor = color.rgb(120, 123, 134, 70) if normalbuyarea / (normalbuyarea + normalsellarea) > 0.6 normalcolor := color.rgb(76, 175, 79, 70) if normalsellarea / (normalbuyarea + normalsellarea) > 0.6 normalcolor := color.rgb(175, 76, 76, 70) line3 = hline(10, '15', color.rgb(255, 255, 255, 100)) line4 = hline(6, '11', color.rgb(255, 255, 255, 100)) fill(line3, line4, color = normalcolor) longcolor = color.rgb(120, 123, 134, 70) if longbuyarea / (longbuyarea + longsellarea) > 0.6 longcolor := color.rgb(76, 175, 79, 70) if longsellarea / (longbuyarea + longsellarea) > 0.6 longcolor := color.rgb(175, 76, 76, 70) longrendarea = 0 longrendareacolor = color.gray if longbuyarea > longsellarea longrendarea := (longbuyarea / (longbuyarea + longsellarea)) * 100 longrendareacolor := color.green if longsellarea > longbuyarea longrendarea := (longsellarea / (longbuyarea + longsellarea)) * 100 longrendareacolor := color.red line5 = hline(5, '15', color.rgb(255, 255, 255, 100)) line6 = hline(1, '11', color.rgb(255, 255, 255, 100)) fill(line5, line6, color = longcolor) plot(15, color = shortHeikinAshibuy ? color.green : color.red, style = plot.style_line, linewidth = 1) plot(14, color = shortMFIbuy ? color.green : na, style = plot.style_cross, linewidth = 1) plot(14, color = shortMFIsell ? color.red : na, style = plot.style_cross, linewidth = 1) plot(13, color = shortMACDbuy ? color.green : na, style = plot.style_stepline_diamond, linewidth = 1) plot(13, color = shortMACDsell ? color.red : na, style = plot.style_stepline_diamond, linewidth = 1) plot(12, color = shortpivotbuy ? color.green : na, style = plot.style_cross, linewidth = 1) plot(12, color = shortpivotsell ? color.red : na, style = plot.style_cross, linewidth = 1) plot(11, color = shortsarbuy ? color.green : na, style = plot.style_line, linewidth = 1) plot(11, color = shortsarsell ? color.red : na, style = plot.style_line, linewidth = 1) plot(10, color = normalHeikinAshibuy ? color.green : color.red, style = plot.style_line, linewidth = 1) plot(9, color = normalMFIbuy ? color.green : na, style = plot.style_cross, linewidth = 1) plot(9, color = normalMFIsell ? color.red : na, style = plot.style_cross, linewidth = 1) plot(8, color = normalMACDbuy ? color.green : na, style = plot.style_stepline_diamond, linewidth = 1) plot(8, color = normalMACDsell ? color.red : na, style = plot.style_stepline_diamond, linewidth = 1) plot(7, color = normalpivotbuy ? color.green : na, style = plot.style_cross, linewidth = 1) plot(7, color = normalpivotsell ? color.red : na, style = plot.style_cross, linewidth = 1) plot(6, color = normalsarbuy ? color.green : na, style = plot.style_line, linewidth = 1) plot(6, color = normalsarsell ? color.red : na, style = plot.style_line, linewidth = 1) plot(5, color = longHeikinAshibuy ? color.green : color.red, style = plot.style_line, linewidth = 1) plot(4, color = longMFIbuy ? color.green : na, style = plot.style_cross, linewidth = 1) plot(4, color = longMFIsell ? color.red : na, style = plot.style_cross, linewidth = 1) plot(3, color = longMACDbuy ? color.green : na, style = plot.style_stepline_diamond, linewidth = 1) plot(3, color = longMACDsell ? color.red : na, style = plot.style_stepline_diamond, linewidth = 1) plot(2, color = longpivotbuy ? color.green : na, style = plot.style_cross, linewidth = 1) plot(2, color = longpivotsell ? color.red : na, style = plot.style_cross, linewidth = 1) plot(1, color = longsarbuy ? color.green : na, style = plot.style_line, linewidth = 1) plot(1, color = longsarsell ? color.red : na, style = plot.style_line, linewidth = 1) plot(-5, color = color.rgb(255, 255, 255, 100)) plot(19, color = color.rgb(255, 255, 255, 100)) newcolor = color.rgb(120, 123, 134, 90) microqualitydirection = ' --- ' qualitydirection = ' --- ' macroqualitydirection = ' --- ' ATRpercentiledirection = ' --- ' trueareadirection = ' --- ' if percentilemicro[arrownumber] < percentilemicro[0] microqualitydirection := '↑' if percentilemicro[arrownumber] > percentilemicro[0] microqualitydirection := '↓' if percentile[arrownumber] < percentile[0] qualitydirection := '↑' if percentile[arrownumber] > percentile[0] qualitydirection := '↓' if percentilemacro[arrownumber] < percentilemacro[0] macroqualitydirection := '↑' if percentilemacro[arrownumber] > percentilemacro[0] macroqualitydirection := '↓' if ATRpercentile[arrownumber] < ATRpercentile[0] ATRpercentiledirection := '↑' if ATRpercentile[arrownumber] > ATRpercentile[0] ATRpercentiledirection := '↓' activetrend = 'Mean Reversion' activetrendcolor = color.gray barinndercolor := color.rgb(120, 123, 134, 50) baroutercolor := color.gray areatrend = 'None' if longbuyarea > longsellarea areatrend := "Bullish" if longbuyarea < longsellarea areatrend := "Bearish" if (microqualitydirection == '↓' or qualitydirection == '↓') and ha_diff60 == 2 activetrend := 'Bullish Potential' activetrendcolor := color.rgb(255, 255, 255) barinndercolor := color.rgb(255, 255, 255, 50) baroutercolor := color.rgb(255, 255, 255) if (microqualitydirection == '↓' and qualitydirection == '↓') and ha_diff60 == 2 and close < ta.sma(close, 200) activetrend := 'Bullish Pre-Active' activetrendcolor := color.rgb(39, 155, 176) barinndercolor := color.rgb(39, 155, 176, 50) baroutercolor := color.rgb(39, 155, 176) if (microqualitydirection == '↓' or qualitydirection == '↓') and ha_diff60 == 2 and close > ta.sma(close, 200) activetrend := 'Bullish Extension' activetrendcolor := color.rgb(127, 181, 129) barinndercolor := color.rgb(127, 181, 129, 50) baroutercolor := color.green if (microqualitydirection == '↓' or qualitydirection == '↓') and ha_diff60 == 1 activetrendcolor := color.rgb(255, 255, 255) barinndercolor := color.rgb(255, 255, 255, 50) baroutercolor := color.rgb(255, 255, 255) if (microqualitydirection == '↓' and qualitydirection == '↓') and ha_diff60 == 1 activetrend := 'Bearish Pre-Active' activetrendcolor := color.purple barinndercolor := color.rgb(155, 39, 176, 50) baroutercolor := color.purple if (microqualitydirection == '↓' or qualitydirection == '↓') and ha_diff60 == 1 and close < ta.sma(close, 200) activetrend := 'Bearish Extension' activetrendcolor := color.rgb(255, 168, 168) barinndercolor := color.rgb(255, 168, 168, 50) baroutercolor := color.red if macroqualitydirection == '↓' and (ha_diff60 == 2) activetrend := 'Bullish Active' activetrendcolor := color.green barinndercolor := color.rgb(76, 175, 79, 50) baroutercolor := color.green if macroqualitydirection == '↓' and (ha_diff60 == 1) activetrend := 'Bearish Active' activetrendcolor := color.red barinndercolor := color.rgb(255, 82, 82, 50) baroutercolor := color.red if microqualitydirection == '↑' and qualitydirection == '↑' activetrend := 'Mean Reversion' activetrendcolor := color.gray barinndercolor := color.rgb(120, 123, 134, 50) baroutercolor := color.gray statusquoshort = "" if ha_diffshort[2] == 2 statusquoshort += 'G' else statusquoshort += 'R' if ha_diffshort[1] == 2 statusquoshort += 'G' else statusquoshort += 'R' if ha_diffshort[0] == 2 statusquoshort += 'G' else statusquoshort += 'R' if testingshort == false statusquoshort := "" statusquonormal = "" if ha_diffnormal[2] == 2 statusquonormal += 'G' else statusquonormal += 'R' if ha_diffnormal[1] == 2 statusquonormal += 'G' else statusquonormal += 'R' if ha_diffnormal[0] == 2 statusquonormal += 'G' else statusquonormal += 'R' if testingnormal== false statusquonormal := "" statusquolong = "" if ha_difflong[2] == 2 statusquolong += 'G' else statusquolong += 'R' if ha_difflong[1] == 2 statusquolong += 'G' else statusquolong += 'R' if ha_difflong[0] == 2 statusquolong += 'G' else statusquolong += 'R' if testinglong == false statusquolong := "" statusquo = statusquoshort + statusquonormal + statusquolong PatternSuccessMicro = 0.0 PatternSuccessNormal = 0.0 PatternSuccessMacro = 0.0 PatternFailMicro = 0.0 PatternFailNormal = 0.0 PatternFailMacro = 0.0 BullishFrequencyMicro = 0.0 BearishFrequencyMicro = 0.0 BullishFrequencyNormal = 0.0 BearishFrequencyNormal = 0.0 BullishFrequencyMacro = 0.0 BearishFrequencyMacro = 0.0 if statusquo == statusquoshort + statusquonormal + statusquolong for i = testingnumberMacro to backtracknumber if statusquo[i] == statusquoshort + statusquonormal + statusquolong if close[i] < close[i - testingnumberMicro] BullishFrequencyMicro += 1 if close[i] > close[i - testingnumberMicro] BearishFrequencyMicro += 1 if close[i] < close[i - testingnumberNormal] BullishFrequencyNormal += 1 if close[i] > close[i - testingnumberNormal] BearishFrequencyNormal += 1 if close[i] < close[i - testingnumberMacro] BullishFrequencyMacro += 1 if close[i] > close[i - testingnumberMacro] BearishFrequencyMacro += 1 textcolorMicro = color.gray textcolorNormal = color.gray textcolorMacro = color.gray if BullishFrequencyMicro > BearishFrequencyMicro PatternSuccessMicro := BullishFrequencyMicro / (BullishFrequencyMicro + BearishFrequencyMicro) textcolorMicro := color.green if BullishFrequencyMicro < BearishFrequencyMicro PatternSuccessMicro := BearishFrequencyMicro / (BullishFrequencyMicro + BearishFrequencyMicro) textcolorMicro := color.red if BullishFrequencyNormal > BearishFrequencyNormal PatternSuccessNormal := BullishFrequencyNormal / (BullishFrequencyNormal + BearishFrequencyNormal) textcolorNormal := color.green if BullishFrequencyNormal < BearishFrequencyNormal PatternSuccessNormal := BearishFrequencyNormal / (BullishFrequencyNormal + BearishFrequencyNormal) textcolorNormal := color.red if BullishFrequencyMacro > BearishFrequencyMacro PatternSuccessMacro := BullishFrequencyMacro / (BullishFrequencyMacro + BearishFrequencyMacro) textcolorMacro := color.green if BullishFrequencyMacro < BearishFrequencyMacro PatternSuccessMacro := BearishFrequencyMacro / (BullishFrequencyMacro + BearishFrequencyMacro) textcolorMacro := color.red FrequencyOfPattern = (BullishFrequencyMicro + BearishFrequencyMicro) FrequencyMicro = 0.0 if BullishFrequencyMicro > BearishFrequencyMicro FrequencyMicro := BullishFrequencyMicro textcolorMicro := color.green else FrequencyMicro := BearishFrequencyMicro textcolorMicro := color.red FrequencyNormal = 0.0 if BullishFrequencyNormal > BearishFrequencyNormal FrequencyNormal := BullishFrequencyNormal textcolorNormal := color.green else FrequencyNormal := BearishFrequencyNormal textcolorNormal := color.red FrequencyMacro = 0.0 if BullishFrequencyMacro > BearishFrequencyMacro FrequencyMacro := BullishFrequencyMacro textcolorMacro := color.green else FrequencyMacro := BearishFrequencyMacro textcolorMacro := color.red percentageMicro = (FrequencyMicro / FrequencyOfPattern) * 100 percentageNormal = (FrequencyNormal / FrequencyOfPattern) * 100 percentageMacro = (FrequencyMacro / FrequencyOfPattern) * 100 consistencymicroScore = ((BullishFrequencyMicro + 0) / (FrequencyOfPattern + (100))) * 100 consistencynormalScore = ((BullishFrequencyNormal + 0) / (FrequencyOfPattern + (100))) * 100 consistencymacroScore = ((BullishFrequencyMacro + 0) / (FrequencyOfPattern + (100))) * 100 needed = 0 buyarea = longbuyarea + normalbuyarea + shortbuyarea sellarea = longsellarea + normalsellarea + shortsellarea currentbuyarea = buyarea[0] rankedbuyarea = 1 for i = 1 to 1000 if buyarea[i] > currentbuyarea rankedbuyarea := rankedbuyarea + 1 percentilebuyarea = ((rankedbuyarea - 1) * 100) / 1000 currentsellarea = sellarea[0] rankedsellarea = 1 for i = 1 to 1000 if sellarea[i] > currentsellarea rankedsellarea := rankedsellarea + 1 percentilesellarea = ((rankedsellarea - 1) * 100) / 1000 patternpercentage = buyarea > sellarea ? percentilesellarea : percentilebuyarea toughtnesscolor1 = defaultcolor toughtnesscolor2 = defaultcolor toughtnesscolor3 = defaultcolor toughtnesscolor4 = defaultcolor toughtnesscolor5 = defaultcolor toughtnesscolor6 = defaultcolor toughtnesscolor7 = defaultcolor toughtnesscolor8 = defaultcolor toughtnesscolor9 = defaultcolor toughtnesscolor10 = defaultcolor toughtnesscolor11 = defaultcolor toughtnesscolor12 = defaultcolor toughtnesscolor13 = defaultcolor toughtnesscolor14 = defaultcolor toughtnesscolor15 = defaultcolor toughtnesscolor16 = defaultcolor toughtnesscolor17 = defaultcolor toughtnesscolor18 = defaultcolor toughtnesscolor19 = defaultcolor toughtnesscolor20 = defaultcolor toughtnesscolor21 = defaultcolor toughtnesscolor22 = defaultcolor toughtnesscolor23 = defaultcolor toughtnesscolor24 = defaultcolor toughtnesscolor25 = defaultcolor toughtnesscolor26 = defaultcolor toughtnesscolor27 = defaultcolor toughtnesscolor28 = defaultcolor toughtnesscolor29 = defaultcolor toughtnesscolor30 = defaultcolor toughtnesscolor31 = defaultcolor toughtnesscolor32 = defaultcolor toughtnesscolor33 = defaultcolor toughtnesscolor34 = defaultcolor toughtnesscolor35 = defaultcolor toughtnesscolor36 = defaultcolor toughtnesscolor37 = defaultcolor toughtnesscolor38 = defaultcolor toughtnesscolor39 = defaultcolor toughtnesscolor40 = defaultcolor toughtnesscolor41 = defaultcolor toughtnesscolor42 = defaultcolor toughtnesscolor43 = defaultcolor toughtnesscolor44 = defaultcolor toughtnesscolor45 = defaultcolor toughtnesscolor46 = defaultcolor toughtnesscolor47 = defaultcolor toughtnesscolor48 = defaultcolor toughtnesscolor49 = defaultcolor toughtnesscolor50 = defaultcolor toughtnesscolor51 = defaultcolor toughtnesscolor52 = defaultcolor toughtnesscolor53 = defaultcolor toughtnesscolor54 = defaultcolor toughtnesscolor55 = defaultcolor toughtnesscolor56 = defaultcolor toughtnesscolor57 = defaultcolor toughtnesscolor58 = defaultcolor toughtnesscolor59 = defaultcolor toughtnesscolor60 = defaultcolor toughtnesscolor61 = defaultcolor toughtnesscolor62 = defaultcolor toughtnesscolor63 = defaultcolor toughtnesscolor64 = defaultcolor toughtnesscolor65 = defaultcolor toughtnesscolor66 = defaultcolor toughtnesscolor67 = defaultcolor toughtnesscolor68 = defaultcolor toughtnesscolor69 = defaultcolor toughtnesscolor70 = defaultcolor toughtnesscolor71 = defaultcolor toughtnesscolor72 = defaultcolor toughtnesscolor73 = defaultcolor toughtnesscolor74 = defaultcolor toughtnesscolor75 = defaultcolor toughtnesscolor76 = defaultcolor toughtnesscolor77 = defaultcolor toughtnesscolor78 = defaultcolor toughtnesscolor79 = defaultcolor toughtnesscolor80 = defaultcolor toughtnesscolor81 = defaultcolor toughtnesscolor82 = defaultcolor toughtnesscolor83 = defaultcolor toughtnesscolor84 = defaultcolor toughtnesscolor85 = defaultcolor toughtnesscolor86 = defaultcolor toughtnesscolor87 = defaultcolor toughtnesscolor88 = defaultcolor toughtnesscolor89 = defaultcolor toughtnesscolor90 = defaultcolor toughtnesscolor91 = defaultcolor toughtnesscolor92 = defaultcolor toughtnesscolor93 = defaultcolor toughtnesscolor94 = defaultcolor toughtnesscolor95 = defaultcolor toughtnesscolor96 = defaultcolor toughtnesscolor97 = defaultcolor toughtnesscolor98 = defaultcolor toughtnesscolor99 = defaultcolor if tradabilitybar == "On" if yellowthing > 0 toughtnesscolor1 := yellowcolor if yellowthing > 1 toughtnesscolor2 := yellowcolor if yellowthing > 2 toughtnesscolor3 := yellowcolor if yellowthing > 3 toughtnesscolor4 := yellowcolor if yellowthing > 4 toughtnesscolor5 := yellowcolor if yellowthing > 5 toughtnesscolor6 := yellowcolor if yellowthing > 6 toughtnesscolor7 := yellowcolor if yellowthing > 7 toughtnesscolor8 := yellowcolor if yellowthing > 8 toughtnesscolor9 := yellowcolor if yellowthing > 9 toughtnesscolor10 := yellowcolor if yellowthing > 10 toughtnesscolor11 := yellowcolor if yellowthing > 11 toughtnesscolor12 := yellowcolor if yellowthing > 12 toughtnesscolor13 := yellowcolor if yellowthing > 13 toughtnesscolor14 := yellowcolor if yellowthing > 14 toughtnesscolor15 := yellowcolor if yellowthing > 15 toughtnesscolor16 := yellowcolor if yellowthing > 16 toughtnesscolor17 := yellowcolor if yellowthing > 17 toughtnesscolor18 := yellowcolor if yellowthing > 18 toughtnesscolor19 := yellowcolor if yellowthing > 19 toughtnesscolor20 := yellowcolor if yellowthing > 20 toughtnesscolor21 := yellowcolor if yellowthing > 21 toughtnesscolor22 := yellowcolor if yellowthing > 22 toughtnesscolor23 := yellowcolor if yellowthing > 23 toughtnesscolor24 := yellowcolor if yellowthing > 24 toughtnesscolor25 := yellowcolor if yellowthing > 25 toughtnesscolor26 := yellowcolor if yellowthing > 26 toughtnesscolor27 := yellowcolor if yellowthing > 27 toughtnesscolor28 := yellowcolor if yellowthing > 28 toughtnesscolor29 := yellowcolor if yellowthing > 29 toughtnesscolor30 := yellowcolor if yellowthing > 30 toughtnesscolor31 := yellowcolor if yellowthing > 31 toughtnesscolor32 := yellowcolor if yellowthing > 32 toughtnesscolor33 := yellowcolor if yellowthing > 33 toughtnesscolor34 := yellowcolor if yellowthing > 34 toughtnesscolor35 := yellowcolor if yellowthing > 35 toughtnesscolor36 := yellowcolor if yellowthing > 36 toughtnesscolor37 := yellowcolor if yellowthing > 37 toughtnesscolor38 := yellowcolor if yellowthing > 38 toughtnesscolor39 := yellowcolor if yellowthing > 39 toughtnesscolor40 := yellowcolor if yellowthing > 40 toughtnesscolor41 := yellowcolor if yellowthing > 41 toughtnesscolor42 := yellowcolor if yellowthing > 42 toughtnesscolor43 := yellowcolor if yellowthing > 43 toughtnesscolor44 := yellowcolor if yellowthing > 44 toughtnesscolor45 := yellowcolor if yellowthing > 45 toughtnesscolor46 := yellowcolor if yellowthing > 46 toughtnesscolor47 := yellowcolor if yellowthing > 47 toughtnesscolor48 := yellowcolor if yellowthing > 48 toughtnesscolor49 := yellowcolor if yellowthing > 49 toughtnesscolor50 := yellowcolor if yellowthing > 50 toughtnesscolor51 := yellowcolor if yellowthing > 51 toughtnesscolor52 := yellowcolor if yellowthing > 52 toughtnesscolor53 := yellowcolor if yellowthing > 53 toughtnesscolor54 := yellowcolor if yellowthing > 54 toughtnesscolor54 := yellowcolor if yellowthing > 54 toughtnesscolor55 := yellowcolor if yellowthing > 55 toughtnesscolor56 := yellowcolor if yellowthing > 56 toughtnesscolor57 := yellowcolor if yellowthing > 57 toughtnesscolor58 := yellowcolor if yellowthing > 58 toughtnesscolor59 := yellowcolor if yellowthing > 59 toughtnesscolor60 := yellowcolor if yellowthing > 60 toughtnesscolor61 := yellowcolor if yellowthing > 61 toughtnesscolor62 := yellowcolor if yellowthing > 62 toughtnesscolor63 := yellowcolor if yellowthing > 63 toughtnesscolor64 := yellowcolor if yellowthing > 64 toughtnesscolor65 := yellowcolor if yellowthing > 65 toughtnesscolor66 := yellowcolor if yellowthing > 66 toughtnesscolor67 := yellowcolor if yellowthing > 67 toughtnesscolor68 := yellowcolor if yellowthing > 68 toughtnesscolor69 := yellowcolor if yellowthing > 69 toughtnesscolor70 := yellowcolor if yellowthing > 70 toughtnesscolor71 := yellowcolor if yellowthing > 71 toughtnesscolor72 := yellowcolor if yellowthing > 72 toughtnesscolor73 := yellowcolor if yellowthing > 73 toughtnesscolor74 := yellowcolor if yellowthing > 74 toughtnesscolor75 := yellowcolor if yellowthing > 75 toughtnesscolor76 := yellowcolor if yellowthing > 76 toughtnesscolor77 := yellowcolor if yellowthing > 77 toughtnesscolor78 := yellowcolor if yellowthing > 78 toughtnesscolor79 := yellowcolor if yellowthing > 79 toughtnesscolor80 := yellowcolor if yellowthing > 80 toughtnesscolor81 := yellowcolor if yellowthing > 81 toughtnesscolor82 := yellowcolor if yellowthing > 82 toughtnesscolor83 := yellowcolor if yellowthing > 83 toughtnesscolor84 := yellowcolor if yellowthing > 84 toughtnesscolor85 := yellowcolor if yellowthing > 85 toughtnesscolor86 := yellowcolor if yellowthing > 86 toughtnesscolor87 := yellowcolor if yellowthing > 87 toughtnesscolor88 := yellowcolor if yellowthing > 88 toughtnesscolor89 := yellowcolor if yellowthing > 89 toughtnesscolor90 := yellowcolor if yellowthing > 90 toughtnesscolor91 := yellowcolor if yellowthing > 91 toughtnesscolor92 := yellowcolor if yellowthing > 92 toughtnesscolor93 := yellowcolor if yellowthing > 93 toughtnesscolor94 := yellowcolor if yellowthing > 94 toughtnesscolor95 := yellowcolor if yellowthing > 95 toughtnesscolor96 := yellowcolor if yellowthing > 96 toughtnesscolor97 := yellowcolor if yellowthing > 97 toughtnesscolor98 := yellowcolor if yellowthing > 98 toughtnesscolor99 := yellowcolor if tradabilitybarn > 0 toughtnesscolor1 := barinndercolor if tradabilitybarn > 1 toughtnesscolor2 := barinndercolor if tradabilitybarn > 2 toughtnesscolor3 := barinndercolor if tradabilitybarn > 3 toughtnesscolor4 := barinndercolor if tradabilitybarn > 4 toughtnesscolor5 := barinndercolor if tradabilitybarn > 5 toughtnesscolor6 := barinndercolor if tradabilitybarn > 6 toughtnesscolor7 := barinndercolor if tradabilitybarn > 7 toughtnesscolor8 := barinndercolor if tradabilitybarn > 8 toughtnesscolor9 := barinndercolor if tradabilitybarn > 9 toughtnesscolor10 := barinndercolor if tradabilitybarn > 10 toughtnesscolor11 := barinndercolor if tradabilitybarn > 11 toughtnesscolor12 := barinndercolor if tradabilitybarn > 12 toughtnesscolor13 := barinndercolor if tradabilitybarn > 13 toughtnesscolor14 := barinndercolor if tradabilitybarn > 14 toughtnesscolor15 := barinndercolor if tradabilitybarn > 15 toughtnesscolor16 := barinndercolor if tradabilitybarn > 16 toughtnesscolor17 := barinndercolor if tradabilitybarn > 17 toughtnesscolor18 := barinndercolor if tradabilitybarn > 18 toughtnesscolor19 := barinndercolor if tradabilitybarn > 19 toughtnesscolor20 := barinndercolor if tradabilitybarn > 20 toughtnesscolor21 := barinndercolor if tradabilitybarn > 21 toughtnesscolor22 := barinndercolor if tradabilitybarn > 22 toughtnesscolor23 := barinndercolor if tradabilitybarn > 23 toughtnesscolor24 := barinndercolor if tradabilitybarn > 24 toughtnesscolor25 := barinndercolor if tradabilitybarn > 25 toughtnesscolor26 := barinndercolor if tradabilitybarn > 26 toughtnesscolor27 := barinndercolor if tradabilitybarn > 27 toughtnesscolor28 := barinndercolor if tradabilitybarn > 28 toughtnesscolor29 := barinndercolor if tradabilitybarn > 29 toughtnesscolor30 := barinndercolor if tradabilitybarn > 30 toughtnesscolor31 := barinndercolor if tradabilitybarn > 31 toughtnesscolor32 := barinndercolor if tradabilitybarn > 32 toughtnesscolor33 := barinndercolor if tradabilitybarn > 33 toughtnesscolor34 := barinndercolor if tradabilitybarn > 34 toughtnesscolor35 := barinndercolor if tradabilitybarn > 35 toughtnesscolor36 := barinndercolor if tradabilitybarn > 36 toughtnesscolor37 := barinndercolor if tradabilitybarn > 37 toughtnesscolor38 := barinndercolor if tradabilitybarn > 38 toughtnesscolor39 := barinndercolor if tradabilitybarn > 39 toughtnesscolor40 := barinndercolor if tradabilitybarn > 40 toughtnesscolor41 := barinndercolor if tradabilitybarn > 41 toughtnesscolor42 := barinndercolor if tradabilitybarn > 42 toughtnesscolor43 := barinndercolor if tradabilitybarn > 43 toughtnesscolor44 := barinndercolor if tradabilitybarn > 44 toughtnesscolor45 := barinndercolor if tradabilitybarn > 45 toughtnesscolor46 := barinndercolor if tradabilitybarn > 46 toughtnesscolor47 := barinndercolor if tradabilitybarn > 47 toughtnesscolor48 := barinndercolor if tradabilitybarn > 48 toughtnesscolor49 := barinndercolor if tradabilitybarn > 49 toughtnesscolor50 := barinndercolor if tradabilitybarn > 50 toughtnesscolor51 := barinndercolor if tradabilitybarn > 51 toughtnesscolor52 := barinndercolor if tradabilitybarn > 52 toughtnesscolor53 := barinndercolor if tradabilitybarn > 53 toughtnesscolor54 := barinndercolor if tradabilitybarn > 54 toughtnesscolor55 := barinndercolor if tradabilitybarn > 55 toughtnesscolor56 := barinndercolor if tradabilitybarn > 56 toughtnesscolor57 := barinndercolor if tradabilitybarn > 57 toughtnesscolor58 := barinndercolor if tradabilitybarn > 58 toughtnesscolor59 := barinndercolor if tradabilitybarn > 59 toughtnesscolor60 := barinndercolor if tradabilitybarn > 60 toughtnesscolor61 := barinndercolor if tradabilitybarn > 61 toughtnesscolor62 := barinndercolor if tradabilitybarn > 62 toughtnesscolor63 := barinndercolor if tradabilitybarn > 63 toughtnesscolor64 := barinndercolor if tradabilitybarn > 64 toughtnesscolor65 := barinndercolor if tradabilitybarn > 65 toughtnesscolor66 := barinndercolor if tradabilitybarn > 66 toughtnesscolor67 := barinndercolor if tradabilitybarn > 67 toughtnesscolor68 := barinndercolor if tradabilitybarn > 68 toughtnesscolor69 := barinndercolor if tradabilitybarn > 69 toughtnesscolor70 := barinndercolor if tradabilitybarn > 70 toughtnesscolor71 := barinndercolor if tradabilitybarn > 71 toughtnesscolor72 := barinndercolor if tradabilitybarn > 72 toughtnesscolor73 := barinndercolor if tradabilitybarn > 73 toughtnesscolor74 := barinndercolor if tradabilitybarn > 74 toughtnesscolor75 := barinndercolor if tradabilitybarn > 75 toughtnesscolor76 := barinndercolor if tradabilitybarn > 76 toughtnesscolor77 := barinndercolor if tradabilitybarn > 77 toughtnesscolor78 := barinndercolor if tradabilitybarn > 78 toughtnesscolor79 := barinndercolor if tradabilitybarn > 79 toughtnesscolor80 := barinndercolor if tradabilitybarn > 80 toughtnesscolor81 := barinndercolor if tradabilitybarn > 81 toughtnesscolor82 := barinndercolor if tradabilitybarn > 82 toughtnesscolor83 := barinndercolor if tradabilitybarn > 83 toughtnesscolor84 := barinndercolor if tradabilitybarn > 84 toughtnesscolor85 := barinndercolor if tradabilitybarn > 85 toughtnesscolor86 := barinndercolor if tradabilitybarn > 86 toughtnesscolor87 := barinndercolor if tradabilitybarn > 87 toughtnesscolor88 := barinndercolor if tradabilitybarn > 88 toughtnesscolor89 := barinndercolor if tradabilitybarn > 89 toughtnesscolor90 := barinndercolor if tradabilitybarn > 90 toughtnesscolor91 := barinndercolor if tradabilitybarn > 91 toughtnesscolor92 := barinndercolor if tradabilitybarn > 92 toughtnesscolor93 := barinndercolor if tradabilitybarn > 93 toughtnesscolor94 := barinndercolor if tradabilitybarn > 94 toughtnesscolor95 := barinndercolor if tradabilitybarn > 95 toughtnesscolor96 := barinndercolor if tradabilitybarn > 96 toughtnesscolor97 := barinndercolor if tradabilitybarn > 97 toughtnesscolor98 := barinndercolor if tradabilitybarn > 98 toughtnesscolor99 := barinndercolor textcolorthing = color.black if yellowthing < 50 textcolorthing := barinndercolor var toughness = table.new(position.bottom_center, 101, 2, border_width = 0, border_color = baroutercolor, frame_color = color.white, frame_width = 2) hi = 9 why = 0.1 locationcolor = color.rgb(0, 0, 0, 100) if tradabilitybar == "On" table.cell(toughness, 20, 0, ' ', bgcolor=toughtnesscolor20, height=hi, width=why) table.cell(toughness, 21, 0, ' ', bgcolor=toughtnesscolor21, height=hi, width=why) table.cell(toughness, 22, 0, ' ', bgcolor=toughtnesscolor22, height=hi, width=why) table.cell(toughness, 22, 0, ' ', bgcolor=toughtnesscolor22, height=hi, width=why) table.cell(toughness, 24, 0, ' ', bgcolor=toughtnesscolor24, height=hi, width=why) table.cell(toughness, 25, 0, ' ', bgcolor=toughtnesscolor25, height=hi, width=why) table.cell(toughness, 26, 0, ' ', bgcolor=toughtnesscolor26, height=hi, width=why) table.cell(toughness, 27, 0, ' ', bgcolor=toughtnesscolor27, height=hi, width=why) table.cell(toughness, 28, 0, ' ', bgcolor=toughtnesscolor28, height=hi, width=why) table.cell(toughness, 29, 0, ' ', bgcolor=toughtnesscolor29, height=hi, width=why) table.cell(toughness, 30, 0, ' ', bgcolor=toughtnesscolor40, height=hi, width=why) table.cell(toughness, 30, 0, ' ', bgcolor=toughtnesscolor30, height=hi, width=why) table.cell(toughness, 31, 0, ' ', bgcolor=toughtnesscolor31, height=hi, width=why) table.cell(toughness, 32, 0, ' ', bgcolor=toughtnesscolor32, height=hi, width=why) table.cell(toughness, 33, 0, ' ', bgcolor=toughtnesscolor33, height=hi, width=why) table.cell(toughness, 34, 0, ' ', bgcolor=toughtnesscolor34, height=hi, width=why) table.cell(toughness, 35, 0, ' ', bgcolor=toughtnesscolor35, height=hi, width=why) table.cell(toughness, 36, 0, ' ', bgcolor=toughtnesscolor36, height=hi, width=why) table.cell(toughness, 37, 0, ' ', bgcolor=toughtnesscolor37, height=hi, width=why) table.cell(toughness, 38, 0, ' ', bgcolor=toughtnesscolor38, height=hi, width=why) table.cell(toughness, 39, 0, ' ', bgcolor=toughtnesscolor39, height=hi, width=why) table.cell(toughness, 40, 0, ' ', bgcolor=toughtnesscolor40, height=hi, width=why) table.cell(toughness, 41, 0, ' ', bgcolor=toughtnesscolor41, height=hi, width=why) table.cell(toughness, 42, 0, ' ', bgcolor=toughtnesscolor42, height=hi, width=why) table.cell(toughness, 43, 0, ' ', bgcolor=toughtnesscolor43, height=hi, width=why) table.cell(toughness, 44, 0, ' ', bgcolor=toughtnesscolor44, height=hi, width=why) table.cell(toughness, 45, 0, ' ', bgcolor=toughtnesscolor45, height=hi, width=why) table.cell(toughness, 46, 0, ' ', bgcolor=toughtnesscolor46, height=hi, width=why) table.cell(toughness, 47, 0, ' ', bgcolor=toughtnesscolor47, height=hi, width=why) table.cell(toughness, 48, 0, ' ', bgcolor=toughtnesscolor48, height=hi, width=why) table.cell(toughness, 49, 0, ' ', bgcolor=toughtnesscolor49, height=hi, width=why) table.cell(toughness, 50, 0, ' ', bgcolor=toughtnesscolor50, height=hi, width=why) table.cell(toughness, 51, 0, ' ', bgcolor=toughtnesscolor51, height=hi, width=why) table.cell(toughness, 52, 0, ' ', bgcolor=toughtnesscolor52, height=hi, width=why) table.cell(toughness, 53, 0, ' ', bgcolor=toughtnesscolor53, height=hi, width=why) table.cell(toughness, 54, 0, ' ', bgcolor=toughtnesscolor54, height=hi, width=why) table.cell(toughness, 55, 0, ' ', bgcolor=toughtnesscolor55, height=hi, width=why) table.cell(toughness, 56, 0, ' ', bgcolor=toughtnesscolor56, height=hi, width=why) table.cell(toughness, 57, 0, ' ', bgcolor=toughtnesscolor57, height=hi, width=why) table.cell(toughness, 58, 0, ' ', bgcolor=toughtnesscolor58, height=hi, width=why) table.cell(toughness, 59, 0, str.tostring(yellowthing, '#') + ' %', bgcolor=toughtnesscolor59, height=hi, width=why, text_color = color.white) table.cell(toughness, 60, 0, ' ', bgcolor=toughtnesscolor60, height=hi, width=why) table.cell(toughness, 61, 0, ' ', bgcolor=toughtnesscolor61, height=hi, width=why) table.cell(toughness, 62, 0, ' ', bgcolor=toughtnesscolor62, height=hi, width=why) table.cell(toughness, 63, 0, ' ', bgcolor=toughtnesscolor63, height=hi, width=why) table.cell(toughness, 64, 0, ' ', bgcolor=toughtnesscolor64, height=hi, width=why) table.cell(toughness, 65, 0, ' ', bgcolor=toughtnesscolor65, height=hi, width=why) table.cell(toughness, 66, 0, ' ', bgcolor=toughtnesscolor66, height=hi, width=why) table.cell(toughness, 67, 0, ' ', bgcolor=toughtnesscolor67, height=hi, width=why) table.cell(toughness, 68, 0, ' ', bgcolor=toughtnesscolor68, height=hi, width=why) table.cell(toughness, 69, 0, ' ', bgcolor=toughtnesscolor69, height=hi, width=why) table.cell(toughness, 70, 0, ' ', bgcolor=toughtnesscolor70, height=hi, width=why) table.cell(toughness, 71, 0, ' ', bgcolor=toughtnesscolor71, height=hi, width=why) table.cell(toughness, 72, 0, ' ', bgcolor=toughtnesscolor72, height=hi, width=why) table.cell(toughness, 73, 0, ' ', bgcolor=toughtnesscolor73, height=hi, width=why) table.cell(toughness, 74, 0, ' ', bgcolor=toughtnesscolor74, height=hi, width=why) table.cell(toughness, 75, 0, ' ', bgcolor=toughtnesscolor75, height=hi, width=why) table.cell(toughness, 76, 0, ' ', bgcolor=toughtnesscolor76, height=hi, width=why) table.cell(toughness, 77, 0, ' ', bgcolor=toughtnesscolor77, height=hi, width=why) table.cell(toughness, 78, 0, ' ', bgcolor=toughtnesscolor78, height=hi, width=why) table.cell(toughness, 79, 0, ' ', bgcolor=toughtnesscolor79, height=hi, width=why) table.cell(toughness, 80, 0, ' ', bgcolor=toughtnesscolor80, height=hi, width=why) table.cell(toughness, 81, 0, ' ', bgcolor=toughtnesscolor81, height=hi, width=why) table.cell(toughness, 82, 0, ' ', bgcolor=toughtnesscolor82, height=hi, width=why) table.cell(toughness, 83, 0, ' ', bgcolor=toughtnesscolor83, height=hi, width=why) table.cell(toughness, 84, 0, ' ', bgcolor=toughtnesscolor84, height=hi, width=why) table.cell(toughness, 85, 0, ' ', bgcolor=toughtnesscolor85, height=hi, width=why) table.cell(toughness, 86, 0, ' ', bgcolor=toughtnesscolor86, height=hi, width=why) table.cell(toughness, 87, 0, ' ', bgcolor=toughtnesscolor87, height=hi, width=why) table.cell(toughness, 89, 0, ' ', bgcolor=toughtnesscolor89, height=hi, width=why) table.cell(toughness, 90, 0, ' ', bgcolor=toughtnesscolor90, height=hi, width=why) table.cell(toughness, 91, 0, ' ', bgcolor=toughtnesscolor91, height=hi, width=why) table.cell(toughness, 92, 0, ' ', bgcolor=toughtnesscolor92, height=hi, width=why) table.cell(toughness, 93, 0, ' ', bgcolor=toughtnesscolor93, height=hi, width=why) table.cell(toughness, 94, 0, ' ', bgcolor=toughtnesscolor94, height=hi, width=why) table.cell(toughness, 95, 0, ' ', bgcolor=toughtnesscolor95, height=hi, width=why) table.cell(toughness, 96, 0, ' ', bgcolor=toughtnesscolor96, height=hi, width=why) table.cell(toughness, 97, 0, ' ', bgcolor=toughtnesscolor97, height=hi, width=why) table.cell(toughness, 98, 0, ' ', bgcolor=toughtnesscolor98, height=hi, width=why) table.cell(toughness, 99, 0, ' ', bgcolor=toughtnesscolor99, height=hi, width=why) table.merge_cells(toughness, 59, 0, 61, 0) table.set_frame_color(toughness, baroutercolor) patterntrendcolor1 = defaultcolor patterntrendcolor2 = defaultcolor patterntrendcolor3 = defaultcolor patterntrendcolor4 = defaultcolor patterntrendcolor5 = defaultcolor patterntrendcolor6 = defaultcolor patterntrendcolor7 = defaultcolor patterntrendcolor8 = defaultcolor patterntrendcolor9 = defaultcolor patterntrendcolor10 = defaultcolor patterntrendcolor11 = defaultcolor patterntrendcolor12 = defaultcolor patterntrendcolor13 = defaultcolor patterntrendcolor14 = defaultcolor patterntrendcolor15 = defaultcolor patterntrendcolor16 = defaultcolor patterntrendcolor17 = defaultcolor patterntrendcolor18 = defaultcolor patterntrendcolor19 = defaultcolor patterntrendcolor20 = defaultcolor patterntrendcolor21 = defaultcolor patterntrendcolor22 = defaultcolor patterntrendcolor23 = defaultcolor patterntrendcolor24 = defaultcolor patterntrendcolor25 = defaultcolor patterntrendcolor26 = defaultcolor patterntrendcolor27 = defaultcolor patterntrendcolor28 = defaultcolor patterntrendcolor29 = defaultcolor patterntrendcolor30 = defaultcolor patterntrendcolor31 = defaultcolor patterntrendcolor32 = defaultcolor patterntrendcolor33 = defaultcolor patterntrendcolor34 = defaultcolor patterntrendcolor35 = defaultcolor patterntrendcolor36 = defaultcolor patterntrendcolor37 = defaultcolor patterntrendcolor38 = defaultcolor patterntrendcolor39 = defaultcolor patterntrendcolor40 = defaultcolor patterntrendcolor41 = defaultcolor patterntrendcolor42 = defaultcolor patterntrendcolor43 = defaultcolor patterntrendcolor44 = defaultcolor patterntrendcolor45 = defaultcolor patterntrendcolor46 = defaultcolor patterntrendcolor47 = defaultcolor patterntrendcolor48 = defaultcolor patterntrendcolor49 = defaultcolor patterntrendcolor50 = defaultcolor patterntrendcolor51 = defaultcolor patterntrendcolor52 = defaultcolor patterntrendcolor53 = defaultcolor patterntrendcolor54 = defaultcolor patterntrendcolor55 = defaultcolor patterntrendcolor56 = defaultcolor patterntrendcolor57 = defaultcolor patterntrendcolor58 = defaultcolor patterntrendcolor59 = defaultcolor patterntrendcolor60 = defaultcolor patterntrendcolor61 = defaultcolor patterntrendcolor62 = defaultcolor patterntrendcolor63 = defaultcolor patterntrendcolor64 = defaultcolor patterntrendcolor65 = defaultcolor patterntrendcolor66 = defaultcolor patterntrendcolor67 = defaultcolor patterntrendcolor68 = defaultcolor patterntrendcolor69 = defaultcolor patterntrendcolor70 = defaultcolor patterntrendcolor71 = defaultcolor patterntrendcolor72 = defaultcolor patterntrendcolor73 = defaultcolor patterntrendcolor74 = defaultcolor patterntrendcolor75 = defaultcolor patterntrendcolor76 = defaultcolor patterntrendcolor77 = defaultcolor patterntrendcolor78 = defaultcolor patterntrendcolor79 = defaultcolor patterntrendcolor80 = defaultcolor patterntrendcolor81 = defaultcolor patterntrendcolor82 = defaultcolor patterntrendcolor83 = defaultcolor patterntrendcolor84 = defaultcolor patterntrendcolor85 = defaultcolor patterntrendcolor86 = defaultcolor patterntrendcolor87 = defaultcolor patterntrendcolor88 = defaultcolor patterntrendcolor89 = defaultcolor patterntrendcolor90 = defaultcolor patterntrendcolor91 = defaultcolor patterntrendcolor92 = defaultcolor patterntrendcolor93 = defaultcolor patterntrendcolor94 = defaultcolor patterntrendcolor95 = defaultcolor patterntrendcolor96 = defaultcolor patterntrendcolor97 = defaultcolor patterntrendcolor98 = defaultcolor patterntrendcolor99 = defaultcolor barinndercolor2 = color.gray baroutercolor2 = color.gray if buyarea >= sellarea barinndercolor2 := color.rgb(76, 175, 79, 50) baroutercolor2:= color.green if buyarea < sellarea barinndercolor2 := color.rgb(255, 82, 82, 50) baroutercolor2:= color.red if patternpercentage > 0 patterntrendcolor1 := barinndercolor2 if patternpercentage > 1 patterntrendcolor2 := barinndercolor2 if patternpercentage > 2 patterntrendcolor3 := barinndercolor2 if patternpercentage > 3 patterntrendcolor4 := barinndercolor2 if patternpercentage > 4 patterntrendcolor5 := barinndercolor2 if patternpercentage > 5 patterntrendcolor6 := barinndercolor2 if patternpercentage > 6 patterntrendcolor7 := barinndercolor2 if patternpercentage > 7 patterntrendcolor8 := barinndercolor2 if patternpercentage > 8 patterntrendcolor9 := barinndercolor2 if patternpercentage > 9 patterntrendcolor10 := barinndercolor2 if patternpercentage > 10 patterntrendcolor11 := barinndercolor2 if patternpercentage > 11 patterntrendcolor12 := barinndercolor2 if patternpercentage > 12 patterntrendcolor13 := barinndercolor2 if patternpercentage > 13 patterntrendcolor14 := barinndercolor2 if patternpercentage > 14 patterntrendcolor15 := barinndercolor2 if patternpercentage > 15 patterntrendcolor16 := barinndercolor2 if patternpercentage > 16 patterntrendcolor17 := barinndercolor2 if patternpercentage > 17 patterntrendcolor18 := barinndercolor2 if patternpercentage > 18 patterntrendcolor19 := barinndercolor2 if patternpercentage > 19 patterntrendcolor20 := barinndercolor2 if patternpercentage > 20 patterntrendcolor21 := barinndercolor2 if patternpercentage > 21 patterntrendcolor22 := barinndercolor2 if patternpercentage > 22 patterntrendcolor23 := barinndercolor2 if patternpercentage > 23 patterntrendcolor24 := barinndercolor2 if patternpercentage > 24 patterntrendcolor25 := barinndercolor2 if patternpercentage > 25 patterntrendcolor26 := barinndercolor2 if patternpercentage > 26 patterntrendcolor27 := barinndercolor2 if patternpercentage > 27 patterntrendcolor28 := barinndercolor2 if patternpercentage > 28 patterntrendcolor29 := barinndercolor2 if patternpercentage > 29 patterntrendcolor30 := barinndercolor2 if patternpercentage > 30 patterntrendcolor31 := barinndercolor2 if patternpercentage > 31 patterntrendcolor32 := barinndercolor2 if patternpercentage > 32 patterntrendcolor33 := barinndercolor2 if patternpercentage > 33 patterntrendcolor34 := barinndercolor2 if patternpercentage > 34 patterntrendcolor35 := barinndercolor2 if patternpercentage > 35 patterntrendcolor36 := barinndercolor2 if patternpercentage > 36 patterntrendcolor37 := barinndercolor2 if patternpercentage > 37 patterntrendcolor38 := barinndercolor2 if patternpercentage > 38 patterntrendcolor39 := barinndercolor2 if patternpercentage > 39 patterntrendcolor40 := barinndercolor2 if patternpercentage > 40 patterntrendcolor41 := barinndercolor2 if patternpercentage > 41 patterntrendcolor42 := barinndercolor2 if patternpercentage > 42 patterntrendcolor43 := barinndercolor2 if patternpercentage > 43 patterntrendcolor44 := barinndercolor2 if patternpercentage > 44 patterntrendcolor45 := barinndercolor2 if patternpercentage > 45 patterntrendcolor46 := barinndercolor2 if patternpercentage > 46 patterntrendcolor47 := barinndercolor2 if patternpercentage > 47 patterntrendcolor48 := barinndercolor2 if patternpercentage > 48 patterntrendcolor49 := barinndercolor2 if patternpercentage > 49 patterntrendcolor50 := barinndercolor2 if patternpercentage > 50 patterntrendcolor51 := barinndercolor2 if patternpercentage > 51 patterntrendcolor52 := barinndercolor2 if patternpercentage > 52 patterntrendcolor53 := barinndercolor2 if patternpercentage > 53 patterntrendcolor54 := barinndercolor2 if patternpercentage > 54 patterntrendcolor55 := barinndercolor2 if patternpercentage > 55 patterntrendcolor56 := barinndercolor2 if patternpercentage > 56 patterntrendcolor57 := barinndercolor2 if patternpercentage > 57 patterntrendcolor58 := barinndercolor2 if patternpercentage > 58 patterntrendcolor59 := barinndercolor2 if patternpercentage > 59 patterntrendcolor60 := barinndercolor2 if patternpercentage > 60 patterntrendcolor61 := barinndercolor2 if patternpercentage > 61 patterntrendcolor62 := barinndercolor2 if patternpercentage > 62 patterntrendcolor63 := barinndercolor2 if patternpercentage > 63 patterntrendcolor64 := barinndercolor2 if patternpercentage > 64 patterntrendcolor65 := barinndercolor2 if patternpercentage > 65 patterntrendcolor66 := barinndercolor2 if patternpercentage > 66 patterntrendcolor67 := barinndercolor2 if patternpercentage > 67 patterntrendcolor68 := barinndercolor2 if patternpercentage > 68 patterntrendcolor69 := barinndercolor2 if patternpercentage > 69 patterntrendcolor70 := barinndercolor2 if patternpercentage > 70 patterntrendcolor71 := barinndercolor2 if patternpercentage > 71 patterntrendcolor72 := barinndercolor2 if patternpercentage > 72 patterntrendcolor73 := barinndercolor2 if patternpercentage > 73 patterntrendcolor74 := barinndercolor2 if patternpercentage > 74 patterntrendcolor75 := barinndercolor2 if patternpercentage > 75 patterntrendcolor76 := barinndercolor2 if patternpercentage > 76 patterntrendcolor77 := barinndercolor2 if patternpercentage > 77 patterntrendcolor78 := barinndercolor2 if patternpercentage > 78 patterntrendcolor79 := barinndercolor2 if patternpercentage > 79 patterntrendcolor80 := barinndercolor2 if patternpercentage > 80 patterntrendcolor81 := barinndercolor2 if patternpercentage > 81 patterntrendcolor82 := barinndercolor2 if patternpercentage > 82 patterntrendcolor83 := barinndercolor2 if patternpercentage > 83 patterntrendcolor84 := barinndercolor2 if patternpercentage > 84 patterntrendcolor85 := barinndercolor2 if patternpercentage > 85 patterntrendcolor86 := barinndercolor2 if patternpercentage > 86 patterntrendcolor87 := barinndercolor2 if patternpercentage > 87 patterntrendcolor88 := barinndercolor2 if patternpercentage > 88 patterntrendcolor89 := barinndercolor2 if patternpercentage > 89 patterntrendcolor90 := barinndercolor2 if patternpercentage > 90 patterntrendcolor91 := barinndercolor2 if patternpercentage > 91 patterntrendcolor92 := barinndercolor2 if patternpercentage > 92 patterntrendcolor93 := barinndercolor2 if patternpercentage > 93 patterntrendcolor94 := barinndercolor2 if patternpercentage > 94 patterntrendcolor95 := barinndercolor2 if patternpercentage > 95 patterntrendcolor96 := barinndercolor2 if patternpercentage > 96 patterntrendcolor97 := barinndercolor2 if patternpercentage > 97 patterntrendcolor98 := barinndercolor2 if patternpercentage > 98 patterntrendcolor99 := barinndercolor2 var patterntrend = table.new(position.middle_center, 101, 21, border_width = 0, border_color = baroutercolor, frame_color = color.white, frame_width = 2) if tradabilitybar == "On" for i = 0 to 7 table.cell(patterntrend, 20, i, ' ', bgcolor=color.rgb(255, 255, 255, 100), height=hi, width=why) table.cell(patterntrend, 20, 14, ' ', bgcolor=patterntrendcolor20, height=hi, width=why) table.cell(patterntrend, 21, 14, ' ', bgcolor=patterntrendcolor21, height=hi, width=why) table.cell(patterntrend, 22, 14, ' ', bgcolor=patterntrendcolor22, height=hi, width=why) table.cell(patterntrend, 23, 14, ' ', bgcolor=patterntrendcolor23, height=hi, width=why) table.cell(patterntrend, 24, 14, ' ', bgcolor=patterntrendcolor24, height=hi, width=why) table.cell(patterntrend, 25, 14, ' ', bgcolor=patterntrendcolor25, height=hi, width=why) table.cell(patterntrend, 26, 14, ' ', bgcolor=patterntrendcolor26, height=hi, width=why) table.cell(patterntrend, 27, 14, ' ', bgcolor=patterntrendcolor27, height=hi, width=why) table.cell(patterntrend, 28, 14, ' ', bgcolor=patterntrendcolor28, height=hi, width=why) table.cell(patterntrend, 29, 14, ' ', bgcolor=patterntrendcolor29, height=hi, width=why) table.cell(patterntrend, 30, 14, ' ', bgcolor=patterntrendcolor40, height=hi, width=why) table.cell(patterntrend, 30, 14, ' ', bgcolor=patterntrendcolor30, height=hi, width=why) table.cell(patterntrend, 31, 14, ' ', bgcolor=patterntrendcolor31, height=hi, width=why) table.cell(patterntrend, 32, 14, ' ', bgcolor=patterntrendcolor32, height=hi, width=why) table.cell(patterntrend, 33, 14, ' ', bgcolor=patterntrendcolor33, height=hi, width=why) table.cell(patterntrend, 34, 14, ' ', bgcolor=patterntrendcolor34, height=hi, width=why) table.cell(patterntrend, 35, 14, ' ', bgcolor=patterntrendcolor35, height=hi, width=why) table.cell(patterntrend, 36, 14, ' ', bgcolor=patterntrendcolor36, height=hi, width=why) table.cell(patterntrend, 37, 14, ' ', bgcolor=patterntrendcolor37, height=hi, width=why) table.cell(patterntrend, 38, 14, ' ', bgcolor=patterntrendcolor38, height=hi, width=why) table.cell(patterntrend, 39, 14, ' ', bgcolor=patterntrendcolor39, height=hi, width=why) table.cell(patterntrend, 40, 14, ' ', bgcolor=patterntrendcolor40, height=hi, width=why) table.cell(patterntrend, 41, 14, ' ', bgcolor=patterntrendcolor41, height=hi, width=why) table.cell(patterntrend, 42, 14, ' ', bgcolor=patterntrendcolor42, height=hi, width=why) table.cell(patterntrend, 43, 14, ' ', bgcolor=patterntrendcolor43, height=hi, width=why) table.cell(patterntrend, 44, 14, ' ', bgcolor=patterntrendcolor44, height=hi, width=why) table.cell(patterntrend, 45, 14, ' ', bgcolor=patterntrendcolor45, height=hi, width=why) table.cell(patterntrend, 46, 14, ' ', bgcolor=patterntrendcolor46, height=hi, width=why) table.cell(patterntrend, 47, 14, ' ', bgcolor=patterntrendcolor47, height=hi, width=why) table.cell(patterntrend, 48, 14, ' ', bgcolor=patterntrendcolor48, height=hi, width=why) table.cell(patterntrend, 49, 14, ' ', bgcolor=patterntrendcolor49, height=hi, width=why) table.cell(patterntrend, 50, 14, ' ', bgcolor=patterntrendcolor50, height=hi, width=why) table.cell(patterntrend, 51, 14, ' ', bgcolor=patterntrendcolor51, height=hi, width=why) table.cell(patterntrend, 52, 14, ' ', bgcolor=patterntrendcolor52, height=hi, width=why) table.cell(patterntrend, 53, 14, ' ', bgcolor=patterntrendcolor53, height=hi, width=why) table.cell(patterntrend, 54, 14, ' ', bgcolor=patterntrendcolor54, height=hi, width=why) table.cell(patterntrend, 55, 14, ' ', bgcolor=patterntrendcolor55, height=hi, width=why) table.cell(patterntrend, 56, 14, ' ', bgcolor=patterntrendcolor56, height=hi, width=why) table.cell(patterntrend, 57, 14, ' ', bgcolor=patterntrendcolor57, height=hi, width=why) table.cell(patterntrend, 58, 14, ' ', bgcolor=patterntrendcolor58, height=hi, width=why) table.cell(patterntrend, 59, 14, str.tostring(patternpercentage, '#') + ' %', bgcolor=patterntrendcolor59, height=hi, width=why, text_color = color.white) table.cell(patterntrend, 60, 14, ' ', bgcolor=patterntrendcolor60, height=hi, width=why) table.cell(patterntrend, 61, 14, ' ', bgcolor=patterntrendcolor61, height=hi, width=why) table.cell(patterntrend, 62, 14, ' ', bgcolor=patterntrendcolor62, height=hi, width=why) table.cell(patterntrend, 63, 14, ' ', bgcolor=patterntrendcolor63, height=hi, width=why) table.cell(patterntrend, 64, 14, ' ', bgcolor=patterntrendcolor64, height=hi, width=why) table.cell(patterntrend, 65, 14, ' ', bgcolor=patterntrendcolor65, height=hi, width=why) table.cell(patterntrend, 66, 14, ' ', bgcolor=patterntrendcolor66, height=hi, width=why) table.cell(patterntrend, 67, 14, ' ', bgcolor=patterntrendcolor67, height=hi, width=why) table.cell(patterntrend, 68, 14, ' ', bgcolor=patterntrendcolor68, height=hi, width=why) table.cell(patterntrend, 69, 14, ' ', bgcolor=patterntrendcolor69, height=hi, width=why) table.cell(patterntrend, 70, 14, ' ', bgcolor=patterntrendcolor70, height=hi, width=why) table.cell(patterntrend, 71, 14, ' ', bgcolor=patterntrendcolor71, height=hi, width=why) table.cell(patterntrend, 72, 14, ' ', bgcolor=patterntrendcolor72, height=hi, width=why) table.cell(patterntrend, 73, 14, ' ', bgcolor=patterntrendcolor73, height=hi, width=why) table.cell(patterntrend, 74, 14, ' ', bgcolor=patterntrendcolor74, height=hi, width=why) table.cell(patterntrend, 75, 14, ' ', bgcolor=patterntrendcolor75, height=hi, width=why) table.cell(patterntrend, 76, 14, ' ', bgcolor=patterntrendcolor76, height=hi, width=why) table.cell(patterntrend, 77, 14, ' ', bgcolor=patterntrendcolor77, height=hi, width=why) table.cell(patterntrend, 78, 14, ' ', bgcolor=patterntrendcolor78, height=hi, width=why) table.cell(patterntrend, 79, 14, ' ', bgcolor=patterntrendcolor79, height=hi, width=why) table.cell(patterntrend, 80, 14, ' ', bgcolor=patterntrendcolor80, height=hi, width=why) table.cell(patterntrend, 81, 14, ' ', bgcolor=patterntrendcolor81, height=hi, width=why) table.cell(patterntrend, 82, 14, ' ', bgcolor=patterntrendcolor82, height=hi, width=why) table.cell(patterntrend, 83, 14, ' ', bgcolor=patterntrendcolor83, height=hi, width=why) table.cell(patterntrend, 84, 14, ' ', bgcolor=patterntrendcolor84, height=hi, width=why) table.cell(patterntrend, 85, 14, ' ', bgcolor=patterntrendcolor85, height=hi, width=why) table.cell(patterntrend, 86, 14, ' ', bgcolor=patterntrendcolor86, height=hi, width=why) table.cell(patterntrend, 87, 14, ' ', bgcolor=patterntrendcolor87, height=hi, width=why) table.cell(patterntrend, 89, 14, ' ', bgcolor=patterntrendcolor89, height=hi, width=why) table.cell(patterntrend, 90, 14, ' ', bgcolor=patterntrendcolor90, height=hi, width=why) table.cell(patterntrend, 91, 14, ' ', bgcolor=patterntrendcolor91, height=hi, width=why) table.cell(patterntrend, 92, 14, ' ', bgcolor=patterntrendcolor92, height=hi, width=why) table.cell(patterntrend, 93, 14, ' ', bgcolor=patterntrendcolor93, height=hi, width=why) table.cell(patterntrend, 94, 14, ' ', bgcolor=patterntrendcolor94, height=hi, width=why) table.cell(patterntrend, 95, 14, ' ', bgcolor=patterntrendcolor95, height=hi, width=why) table.cell(patterntrend, 96, 14, ' ', bgcolor=patterntrendcolor96, height=hi, width=why) table.cell(patterntrend, 97, 14, ' ', bgcolor=patterntrendcolor97, height=hi, width=why) table.cell(patterntrend, 98, 14, ' ', bgcolor=patterntrendcolor98, height=hi, width=why) table.cell(patterntrend, 99, 14, ' ', bgcolor=patterntrendcolor99, height=hi, width=why) table.merge_cells(patterntrend, 59, 14, 61, 14) table.set_frame_color(patterntrend, color.rgb(255, 255, 255, 100)) barinndercolor1 = color.new(barinndercolor, 80) if useV4 and overlay == false for i = 0 to 8 table.cell(stop, i, 30, '', bgcolor=barinndercolor1, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) for i = 16 to 26 table.cell(stop, i, 30, '', bgcolor=barinndercolor1, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 11, 30, 'Micro Quality: '+ str.tostring(percentilemicro, '#') + ' % ' + microqualitydirection, bgcolor=barinndercolor1, text_color = color.from_gradient(percentilemicro, 0, 100, color.blue, color.yellow), height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 12, 30, 'Quality: '+ str.tostring(percentile, '#') + ' % ' + qualitydirection, bgcolor=barinndercolor1, text_color = color.from_gradient(percentile, 0, 100, color.blue, color.yellow), height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 13, 30, 'Macro Quality: '+ str.tostring(percentilemacro, '#') + ' % ' + macroqualitydirection, bgcolor=barinndercolor1, text_color = color.from_gradient(percentilemacro, 0, 100, color.blue, color.yellow), height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 14, 30, 'Micro Trend Area: '+ str.tostring(shortrendarea, '#') + ' %', bgcolor=barinndercolor1, text_color = shortrendareacolor, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 15, 30, 'Trend Area: '+ str.tostring(normalrendarea, '#') + ' %', bgcolor=barinndercolor1, text_color = normalrendareacolor, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 16, 30, 'Macro Trend Area: '+ str.tostring(longrendarea, '#') + ' %', bgcolor=barinndercolor1, text_color = longrendareacolor, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 17, 30, 'Phase: ' + activetrend, bgcolor=barinndercolor1, text_color = activetrendcolor, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 18, 30, 'Current Pattern Stats', bgcolor=barinndercolor1, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 18, 32, 'Micro Stats: ' + str.tostring(FrequencyMicro) + ' / ' + str.tostring(FrequencyOfPattern) + ' = ' + str.tostring(percentageMicro, '#') + '%', bgcolor=color.rgb(120, 123, 134, 95), text_color = textcolorMicro, height=hii, width=9, text_size = size.tiny) table.cell(stop, 18, 33, 'Normal Stats: ' + str.tostring(FrequencyNormal) + ' / ' + str.tostring(FrequencyOfPattern) + ' = ' + str.tostring(percentageNormal, '#') + '%', bgcolor=color.rgb(120, 123, 134, 95), text_color = textcolorNormal, height=hii, width=9, text_size = size.tiny) table.cell(stop, 18, 34, 'Macro Stats: ' + str.tostring(FrequencyMacro) + ' / ' + str.tostring(FrequencyOfPattern) + ' = ' + str.tostring(percentageMacro, '#') + '%', bgcolor=color.rgb(120, 123, 134, 95), text_color = textcolorMacro, height=hii, width=9, text_size = size.tiny) table.cell(stop, 18, 36, 'Consistancy Scores', bgcolor=barinndercolor1, text_color = color.white, height=hii, width=whyy, text_size = size.tiny) table.cell(stop, 18, 37, 'Micro Score: ' + str.tostring(consistencymicroScore, '#') + '%', bgcolor=color.rgb(120, 123, 134, 95), text_color = textcolorMicro, height=hii, width=9, text_size = size.tiny) table.cell(stop, 18, 38, 'Normal Score: ' + str.tostring(consistencynormalScore, '#') + '%', bgcolor=color.rgb(120, 123, 134, 95), text_color = textcolorNormal, height=hii, width=9, text_size = size.tiny) table.cell(stop, 18, 39, 'Macro Score: ' + str.tostring(consistencymacroScore, '#') + '%', bgcolor=color.rgb(120, 123, 134, 95), text_color = textcolorMacro, height=hii, width=9, text_size = size.tiny) PHASEALERT = -1 > 1 if abovebelow == "Above" PHASEALERT := (alertmewhen == "Pre-Active" and (activetrend == "Bullish Pre-Active" or activetrend == "Bearish Pre-Active")) or (alertmewhen == "Active" and (activetrend == "Bullish Active" or activetrend == "Bearish Active")) or (alertmewhen == "Mean Reversion" and (activetrend == "Mean Reversion")) or alertmewhen == "None" and (patternpercentage >= trendarea) and (yellowthing >= tradabilityvalue) and (percentilemicro >= microqualityalert) and (percentile >= qualityalert) and (percentilemacro >= macroqualityalert) and (shortrendarea >= microtrendalert) and (normalrendarea >= trendalert) and (longrendarea >= macrotrendalert) if abovebelow == "Below" PHASEALERT := (alertmewhen == "Pre-Active" and (activetrend == "Bullish Pre-Active" or activetrend == "Bearish Pre-Active")) or (alertmewhen == "Active" and (activetrend == "Bullish Active" or activetrend == "Bearish Active")) or (alertmewhen == "Mean Reversion" and (activetrend == "Mean Reversion")) or alertmewhen == "None" and (patternpercentage <= trendarea) and (yellowthing <= tradabilityvalue) and (percentilemicro <= microqualityalert) and (percentile <= qualityalert) and (percentilemacro <= macroqualityalert) and (shortrendarea <= microtrendalert) and (normalrendarea <= trendalert) and (longrendarea <= macrotrendalert) PATTERNALERT = -1 > 1 if andor == "AND" PATTERNALERT := (consistencymicroScoreAlert >= consistencymicroScore) and (consistencynormalScoreAlert >= consistencynormalScore) and (consistencymacroScoreAlert >= consistencymacroScore) if andor == "OR" PATTERNALERT := (consistencymicroScoreAlert >= consistencymicroScore) or (consistencynormalScoreAlert >= consistencynormalScore) or (consistencymacroScoreAlert >= consistencymacroScore) alertcondition(PHASEALERT, "Alert Me When", "Alert for {{ticker}}") plot(0, color = activetrendcolor, linewidth = 10, style = plot.style_stepline_diamond)
Goldmine Wealth Builder - DKK/SKK
https://www.tradingview.com/script/zWA6sMnw-Goldmine-Wealth-Builder-DKK-SKK/
Deepak-Patil
https://www.tradingview.com/u/Deepak-Patil/
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/ // © Deepak-Patil //@version=5 //SuperTrend+3EMA Crosses for Goldmine Wealth Builder - DKK/SKK/SKK2 system with Alrt and Signals for Buying on Bottom when Reversal in ETF's/Stocks indicator('Goldmine Wealth Builder', overlay=true) // Super Trend Settings Periods = 10 // default ATR Period Multiplier = 3 //default ATR Multiplier changeATR = true // Default setting for changing ATR Calculation Method src = hl2 // Default setting for source atr2 = ta.sma(ta.tr, Periods) atr = changeATR ? ta.atr(Periods) : atr2 up = src - Multiplier * atr up1 = nz(up[1], up) up := close[1] > up1 ? math.max(up, up1) : up dn = src + Multiplier * atr dn1 = nz(dn[1], dn) dn := close[1] < dn1 ? math.min(dn, dn1) : dn trend = 1 trend := nz(trend[1], trend) trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend // Input for EMA lengths ema1_length = input.int(20, title='EMA 1 Length', group='EMA Settings') ema2_length = input.int(50, title='EMA 2 Length', group='EMA Settings') ema3_length = input.int(200, title='EMA 3 Length', group='EMA Settings') // Show Signals/EMA's/SuperTrend On/Off show_EMA = input(title='Show EMA\'s', defval=true) show_Crossover = input(title='Show EMA Cross', defval=false) show_SuperTrend = input(title='Show SuperTrend', defval=true) show_AlertSignal = input(title='Show DKK/SKK Alert Signals', defval=true) show_SKK = input(title='Show SKK Signals for ETFs/Funds', defval=false) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Calculate EMAs ema1 = ta.ema(close, ema1_length) ema2 = ta.ema(close, ema2_length) ema3 = ta.ema(close, ema3_length) // Calculate RSI rsi = ta.rsi(close, 14) // Check if the instrument is a Stock/ETF/Funds isSelectedStock = (ticker.standard(syminfo.tickerid) == "NSE:INDIGRID") or (ticker.standard(syminfo.tickerid) == "NSE:PGINVIT") or (ticker.standard(syminfo.tickerid) == "NSE:IRBINVIT") // Define the selected stock symbol isStock = syminfo.type == 'stock' and not isSelectedStock isFund = syminfo.type == 'fund' or isSelectedStock isStockOrFund = isStock or isFund // SKK for ETF/Funds condition if show_SKK isStockOrFund := isStock or isFund else isStockOrFund := isStock // Define only Daily timeframe isDaily = timeframe.isdaily ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SuperTrend plot Settings transparency = 90 // Define transparency using color.new() plotSuperTrend = show_SuperTrend ? true : na mPlot = plot(plotSuperTrend ? close : na, title='Plot', style=plot.style_linebr, linewidth=1, display=display.none, editable = false) upPlot = plot(plotSuperTrend ? trend == 1 ? up : na : na, title='Up Trend', style=plot.style_linebr, linewidth=1, color=color.new(color.green, 0)) dnPlot = plot(plotSuperTrend ? trend == 1 ? na : dn : na, title='Down Trend', style=plot.style_linebr, linewidth=1, color=color.new(color.red, 0)) fill(mPlot, upPlot, color=color.new(color.green, transparency), fillgaps=false) fill(mPlot, dnPlot, color=color.new(color.red, transparency), fillgaps=false) changeCond = trend != trend[1] // Plot EMAs on the chart plot(show_EMA ? ema1 : na, title='EMA 1', color=color.new(color.blue, 0), linewidth=1) plot(show_EMA ? ema2 : na, title='EMA 2', color=color.new(color.purple, 0), linewidth=2) plot(show_EMA ? ema3 : na, title='EMA 3', color=color.new(#f23645, 0), linewidth=3) // Plot EMA crossover crossUpCondition = show_Crossover ? isDaily ? isStock ? ta.crossover(ema1, ema2) ? ema1 : na : na : na : na crossDownCondition = show_Crossover ? isDaily ? isStock ? ta.crossunder(ema1, ema2) ? ema1 : na : na : na : na plot(crossUpCondition, title='Cross_Up 1', style=plot.style_cross, color=color.new(color.orange, 0), linewidth=3, display = display.all - display.status_line) plot(crossDownCondition, title='Cross_Down 1', style=plot.style_cross, color=color.new(color.red, 0), linewidth=3, display = display.all - display.status_line) var tbl = table.new(position.bottom_right, 1, 2) if time > timestamp(2023, 12, 12) table.cell(tbl, 0, 0, "@ Deepak Patil", text_color = color.new(#5d606b, 50)) table.cell(tbl, 0, 1, "", text_color = color.new(#5d606b, 50), text_size = size.small) ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DKK System for accumulating ETF's for long-terms // // Condition for a red candle closing below the 200EMA and RSI less than 40 redCandleAlert = isFund and isDaily and close < ema3 and close < open and rsi < 40 // Marking Trigger Candle for DKK plotshape(series=show_AlertSignal and redCandleAlert, title='DKK Buy Signal', location=location.belowbar, color=color.new(color.red, 0), style=shape.triangleup, size=size.small, display = display.all - display.status_line) //DKK end ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SKK System for accumulating Stocks for long-terms conservative investment// // Detecting SuperTrend Zone Transition superTrendRedToGreen = trend == 1 and trend[1] == -1 superTrendGreen = trend == 1 superTrendRed = trend == -1 // SKK system Active condition var bool SKK_activeSignal = true var bool SKK_activeSignal2 = false var bool SKK_activeSignal3 = false SKK_active = SKK_activeSignal and close < open and close < ema3 and superTrendRed if SKK_active SKK_activeSignal := false SKK_activeSignal2 := true // SuperTrend Crossover Rod to green triggerCondition = SKK_activeSignal2 and superTrendRedToGreen if triggerCondition SKK_activeSignal3 := true // Detecting Trigger Candle triggerCandle = SKK_activeSignal3 and isStockOrFund and isDaily and close > open and superTrendGreen // Mark high of Trigger Candle var float triggerHigh = na if triggerCandle triggerHigh := high SKK_activeSignal3 := false // Marking Trigger Candle for SKK plotshape(series=show_AlertSignal and triggerCandle, title='SKK Alert Signal', location=location.belowbar, color=color.new(color.orange, 0), style=shape.triangleup, size=size.small, display = display.all - display.status_line) // Buy Signal Condition buySignal = close > triggerHigh and close > open // SKK Final Buy Signal // Mark high of Trigger Candle to na after Buy Signal true and Mark close of Buy Candle for Entry var float buyClose = na var float buyHigh = na if buySignal triggerHigh := na buyClose := close buyHigh := high // Convert buyClose value closeToHigh = high > buyClose and open <= buyClose and close < buyClose // Calculate the crossover condition crossoverCondition = ta.crossover(close, buyClose) or open > buyClose // Calculate buySignal as per High instead of close closeToHighCondition = high > buyHigh // Check both condition finalBuySignal = if closeToHigh closeToHighCondition else crossoverCondition if finalBuySignal buyClose := na buyHigh := na SKK_activeSignal := true SKK_activeSignal2 := false // Plot Buy Signal plotshape(series=show_AlertSignal and buySignal, title='SKK Buy Signal', location=location.belowbar, color=color.new(color.green, 0), style=shape.triangleup, size=size.small, display = display.all - display.status_line) // SKK end ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // SKK2 System for accumulating Stocks for long-terms aggressive investment// var bool triggerActive = true // Mark Trigger Active var bool SKK2Alert = false // Mark Alert Active // Define trigger candle condition for SKK2 triggerCandleCondition = triggerActive and isStock and isDaily and close < ema2 and rsi < 40 and close < open and close > ema3 SKK2Deactive = close < ema3 if triggerCandleCondition triggerActive := false SKK2Alert := true // Define buy signal condition buySignalCondition = SKK2Alert and rsi > 40 and close > open // Mark high of Buy Signal Candle var float buySignalHigh = na if buySignalCondition buySignalHigh := high // Mark Alert Re-ctive after Buy Signal Complete if buySignalCondition or SKK2Deactive SKK2Alert := false // SKK2 Final Buy Signal SKK2finalBuySignal = high > buySignalHigh if SKK2finalBuySignal or SKK2Deactive buySignalHigh := na triggerActive := true // Plot shapes for the trigger candle condition plotshape(series=show_AlertSignal and triggerCandleCondition, title='SKK2 Alert Signal', location=location.abovebar, color=color.new(color.red, 0), style=shape.triangledown, size=size.small, display = display.all - display.status_line) // Plot shapes for the buy signal condition plotshape(series=show_AlertSignal and buySignalCondition, title='SKK2 Buy Signal', location=location.belowbar, color=color.new(color.purple, 0), style=shape.triangleup, size=size.small, display = display.all - display.status_line) //SKK2 end
Trendinator Lite
https://www.tradingview.com/script/N1b2yE9O-Trendinator-Lite/
marcuskhlim
https://www.tradingview.com/u/marcuskhlim/
23
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/ // ©marcuskhlim //@version=5 indicator(shorttitle="Trendinator Lite", title="Trendinator Lite", overlay=true) var bars_since_started_trending_up = 0 var bars_since_started_trending_down = 0 var bars_since_bb_up_in_no_trending = 0 var bars_since_bb_down_in_no_trending = 0 var started_trending_up = false var started_trending_down = false var stopped_trending = true var got_bb_up_touch = false var got_bb_down_touch = false var float highest_bollinger_up_touch = na var float highest_close = 0 var float lowest_bollinger_down_touch = na var float lowest_close = 0 var color colorForNextCandle = na basis = ta.sma(close, 20) dev = 2.0 * ta.stdev(close, 20) upper = basis + dev lower = basis - dev consider_bar_up = true consider_bar_down = true if started_trending_up x = bar_index y = high txt = str.tostring(bars_since_started_trending_up) if high > highest_bollinger_up_touch bars_since_started_trending_up := 0 highest_bollinger_up_touch := high else bars_since_started_trending_up := bars_since_started_trending_up + 1 if low <= lower or bars_since_started_trending_up >= 20 got_bb_up_touch := false started_trending_up := false started_trending_down := false stopped_trending := true highest_bollinger_up_touch := na lowest_bollinger_down_touch := na if high >= upper consider_bar_up := false if started_trending_down if low < lowest_bollinger_down_touch bars_since_started_trending_down := 0 lowest_bollinger_down_touch := low else bars_since_started_trending_down := bars_since_started_trending_down + 1 if high >= upper or bars_since_started_trending_down >= 20 got_bb_down_touch := false started_trending_down := false started_trending_up := false stopped_trending := true highest_bollinger_up_touch := na lowest_bollinger_down_touch := na if low <= lower consider_bar_down := false if stopped_trending bars_since_bb_up_in_no_trending := bars_since_bb_up_in_no_trending + 1 bars_since_bb_down_in_no_trending := bars_since_bb_down_in_no_trending + 1 if high > highest_bollinger_up_touch and close > highest_close and got_bb_up_touch and low > lower started_trending_up := true stopped_trending := false bars_since_started_trending_up := 0 got_bb_up_touch := false if low < lowest_bollinger_down_touch and close < lowest_close and got_bb_down_touch and high < upper started_trending_down := true stopped_trending := false bars_since_started_trending_down := 0 got_bb_down_touch := false if low <= lower and consider_bar_down if na(lowest_bollinger_down_touch) or low <= lowest_bollinger_down_touch bars_since_bb_down_in_no_trending := 0 lowest_bollinger_down_touch := low if not got_bb_down_touch got_bb_down_touch := true lowest_close := close else if close < lowest_close lowest_close := close if high < upper got_bb_up_touch := false if high >= upper highest_bollinger_up_touch := high else highest_bollinger_up_touch := na if high >= upper and consider_bar_up if na(highest_bollinger_up_touch) or high >= highest_bollinger_up_touch bars_since_bb_up_in_no_trending := 0 highest_bollinger_up_touch := high if not got_bb_up_touch got_bb_up_touch := true highest_close := close else if close > highest_close highest_close := close if low > lower got_bb_down_touch := false if low <= lower lowest_bollinger_down_touch := low else lowest_bollinger_down_touch := na if not na(highest_bollinger_up_touch) and high > highest_bollinger_up_touch highest_bollinger_up_touch := high if not na(lowest_bollinger_down_touch) and low < lowest_bollinger_down_touch lowest_bollinger_down_touch := low if close > highest_close highest_close := close if close < lowest_close lowest_close := close // Colour background backgroundColour = if started_trending_up color.new(color.green, 85) else if started_trending_down color.new(color.red, 85) else if stopped_trending color.new(color.yellow, 85) upper_bb=plot(upper,'upper_bb',offset=0,color=color.rgb(0, 0,255)) lower_bb=plot(lower,'lower_bb',offset=0,color=color.rgb(0, 0,255)) fill(upper_bb, lower_bb, colorForNextCandle) colorForNextCandle := backgroundColour
Choose Symbol, candle and Trend mode
https://www.tradingview.com/script/jTRttdvn/
erdas0
https://www.tradingview.com/u/erdas0/
11
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/ // © erdas0 //@version=5 indicator('Choose Symbol, candle and Trend mode', overlay=false) //Komut ha = input(false, title='Heikin-Ashi mode?') len = input(1) users = input(true, title='Use Current Chart Resolution?') tf = input.timeframe(title='Use Different Timeframe?', defval='') res = users ? timeframe.period : tf sym = input.symbol(defval = 'BINANCE:BTCUSDT',title = "Symbol") symo1 = request.security(sym, res, open) symh1 = request.security(sym, res, high) syml1 = request.security(sym, res, low) symc1 = request.security(sym, res, close) symo = ta.ema(symo1,len) symh = ta.ema(symh1,len) syml = ta.ema(syml1,len) symc = ta.ema(symc1,len) o = ha ? (symo[1]+symc[1])/2 : symo h = ha ? math.max(symh,symo,symc) : symh l = ha ? math.min(syml,symo,symc) : syml c = ha ? (symo+symc+symh+syml)/4 : symc op = request.security(sym, res, o) hp = request.security(sym, res, h) lp = request.security(sym, res, l) cp = request.security(sym, res, c) col = 0.0 col := cp > op and cp > cp[1] ? 1 : cp < op and cp < cp[1] ? -1 : col[1] clr = col == 1 ? color.teal : col == -1 ? color.red : color.yellow // Plots plotcandle(op, hp, lp, cp, color=clr, wickcolor=clr, bordercolor=clr, title='Candle') //Trend fast=input.int(2,"Fast", group="Trend") slow=input.int(10,"Slow") overb=input.int(90,"Over Bought") overs=input.int(10,"Over Sold") size=input.string(size.small,options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge]) ema=ta.ema(ta.rsi(c,fast),slow) cle= ema>ema[1] ? color.lime : ema<ema[1] ? color.red : color.blue buy= ema>ema[1] buyt= overb-ema txtb=str.tostring(buyt,"#.##") txts=str.tostring(ema+overs,"#.##") var label lbl = na label.delete(lbl) if ema>ema[1] lbl := label.new(bar_index,c*0.96, txtb, color=color.lime, style=label.style_label_up,size=size) label.set_text(lbl, "BUY" + "\n" + txtb+"%") else lbl := label.new(bar_index,c*1.06, txts, color=color.red, style=label.style_label_down,size=size) label.set_text(lbl, "SELL" + "\n" + txts+"%") pema=math.max(math.min(ema,1),0.9)*c plot(pema,color=cle,display = display.none)
Quantitative Risk Navigator [kikfraben]
https://www.tradingview.com/script/MDbZHrS4-Quantitative-Risk-Navigator-kikfraben/
kikfraben
https://www.tradingview.com/u/kikfraben/
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/ // © kikfraben // Updated last on Nov 14 2023 // @version = 5 indicator("Quantitative Risk Navigator [kikfraben]", "QRN", false, precision = 2) // Get Base Symbol symbol = input.symbol("BTCUSD", "Base Symbol", group = "General Inputs") src = input.source(close, "Source", group = "General Inputs") base = request.security(symbol, "D", src) // Get Risk Free Rate risk_free_rate = input.float(0, "Risk Free Rate", group = "General Inputs") // Get Lengths length_1 = input(30, "Length 1", group = "Length Inputs", tooltip = "Defines the length for Alpha 1, Beta 1, Correlation 1, Sharpe 1, Sortino 1, Omega 1") length_2 = input(60, "Length 2", group = "Length Inputs", tooltip = "Defines the length for Alpha 2, Beta 2, Correlation 2, Sharpe 2, Sortino 2, Omega 2") length_3 = input(90, "Length 3", group = "Length Inputs", tooltip = "Defines the length for Alpha 3, Beta 3, Correlation 3, Sharpe 3, Sortino 3, Omega 3") // Get Beta beta(src, base, length) => returns = src / src[1] - 1 base_returns = base / base[1] - 1 returns_array = array.new_float(0) base_returns_array = array.new_float(0) for x = 0 to length array.push(returns_array, returns[x]) array.push(base_returns_array, base_returns[x]) array.covariance(returns_array, base_returns_array) / array.variance(base_returns_array) beta_1 = beta(src, base, length_1) beta_2 = beta(src, base, length_2) beta_3 = beta(src, base, length_3) beta_avg = math.avg(beta_1, beta_2, beta_3) // Get Alpha alpha(src, base, length) => returns = src / src[1] - 1 base_returns = base / base[1] - 1 returns_array = array.new_float(0) base_returns_array = array.new_float(0) for x = 0 to length array.push(returns_array, returns[x]) array.push(base_returns_array, base_returns[x]) array.sum(returns_array) - (risk_free_rate + beta(src, base, length) * (array.sum(base_returns_array) - risk_free_rate)) alpha_1 = alpha(src, base, length_1) alpha_2 = alpha(src, base, length_2) alpha_3 = alpha(src, base, length_3) alpha_avg = math.avg(alpha_1, alpha_2, alpha_3) // Get Correlation correlation_1 = ta.correlation(src, base, length_1) correlation_2 = ta.correlation(src, base, length_2) correlation_3 = ta.correlation(src, base, length_3) correlation_avg = math.avg(correlation_1, correlation_2, correlation_3) // Get Omega Ratio omega(src, length) => returns = src / src[1] - 1 negative_returns_array = array.new_float(0) positive_returns_array = array.new_float(0) for x = 0 to length if returns[x] <= 0.0 array.push(negative_returns_array, returns[x]) else array.push(positive_returns_array, returns[x]) postive_returns = array.sum(positive_returns_array) negative_returns = array.sum(negative_returns_array) * (-1) math.round(postive_returns / negative_returns, 2) omega_1 = omega(src, length_1) omega_2 = omega(src, length_2) omega_3 = omega(src, length_3) omega_avg = math.avg(omega_1, omega_2, omega_3) // Get Sharpe Ratio sharpe(src, length) => returns = src / src[1] - 1 returns_array = array.new_float(0) for x = 0 to length array.push(returns_array, returns[x]) standard_deviation = array.stdev(returns_array) mean = array.avg(returns_array) math.round(mean / standard_deviation * math.sqrt(length), 2) sharpe_1 = sharpe(src, length_1) sharpe_2 = sharpe(src, length_2) sharpe_3 = sharpe(src, length_3) sharpe_avg = math.avg(sharpe_1, sharpe_2, sharpe_3) // Get Sortino Ratio sortino(src, length) => returns = src / src[1] - 1 returns_array = array.new_float(0) negative_returns_array = array.new_float(0) for x = 0 to length array.push(returns_array, returns[x]) if returns[x] <= 0.0 array.push(negative_returns_array, returns[x]) standard_deviation_negative_returns = array.stdev(negative_returns_array) mean = array.avg(returns_array) math.round(mean / standard_deviation_negative_returns * math.sqrt(length), 2) sortino_1 = sortino(src, length_1) sortino_2 = sortino(src, length_2) sortino_3 = sortino(src, length_3) sortino_avg = math.avg(sortino_1, sortino_2, sortino_3) // Get Plot Options plot_alpha_avg = input.bool(false, "Alpha AVG", inline = "1", group = "Plot Options") plot_alpha_1 = input.bool(false, "Alpha 1", inline = "1", group = "Plot Options") plot_alpha_2 = input.bool(false, "Alpha 2", inline = "1", group = "Plot Options") plot_alpha_3 = input.bool(false, "Alpha 3", inline = "1", group = "Plot Options") plot_beta_avg = input.bool(false, "Beta AVG", inline = "2", group = "Plot Options") plot_beta_1 = input.bool(false, "Beta 1", inline = "2", group = "Plot Options") plot_beta_2 = input.bool(false, "Beta 2", inline = "2", group = "Plot Options") plot_beta_3 = input.bool(false, "Beta 3", inline = "2", group = "Plot Options") plot_correlation_avg = input.bool(false, "Correl AVG", inline = "3", group = "Plot Options") plot_correlation_1 = input.bool(false, "Correl 1", inline = "3", group = "Plot Options") plot_correlation_2 = input.bool(false, "Correl 2", inline = "3", group = "Plot Options") plot_correlation_3 = input.bool(false, "Correl 3", inline = "3", group = "Plot Options") plot_sharpe_avg = input.bool(false, "Sharpe AVG", inline = "4", group = "Plot Options") plot_sharpe_1 = input.bool(false, "Sharpe 1", inline = "4", group = "Plot Options") plot_sharpe_2 = input.bool(false, "Sharpe 2", inline = "4", group = "Plot Options") plot_sharpe_3 = input.bool(false, "Sharpe 3", inline = "4", group = "Plot Options") plot_sortino_avg = input.bool(false, "Sortino AVG", inline = "5", group = "Plot Options") plot_sortino_1 = input.bool(false, "Sortino 1", inline = "5", group = "Plot Options") plot_sortino_2 = input.bool(false, "Sortino 2", inline = "5", group = "Plot Options") plot_sortino_3 = input.bool(false, "Sortino 3", inline = "5", group = "Plot Options") plot_omega_avg = input.bool(false, "Omega AVG", inline = "6", group = "Plot Options") plot_omega_1 = input.bool(false, "Omega 1", inline = "6", group = "Plot Options") plot_omega_2 = input.bool(false, "Omega 2", inline = "6", group = "Plot Options") plot_omega_3 = input.bool(false, "Omega 3", inline = "6", group = "Plot Options") plot_table = input.bool(true, "Metrics Table", inline = "7", group = "Plot Options") table_y_position = input.string(defval = "middle", title = "Table Position", options = ["top", "middle", "bottom"], inline = "8", group = "Plot Options") table_x_position = input.string(defval = "center", title = "", options = ["left", "center", "right"], inline = "8", group = "Plot Options") // Get Colors up_color = input.color(#3fa8c9, title = "Bullish Color", group = "Color Inputs", inline = "1") down_color = input.color(#c93f3f, title = "Bearish Color", group = "Color Inputs", inline = "1") background_color = color.new(color.white, 95) txt_color = color.white txt_color1 = color.new(color.white, 25) table_color = color.new(color.white, 70) alpha_color = input.color(color.red, "Alpha Color", group = "Color Inputs", inline = "2") beta_color = input.color(color.orange, "Beta Color", group = "Color Inputs", inline = "2") correlation_color = input.color(color.yellow, "Correl Color", group = "Color Inputs", inline = "2") sharpe_color = input.color(color.purple, "Sharpe Color", group = "Color Inputs", inline = "3") sortino_color = input.color(color.blue, "Sortino Color", group = "Color Inputs", inline = "3") omega_color = input.color(color.green, "Omega Color", group = "Color Inputs", inline = "3") // Get Plots plot(plot_alpha_1 ? alpha_1 : na, color = color.new(alpha_color, 60)) plot(plot_alpha_2 ? alpha_2 : na, color = color.new(alpha_color, 40)) plot(plot_alpha_3 ? alpha_3 : na, color = color.new(alpha_color, 20)) plot(plot_alpha_avg ? alpha_avg : na, color = alpha_color) plot(plot_beta_1 ? beta_1 : na, color = color.new(beta_color, 60)) plot(plot_beta_2 ? beta_2 : na, color = color.new(beta_color, 40)) plot(plot_beta_3 ? beta_3 : na, color = color.new(beta_color, 20)) plot(plot_beta_avg ? beta_avg : na, color = beta_color) plot(plot_correlation_1 ? correlation_1 : na, color = color.new(correlation_color, 60)) plot(plot_correlation_2 ? correlation_2 : na, color = color.new(correlation_color, 40)) plot(plot_correlation_3 ? correlation_3 : na, color = color.new(correlation_color, 20)) plot(plot_correlation_avg ? correlation_avg : na, color = correlation_color) plot(plot_sharpe_1 ? sharpe_1 : na, color = color.new(sharpe_color, 60)) plot(plot_sharpe_2 ? sharpe_2 : na, color = color.new(sharpe_color, 40)) plot(plot_sharpe_3 ? sharpe_3 : na, color = color.new(sharpe_color, 20)) plot(plot_sharpe_avg ? sharpe_avg : na, color = sharpe_color) plot(plot_sortino_1 ? sortino_1 : na, color = color.new(sortino_color, 60)) plot(plot_sortino_2 ? sortino_2 : na, color = color.new(sortino_color, 40)) plot(plot_sortino_3 ? sortino_3 : na, color = color.new(sortino_color, 20)) plot(plot_sortino_avg ? sortino_avg : na, color = sortino_color) plot(plot_omega_1 ? omega_1 : na, color = color.new(omega_color, 60)) plot(plot_omega_2 ? omega_2 : na, color = color.new(omega_color, 40)) plot(plot_omega_3 ? omega_3 : na, color = color.new(omega_color, 20)) plot(plot_omega_avg ? omega_avg : na, color = omega_color) // Get Metrics Table if plot_table == true metrics = table.new(table_y_position + "_" + table_x_position, 10, 10, frame_color = table_color, border_color = table_color, frame_width = 2, border_width = 2) table.merge_cells(metrics, 0, 0, 4, 0) table.cell(metrics, 0, 0, "Quantitative Risk Navigator", text_color = color.yellow, bgcolor = background_color) table.cell(metrics, 0, 1, "Metric", text_color = txt_color, bgcolor = background_color) table.cell(metrics, 1, 1, "Length 1", text_color = txt_color, bgcolor = background_color) table.cell(metrics, 2, 1, "Length 2", text_color = txt_color, bgcolor = background_color) table.cell(metrics, 3, 1, "Length 3", text_color = txt_color, bgcolor = background_color) table.cell(metrics, 4, 1, "Average", text_color = txt_color, bgcolor = background_color) table.cell(metrics, 0, 2, "Alpha", text_color = txt_color1, bgcolor = background_color) table.cell(metrics, 0, 3, "Beta", text_color = txt_color1, bgcolor = background_color) table.cell(metrics, 0, 4, "Correlation", text_color = txt_color1, bgcolor = background_color) table.cell(metrics, 0, 5, "Sharpe", text_color = txt_color1, bgcolor = background_color) table.cell(metrics, 0, 6, "Sortino", text_color = txt_color1, bgcolor = background_color) table.cell(metrics, 0, 7, "Omega", text_color = txt_color1, bgcolor = background_color) table.cell(metrics, 1, 2, str.tostring(alpha_1, "#.##"), text_color = txt_color, bgcolor = alpha_1 >= 0 ? (alpha_1 <= 0.25 ? color.new(up_color, 60) : (alpha_1 <= 0.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (alpha_1 >= -0.25 ? color.new(down_color, 60) : (alpha_1 >= -0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 2, 2, str.tostring(alpha_2, "#.##"), text_color = txt_color, bgcolor = alpha_2 >= 0 ? (alpha_2 <= 0.25 ? color.new(up_color, 60) : (alpha_2 <= 0.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (alpha_2 >= -0.25 ? color.new(down_color, 60) : (alpha_2 >= -0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 3, 2, str.tostring(alpha_3, "#.##"), text_color = txt_color, bgcolor = alpha_3 >= 0 ? (alpha_3 <= 0.25 ? color.new(up_color, 60) : (alpha_3 <= 0.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (alpha_3 >= -0.25 ? color.new(down_color, 60) : (alpha_3 >= -0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 4, 2, str.tostring(alpha_avg, "#.##"), text_color = txt_color, bgcolor = alpha_avg >= 0 ? (alpha_avg <= 0.25 ? color.new(up_color, 60) : (alpha_avg <= 0.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (alpha_avg >= -0.25 ? color.new(down_color, 60) : (alpha_avg >= -0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 1, 3, str.tostring(beta_1, "#.##"), text_color = txt_color, bgcolor = beta_1 >= 1 ? (beta_1 <= 1.25 ? color.new(up_color, 60) : (beta_1 <= 1.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (beta_1 >= 0.75 ? color.new(down_color, 60) : (beta_1 >= 0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 2, 3, str.tostring(beta_2, "#.##"), text_color = txt_color, bgcolor = beta_2 >= 1 ? (beta_2 <= 1.25 ? color.new(up_color, 60) : (beta_2 <= 1.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (beta_2 >= 0.75 ? color.new(down_color, 60) : (beta_2 >= 0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 3, 3, str.tostring(beta_3, "#.##"), text_color = txt_color, bgcolor = beta_3 >= 1 ? (beta_3 <= 1.25 ? color.new(up_color, 60) : (beta_3 <= 1.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (beta_3 >= 0.75 ? color.new(down_color, 60) : (beta_3 >= 0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 4, 3, str.tostring(beta_avg, "#.##"), text_color = txt_color, bgcolor = beta_avg >= 1 ? (beta_avg <= 1.25 ? color.new(up_color, 60) : (beta_avg <= 1.50 ? color.new(up_color, 40) : color.new(up_color, 10))) : (beta_avg >= 0.75 ? color.new(down_color, 60) : (beta_avg >= 0.50 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 1, 4, str.tostring(correlation_1, "#.##"), text_color = txt_color, bgcolor = correlation_1 >= 0 ? (correlation_1 <= 0.33 ? color.new(up_color, 60) : (correlation_2 <= 0.66 ? color.new(up_color, 40) : color.new(up_color, 10))) : (correlation_1 >= -0.33 ? color.new(down_color, 60) : (correlation_1 >= -0.66 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 2, 4, str.tostring(correlation_2, "#.##"), text_color = txt_color, bgcolor = correlation_2 >= 0 ? (correlation_2 <= 0.33 ? color.new(up_color, 60) : (correlation_2 <= 0.66 ? color.new(up_color, 40) : color.new(up_color, 10))) : (correlation_2 >= -0.33 ? color.new(down_color, 60) : (correlation_2 >= -0.66 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 3, 4, str.tostring(correlation_3, "#.##"), text_color = txt_color, bgcolor = correlation_3 >= 0 ? (correlation_3 <= 0.33 ? color.new(up_color, 60) : (correlation_3 <= 0.66 ? color.new(up_color, 40) : color.new(up_color, 10))) : (correlation_3 >= -0.33 ? color.new(down_color, 60) : (correlation_3 >= -0.66 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 4, 4, str.tostring(correlation_avg, "#.##"), text_color = txt_color, bgcolor = correlation_avg >= 0 ? (correlation_avg <= 0.33 ? color.new(up_color, 60) : (correlation_avg <= 0.66 ? color.new(up_color, 40) : color.new(up_color, 10))) : (correlation_avg >= -0.33 ? color.new(down_color, 60) : (correlation_avg >= -0.66 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 1, 5, str.tostring(sharpe_1, "#.##"), text_color = txt_color, bgcolor = sharpe_1 >= 1 ? (sharpe_1 <= 1.50 ? color.new(up_color, 60) : (sharpe_1 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sharpe_1 >= 0.50 ? color.new(down_color, 60) : (sharpe_1 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 2, 5, str.tostring(sharpe_2, "#.##"), text_color = txt_color, bgcolor = sharpe_2 >= 1 ? (sharpe_2 <= 1.50 ? color.new(up_color, 60) : (sharpe_2 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sharpe_2 >= 0.50 ? color.new(down_color, 60) : (sharpe_2 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 3, 5, str.tostring(sharpe_3, "#.##"), text_color = txt_color, bgcolor = sharpe_3 >= 1 ? (sharpe_3 <= 1.50 ? color.new(up_color, 60) : (sharpe_3 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sharpe_3 >= 0.50 ? color.new(down_color, 60) : (sharpe_3 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 4, 5, str.tostring(sharpe_avg, "#.##"), text_color = txt_color, bgcolor = sharpe_avg >= 1 ? (sharpe_avg <= 1.50 ? color.new(up_color, 60) : (sharpe_avg <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sharpe_avg >= 0.50 ? color.new(down_color, 60) : (sharpe_avg >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 1, 6, str.tostring(sortino_1, "#.##"), text_color = txt_color, bgcolor = sortino_1 >= 1 ? (sortino_1 <= 1.50 ? color.new(up_color, 60) : (sortino_1 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sortino_1 >= 0.50 ? color.new(down_color, 60) : (sortino_1 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 2, 6, str.tostring(sortino_2, "#.##"), text_color = txt_color, bgcolor = sortino_2 >= 1 ? (sortino_2 <= 1.50 ? color.new(up_color, 60) : (sortino_2 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sortino_2 >= 0.50 ? color.new(down_color, 60) : (sortino_2 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 3, 6, str.tostring(sortino_3, "#.##"), text_color = txt_color, bgcolor = sortino_3 >= 1 ? (sortino_3 <= 1.50 ? color.new(up_color, 60) : (sortino_3 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sortino_3 >= 0.50 ? color.new(down_color, 60) : (sortino_3 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 4, 6, str.tostring(sortino_avg, "#.##"), text_color = txt_color, bgcolor = sortino_avg >= 1 ? (sortino_avg <= 1.50 ? color.new(up_color, 60) : (sortino_avg <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (sortino_avg >= 0.50 ? color.new(down_color, 60) : (sortino_avg >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 1, 7, str.tostring(omega_1, "#.##"), text_color = txt_color, bgcolor = omega_1 >= 1 ? (omega_1 <= 1.50 ? color.new(up_color, 60) : (omega_1 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (omega_1 >= 0.50 ? color.new(down_color, 60) : (omega_1 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 2, 7, str.tostring(omega_2, "#.##"), text_color = txt_color, bgcolor = omega_2 >= 1 ? (omega_2 <= 1.50 ? color.new(up_color, 60) : (omega_2 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (omega_2 >= 0.50 ? color.new(down_color, 60) : (omega_2 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 3, 7, str.tostring(omega_3, "#.##"), text_color = txt_color, bgcolor = omega_3 >= 1 ? (omega_3 <= 1.50 ? color.new(up_color, 60) : (omega_3 <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (omega_3 >= 0.50 ? color.new(down_color, 60) : (omega_3 >= 0 ? color.new(down_color, 40) : color.new(down_color, 10)))) table.cell(metrics, 4, 7, str.tostring(omega_avg, "#.##"), text_color = txt_color, bgcolor = omega_avg >= 1 ? (omega_avg <= 1.50 ? color.new(up_color, 60) : (omega_avg <= 2 ? color.new(up_color, 40) : color.new(up_color, 10))) : (omega_avg >= 0.50 ? color.new(down_color, 60) : (omega_avg >= 0 ? color.new(down_color, 40) : color.new(down_color, 10))))
Machine Learning: Trend Lines [YinYangAlgorithms]
https://www.tradingview.com/script/U3CHwiXZ-Machine-Learning-Trend-Lines-YinYangAlgorithms/
YinYangAlgorithms
https://www.tradingview.com/u/YinYangAlgorithms/
144
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/ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ // @@@@@@@@@@@@@@@@@@@@@@@@@@@ @ // @@@@@@@@@@@@@@@@@@@@@@@@@ @@ // @@@@@@@@@@@@@@@@@@@@@@@ @@ // @@@@@@@@@@@@@@@@@@@@@@ @@@ // @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // © YinYangAlgorithms //@version=5 indicator('Machine Learning: Trend Lines [YinYangAlgorithms]', overlay=true) // ~~~~~~~~~~~~ INPUTS ~~~~~~~~~~~~ // useMLSources = input.bool(true, "Use Machine Learning Sources", tooltip="If disabled Traditional Trend line sources (High and Low) will be used rather than Rational Quadratics.") useKNN = input.bool(true, "Use KNN Distance Sorting", tooltip="You can disable this if you wish to not have the Machine Learning Data sorted using KNN. If disabled trend line logic will be Traditional.") useExponentialAverage = input.bool(true, "Use Exponential Data Average", tooltip="This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN.") //Notice: If any of these values are changed, you will likely need to 'Fine Tune' the rest as they all effect each other quite drastically //and can lead to poor results if they aren't adjusted together accordingly. mlLength = input.int(50, "Machine Learning Length", tooltip="How strong is our Machine Learning Memory? Please note, when this value is too high the data is almost 'too' much and can lead to poor results.") knnLength = input.int(5, "K-Nearest Neighbour (KNN) Length", tooltip="How many K-Nearest Neighbours are allowed with our Distance Clustering? Please note, too high or too low may lead to poor results.") projectionLength_fast = input.int(5, "Fast ML Data Length", tooltip="Fast and Slow speed needs to be adjusted properly to see results. 3/5/7 all seem to work well for Fast.") projectionLength_slow = input.int(30, "Slow ML Data Length", tooltip="Fast and Slow speed needs to be adjusted properly to see results. 20 - 50 all seem to work well for Slow.") // ~~~~~~~~~~~~ VARIABLES ~~~~~~~~~~~~ // var line upwardTrendLine = na var line downwardTrendLine = na var float topLine = na var float botLine = na // ~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~ // //Get the exponential average of an array, where the exponential weight is focused on the first value of this array (current source) getExponentialDataAverage(_data, _length) => avg = 0. maxLen = math.min(_data.size(), _length) if maxLen > 0 for i = 0 to maxLen - 1 curData = _data.get(i) tempAvg = curData if i > 0 for a = 0 to i tempAvg += array.get(_data, a) tempAvg := math.avg(_data.get(0), tempAvg / i) avg += math.avg(_data.get(0), math.avg(curData, tempAvg)) avg / _length else avg //Uses KNN to sort distances with our ML fast and slow data //This is a modified version that sorts distances but rather than saving and outputting the distance average it outputs the mean of the valid distance and averages the total knnAverage_fromDistance(_dataFast, _dataSlow, _minDist, _maxDist) => //failsafe we need at least 1 distance maxDist = not _minDist ? true : _maxDist //Calculate the distance between slow and fast moving MIF distances = array.new_float(0) for i = 0 to _dataSlow.size() - 1 distance = _dataSlow.get(i) - _dataFast.get(i) distances.push(distance) //clone the array so it doesn't modify it clonedDistances = distances.copy() //slice the length from the array and calculate the max value from this slice splicedDistances = clonedDistances.slice(0, math.min(knnLength, clonedDistances.size())) maxDistanceAllowed = splicedDistances.max() minDistanceAllowed = splicedDistances.min() //scan all distances and add any that are less than max distance validDistances = array.new_float(0) for i = 0 to distances.size() - 1 if (not maxDist or distances.get(i) <= maxDistanceAllowed) and (not _minDist or distances.get(i) >= minDistanceAllowed) distAvg = (_dataSlow.get(i) + _dataFast.get(i)) / 2 validDistances.push(distAvg) //Get exponential or regular average if useExponentialAverage getExponentialDataAverage(validDistances, 1) else validDistances.avg() //@jdehorty Kernel Function //used to turn a source into a rational quadratic which performs better in ML calculations rationalQuadratic(_src, _lookback, _relativeWeight, _startAtBar) => float _currentWeight = 0. float _cumulativeWeight = 0. _size = array.size(array.from(_src)) for i = 0 to _size + _startAtBar y = _src[i] w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_lookback, 2) * 2 * _relativeWeight))), -_relativeWeight) _currentWeight += y*w _cumulativeWeight += w yhat = _currentWeight / _cumulativeWeight yhat // ~~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~~ // //Get High and Low sources mlHigh = rationalQuadratic(high, 8, 8., 25) mlLow = rationalQuadratic(low, 8, 8., 25) //Define which source type is used highSource = useMLSources ? mlHigh : high lowSource = useMLSources ? mlLow : low //calculate our length and bar average length trendLine_length = projectionLength_fast + projectionLength_slow + 1 trendLine_barAvg = (projectionLength_fast + projectionLength_slow) / 2 // ---- Highest (Downward Trend Lines) ---- // //Get out Slow and Fast moving ML Lengths int mlHighestbar_fast = ta.highestbars(highSource, projectionLength_fast * 2 + 1) int mlHighestbar_slow = ta.highestbars(highSource, projectionLength_slow * 2 + 1) //Create the ml storage mlHighestBars_fast = array.new_int(mlLength) mlHighestBars_slow = array.new_int(mlLength) //populate slow and fast ML storage for downward trend lines for h = 0 to mlLength - 1 mlHighestBars_fast.set(h, mlHighestbar_fast[h]) mlHighestBars_slow.set(h, mlHighestbar_slow[h]) //calculate the ml highest bar using KNN highestbars_1 = useKNN ? knnAverage_fromDistance(mlHighestBars_fast, mlHighestBars_slow, true, true) : ta.highestbars(highSource, trendLine_length) //check if we have a new highest bar iff_1 = highestbars_1 == -trendLine_barAvg ? highSource[trendLine_barAvg] : na topLine := not na(highSource[trendLine_length]) ? iff_1 : na //create a new downward trend line when we have a new topLine lineTop = ta.valuewhen(topLine, topLine, 1) trend_startTop = 0 trend_startTop := topLine ? 1 : nz(trend_startTop[1]) + 1 var float topAngle = 0.0 topAngle := topAngle[1] if not na(lineTop) and not na(topLine) if lineTop > topLine downwardTrendLine := line.new(bar_index - trend_startTop[1] - trendLine_barAvg, highSource[trend_startTop[1] + trendLine_barAvg], bar_index - trendLine_barAvg, highSource[trendLine_barAvg], color=color.red, extend=extend.right) topAngle := (highSource[trend_startTop[1] + trendLine_barAvg] - highSource[trendLine_barAvg]) / trend_startTop[1] if lineTop <= topLine topAngle := 0.0 // ---- Lowest (Upward Trend Lines) ---- // //Get out Slow and Fast moving ML Lengths int mlLowestbar_fast = ta.lowestbars(lowSource, projectionLength_fast * 2 + 1) int mlLowestbar_slow = ta.lowestbars(lowSource, projectionLength_slow * 2 + 1) //Create the ml storage mlLowestBars_fast = array.new_int(mlLength) mlLowestBars_slow = array.new_int(mlLength) //populate slow and fast ML storage for upward trend lines for l = 0 to mlLength - 1 mlLowestBars_fast.set(l, mlHighestbar_fast[l]) mlLowestBars_slow.set(l, mlHighestbar_slow[l]) //calculate the ml lowest bar using KNN lowestbars_1 = useKNN ? knnAverage_fromDistance(mlLowestBars_fast, mlLowestBars_slow, true, true) : ta.lowestbars(lowSource, trendLine_length) //check if we have a new lowest bar iff_2 = lowestbars_1 == -trendLine_barAvg ? lowSource[trendLine_barAvg] : na botLine := not na(lowSource[trendLine_length]) ? iff_2 : na //create a new upward trend line when we have a new botline lineBottom = ta.valuewhen(botLine, botLine, 1) trend_startBot = 0 trend_startBot := botLine ? 1 : nz(trend_startBot[1]) + 1 var float botAngle = 0.0 botAngle := botAngle[1] if not na(lineBottom) and not na(botLine) if lineBottom < botLine upwardTrendLine := line.new(bar_index - trend_startBot[1] - trendLine_barAvg, lowSource[trend_startBot[1] + trendLine_barAvg], bar_index - trendLine_barAvg, lowSource[trendLine_barAvg], color=color.green, extend=extend.right) botAngle := (lowSource[trend_startBot[1] + trendLine_barAvg] - lowSource[trendLine_barAvg]) / trend_startBot[1] if lineBottom >= botLine botAngle := 0.0 // ~~~~~~~~~~~~ END ~~~~~~~~~~~~ //
BB phases
https://www.tradingview.com/script/18LwNhAM-BB-phases/
JuicY-trading
https://www.tradingview.com/u/JuicY-trading/
24
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/ // © JuicyWolf //@version=5 indicator("BB phases", overlay = true) bullishColor = input.color(color.rgb(76, 175, 79, 80), "bullish color", group = "personalisation") bearishColor = input.color(color.rgb(255, 82, 82, 80), "bearish color", group = "personalisation") squeezeColor = input.color(color.rgb(33, 149, 243, 80), "squeeze color", group = "personalisation") [middleBB, upperBB, lowerBB] = ta.bb(close, 20, 2) marketPhase = close < upperBB and close > lowerBB ? "squeeze" : close > upperBB ? "pump" : close < lowerBB ? "dump" : "error" if marketPhase[1] == "pump" if close > middleBB marketPhase := "pump" if marketPhase[1] == "dump" if close < middleBB marketPhase := "dump" bbColor = marketPhase == "squeeze" ? squeezeColor : marketPhase == "pump" ? bullishColor : marketPhase == "dump" ? bearishColor : color.gray u = plot(upperBB, color=color.rgb(255, 235, 59, 64)) l = plot(lowerBB, color=color.rgb(255, 235, 59, 64)) fill(u, l, color=bbColor) reintegrateBollingerHigh = close < upperBB and close[1] > upperBB reintegrateBollingerLow = close > lowerBB and close[1] < lowerBB plotshapeSize = size.normal plotshape(series=reintegrateBollingerHigh, style=shape.triangledown, color=bearishColor, text="", size=plotshapeSize, location=location.abovebar) plotshape(series=reintegrateBollingerLow, style=shape.triangleup, color=bullishColor, text="", size=plotshapeSize, location=location.belowbar)
WU Sahm Recession Indicator
https://www.tradingview.com/script/8BOPqkaa-WU-Sahm-Recession-Indicator/
WealthUmbrella
https://www.tradingview.com/u/WealthUmbrella/
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/ // © WealthUmbrella //@version=5 indicator("WU Sahm Recession Indicator (Work on Monthly)") UNRate=request.security("UNRATE", "M", close) UNRate3M=ta.sma(UNRate,3) UNRateMin12M=ta.lowest(UNRate,12)+0.5 plot(timeframe.ismonthly? UNRate3M:na,"Signal line",color=color.blue) plot(timeframe.ismonthly? UNRateMin12M:na,"Threshold line",color=color.red) plot(not timeframe.ismonthly? 0:na,"Threshold line",color=color.red) signal=(UNRate3M>UNRateMin12M) and (UNRate3M[1]<UNRateMin12M[1]) //plotshape(not timeframe.ismonthly and signal, text='Put the chart in Monthly please', location = location.belowbar, textcolor=color.white,color=color.green, style=shape.labelup,size=size.large) bgcolor((UNRate3M==UNRateMin12M ) and timeframe.ismonthly? color.new(color.yellow,50):na) bgcolor((UNRate3M>UNRateMin12M ) and timeframe.ismonthly? color.new(color.red,50):na) bgcolor((UNRate3M<UNRateMin12M) and timeframe.ismonthly ? color.new(color.green,50):na) //bgcolor(signal ? color.new(color.blue,50):na) alertcondition(signal, title = "Recession", message ="Incomming recession")
Dashboard 123456789
https://www.tradingview.com/script/vzaMRYuv/
duthuan244
https://www.tradingview.com/u/duthuan244/
11
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/ // © duthuan244 //@version=5 indicator("Dashboard", overlay = true) //Data for Dashboard volumeDash = volume rsiDash = ta.rsi(close, 14) mfiDash = ta.mfi(hlc3, 14) momDash = (close / close[10]) * 100 buyingPressure = volume * (close - low) / (high - low) sellingPressure = volume * (high - close) / (high - low) percentSellingVol = math.round((sellingPressure / volume) * 100, 0) percentBuyingVol = 100 - percentSellingVol //Defines Each Timeframe for Trend Panel sma = ta.sma(close, 50) oneH = request.security(syminfo.tickerid, "60", sma, barmerge.gaps_off, barmerge.lookahead_off) twoH = request.security(syminfo.tickerid, "120", sma, barmerge.gaps_off, barmerge.lookahead_off) fourH = request.security(syminfo.tickerid, "240", sma, barmerge.gaps_off, barmerge.lookahead_off) daily = request.security(syminfo.tickerid, "D", sma, barmerge.gaps_off, barmerge.lookahead_off) weekly = request.security(syminfo.tickerid, "W", sma, barmerge.gaps_off, barmerge.lookahead_off) monthly = request.security(syminfo.tickerid, "M", sma, barmerge.gaps_off, barmerge.lookahead_off) //Defines An Uptrend for Trend Panel oneHUp = oneH > oneH[1] twoHUp = twoH > twoH[1] fourHUp = fourH > fourH[1] dailyUp = daily > daily[1] weeklyUp = weekly > weekly[1] monthlyUp = monthly > monthly[1] rsiDashUp = rsiDash > rsiDash[1] mfiDashUp = mfiDash > mfiDash[1] momDashUp = momDash > momDash[1] //Checks if the Current State is an Uptrend or Downtrend for the Trend Panel up = "📈" down = "📉" oneHTrend = oneHUp ? up : down twoHTrend = twoHUp ? up : down fourHTrend = fourHUp ? up : down dailyTrend = dailyUp ? up : down weeklyTrend = weeklyUp ? up : down monthlyTrend = monthlyUp ? up : down rsiTrend = rsiDashUp ? up : down mfiTrend = mfiDashUp ? up : down momTrend = momDashUp ? up : down dashOn = input(true, "Dashboard On / Off") dashDist = input(38, "Dashboard Distance") dashColor = input(color.new(#696969, 80), "Dashboard Color", inline="Dash Line") dashTextColor = input(color.new(#ffffff, 0), "Text Color", inline="Dash Line") if dashOn label Label = label.new(time, close, text=" 👑 Du Thuan 0795332997 👑" + "\n━━━━━━━━━━━━━━━━━" + "\n Market Information" + "\n━━━━━━━━━━━━━━━━━" + "\n 🚀 Volume             | " + str.tostring(volume, "##.##" ) + "\n 🚀 RSI                         | " + str.tostring(rsiDash, "##.##") + rsiTrend + "\n 🚀 MFI                       | " + str.tostring(mfiDash, "##.##") + mfiTrend + "\n 🚀 Momentum | " + str.tostring(momDash, "##.##") + momTrend + "\n 🚀 % Buy             | " + str.tostring(percentBuyingVol, "##.##" ) + "\n 🚀 % Sell             | " + str.tostring(percentSellingVol, "##.##" ) + "\n━━━━━━━━━━━━━━━━━" + "\n Trend Panel" + "\n━━━━━━━━━━━━━━━━━" + "\n 1 Hour | " + oneHTrend + " Daily | " + dailyTrend + "\n 2 Hour | " + twoHTrend + " Weekly | " + weeklyTrend + "\n 4 Hour | " + fourHTrend + " Monthly | " + monthlyTrend + "\n━━━━━━━━━━━━━━━━━" + "\n 💎High Risk High Return💎", color=dashColor, xloc= xloc.bar_time, style=label.style_label_left, textcolor=dashTextColor, textalign=text.align_left) label.set_x(Label, label.get_x(Label) + math.round(ta.change(time)*dashDist)) label.delete(Label[1])
Heat profile
https://www.tradingview.com/script/bfuxUk6k-Heat-profile/
veryevilone
https://www.tradingview.com/u/veryevilone/
11
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/ // © veryevilone //@version=5 indicator("Heat profile", overlay = true) topHeatHigh = chart.point.now(high) topHeatLow = if close > open chart.point.now(close) else chart.point.now(open) bottomHeatLow = chart.point.now(low) bottomHeatHigh = if close < open chart.point.now(close) else chart.point.now(open) topHeatColor = input.color(color.rgb(128,128,128,98)) bottomHeatColor = input.color(color.rgb(128,128,128,98)) box.new(topHeatHigh, topHeatLow, topHeatColor, bgcolor=topHeatColor, extend=extend.right) box.new(bottomHeatHigh, bottomHeatLow, bottomHeatColor, bgcolor=bottomHeatColor, extend=extend.right)
Supertrend Multiasset Correlation - vanAmsen
https://www.tradingview.com/script/ZiyF71CD-Supertrend-Multiasset-Correlation-vanAmsen/
vanAmsen
https://www.tradingview.com/u/vanAmsen/
24
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/ // © vanAmsen //@version=5 indicator("vanAmsen - Supertrend Multiasset Correlation", overlay = true) // ------- INPUT SETTINGS ------- // Existing inputs atrPeriod = input.int(10, title="ATR Length", tooltip="Specifies the period over which the Average True Range (ATR) is calculated.", minval=1) factor = input.float(6, title="Factor", tooltip="Multiplier factor for the ATR to define the distance of the Supertrend line from the price.", minval=0.1, step=0.1) upColor = input.color(color.rgb(122,244,122), title="Up Color", tooltip="Color for the Supertrend line when the trend is upwards or bullish.") downColor = input.color(color.rgb(244,122,122), title="Down Color", tooltip="Color for the Supertrend line when the trend is downwards or bearish.") correlationLength = input.int(100, title="Correlation Length", tooltip="Length for the correlation calculation.", minval=1) // New input for showTable showTable = input.bool(true, title="Show Table", tooltip="Display the correlation prediction table.") // Input symbols ticker0 = input.symbol("VUG", title="Ticker 0") ticker1 = input.symbol("VTV", title="Ticker 1") ticker2 = input.symbol("XLF", title="Ticker 2") ticker3 = input.symbol("XLV", title="Ticker 3") ticker4 = input.symbol("XLE", title="Ticker 4") ticker5 = input.symbol("XLK", title="Ticker 5") ticker6 = input.symbol("XLY", title="Ticker 6") ticker7 = input.symbol("XLI", title="Ticker 7") ticker8 = input.symbol("XLB", title="Ticker 8") ticker9 = input.symbol("TLT", title="Ticker 9") ticker10 = input.symbol("IAU", title="Ticker 10") ticker11 = input.symbol("XLU", title="Ticker 11") // ... Add more ticker inputs as needed ... // ------- INITIALIZATION ------- // Prediction initialization var float prediction = na prediction := 0.0 // Table & Array setups var table tbl = table.new(position.top_right, 4, 15) var dirArray = array.new<float>(13, na) var corrArray = array.new<float>(13, na) var predArray = array.new<float>(13, na) // ------- FUNCTION DEFINITIONS ------- // Calculate correlation prediction for a given ticker based on ROC (Rate of Change) correlationPrediction(ticker) => [tickerSupertrend, tickerDirection] = request.security(ticker, timeframe.period, ta.supertrend(factor, atrPeriod)) currentROC = ta.roc(close, 1) // Rate of Change for main asset for 1 day tickerROC = request.security(ticker, timeframe.period, ta.roc(close, 1)) // Rate of Change for ticker for 1 day tickerCorrelation = ta.correlation(currentROC, tickerROC, correlationLength) tickerCorrelation * tickerCorrelation * tickerDirection // Update table with ticker correlation data based on ROC (Rate of Change) correlationPredictionAndUpdateTable(ticker, colIndex) => [tickerSupertrend, tickerDirection] = request.security(ticker, timeframe.period, ta.supertrend(factor, atrPeriod)) currentROC = ta.roc(close, 1) // Rate of Change for main asset for 1 day tickerROC = request.security(ticker, timeframe.period, ta.roc(close, 1)) // Rate of Change for ticker for 1 day tickerCorrelation = ta.correlation(currentROC, tickerROC, correlationLength) tickerDirection := tickerDirection*-1 correlatedPred = tickerCorrelation * tickerCorrelation * tickerDirection // Update table table.cell(tbl, 0, colIndex, ticker, bgcolor=color.silver, text_color=color.black) table.cell(tbl, 1, colIndex, str.tostring(tickerDirection), bgcolor=tickerDirection > 0 ? upColor : downColor) table.cell(tbl, 2, colIndex, str.tostring(tickerCorrelation, "#.00"), bgcolor=tickerCorrelation > 0 ? upColor : downColor) table.cell(tbl, 3, colIndex, str.tostring(correlatedPred, "#.00"), bgcolor=correlatedPred > 0 ? upColor : downColor) // Store in arrays array.set(dirArray, colIndex-1, tickerDirection) array.set(corrArray, colIndex-1, tickerCorrelation) array.set(predArray, colIndex-1, correlatedPred) [tickerDirection, tickerCorrelation, correlatedPred] // Return as tuple // ------- MAIN LOGIC ------- // Accumulate predictions prediction := correlationPrediction(syminfo.ticker) + correlationPrediction(ticker0) + correlationPrediction(ticker1) + correlationPrediction(ticker2) + correlationPrediction(ticker3) + correlationPrediction(ticker4) + correlationPrediction(ticker5) + correlationPrediction(ticker6) + correlationPrediction(ticker7) + correlationPrediction(ticker8) + correlationPrediction(ticker9) + correlationPrediction(ticker10) + correlationPrediction(ticker11) prediction := prediction / 13 // Determine the plot position based on prediction atrValue = ta.atr(correlationLength) plotPosition = prediction < 0 ? close - (atrValue * (-prediction+1)) : close + (atrValue * (1+prediction)) plot(plotPosition, color=prediction < 0 ? upColor : downColor, title="Prediction", linewidth=1) // Display table if condition met if showTable and session.islastbar // Headers table.cell(tbl, 0, 0, "Tkr", bgcolor=color.silver, text_color=color.black) // Ticker table.cell(tbl, 1, 0, "Dir", bgcolor=color.silver, text_color=color.black) // Direction table.cell(tbl, 2, 0, "Corr", bgcolor=color.silver, text_color=color.black) // Correlation table.cell(tbl, 3, 0, "Pred", bgcolor=color.silver, text_color=color.black) // Prediction // Populate the table with data for each ticker correlationPredictionAndUpdateTable(syminfo.ticker, 1) correlationPredictionAndUpdateTable(ticker0, 2) correlationPredictionAndUpdateTable(ticker1, 3) correlationPredictionAndUpdateTable(ticker2, 4) correlationPredictionAndUpdateTable(ticker3, 5) correlationPredictionAndUpdateTable(ticker4, 6) correlationPredictionAndUpdateTable(ticker5, 7) correlationPredictionAndUpdateTable(ticker6, 8) correlationPredictionAndUpdateTable(ticker7, 9) correlationPredictionAndUpdateTable(ticker8, 10) correlationPredictionAndUpdateTable(ticker9, 11) correlationPredictionAndUpdateTable(ticker10, 12) correlationPredictionAndUpdateTable(ticker11, 13) // Calculate averages avgDirection = array.avg(dirArray) avgCorrelation = array.avg(corrArray) avgPrediction = array.avg(predArray) // Add the average values to the table table.cell(tbl, 0, 14, "Avg", bgcolor=color.silver, text_color=color.black) table.cell(tbl, 1, 14, str.tostring(avgDirection, "#.00"), bgcolor=avgDirection > 0 ? upColor : downColor) table.cell(tbl, 2, 14, str.tostring(avgCorrelation, "#.00"), bgcolor=avgCorrelation > 0 ? upColor : downColor) table.cell(tbl, 3, 14, str.tostring(avgPrediction, "#.00"), bgcolor=avgPrediction > 0 ? upColor : downColor)
Triple Ehlers Market State
https://www.tradingview.com/script/6vcvpsLs-Triple-Ehlers-Market-State/
alphaXiom
https://www.tradingview.com/u/alphaXiom/
273
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 //╱//╭╮╱╱/╭╮╱╱╱/╭━╮╭━╮ //╱//┃┃╱//┃┃╱╱//╰╮╰╯╭╯ //╭━━┫┃╭━━┫╰━┳━━╮╰╮╭╯╭┳━━┳╮╭╮ //┃╭╮┃┃┃╭╮┃╭╮┃╭╮┃╭╯╰╮┣┫╭╮┃╰╯┃ //┃╭╮┃╰┫╰╯┃┃┃┃╭╮┣╯╭╮╰┫┃╰╯┃┃┃┃ //╰╯╰┻━┫╭━┻╯╰┻╯╰┻━╯╰━┻┻━━┻┻┻╯ //╱╱╱╱/┃┃ //╱╱╱//╰╯ indicator('Triple Market State', 'Triple MS', false, format.price, 2) source = input(close, 'Source') period1 = input.int(28, '  Slow Period', minval=2, inline = 'rp', group = 'Triple Market State') thresholdMS1 = input.int(9, 'Threshold °', minval=1, inline = 'rp', group = 'Triple Market State') period2 = input.int(18, 'Medium Period', minval=2, inline = 'rp', group = 'Triple Market State') thresholdMS2 = input.int(15, 'Threshold °', minval=1, inline = 'rp', group = 'Triple Market State') period3 = input.int(9, '  Fast Period', minval=2, inline = 'rp', group = 'Triple Market State') thresholdMS3 = input.int(10, 'Threshold °', minval=1, inline = 'rp', group = 'Triple Market State') weighting = input.bool(defval = true, title = 'Recent trend weighting', inline = 'e', group = 'Triple Market State', tooltip = "Shows on bars ONLY") var M1 = 'Classic' var M2 = 'Night' var M3 = 'Mono' var M4 = 'Urban' var string GRP_UI = '══════ UI ══════' the_m = input.string(M1, "Theme", options = [M1, M2, M3, M4], inline= 'ez', group=GRP_UI) bars = input.bool(defval = true, title = 'Bar coloring', inline = 'ez', group=GRP_UI) i_bullColor_c = input.color(#41c607, "Up", inline='COLORc', group=GRP_UI) i_bearColor_c = input.color(#ca066c, "Down", inline='COLORc', group=GRP_UI) i_consColor_c = input.color(#d88305, "Retracement", inline='COLORc', group=GRP_UI) i_bullColor_a = input.color(#cdb14e, "Up", inline='COLORa', group=GRP_UI) i_bearColor_a = input.color(#c068e3, "Down", inline='COLORa', group=GRP_UI) i_consColor_a = input.color(#2e6d80, "Retracement", inline='COLORa', group=GRP_UI) i_bullColor_o = input.color(#c2bdbd, "Up", inline='COLORo', group=GRP_UI) i_bearColor_o = input.color(#3179f5, "Down", inline='COLORo', group=GRP_UI) i_consColor_o = input.color(#d88305, "Retracement", inline='COLORo', group=GRP_UI) i_bullColor_u = input.color(#cdb14e, "Up", inline='COLORu', group=GRP_UI) i_bearColor_u = input.color(#3179f5, "Down", inline='COLORu', group=GRP_UI) i_consColor_u = input.color(#ffffff, "Retracement", inline='COLORu', group=GRP_UI) up_ = the_m == M1 ? i_bullColor_c : the_m == M2 ? i_bullColor_a : the_m == M3 ? i_bullColor_o : the_m == M4 ? i_bullColor_u : na dn_ = the_m == M1 ? i_bearColor_c : the_m == M2 ? i_bearColor_a : the_m == M3 ? i_bearColor_o : the_m == M4 ? i_bearColor_u : na md_ = the_m == M1 ? i_consColor_c : the_m == M2 ? i_consColor_a : the_m == M3 ? i_consColor_o : the_m == M4 ? i_consColor_u : na areaTransp = input.int(70, 'Slow Period area transparency', minval = 0, maxval = 100, inline= 'r', group = GRP_UI) // Functions ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ rad2deg(Rad) => // Radians To Degrees var DEGREES_IN_1_RADIAN = 90.0 / math.asin(1.0) // 57.29577951308 Constant Rad * DEGREES_IN_1_RADIAN cc(Series, Period) => // Correlation Cycle Function var PIx2 = 4.0 * math.asin(1.0) // 6.28318530718 Constant period = math.max(2, Period) Rx = 0.0 Rxx = 0.0 Rxy = 0.0 Ryy = 0.0 Ry = 0.0 Ix = 0.0 Ixx = 0.0 Ixy = 0.0 Iyy = 0.0 Iy = 0.0 for i = 1 to period by 1 iMinusOne = i - 1 X = nz(Series[iMinusOne]) temp = PIx2 * iMinusOne / period Yc = math.cos(temp) Ys = -math.sin(temp) Rx += X Ix += X Rxx += X * X Ixx += X * X Rxy += X * Yc Ixy += X * Ys Ryy += Yc * Yc Iyy += Ys * Ys Ry += Yc Iy += Ys Iy realPart = 0.0 temp_1 = period * Rxx - Rx * Rx temp_2 = period * Ryy - Ry * Ry if temp_1 > 0.0 and temp_2 > 0.0 realPart := (period * Rxy - Rx * Ry) / math.sqrt(temp_1 * temp_2) realPart imagPart = 0.0 temp_1 := period * Ixx - Ix * Ix temp_2 := period * Iyy - Iy * Iy if temp_1 > 0.0 and temp_2 > 0.0 imagPart := (period * Ixy - Ix * Iy) / math.sqrt(temp_1 * temp_2) imagPart [realPart, imagPart] cap(RealPart, ImaginaryPart) => // Correlation Angle Phasor Function var HALF_OF_PI = math.asin(1.0) // 1.57079632679 Constant angle = ImaginaryPart == 0.0 ? 0.0 : rad2deg(math.atan(RealPart / ImaginaryPart) + HALF_OF_PI) if ImaginaryPart > 0.0 angle -= 180.0 angle priorAngle = nz(angle[1]) if priorAngle > angle and priorAngle - angle < 270.0 angle := priorAngle angle angle mstate(Angle, Degrees) => // Market State Function var thresholdInDegrees = Degrees state = 0 temp = math.abs(Angle - Angle[1]) < thresholdInDegrees if Angle >= 0.0 and temp state := 1 state if Angle < 0.0 and temp state := -1 state state // Correlation Cycle ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ [real1, imaginary1] = cc(source, period1) [real2, imaginary2] = cc(source, period2) [real3, imaginary3] = cc(source, period3) // Correlation Angle/Phasor ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ angle1 = cap(real1, imaginary1) angle2 = cap(real2, imaginary2) angle3 = cap(real3, imaginary3) // Market State ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ state1 = mstate(angle1, thresholdMS1) state2 = mstate(angle2, thresholdMS2) state3 = mstate(angle3, thresholdMS3) colorMS1 = state1 > 0.5 ? color.new(up_, areaTransp) : state1 < -0.5 ? color.new(dn_, areaTransp) : na colorMS2 = state2 > 0.5 ? color.new(up_, 0) : state2 < -0.5 ? color.new(dn_, 0) : na colorMS3 = state3 > 0.5 ? color.new(up_, 0) : state3 < -0.5 ? color.new(dn_, 0) : na plot(state1, color = colorMS1, style = plot.style_area, title = 'State Slow', linewidth = 2) plot(-state1, color = colorMS1, style = plot.style_area, title = 'State Slow', linewidth = 2) plot(-state2, color = colorMS2, style = plot.style_histogram, title = 'State Medium') plot(-state3, color = colorMS3, style = plot.style_circles, title = 'State Fast', linewidth = 2) // Bar Gates ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ var trend_slo = 0 if state1 > 0.5 trend_slo := 1 trend_slo if state1 < -0.5 trend_slo := -1 trend_slo if state1 < 0.5 and state1 > -0.5 trend_slo := 2 trend_slo var trend_med = 0 if state2 > 0.5 trend_med := 1 trend_med if state2 < -0.5 trend_med := -1 trend_med if state2 < 0.5 and state2 > -0.5 trend_med := 2 trend_med var trend_fas = 0 if state3 > 0.5 trend_fas := 1 trend_fas if state3 < -0.5 trend_fas := -1 trend_fas if state3 < 0.5 and state3 > -0.5 trend_fas := 2 trend_fas var trend_double = 0 if trend_slo == 1 and trend_med == 1 or trend_slo == 1 and trend_fas == 1 or trend_med == 1 and trend_fas == 1 trend_double := 1 trend_double if trend_slo == -1 and trend_med == -1 or trend_slo == -1 and trend_fas == -1 or trend_med == -1 and trend_fas == -1 trend_double := -1 trend_double // Parliament arrays ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ sig_up = array.from( trend_slo == 1 ? 1 : 0 , trend_med == 1 ? 1 : 0 , trend_fas == 1 ? 1 : 0 , trend_double == 1 and weighting ? 1 : 0) sigSum_up = array.sum (sig_up) sig_dn = array.from( trend_slo == -1 ? 1 : 0 , trend_med == -1 ? 1 : 0 , trend_fas == -1 ? 1 : 0 , trend_double == -1 and weighting ? 1 : 0) sigSum_dn = array.sum (sig_dn) mid_signal = sigSum_up == sigSum_dn plot(mid_signal ? 0 : na, color = color.new(md_, 0), style = plot.style_circles, title = 'Retracement', linewidth = 2) // ------------------------------------------------------------------------------ // Bars var bar_trigs = 0 if sigSum_up > sigSum_dn bar_trigs := 1 bar_trigs if sigSum_up < sigSum_dn bar_trigs := -1 bar_trigs if sigSum_up == sigSum_dn bar_trigs := 2 bar_trigs agreg_trig_color = bar_trigs == 1 ? color.new(up_, 0) : bar_trigs == -1 ? color.new(dn_, 0) : bar_trigs == 2 ? color.new(md_, 0) : color.white //plotshape(close, title='Trend', style=shape.circle, location=location.bottom, color=alert_trig_color, size = size.tiny) // test alerts barcolor(bars ? agreg_trig_color : na) // ------------------------------------------------------------------------------ // Alerts bull_mega = bar_trigs == 1 and bar_trigs[1] == -1 or bar_trigs == 1 and bar_trigs[1] == 2 bull_close = bar_trigs == -1 and bar_trigs[1] == 1 or bar_trigs == 2 and bar_trigs[1] == 1 bear_mega = bar_trigs == -1 and bar_trigs[1] == 1 or bar_trigs == -1 and bar_trigs[1] == 2 bear_close = bar_trigs == 1 and bar_trigs[1] == -1 or bar_trigs == 2 and bar_trigs[1] == -1 all_trigs = bull_mega or bull_close or bear_mega or bear_close alertcondition(all_trigs, '..... TMS Any alert 🟢🟡🔴', 'TMS Any alert 🟢🟡🔴') alertcondition(bull_mega, '....TMS BUY 🟢', 'Up 🟢') alertcondition(bull_close, '...TMS Close long: retrace/reverse 🟡❎', 'Close long 🟡❎') alertcondition(bear_mega, '..TMS SELL 🔴', 'Down 🔴') alertcondition(bear_close, '.TMS Close short: retrace/reverse 🟡❌', 'Close short 🟡❌') plotshape(all_trigs, title='any alert test', style=shape.circle, location=location.top, color = #ffffff, size = size.tiny, display = display.none) // test alerts plotshape(bull_mega, title='long test', style=shape.circle, location=location.top, color = up_, size = size.tiny, display = display.none) // test alerts plotshape(bull_close, title='close long test', style=shape.circle, location=location.top, color = #c7db90, size = size.tiny, display = display.none) // test alerts plotshape(bear_mega, title='short test', style=shape.circle, location=location.top, color = dn_, size = size.tiny, display = display.none) // test alerts plotshape(bear_close, title='close short test', style=shape.circle, location=location.top, color = #cf9a9a, size = size.tiny, display = display.none) // test alerts // ( __)( ( \( \ // ) _) / / ) D ( // (____)\_)__)(____/ // ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟ ⮟
Pullback and Throwback Candle [TrendX_]
https://www.tradingview.com/script/eEJ43MME-Pullback-and-Throwback-Candle-TrendX/
TrendX_
https://www.tradingview.com/u/TrendX_/
29
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/ // © TrendX_ //@version=5 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxx // XXX.....X....X....X..XX:X...XX xx // X:XXX:..:X:...X:X.X:X:XX.XXXXX // XXXXX:XXX: .X:...X:XX..X:..XX xx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX xxxxxxxxxxxxxxxxxxxxxxxxxx // indicator("Pullback and Throwback Candle [TrendX_]" ,overlay=true ) /// ____ RSI condition ____ //// //Input T_price = input.source(defval = close, title = "Source of Price data" ) rsiLen = input.int( defval = 34 , title = "Length of RSI" , group = "RSI setting" ) rsiType = input.string(defval = "RMA", title = "Smoothing type of RSI", group = "RSI setting", options = ["RMA", "EMA"]) OB = input.int( defval = 75 , title ="RSI overbought" , group = "RSI setting" ) OS = input.int( defval = 35 , title ="RSI oversold" , group = "RSI setting" ) //Setting RSI function rsiFunc(rsiType, srcRSI, rsiLen) => op1 = ta.ema(srcRSI, rsiLen) op2 = ta.rma(srcRSI, rsiLen) rsiType == "RMA" ? op2 : op1 //Define RSI ups = rsiFunc(rsiType, math.max(ta.change(hlc3) , 0), rsiLen) lows = rsiFunc(rsiType, -math.min(ta.change(hlc3), 0), rsiLen) rsi = lows == 0 ? 100 : ups == 0 ? 0 : 100 - (100 / (1 + ups / lows)) //Define Overbought and Oversold RSi logic rsiOS = rsi < OS and rsi rsiOB = rsi > OB and rsi //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// ____ Pullback and Throwback by TrendX ____ //// //Input PBcondition = ta.lowestbars( low , 8) >= -1 TBcondition = ta.highestbars(high, 8) >= -1 //Define Pullback (PB) and Throwback (TB) PB = (T_price[2] < T_price[3]) and (T_price[1] < T_price[2]) and (T_price > T_price[1]) and PBcondition TB = (T_price[2] > T_price[3]) and (T_price[1] > T_price[2]) and (T_price < T_price[1]) and TBcondition //Plotting PB and TB zone plotshape( PB and rsiOS, style = shape.triangleup , size = size.tiny, color = color.green, location = location.belowbar, display = display.none ) plotshape( TB and rsiOB, style = shape.triangledown, size = size.tiny, color = color.red , location = location.abovebar, display = display.none ) bgcolor( color = (PB and rsiOS) ? color.rgb(50 , 205, 50, 80) : na ) bgcolor( color = (TB and rsiOB) ? color.rgb(255, 0, 0, 70) : na ) //Alerts alertcondition(PB and rsiOS, "PB", "PB at {{ticker}}") alertcondition(TB and rsiOB, "TB", "TB at {{ticker}}") ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ATR Based Stoploss - TakeProfit [CharmyDexter]
https://www.tradingview.com/script/un9hzfTN-ATR-Based-Stoploss-TakeProfit-CharmyDexter/
CharmyDexter
https://www.tradingview.com/u/CharmyDexter/
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/ // © CharmyDexter //@version=5 indicator("ATR Based Stoploss - TakeProfit [CharmyDexter]", overlay=true) main = "Main" //NATR Surge natrlbprd = input.int(30, "ATR Lookback Period", group=main, tooltip="Lookback Period for Volatility Expansion") atrLength = input.int(14, "ATR Length", group=main) tnatrSim = 100 * ta.atr(1)/close natr = ta.atr(atrLength) natrSim = ta.atr(1) natrSH = ta.highest(natrSim, natrlbprd) surgeReset = ta.barssince(natrSH > natrSH[1]) > 5 natrSurgeH = 0 natrSurgeH := natrSH > natrSH[1] ? 1 : surgeReset ? 0 : natrSurgeH[1] freqnatrSurge = ta.crossover(natrSurgeH, 0) SimVal = 0. SimVal := freqnatrSurge ? natrSim : SimVal[1] var float[] natrSHArray = array.new_float(0) var float natrSHAvg = na if freqnatrSurge array.push(natrSHArray, natrSH) if array.size(natrSHArray) > 0 natrSHAvg := array.avg(natrSHArray) changeLines = natrSHAvg != natrSHAvg[1] natrSurge = freqnatrSurge and tnatrSim > 1 usenavg = input.string("ATR Surge Average", options=["ATR", "ATR Surge Average"], title="Stop Loss Take Profit Type", group=main) natrPM = input.float(4, "ATR Profit Multiplier", group=main) natrLM = input.float(1, "ATR Loss Multiplier", group=main) natrP = usenavg == "ATR Surge Average" ? natrSHAvg*natrPM : natr*natrPM natrL = usenavg == "ATR Surge Average" ? natrSHAvg*natrLM : natr*natrLM psnatr = 0. psnatr := natrSurge ? natrP : psnatr[1] lsnatr = 0. lsnatr := natrSurge ? natrL : lsnatr[1] // The MA maLength = input.int(8, title="MA Length", group=main) theMA = ta.sma(ohlc4, maLength) theMAPlus = theMA+psnatr theMANeg = theMA-psnatr theplusstop = theMA+lsnatr thenegstop = theMA-lsnatr plot(theMA, "Moving Average", color=color.new(color.blue, 0)) plot(theMAPlus, title='Long Take Profit', color=color.new(color.lime, 60), linewidth=1) plot(theMANeg, title='Short Take Profit', color=color.new(color.maroon, 60), linewidth=1) plot(theplusstop, title='Short Stop Loss', color=color.new(color.fuchsia, 80), linewidth=1) plot(thenegstop, title='Long Stop Loss', color=color.new(color.orange, 80), linewidth=1) //natrSPump = natrSurge and open < close natrSDump = natrSurge and open > close //plotshape(natrSPump ? low : na, title='Surge Up', text='💥', style=shape.labelup, location=location.absolute, color=color.new(color.black, 100), textcolor=color.new(color.green, 0), size=size.tiny) //plotshape(natrSDump ? high : na, title='Surge Down', text='🔥', style=shape.labeldown, location=location.absolute, color=color.new(color.black, 100), textcolor=color.new(color.red, 0), size=size.tiny) //Simple Alerts //alertcondition(natrSurge, "Volatility Expansion", "Volatility Increasing") //Preparing Table tablePosition = input.string("Bottom right", options=["Bottom right", "Top right", "Top left", "Bottom left"], title="Table Position") tablePosinp = tablePosition == "Top right" ? position.top_right : tablePosition == "Top left" ? position.top_left : tablePosition == "Bottom right" ? position.bottom_right : position.bottom_left var table dashboarD = table.new(tablePosinp, 3, 2, border_width=1) var tbbgcolor = color.new(color.black, 0) tableF(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + '\n' + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size = size.small) tnatr = 100 * ta.atr(atrLength)/close tnatrSH = ta.highest(tnatrSim, natrlbprd) var float[] tnatrSHArray = array.new_float(0) var float tnatrSHAvg = na if freqnatrSurge array.push(tnatrSHArray, tnatrSH) if array.size(tnatrSHArray) > 0 tnatrSHAvg := array.avg(tnatrSHArray) tnatrP = usenavg == "ATR Surge Average" ? tnatrSHAvg*natrPM : tnatr*natrPM tnatrL = usenavg == "ATR Surge Average" ? tnatrSHAvg*natrLM : tnatr*natrLM prftpcnt = 0. prftpcnt := natrSurge ? tnatrP : prftpcnt[1] losspcnt = 0. losspcnt := natrSurge ? tnatrL : losspcnt[1] risK = input.float(0.3, title="$Risk") funD = (risK/losspcnt)*99.85 prfT = funD*(1+(prftpcnt/100)) - funD lCol = color.new(color.red, 60) tableF(dashboarD, 0, 0, 'Fund', '$' + str.tostring(math.round(funD, 2)), tbbgcolor, color.white) tableF(dashboarD, 1, 0, 'Max P/L', str.tostring(prftpcnt, format.percent)+"/"+'$'+str.tostring(math.round(prfT, 2)), tbbgcolor, color.white) tableF(dashboarD, 0, 1, 'ATR',str.tostring(natr), tbbgcolor, color.white) tableF(dashboarD, 1, 1, 'Min P/L', str.tostring(losspcnt, format.percent)+"/"+'$'+str.tostring(math.round(risK, 2)), lCol, color.white)
1 Minute Scalping
https://www.tradingview.com/script/Q7O91NIB-1-Minute-Scalping/
digit23
https://www.tradingview.com/u/digit23/
11
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/ // © digit23 //@version=5 indicator("1 Minute Scalping", overlay = true) ema50 = ta.ema(close, 50) plot(ema50)
Monthly beta (5Y monthly) with multi-timeframe support
https://www.tradingview.com/script/9hZVpuXv-Monthly-beta-5Y-monthly-with-multi-timeframe-support/
haribotagada
https://www.tradingview.com/u/haribotagada/
9
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/ // © haribotagada //@version=5 indicator("Monthly beta", overlay= false) // Inputs calculationPeriod = input.string('5Y', 'Calculation period', options = ['1Y', '2Y', '3Y', '4Y', '5Y'], tooltip = 'Need at least 1Y of data to calculate.\nOver longer periods we incorprate new monthly data points available at the time until we reach desired window length.') indexSymbol = input.symbol('SP:SPX', 'Base index') numMonthlyBars = switch calculationPeriod '1Y' => 12 '2Y' => 2 * 12 '3Y' => 3 * 12 '4Y' => 4 * 12 '5Y' => 5 * 12 // Price data [stockReturn, monthlyBarLabel] = request.security(syminfo.tickerid, '1M', [ta.roc(close,1) , str.tostring(year) + str.tostring(month)]) indexReturn = request.security(indexSymbol, '1M', ta.roc(close,1)) // Vars var lastAddedBarLabel = string(na) var stockReturns = array.new_float(na) var indexReturns = array.new_float(na) beta = float(na) // Process new monthly return if not na(stockReturn) and not na(indexReturn) and monthlyBarLabel != lastAddedBarLabel array.push(stockReturns, stockReturn) array.push(indexReturns, indexReturn) lastAddedBarLabel := monthlyBarLabel numStockValues = array.size(stockReturns) numIndexValues = array.size(indexReturns) if numStockValues > numMonthlyBars array.shift(stockReturns) if numIndexValues > numMonthlyBars array.shift(indexReturns) if numStockValues < 12 log.info('Not enough data to calculate beta.') beta := na else log.info('Calculating beta as of ' + lastAddedBarLabel + ' using ' + str.tostring(array.size(stockReturns)) + ' month(s) of data with the following stock and index values: \n' + str.tostring(stockReturns) + '\n' + str.tostring(indexReturns)) covariance = array.covariance(stockReturns, indexReturns) varianceIndex = array.variance(indexReturns) beta := covariance / varianceIndex hline(1) plot(beta, style= plot.style_circles, linewidth=1, join = true, color = beta > 1 ? color.new(#009688, 0) : color.new(#f44336, 00), trackprice = true)
ADX Speed Derivative
https://www.tradingview.com/script/Fqey3Wff-ADX-Speed-Derivative/
Alphacrafting
https://www.tradingview.com/u/Alphacrafting/
11
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/ // © Alphacrafting // This script calculates the first and second derivates (rates of change) for the ADX indicator, // displaying each as a non-overlay oscillator with an included midline. //@version=5 // Administrative Declarations and Inputs indicator(title="ADX Speed Derivative", shorttitle="ADXSD", format=format.price, precision=4, timeframe="", timeframe_gaps=true) lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50) len = input.int(14, minval=1, title="DI Length") degree = input.int(1, minval = 1, title = "Derivative Lengths", tooltip = "Sets lookback value for derivatives") // Calculation of ADX up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) trur = ta.rma(ta.tr, len) plus = fixnan(100 * ta.rma(plusDM, len) / trur) minus = fixnan(100 * ta.rma(minusDM, len) / trur) sum = plus + minus adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig) // Derivative functions // NOTE: Derivatives are calculated using the Average Rate Of Change (AROC) model first_derivative() => aroc = (adx - adx[degree]) / degree aroc second_derivative(first) => aroc = (first - first[degree]) / degree aroc // Assignment of values first_d = first_derivative() second_d = second_derivative(first_d) // Export to the chart plot(first_d, color = color.white, title = "1st ADX Derivative", linewidth = 1) plot(second_d, color = color.purple, title = "2nd ADX Derivative", linewidth = 1) plot(0, color = color.new(color.white, 70))
MA + MACD alert Trends
https://www.tradingview.com/script/dV9mvs02-MA-MACD-alert-Trends/
Ducanhdavinci
https://www.tradingview.com/u/Ducanhdavinci/
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/ // © Ducanhdavinci //@version=5 indicator(shorttitle="MA+MACD alert", title="MA + MACD alert", overlay=true) import TradingView/Strategy/3 // Input MA // Input MA len1 = input.int(100, minval=1, title="Length MA1", group="MA 1") src1 = input(close, title="Source MA1", group="MA 1") typeMA1 = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA 1") len2 = input.int(200, minval=1, title="Length MA2", group="MA 2") src2 = input(close, title="Source MA2", group="MA 2") typeMA2 = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA 2") len3 = input.int(25, minval=1, title="Length MA3", group="MA 3") src3 = input(close, title="Source MA3", group="MA 3") typeMA3 = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA 3") len4 = input.int(50, minval=1, title="Length MA4", group="MA 4") src4 = input(close, title="Source MA4", group="MA 4") typeMA4 = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA 4") len5 = input.int(1, minval=1, title="Length MA5", group="MA 5") src5 = input(close, title="Source MA5", group="MA 5") typeMA5 = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA 5") len6 = input.int(2, minval=1, title="Length MA6", group="MA 6") src6 = input(close, title="Source MA6", group="MA 6") typeMA6 = input.string(title = "Method", defval = "EMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA 6") // input MACD // Thông số MACD của khung thời gian lớn hơn 1 khung so với khung vào lệnh fast_length = input(title="Fast Length", defval=12, group = "MACD") slow_length = input(title="Slow Length", defval=46, group = "MACD") signal_length = input.int(title="Signal Smoothing", minval = 1, defval = 9, group = "MACD") src_macd = input(title="Source", defval=close, group = "MACD") // Calculating MA ma(source, length, type) => switch type "SMA" => ta.sma(source, length) "EMA" => ta.ema(source, length) "SMMA (RMA)" => ta.rma(source, length) "WMA" => ta.wma(source, length) "VWMA" => ta.vwma(source, length) MA1 = ma(src1, len1, typeMA1) MA2 = ma(src2, len2, typeMA2) MA3 = ma(src3, len3, typeMA3) MA4 = ma(src4, len4, typeMA4) MA5 = ma(src5, len5, typeMA5) MA6 = ma(src6, len6, typeMA6) // Calculating MACD fast_ma = ta.ema(src_macd, fast_length) slow_ma = ta.ema(src_macd, slow_length) macd = fast_ma - slow_ma signal = ta.ema(macd, signal_length) //hist = macd - signal // CHECK CONDITION ENTRY bool check_macd_buy = ( macd > signal and macd > 0 and ta.lowest(macd,25) < 0 ) bool check_macd_sell = ( macd < signal and macd < 0 and ta.highest(macd,25) > 0 ) bool check_ma_buy = ta.crossunder(MA5,MA6) and MA3 > MA4 and ( close > MA1 or close > MA2 ) and ( MA3>MA1 or MA3>MA2 ) and ta.lowest(MA3-MA4,20)<0 bool check_ma_sell = ta.crossover(MA5,MA6) and MA3 < MA4 and ( close < MA1 or close < MA2 ) and ( MA3<MA1 or MA3<MA2 ) and ta.highest(MA3-MA4,20)>0 bool check_ma_buy2 = ( close > MA1 or close > MA2 ) and ta.crossover(MA3,MA4) and ta.lowest(MA3-MA4,20)<0 bool check_ma_sell2 = ( close < MA1 or close < MA2 ) and ta.crossunder(MA3,MA4) and ta.highest(MA3-MA4,20)>0 // Check entry buy bool buy= check_macd_buy and ( check_ma_buy or check_ma_buy2 ) if buy alert( (str.format("Folow BUY {0} {1}m \n ", syminfo.ticker, timeframe.period )), alert.freq_once_per_bar_close) //str.format("Folow {0} Buy {1}m \n ", syminfo.ticker, timeframe.period // Check entry sell bool sell = check_macd_sell and ( check_ma_sell or check_ma_sell2 ) if sell alert( (str.format("Folow SELL {0} {1}m \n ", syminfo.ticker, timeframe.period )), alert.freq_once_per_bar_close) /////// p_ma1=plot(MA1, title="MA1", color=color.rgb(0, 20, 204, 100)) p_ma2=plot(MA2, title="MA2", color=color.rgb(19, 108, 1, 100)) p_ma3=plot(MA3, title="MA3", color=color.rgb(243, 33, 33, 100)) p_ma4=plot(MA4, title="MA4", color=color.rgb(0, 125, 10, 100)) fill(p_ma1, p_ma2, color = MA1 > MA2 ? color.rgb(255, 233, 35, 55) : color.rgb(255, 233, 35, 55)) fill(p_ma3, p_ma4, color = MA3 > MA4 ? color.rgb(255, 255, 255, 35) : color.rgb(80, 80, 80, 35)) plotchar( buy, "Go Long", "⚑", location.belowbar, color.lime, size = size.small) plotchar( sell, "Go Short", "⚑", location.abovebar, color.red, size = size.small)
Bull Flag Detection
https://www.tradingview.com/script/Dx8OMONZ-Bull-Flag-Detection/
xfuturesgod
https://www.tradingview.com/u/xfuturesgod/
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/ // © xfuturesgod //@version=5 indicator("Bull Flag Detection", overlay = true) // Get user input lookback = input.int(title="Percentage Gain Lookback", defval=20, step=1, tooltip="Lookback period for determining percentage gain threshold") emaMainLength = input.int(title="Longterm EMA Length", defval=200, minval=1) emaDSR1Length = input.int(title="DSR 1 EMA Length", defval=50, minval=1) emaDSR2Length = input.int(title="DSR 2 EMA Length", defval=20, minval=1) percentThreshold = input.float(title="Percentage Treshold", defval = 1.0, tooltip = "Percent gain for determining valid flag pole") swingHighLookback = input.int(title ="Swing High Lookback", defval = 10, tooltip = "Lookback period for determining swing highs") swingLowLookback = input.int(title ="Swing Low Lookback", defval = 10, tooltip = "Lookback period for determining swing lows") // Get moving averages ema200 = ta.ema(close, emaMainLength) ema100 = ta.ema(close,100) ema50 = ta.ema(close, emaDSR1Length) ema20 = ta.ema(close, emaDSR2Length) // Declare variables to detect swing highs and swing lows swingHigh = high[1] == ta.highest(high, 10) and high < high[1] swingLow = low[1] == ta.lowest(low, 10) and low > low[1] // Are we in a short term bull trend or bear trend? bearTrend = ema200 > ema50 and ema50 > ema20 // Bearish trend bullTrend = ema200 < ema50 and ema50 < ema20 // Bullish trend // Draw invisible plot lines required for zone color fill. zone1 = plot(ema20, color=na) zone2 = plot(ema50, color=na) // Fill zone fill(zone1, zone2, color=bullTrend ? color.new(color.blue, 75) : na) // Draw long-term EMA plot(ema200, color=bullTrend ? color.blue : na, linewidth=2) flagPole = (((close - low[lookback]) / low[lookback]) * 100 > percentThreshold) flagPoleStart = not flagPole[1] and flagPole flagPoleEnd = flagPole[1] and not flagPole var x1Array = array.new_int(5, math.round(close)) var x2Array = array.new_int(5, math.round(close)) var y1Array = array.new_float(5, close) var y2Array = array.new_float(5, close) var searchingForLow = false var float highestHigh = na // Initialize the highest high tracker var bool searchingforHigh1 = na var searchingForHigh2 = false var float flagResistance1 = na var float flagResistance2 = na var bool flagComplete = false barsSincePoleStart = ta.barssince(flagPoleStart) barsSincePoleEnd = ta.barssince(flagPoleEnd) polePeriod = barsSincePoleEnd - barsSincePoleStart flagLowDetected = searchingForLow and swingLow flagHighDetected = searchingForHigh2 and swingHigh flagFinished = flagComplete and not flagComplete[1] if flagPoleStart label.new(bar_index, high, text="Flag Pole", style=label.style_label_down, color=color.rgb(192, 238, 194), yloc=yloc.abovebar) searchingForLow := false searchingforHigh1 := true highestHigh := high // Reset the highest high at the start of the flagpole if searchingforHigh1 if high > highestHigh highestHigh := high if flagPoleEnd searchingForLow := true searchingforHigh1 := false array.push(y1Array, highestHigh) array.push(x1Array, bar_index) if flagLowDetected searchingForLow := false if flagLowDetected searchingForHigh2 := true if flagHighDetected and searchingForHigh2 searchingForHigh2 := false flag = searchingforHigh1 or searchingForLow or searchingForHigh2 bgcolor(flag ? color.new(color.green, 90) : na, title="Flag Highlight") plotshape(flagPoleStart, "FP", style = shape.triangledown, location = location.abovebar, color = color.rgb(192, 238, 194))
Treasury Yields Heatmap [By MUQWISHI]
https://www.tradingview.com/script/Y6x4NEm5-Treasury-Yields-Heatmap-By-MUQWISHI/
MUQWISHI
https://www.tradingview.com/u/MUQWISHI/
38
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("Treasury Yields Heatmap", overlay = true) // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | 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", "Table Size   ", ["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], inline = "2", group = "Table Setting") // Table Color tBgCol = input.color(#696969, " Title", group = "Table Setting", inline = "1") txtCl1 = input.color(#ffffff, " Text​ ​", group = "Table Setting", inline = "2") upCol = input.color(#006400, "Cell ", group = "Table Setting", inline = "3") mdCol = input.color(#FFEF00, " ", group = "Table Setting", inline = "3") dnCol = input.color(#882336, " ", group = "Table Setting", inline = "3") txtCl2 = input.color(#000000, "  Text ", group = "Table Setting", inline = "3") // +++++++++++++++ Technical Setting contry = input.string("United States", "Country", ["Australia", "Brazil", "Canada", "China", "Euro", "France", "Germany", "India", "Indonesia", "Italy", "Japan", "Russia", "South Africa", "South Korea", "United Kingdom", "United States"], group = "Technical Setting") timFrm = input.string("Quarterly", "Timeframe", ["Yearly", "Quarterly", "Monthly", "Weekly", "Daily"], group = "Technical Setting") calMod = input.string("Period", "Fetch By", ["Date", "Period"], group = "Technical Setting") sDate = input.time(timestamp("01 Jan 2019 00:00"), " ‣ Date", group = "Technical Setting") sPerd = input.int(25, " ‣ Period", 1, 200, group = "Technical Setting") // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | CALCULATION | // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| code = switch contry "United States" => "US" "Euro" => "EU" "United Kingdom" => "GB" "Germany" => "DE" "France" => "FR" "Italy" => "IT" "Canada" => "CA" "Japan" => "JP" "India" => "IN" "China" => "CN" "Indonesia" => "ID" "Australia" => "AU" "Brazil" => "BR" "Russia" => "RU" "South Korea" => "KR" "South Africa" => "ZA" "Turkey" => "TR" //++++++++++ Pearson Correlation pearson(x) => // Clean NaNs in Matrix a = array.new<float>(0) if array.size(x) > 0 for i = 1 to x.size() - 1 val = x.get(i) if not na(val) a.push(val) // Calculate Pearson Correlation r = float(na) if array.size(a) > 3 n = a.size() X = 0.0, Y = 0.0, for i = 0 to n - 1 X += i, Y += array.get(a, i) Xmean = X/n, Ymean = Y/n XY = 0.0, X2 = 0.0, Y2 = 0.0 for i = 0 to n - 1 XY += (i - Xmean) * (a.get(i) - Ymean) X2 += math.pow(i - Xmean, 2) Y2 += math.pow(a.get(i) - Ymean, 2) // Pearson Correlation Coefficient r := XY / math.sqrt(X2 * Y2) r //++++++++++ Main function main() => var cls = array.new<float>(na) var tim = array.new<float>(na) if calMod == "Date" ? time >= sDate : true cls.unshift(math.round_to_mintick(close)) tim.unshift(int(time/100000)) if calMod == "Date" ? cls.size() > 200 : cls.size() > sPerd cls.pop() tim.pop() [cls, tim] //++++++++++ Collect Data // Title Array titl = array.new<string>(na) // Security Function call(sym, nm) => tf = timFrm == "Yearly" ? "12M" : timFrm == "Quarterly" ? "3M" : timFrm == "Monthly" ? "1M" : timFrm == "Weekly" ? "1W" : "1D" [cls, tim] = request.security(sym, tf, main(), ignore_invalid_symbol = true) c = array.new<float>(0) t = array.new<float>(0) if not na(cls) array.push(titl, nm) c := cls t := tim [c, t] // Import Data [mn01, tmn01] = call(code + "01MY", "1Mo"), [mn03, tmn03] = call(code + "03MY", "3Mo"), [mn06, tmn06] = call(code + "06MY", "6Mo"), [yr01, tyr01] = call(code + "01Y", "1Yr"), [yr03, tyr03] = call(code + "03Y", "3Yr"), [yr05, tyr05] = call(code + "05Y", "5Yr"), [yr07, tyr07] = call(code + "07Y", "7Yr"), [yr10, tyr10] = call(code + "10Y", "10Yr"), [yr30, tyr30] = call(code + "30Y", "30Yr"), // Add "Date" & "Yield Curve" Columns to title array array.unshift(titl, "Date") array.push(titl, "Yield Curve") //++++++++++ Build Matrix cols = titl.size() -1 rows = math.max(mn01.size(), mn03.size(), mn06.size(), yr01.size(), yr03.size(), yr05.size(), yr07.size(), yr10.size(), yr30.size()) mtx = matrix.new<float>(rows, cols, na) addMtx(r, tim, nCol, x, y) => if x.size() > 0 and y.size() > 0 idx = array.indexof(y, mtx.get(r, 0)) if idx > 0 mtx.set(r, titl.indexof(nCol), array.get(x, idx)) else if mtx.get(r, 0) - y.get(0) == 0 mtx.set(r, titl.indexof(nCol), x.get(0)) if barstate.islast if rows > 0 // Fill 1st Cell with Time if rows == yr30.size() mtx.add_col(0, tyr30) else if rows == yr10.size() mtx.add_col(0, tyr10) else if rows == yr07.size() mtx.add_col(0, tyr07) else if rows == yr05.size() mtx.add_col(0, tyr05) else if rows == yr03.size() mtx.add_col(0, tyr03) else if rows == yr01.size() mtx.add_col(0, tyr01) else if rows == mn06.size() mtx.add_col(0, tmn06) else if rows == mn03.size() mtx.add_col(0, tmn03) else if rows == mn01.size() mtx.add_col(0, tmn01) for r = 0 to rows - 1 tim = mtx.get(r, 0) // Fill Matrix With Bonds addMtx(r, tim, "1Mo", mn01, tmn01), addMtx(r, tim, "3Mo", mn03, tmn03), addMtx(r, tim, "6Mo", mn06, tmn06), addMtx(r, tim, "1Yr", yr01, tyr01), addMtx(r, tim, "3Yr", yr03, tyr03), addMtx(r, tim, "5Yr", yr05, tyr05), addMtx(r, tim, "7Yr", yr07, tyr07), addMtx(r, tim, "10Yr", yr10, tyr10), addMtx(r, tim, "30Yr", yr30, tyr30), // Find Pearson Coefficient and add it. mtx.set(r, cols, pearson(mtx.row(r))) // |++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++| // | 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 tbl = table.new(locNsze(tablePos), cols+1, rows+2, color.new(tBgCol, 100), color.new(tBgCol, 100), 1, color.new(tBgCol, 100), 1) // Get Cell Function cell(col, row, txt, color, txtCol) => table.cell(tbl, col, row, text = txt, text_color = txtCol, bgcolor = color, text_size = locNsze(tableSiz)) // Get Cell Color cellCol(max, min, val) => avg = (min + max)/2 if val > avg color.from_gradient(val, avg, max, mdCol, upCol) else if val <= avg color.from_gradient(val, min, avg, dnCol, mdCol) else tBgCol // Get Time Format timeFrm(x) => mnNm = array.from("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") frmt = timFrm == "Yearly" ? "yyyy" : timFrm == "Quarterly" or timFrm == "Monthly" ? "MM-yyyy" : "dd-MM-yyyy" out = str.format_time(int(x*100000)+86400000, frmt, syminfo.timezone) out := timFrm == "Quarterly" or timFrm == "Monthly" ? mnNm.get(int(str.tonumber(str.split(out, "-").get(0)))-1) + "-" + str.split(out, "-").get(1) : out // Get Yield Status yield(x) => out = x >= 0.7 ? "Normal" : x < 0.7 and x >= 0.35 ? "Slight Normal" : x <= -0.7 ? "Inverted" : x > -0.7 and x <= -0.35 ? "Slight Inverted" : "Flat" if barstate.islast and rows > 0 if mtx.rows() > 0 //+++++++ Find Min & Max m = mtx.submatrix(0, mtx.rows()-1, 1, mtx.columns()-2) maxVal = m.max() minVal = m.min() //+++++++ Fill Table y = 0 // Header cell(0, y, (str.contains(contry, " ") ? "The ": "") + contry + " Treasury Yields " + timFrm + " Intervals: " + timeFrm(mtx.get(rows - 1, 0)) +" To "+ timeFrm(mtx.get(0, 0)), tBgCol, txtCl1), table.merge_cells(tbl, 0, 0, cols, 0), y += 1 // Title Columns for i = 0 to cols cell(i, y, titl.get(i), tBgCol, txtCl1) y += 1 // Cells for j = 0 to rows - 1 for i = 0 to cols if i == 0 cell(i, y, timeFrm(mtx.get(j, i)), tBgCol, txtCl1) else if i == cols val = mtx.get(j, i) cell(i, y, na(val) ? "" : yield(val), cellCol(1, -1, val), txtCl2) else val = mtx.get(j, i) cell(i, y, na(val) ? "" : str.tostring(val) + "%", cellCol(maxVal, minVal, val), txtCl2) y += 1
High and low of last D, W, 4W and quater
https://www.tradingview.com/script/f1deQeCR/
Remote-Trading
https://www.tradingview.com/u/Remote-Trading/
29
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/ // © Remote Trading //@version=5 indicator("D, W and 4W H/L", overlay=true, max_lines_count=500, max_bars_back=5000) daily_width = input.int(1, title = "Daily - Width", inline = "daily line", group="Line config") weekly_width = input.int(2, title = "Weekly - Width", inline="weekly line", group="Line config") four_weekly_width = input.int(3, title = "4 Weekly - Width", inline="4 weekly line", group="Line config") quarterly_width = input.int(3, title = "Quaterly - Width", inline="quaterly line", group="Line config") daily_style_string = input.string("Solid", "Style", ["Solid", "Dashed", "Dotted"], inline = "daily line", group="Line config") weekly_style_string = input.string("Dashed", "Style", ["Solid", "Dashed", "Dotted"], inline="weekly line", group="Line config") four_weekly_style_string = input.string("Dotted", "Style", ["Solid", "Dashed", "Dotted"], inline="4 weekly line", group="Line config") quaterly_style_string = input.string("Dashed", "Style", ["Solid", "Dashed", "Dotted"], inline="quaterly line", group="Line config") daily_color = input.color(color.rgb(141, 20, 255), "", inline = "daily line", group="Line config") weekly_color = input.color(#00a800, "", inline="weekly line", group="Line config") four_weekly_color = input.color(#0734ff, "", inline="4 weekly line", group="Line config") quaterly_color = input.color(#801922, "", inline="quaterly line", group="Line config") parseStyle(input) => (input == "Solid" ? line.style_solid : (input == "Dashed" ? line.style_dashed : (input == "Dotted" ? line.style_dotted : na))) input_n_daily_sr = input.int(defval=3, minval=0, maxval=10, title="Number of daily H/L", group="Number of lines to show") input_n_weekly_sr = input.int(defval=3, minval=0, maxval=10, title="Number of weekly H/L", group="Number of lines to show") input_show_4weekly = input.bool(true, "Show 4 weekly H/L", group="Number of lines to show") input_show_quaterly = input.bool(true, "Show quaterly H/L", group="Number of lines to show") input_futur_extension = input.int(defval=10, minval=0, title="N bars to extend lines into future", group="Other things") plot_in_radius_only = input.bool(defval=true, title="Plot within the range of X pip/ticks from current price:", inline="radius", group="Other things") pip_radius = input.int(defval=1000, minval=1, title="", inline="radius", tooltip = "The default value usually works quite well but if you notice lines are missing and you would like to have them shown experiment with the value.", group="Other things") skip_overlapping_lower_lines = input.bool(defval=true, title="Don't plot overlapping lines again", inline="overlap", group="Other things") line_skip_radius = input.float(defval=2, minval=0, step=0.5, title="Min pip/tick distance", inline="overlap", group="Other things") showlabels = input.bool(true, "Show labels", inline="Labels") highSymbol = input.string("▲", title="| High", options=["▲", "△"], inline="Labels") lowSymbol = input.string("▽", title="Low", options=["▼", "▽"], inline="Labels") daily_style = parseStyle(daily_style_string) weekly_style = parseStyle(weekly_style_string) four_weekly_style = parseStyle(four_weekly_style_string) quarterly_style = parseStyle(quaterly_style_string) var lines = array.new_line() var labels = array.new_label() for idx=0 to array.size(lines) if array.size(lines) > 0 ln = array.shift(lines) line.delete(ln) for idx=0 to array.size(labels) if array.size(labels) > 0 lab = array.shift(labels) label.delete(lab) //https://www.tradingview.com/pine-script-docs/en/v4/essential/Drawings.html#max-bars-back-of-time max_bars_back(time, 5000) check_for_existing_line(new_line_price) => bool result = true for index=0 to array.size(lines) if array.size(lines) > index ln = array.get(lines, index) prev_line_y = line.get_y1(ln) if math.abs(new_line_price - prev_line_y) < syminfo.mintick * line_skip_radius result := false break result log.info(str.tostring(syminfo.mintick*pip_radius)) generte_lines(index, timeframe, h_or_l, style, color_, width, labelText) => dh = request.security(syminfo.tickerid, timeframe, h_or_l[index], barmerge.gaps_off, barmerge.lookahead_on) if barstate.islast and (math.abs(dh - close) < syminfo.mintick*pip_radius or not plot_in_radius_only) counter = 0 for ii = 0 to 4990 //specificDate = time[ii] < timestamp(year, month, dayofmonth-2, 18, 00) if h_or_l[ii] == dh counter := ii break if check_for_existing_line(dh) or not skip_overlapping_lower_lines lineID = line.new(bar_index-counter, dh, bar_index+input_futur_extension, dh, color=color_, style=style, width=width) array.push(lines, lineID) if showlabels labelID = label.new(x=bar_index+input_futur_extension, y=dh, color=color.rgb(179, 179, 179, 63), textcolor=color.black, style=label.style_label_left, size=size.small) label.set_text(labelID, text=labelText) array.push(labels, labelID) apply_lines_for_HL(index, timeframe, style, color_, width) => generte_lines(index, timeframe, high, style, color_, width, timeframe + " " + highSymbol + " -" + str.tostring(index)) generte_lines(index, timeframe, low, style, color_, width, timeframe + " " + lowSymbol + " -" + str.tostring(index)) if input_show_quaterly apply_lines_for_HL(1, "3M", quarterly_style, quaterly_color, quarterly_width) if input_show_4weekly apply_lines_for_HL(1, "4W", four_weekly_style,four_weekly_color, four_weekly_width) if input_n_weekly_sr >= 1 apply_lines_for_HL(2, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 2 apply_lines_for_HL(3, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 3 apply_lines_for_HL(4, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 4 apply_lines_for_HL(5, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 5 apply_lines_for_HL(6, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 6 apply_lines_for_HL(7, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 7 apply_lines_for_HL(8, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 8 apply_lines_for_HL(9, "W", weekly_style, weekly_color, weekly_width) if input_n_weekly_sr >= 9 apply_lines_for_HL(10, "W", weekly_style, weekly_color, weekly_width) if input_n_daily_sr >= 1 apply_lines_for_HL(1, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 2 apply_lines_for_HL(2, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 3 apply_lines_for_HL(3, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 4 apply_lines_for_HL(4, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 5 apply_lines_for_HL(5, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 6 apply_lines_for_HL(6, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 7 apply_lines_for_HL(7, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 8 apply_lines_for_HL(8, "D", daily_style, daily_color, daily_width) if input_n_daily_sr >= 9 apply_lines_for_HL(9, "D", daily_style, daily_color, daily_width)
S/R and Reversal Bars
https://www.tradingview.com/script/5tVfClLl-S-R-and-Reversal-Bars/
Pratik_4Clover
https://www.tradingview.com/u/Pratik_4Clover/
80
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/ // © Pratik_4Clover //@version=5 indicator("S/R and Reversal Bars", shorttitle="RB",overlay=true, max_bars_back=500) ShowSR=input(true, title="Show S/R levels") cci = ta.cci(close, 20) ccih = cci >= 200 ccil = cci <= -200 CcColor = ccih ? color.yellow : ccil ? color.white : na plotshape(ccih, style=shape.triangleup, location=location.abovebar, color=CcColor, title='CCI+', editable=false, size=size.auto) plotshape(ccil, style=shape.triangledown, location=location.belowbar, color=CcColor, title='CCI-', editable=false, size=size.auto) ccihcu = ta.crossunder(cci, 180) ccilcu = ta.crossover(cci, -180) plotshape(ccihcu, style=shape.circle, location=location.abovebar, color=color.new(#ff1100, 0), title='CCI+180', editable=false, size=size.auto) plotshape(ccilcu, style=shape.circle, location=location.belowbar, color=color.new(color.lime, 0), title='CCI-180', editable=false, size=size.auto) // Add high and low candle zones var highZone = high var lowZone = low var flag = false for i = 0 to bar_index if ccilcu[i] lowZone := low[i] flag := true break else if ccihcu[i] highZone := high[i] flag := true break if flag break plot(ShowSR ? highZone :na, title="High Zone", color=color.red, style=plot.style_cross, linewidth=2, editable=false, show_last=150) plot(ShowSR ? lowZone :na , title="Low Zone", color=color.lime, style=plot.style_cross, linewidth=2, editable=false, show_last=150) ccihcu2 = ta.crossover(cci, 70) ccilcu2 = ta.crossunder(cci, -70) var highZone2 = high var lowZone2 = low var flag2 = false for i = 0 to bar_index if ccilcu2[i] lowZone2 := low[i] flag2 := true break else if ccihcu2[i] highZone2 := high[i] flag2 := true break plot(ShowSR ? highZone2 :na, title="High Zone", color=color.orange, style=plot.style_circles, linewidth=1, editable=false, show_last=150) plot(ShowSR ? lowZone2 :na, title="Low Zone", color=color.green, style=plot.style_circles, linewidth=1, editable=false, show_last=150) //..zero zerocci=ta.crossunder(ta.cci(close, 20), -0) var cent = hl2 var flag3 = false for i = 0 to bar_index if zerocci[i] cent := low[i] flag3 := true break plot(ShowSR ? cent :na, title="Central", color=color.new(color.yellow,0), style=plot.style_circles, linewidth=1, editable=false, show_last=150)
BarChangeDelta
https://www.tradingview.com/script/R9IBnj1K-BarChangeDelta/
vpirinski
https://www.tradingview.com/u/vpirinski/
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/ // © vpirinski //@version=5 //#region *********** DESCRIPTION *********** //==================================================================================================================== // The "BarChangeDelta" indicator, facilitates the calculation of price delta or percent changes between user-defined start and end points // within the current or between preceding and current bars. It offers several customizable options to fit various trading strategies. // ================================================== INFO ================================================== // This indicator provides the following key functionalities: // - Two Modes: // * PreviousToCurrentBarDelta: Compares user-selected start points from the previous bar to the end points of the current bar. // * CurrentBarDelta: Compares user-selected start and end points within the current bar. // - Start Point/End Point Customization: Allows users to define the source for start and end points used in the delta calculations. // - ABS Mode: Option to display only absolute values, reflected on the histogram drawn. // - Show delta in percents: Enables users to calculate delta in percentage changes instead of price delta. // - Moving Average (MA) Plot: A plot of the MA of the last user-defined number of delta prices or percents. // ================================================== NOTES ================================================== //The "BarChangeDelta" indicator finds practical application in various trading scenarios. It can be particularly useful for: //- Assessing daily price changes between open/close or high/low for determining strike prices, especially for 0DTE trading. //#endregion ======================================================================================================== //#region *********** SETUP *********** indicator( title = "BarChangeDelta", shorttitle = "BarChangeDelta", overlay = false ) //#endregion ======================================================================================================== //#region *********** LIBRARIES *********** import HeWhoMustNotBeNamed/enhanced_ta/14 as eta //#endregion ======================================================================================================== //#region *********** USER_INPUT *********** var string INDICATOR_GROUP_STR = "Inputs" i_mode = input.string (title = "Mode", defval = "CurrentBarDelta", group = INDICATOR_GROUP_STR, options = ["PreviousToCurrentBarDelta", "CurrentBarDelta"]) i_start_price = input.source (title = "Start Point", defval = close, group = INDICATOR_GROUP_STR) i_end_price = input.source (title = "End Point", defval = open, group = INDICATOR_GROUP_STR) i_abs_mode = input.bool (title = "ABS mode", defval = true, group = INDICATOR_GROUP_STR, tooltip = "Histogram plots ABS delta (only positive)") i_delta_in_percents = input.bool (title = "Show delta in percents", defval = false, group = INDICATOR_GROUP_STR) var string DELTA_HISTOGRAM_STR = "Histogram" i_ma_type = input.string (title = "MA type", group = DELTA_HISTOGRAM_STR, defval = "ema", options = ["ema", "sma", "rma", "hma", "wma", "vwma", "swma"]) i_ma_length = input.int (title = "Fast MA Length", group = DELTA_HISTOGRAM_STR, defval = 12) i_col_grow_above = input (#26A69A, "Above   Grow", group=DELTA_HISTOGRAM_STR, inline="Above") i_col_fall_above = input (#B2DFDB, "Fall", group=DELTA_HISTOGRAM_STR, inline="Above") i_col_grow_below = input (#FFCDD2, "Below Grow", group=DELTA_HISTOGRAM_STR, inline="Below") i_col_fall_below = input (#FF5252, "Fall", group=DELTA_HISTOGRAM_STR, inline="Below") //#endregion ======================================================================================================== //#region *********** LOGIC *********** end_price = (i_mode == "CurrentBarDelta") ? i_end_price : i_end_price[1] start_price = i_start_price delta = start_price - end_price delta_abs = math.abs(delta) delta_perc = (start_price - end_price)/end_price * 100 delta_perc_abs = math.abs(delta_perc) delta_plot = (i_delta_in_percents == true and i_abs_mode == true) ? delta_perc_abs : ( i_delta_in_percents == true and i_abs_mode == false) ? delta_perc : ( i_delta_in_percents == false and i_abs_mode == true) ? delta_abs : delta //(i_delta_in_percents == false and i_abs_mode == false) delta_hist_color = i_delta_in_percents ? (delta_perc>=0 ? (delta_perc[1] < delta_perc ? i_col_grow_above : i_col_fall_above) : (delta_perc[1] < delta_perc ? i_col_grow_below : i_col_fall_below)) : (delta>=0 ? (delta[1] < delta ? i_col_grow_above : i_col_fall_above) : ( delta[1] < delta ? i_col_grow_below : i_col_fall_below)) ma = eta.ma(source = i_delta_in_percents ? delta_perc_abs : delta_abs, maType = i_ma_type, length = i_ma_length) //#endregion ======================================================================================================== //#region *********** DEBUG_&_PLOTS *********** hline(price = 0, title = "Zero Line", color=color.new(#787B86, 50)) plot( series = delta_plot, title = "Histogram", style = plot.style_columns, color = delta_hist_color ) plot( series = ma, title = "Delta MA", style = plot.style_line, color = color.white) //#endregion ========================================================================================================
[dharmatech] : Toggle Monthly Candles
https://www.tradingview.com/script/DhOSJWV6-dharmatech-Toggle-Monthly-Candles/
dharmatech
https://www.tradingview.com/u/dharmatech/
8
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(title = "Toggle Monthly Candles", overlay = false) toggle_jan = input.bool(defval = true) toggle_feb = input.bool(defval = false) toggle_mar = input.bool(defval = false) toggle_apr = input.bool(defval = false) toggle_may = input.bool(defval = false) toggle_jun = input.bool(defval = false) toggle_jul = input.bool(defval = false) toggle_aug = input.bool(defval = false) toggle_sep = input.bool(defval = false) toggle_oct = input.bool(defval = false) toggle_nov = input.bool(defval = false) toggle_dec = input.bool(defval = false) check() => ((month(time) == 1) and (toggle_jan)) or ((month(time) == 2) and (toggle_feb)) or ((month(time) == 3) and (toggle_mar)) or ((month(time) == 4) and (toggle_apr)) or ((month(time) == 5) and (toggle_may)) or ((month(time) == 6) and (toggle_jun)) or ((month(time) == 7) and (toggle_jul)) or ((month(time) == 8) and (toggle_aug)) or ((month(time) == 9) and (toggle_sep)) or ((month(time) == 10) and (toggle_oct)) or ((month(time) == 11) and (toggle_nov)) or ((month(time) == 12) and (toggle_dec)) plotcandle( open =check() ? open : na, high =check() ? high : na, low =check() ? low : na, close=check() ? close : na, color=close > open ? color.green : color.red)
Sector relative strength and correlation by Kaschko
https://www.tradingview.com/script/tuUm6Dow-Sector-relative-strength-and-correlation-by-Kaschko/
Kaschko
https://www.tradingview.com/u/Kaschko/
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/ // © Kaschko //@version=5 indicator("Sector RS/Corr", overlay = false, format = format.percent, max_lines_count = 500) // A sector is defined as follows. Aliases and the symbol suffix are optional. // // Sector name:Symbol suffix:Comma separated list of Symbol[Alias] // // Examples: // // "Energies:1!:CL,HO,NG,RB" // This defines the sector "Energies" using continous futures contracts of crude oil,heating oil,natural gas and gasoline // // "Currencies::AXY[AUD],BXY[GBP],CXY[CAD],EXY[EUR],JXY[JPY],ZXY[NZD],SXY[CHF],DXY[USD]" // This defines the sector "Currencies" using various currency indices, creating a simple currency strength meter // Display _sector = input.string(group = "Display", title = "Sector", options = ["Auto-select","Sector #1","Sector #2","Sector #3","Sector #4","Sector #5","Sector #6","Sector #7","Sector #8","Sector #9","Sector #10"], defval = "Auto-select", display = display.none) _width = input.int (group = "Display", title = "Line width", defval = 3, minval = 1, maxval = 10, display = display.none) _showZL = input.bool (group = "Display", title = "Display zero line", defval = true, display = display.none) // Futures _usac = input.bool (group = "Futures", title = "Use settlement as close", defval = false, display = display.none) _ubac = input.bool (group = "Futures", title = "Use back-adjusted contracts", defval = false, display = display.none) // Sectors _sector01 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #1" , defval = "Energies:1!:CL,HO,NG,RB", display = display.none) _sector02 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #2" , defval = "Currencies:1!:6A,6B,6C,6E,6J,6M,6N,6S", display = display.none) _sector03 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #3" , defval = "Metals:1!:GC,HG,PA,PL,SI", display = display.none) _sector04 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #4" , defval = "Meats:1!:GF,HE,LE", display = display.none) _sector05 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #5" , defval = "Softs:1!:LBR,CC,CT,KC,OJ,SB", display = display.none) _sector06 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #6" , defval = "Indices:1!:ES,NQ,YM,RTY", display = display.none) _sector07 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #7" , defval = "Interest:1!:ZB,ZN,ZF,ZT", display = display.none) _sector08 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #8" , defval = "Grains:1!:ZC,ZL,ZM,ZO,ZR,ZS,ZW", display = display.none) _sector09 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #9" , defval = "Crypto:1!:BTC,ETH", display = display.none) _sector10 = input.string(group = "Sector:Suffix:Symbols(comma separated)", title = "Sector #10", defval = "Custom::AAPL,GOOG,META,MSFT", display = display.none) // Legend _lgndX = input.string(group = "Legend" , title = "Horizontal position", options = ["left","center","right"], defval = "right", display = display.none) _lgndY = input.string(group = "Legend" , title = "Vertical position", options = ["top","middle","bottom"], defval = "top", display = display.none) _tsize = input.string(group = "Legend" , title = "Font size", options = ["auto","tiny","small", "normal", "large", "huge"], defval = "auto", display = display.none) var bool _auto = _sector == "Auto-select" _color00 = input.color(group = "Colors", title = "Symbol #1" , defval = #9B05AF) _color01 = input.color(group = "Colors", title = "Symbol #2" , defval = #098EE3) _color02 = input.color(group = "Colors", title = "Symbol #3" , defval = #F01F9E) _color03 = input.color(group = "Colors", title = "Symbol #4" , defval = #8CDD53) _color04 = input.color(group = "Colors", title = "Symbol #5" , defval = #F3D721) _color05 = input.color(group = "Colors", title = "Symbol #6" , defval = #258DAB) _color06 = input.color(group = "Colors", title = "Symbol #7" , defval = #FF9500) _color07 = input.color(group = "Colors", title = "Symbol #8" , defval = #C22106) _color08 = input.color(group = "Colors", title = "Symbol #9" , defval = #FB8667) _color09 = input.color(group = "Colors", title = "Symbol #10", defval = #47F090) var _fsize = switch _tsize "auto" => size.auto "tiny" => size.tiny "small" => size.small "normal" => size.normal "large" => size.large "huge" => size.huge var _a_color = array.from(_color00,_color01,_color02,_color03,_color04,_color05,_color06,_color07,_color08,_color09) // get comma separated list of symbols get_symbols(simple string _sect) => string _symbols = na i = str.length(_sect)-1 while i >= 0 if str.substring(_sect,i,i+1) == ":" _symbols := str.substring(_sect,i+1) break i := i - 1 // remove aliases, if any while str.contains(_symbols,"]") _p1 = str.pos(_symbols,"[") _p2 = str.pos(_symbols,"]") _symbols := str.substring(_symbols,0,_p1) + str.substring(_symbols,_p2+1) "," + _symbols + "," // get comma separated list of aliases get_aliases(simple string _sect) => string _symbols = na string _aliases = "," i = str.length(_sect)-1 while i >= 0 if str.substring(_sect,i,i+1) == ":" _symbols := str.substring(_sect,i+1) break i := i - 1 // extract aliases, if any while str.contains(_symbols,"]") _p1 = str.pos(_symbols,"[") _p2 = str.pos(_symbols,"]") _aliases := _aliases + str.substring(_symbols,_p1+1,_p2) + "," _symbols := str.substring(_symbols,_p2+1) if _aliases == "," _aliases := na _aliases simple string _s_sector01 = get_symbols(_sector01) simple string _s_sector02 = get_symbols(_sector02) simple string _s_sector03 = get_symbols(_sector03) simple string _s_sector04 = get_symbols(_sector04) simple string _s_sector05 = get_symbols(_sector05) simple string _s_sector06 = get_symbols(_sector06) simple string _s_sector07 = get_symbols(_sector07) simple string _s_sector08 = get_symbols(_sector08) simple string _s_sector09 = get_symbols(_sector09) simple string _s_sector10 = get_symbols(_sector10) simple string _s_aliases01 = get_aliases(_sector01) simple string _s_aliases02 = get_aliases(_sector02) simple string _s_aliases03 = get_aliases(_sector03) simple string _s_aliases04 = get_aliases(_sector04) simple string _s_aliases05 = get_aliases(_sector05) simple string _s_aliases06 = get_aliases(_sector06) simple string _s_aliases07 = get_aliases(_sector07) simple string _s_aliases08 = get_aliases(_sector08) simple string _s_aliases09 = get_aliases(_sector09) simple string _s_aliases10 = get_aliases(_sector10) // get nth symbol root from sector string (indexing starts with 0) get_root(simple string _symstr,simple int _idx) => int _nth = -1 int _len = str.length(_symstr) string _ret = na i = 0 // cannot use for loop and/or if statements due to their side effects while i < _len _chr = str.substring(_symstr,i,i+1) while _chr != "," and _nth == _idx _ret := _ret + _chr break while _chr == "," _nth := _nth + 1 break i := i + 1 _ret // get nth alias from sector string (indexing starts with 0) get_alias(simple string _aliasstr,simple int _idx) => int _nth = -1 int _len = str.length(_aliasstr) string _ret = na i = 0 // cannot use for loop and/or if statements due to their side effects while i < _len _chr = str.substring(_aliasstr,i,i+1) while _chr != "," and _nth == _idx _ret := _ret + _chr break while _chr == "," _nth := _nth + 1 break i := i + 1 _ret // get suffix of symbols in selected sector get_suffix(simple string _sect) => _sectstr = switch _sect "Sector #1" => _sector01 "Sector #2" => _sector02 "Sector #3" => _sector03 "Sector #4" => _sector04 "Sector #5" => _sector05 "Sector #6" => _sector06 "Sector #7" => _sector07 "Sector #8" => _sector08 "Sector #9" => _sector09 "Sector #10" => _sector10 _p1 = str.pos(_sectstr,":") + 1 _p2 = str.pos(str.substring(_sectstr,_p1),":") str.substring(_sectstr,_p1,_p1+_p2) // get symbol string for selected sector get_symstr(simple string _sect) => _symbols = switch _sect "Sector #1" => _s_sector01 "Sector #2" => _s_sector02 "Sector #3" => _s_sector03 "Sector #4" => _s_sector04 "Sector #5" => _s_sector05 "Sector #6" => _s_sector06 "Sector #7" => _s_sector07 "Sector #8" => _s_sector08 "Sector #9" => _s_sector09 "Sector #10" => _s_sector10 // get alias string for selected sector get_aliasstr(simple string _sect) => _symbols = switch _sect "Sector #1" => _s_aliases01 "Sector #2" => _s_aliases02 "Sector #3" => _s_aliases03 "Sector #4" => _s_aliases04 "Sector #5" => _s_aliases05 "Sector #6" => _s_aliases06 "Sector #7" => _s_aliases07 "Sector #8" => _s_aliases08 "Sector #9" => _s_aliases09 "Sector #10" => _s_aliases10 // get series get_series(int _no,string _sect) => _symbols = get_symstr(_sect) _root = get_root(_symbols,_no) _tpfix = '={"settlement-as-close":' + (_usac ? "true" : "false") + (_ubac ? ',"backadjustment":"default"' : '') + ',"symbol":"' _tsfix = get_suffix(_sect) + '"}' _ticker = _tpfix + _root + _tsfix // return series request.security(_ticker, timeframe.period, close, gaps = barmerge.gaps_on, ignore_invalid_symbol = true) // get sector of symbol get_sector(simple string _symbol) => _smbl = "," + _symbol + "," str.contains(_s_sector01 ,_smbl) ? "Sector #1" : str.contains(_s_sector02,_smbl) ? "Sector #2" : str.contains(_s_sector03,_smbl) ? "Sector #3" : str.contains(_s_sector04,_smbl) ? "Sector #4" : str.contains(_s_sector05,_smbl) ? "Sector #5" : str.contains(_s_sector06,_smbl) ? "Sector #6" : str.contains(_s_sector07,_smbl) ? "Sector #7" : str.contains(_s_sector08,_smbl) ? "Sector #8" : str.contains(_s_sector09,_smbl) ? "Sector #9" : str.contains(_s_sector10,_smbl) ? "Sector #10" : na // get name of sector get_sectname(simple string _sect) => _name = switch _sect "Sector #1" => str.substring(_sector01,0,str.pos(_sector01,":")) "Sector #2" => str.substring(_sector02,0,str.pos(_sector02,":")) "Sector #3" => str.substring(_sector03,0,str.pos(_sector03,":")) "Sector #4" => str.substring(_sector04,0,str.pos(_sector04,":")) "Sector #5" => str.substring(_sector05,0,str.pos(_sector05,":")) "Sector #6" => str.substring(_sector06,0,str.pos(_sector06,":")) "Sector #7" => str.substring(_sector07,0,str.pos(_sector07,":")) "Sector #8" => str.substring(_sector08,0,str.pos(_sector08,":")) "Sector #9" => str.substring(_sector09,0,str.pos(_sector09,":")) "Sector #10" => str.substring(_sector10,0,str.pos(_sector10,":")) var string _sect = _auto ? get_sector(syminfo.root) : _sector _sym00 = get_series(0,_sect) _sym01 = get_series(1,_sect) _sym02 = get_series(2,_sect) _sym03 = get_series(3,_sect) _sym04 = get_series(4,_sect) _sym05 = get_series(5,_sect) _sym06 = get_series(6,_sect) _sym07 = get_series(7,_sect) _sym08 = get_series(8,_sect) _sym09 = get_series(9,_sect) var _a_series = array.new<string>(0) var _a_aliases = array.new<string>(0) // close of left visible bar for all symbols in sector var float _start00 = na var float _start01 = na var float _start02 = na var float _start03 = na var float _start04 = na var float _start05 = na var float _start06 = na var float _start07 = na var float _start08 = na var float _start09 = na if time == chart.left_visible_bar_time _start00 := _sym00 _start01 := _sym01 _start02 := _sym02 _start03 := _sym03 _start04 := _sym04 _start05 := _sym05 _start06 := _sym06 _start07 := _sym07 _start08 := _sym08 _start09 := _sym09 _symbols = get_symstr (_sect) _aliases = get_aliasstr(_sect) if not na(_start00) array.push(_a_series ,get_root (_symbols,0)) array.push(_a_aliases,get_alias(_aliases,0)) if not na(_start01) array.push(_a_series ,get_root (_symbols,1)) array.push(_a_aliases,get_alias(_aliases,1)) if not na(_start02) array.push(_a_series ,get_root (_symbols,2)) array.push(_a_aliases,get_alias(_aliases,2)) if not na(_start03) array.push(_a_series ,get_root (_symbols,3)) array.push(_a_aliases,get_alias(_aliases,3)) if not na(_start04) array.push(_a_series ,get_root (_symbols,4)) array.push(_a_aliases,get_alias(_aliases,4)) if not na(_start05) array.push(_a_series ,get_root (_symbols,5)) array.push(_a_aliases,get_alias(_aliases,5)) if not na(_start06) array.push(_a_series ,get_root (_symbols,6)) array.push(_a_aliases,get_alias(_aliases,6)) if not na(_start07) array.push(_a_series ,get_root (_symbols,7)) array.push(_a_aliases,get_alias(_aliases,7)) if not na(_start08) array.push(_a_series ,get_root (_symbols,8)) array.push(_a_aliases,get_alias(_aliases,8)) if not na(_start09) array.push(_a_series ,get_root (_symbols,9)) array.push(_a_aliases,get_alias(_aliases,9)) plot(((_sym00/_start00)-1)*100, title = "Symbol #1" , color = _color00, linewidth = _width) plot(((_sym01/_start01)-1)*100, title = "Symbol #2" , color = _color01, linewidth = _width) plot(((_sym02/_start02)-1)*100, title = "Symbol #3" , color = _color02, linewidth = _width) plot(((_sym03/_start03)-1)*100, title = "Symbol #4" , color = _color03, linewidth = _width) plot(((_sym04/_start04)-1)*100, title = "Symbol #5" , color = _color04, linewidth = _width) plot(((_sym05/_start05)-1)*100, title = "Symbol #6" , color = _color05, linewidth = _width) plot(((_sym06/_start06)-1)*100, title = "Symbol #7" , color = _color06, linewidth = _width) plot(((_sym07/_start07)-1)*100, title = "Symbol #8" , color = _color07, linewidth = _width) plot(((_sym08/_start08)-1)*100, title = "Symbol #9" , color = _color08, linewidth = _width) plot(((_sym09/_start09)-1)*100, title = "Symbol #10", color = _color09, linewidth = _width) if barstate.islastconfirmedhistory // table var table _table = table.new(_lgndY + "_" + _lgndX, 1, array.size(_a_series)+1) table.cell(_table, 0, 0, get_sectname(_auto ? get_sector(syminfo.root) : _sector), text_size = _fsize, text_color = #ffffff, bgcolor = #868686) for i = 0 to array.size(_a_series)-1 _text = array.get(_a_aliases,i) if na(_text) _text := array.get(_a_series,i) table.cell(_table, 0, i+1, _text, text_size = _fsize, text_color = #ffffff, bgcolor = array.get(_a_color,i)) hline(_showZL ? 0 : na, title = "Zero", color = #868686, linewidth = 1)
Fair Value Gap Finder
https://www.tradingview.com/script/Qv19ddgG-Fair-Value-Gap-Finder/
sonnyparlin
https://www.tradingview.com/u/sonnyparlin/
9
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/ // © sonnyparlin //@version=5 // 5/20/2023 4:00pm updated chart image indicator("Fair Value Gap Finder", overlay = true) useVolume = input.bool(true, "Use Volume to determine FVGs (Recommended)") vr = input.int(2, "Volume must be X times average", step=1) vl = input.int(20, "Volume moving average length", step=1) ol = input.int(60, "Gap length", step=10) emaLength = input.int(20, "EMA Length", step=1) minGapSize = input.float(0.25, "Minimum Gap Size to show", step=0.01) ob = volume[1] > ta.sma(volume[1], vl) * vr sellFVGColor = input.color(color.new(color.red, 70)) buyFVGColor = input.color(color.new(color.green, 70)) buyFVGText = input.string("Buyers Fair Value Gap") sellFVGText = input.string("Sellers Fair Value Gap") textColor = input.color(color.new(color.black, 10)) sizeOption = input.string(title="Label Size", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], defval="Small") labelSize = (sizeOption == "Huge") ? size.huge : (sizeOption == "Large") ? size.large : (sizeOption == "Small") ? size.small : (sizeOption == "Tiny") ? size.tiny : (sizeOption == "Auto") ? size.auto : size.normal // initialize variables ema = ta.ema(close, emaLength) var buyVolume = 0.0 var sellVolume = 0.0 buyVolume := (high[1]==low[1]) ? 0 : volume[1] * (close[1]-low[1]) / (high[1]-low[1]) sellVolume := (high[1]==low[1]) ? 0 : volume[1] * (high[1]-close[1]) / (high[1]-low[1]) if useVolume if ob and buyVolume > sellVolume and high[2] < low and low - high[2] > minGapSize and close[1] > ema box.new(bar_index, high[2], bar_index + ol, low, border_color = color.new(color.black,100), bgcolor = buyFVGColor, text=buyFVGText, text_color = textColor, text_size = labelSize, text_halign = text.align_right) if ob and buyVolume < sellVolume and low[2] > high and low[2] - high > minGapSize and close[1] < ema box.new(bar_index, low[2], bar_index + ol, high, border_color = color.new(color.black,100), bgcolor = sellFVGColor, text=sellFVGText, text_color = textColor, text_size = labelSize, text_halign = text.align_right) else if high[2] < low and low - high[2] > minGapSize and close[1] > ema box.new(bar_index, high[2], bar_index + ol, low, border_color = color.new(color.black,100), bgcolor = buyFVGColor, text=buyFVGText, text_color = textColor, text_size = labelSize, text_halign = text.align_right) if low[2] > high and low[2] - high > minGapSize and close[1] < ema box.new(bar_index, low[2], bar_index + ol, high, border_color = color.new(color.black,100), bgcolor = sellFVGColor, text=sellFVGText, text_color = textColor, text_size = labelSize, text_halign = text.align_right)
Spot-Vol Correlation
https://www.tradingview.com/script/ib5cCDFu-Spot-Vol-Correlation/
DanJoa
https://www.tradingview.com/u/DanJoa/
24
study
4
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/ // © DanJoa //@version=4 study(title="Spot-Vol Correlation", shorttitle="Spot-Vol Corr", overlay=false) // Inputs symbol1 = input(defval="CBOE:VIX", title="First Symbol", type=input.symbol) symbol2 = input(defval="SPY", title="Second Symbol", type=input.symbol) length = input(defval=10, title="Length of Calculation Period", minval=1) upperBound = input(defval=-0.60, title="Upper Bound of Normal Zone", type=input.float) lowerBound = input(defval=-1.00, title="Lower Bound of Normal Zone", type=input.float) // Fetch data for the symbols asset1 = security(symbol1, timeframe.period, close) asset2 = security(symbol2, timeframe.period, close) // Calculate percentage change for both assets pct_change1 = (asset1 - asset1[1]) / asset1[1] * 100 pct_change2 = (asset2 - asset2[1]) / asset2[1] * 100 // Calculate correlation value correlationValue = correlation(pct_change1, pct_change2, length) // Determine plot color plotColor = (pct_change1 < 0 and pct_change2 > 0) or (pct_change1 > 0 and pct_change2 < 0) ? color.green : color.red // Plotting correlationPlot = plot(correlationValue, title="Correlation Coefficient", color=plotColor, linewidth=2) plot_upper = plot(upperBound, color=color.new(color.blue, 100)) // fully transparent (invisible) plot for upper bound plot_lower = plot(lowerBound, color=color.new(color.blue, 100)) // fully transparent (invisible) plot for lower bound // Fill normal zone fill(plot_upper, plot_lower, color=color.new(color.green, 90), title="Fill between Normal Zone") hline(0, "Zero", color=color.gray)
Trailing stop
https://www.tradingview.com/script/xU3HxfPx-Trailing-stop/
mickes
https://www.tradingview.com/u/mickes/
8
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/ // © mickes //@version=5 indicator("Trailing stop", overlay = true) _entryDefaultTime = 2147483647000 // max unix time _entryTime = input.time(_entryDefaultTime, "Time", group = "Entry") _stopSource = input.string("ATR", "Source", ["ATR", "EMA", "SMA", "Source"], group = "Stop") _atrFactor = input.float(3.5, "ATR factor", group = "ATR") _emaLength = input.int(21, "Length", group = "EMA") _smaLength = input.int(50, "Length", group = "SMA") _source = input.source(close, "Source", tooltip = "An input source can be used to trail the stop. When the signal returns a value (not na), the stop will happen.", group = "Source") type TrailStop float Entry float Limit = -1 int HitBarIndex var _trailingStop = TrailStop.new() enter() => if time == _entryTime _trailingStop.Entry := close trailStop() => float limit = na switch _stopSource "ATR" => limit := low - (ta.atr(14) * _atrFactor) "EMA" => limit := ta.ema(close, _emaLength) "SMA" => limit := ta.sma(close, _smaLength) "Source" => limit := not na(_source) ? 2147483647 : na if not na(_trailingStop.Entry) and limit > _trailingStop.Limit _trailingStop.Limit := limit trailStopHit() => if time != _entryTime and low < _trailingStop.Limit and na(_trailingStop.HitBarIndex) description = "" switch _stopSource "ATR" => description := str.format("ATR with factor {0}", _atrFactor) "EMA" => description := str.format("EMA with length {0}", _emaLength) "SMA" => description := str.format("SMA with length {0}", _smaLength) "Source" => description := "Source" message = str.format("Trailing stop hit ({0})", description) alert(message, alert.freq_once_per_bar) label.new(bar_index, high, str.format("Alert:\n{0}", message), color = color.new(color.red, 30)) _trailingStop.HitBarIndex := bar_index verifyStopSource() => if barstate.isfirst switch _stopSource "Source" => if _source == close runtime.error("Input source is default close") enter() verifyStopSource() trailStop() trailStopHit() middle = plot(hl2, "Middle", display = display.none) stop = plot(na(_trailingStop.HitBarIndex) and not na(_trailingStop.Entry) and _trailingStop.Limit != -1 ? _trailingStop.Limit : na, "Trailing stop", color.red, linewidth = 2) fill(middle, stop, color.new(color.red, 90))
Volumetric Toolkit [LuxAlgo]
https://www.tradingview.com/script/iSs4eqFJ-Volumetric-Toolkit-LuxAlgo/
LuxAlgo
https://www.tradingview.com/u/LuxAlgo/
886
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("Volumetric Toolkit [LuxAlgo]", "LuxAlgo - Volumetric Toolkit", overlay = true, max_lines_count = 500, max_boxes_count = 500) //------------------------------------------------------------------------------ //Settings //-----------------------------------------------------------------------------{ //Ranges Of Interest showRoi = input(true, 'Show Ranges Of Interest' , group = 'Ranges Of Interest') roiLength = input(50, 'Length' , group = 'Ranges Of Interest') roiCss = input(#b2b5be, 'Colors', inline = 'roicss' , group = 'Ranges Of Interest') roiAvg = input(#5d606b, '' , inline = 'roicss' , group = 'Ranges Of Interest') //Impulses showImp = input(true, 'Show Impulses' , group = 'Impulses') impLength = input(20, 'Length' , group = 'Impulses') impBull = input(#089981, 'Colors', inline = 'loicss', group = 'Impulses') impBear = input(#f23645, '' , inline = 'loicss', group = 'Impulses') //Levels Of Interest showLoi = input(false, 'Show' , inline = 'loishow', group = 'Levels Of Interest') loiShowLast = input(5, '' , inline = 'loishow', group = 'Levels Of Interest') loiLength = input(20, 'Length' , group = 'Levels Of Interest') loiBull = input(#2962ff, 'Colors', inline = 'loicss' , group = 'Levels Of Interest') loiBear = input(#f23645, '' , inline = 'loicss' , group = 'Levels Of Interest') //Volume Divergences showDiv = input(false, 'Show Divergences' , group = 'Divergences') divLength = input(10, 'Length' , group = 'Divergences') divBull = input(#5b9cf6, 'Colors', inline = 'vicss' , group = 'Divergences') divBear = input(#ff5d00, '' , inline = 'vicss' , group = 'Divergences') //-----------------------------------------------------------------------------} //Main Variables //-----------------------------------------------------------------------------{ n = bar_index v = volume trail_mean = ta.cum(v) / n //-----------------------------------------------------------------------------} //Levels Of Interest //-----------------------------------------------------------------------------{ var loi_lvls = array.new<line>(0) var loi_vals = array.new<float>(0) loi_phv = ta.pivothigh(v, loiLength, loiLength) if loi_phv and showLoi avg = hl2[loiLength] lvl = line.new(time[loiLength], avg, time, avg, xloc.bar_time, extend.right) loi_lvls.push(lvl) loi_vals.push(avg) if loi_lvls.size() > loiShowLast loi_lvls.get(0).delete() loi_lvls.shift() loi_vals.shift() if barstate.islast for element in loi_lvls element.set_color(color.from_gradient(element.get_y1(), loi_vals.min(), loi_vals.max(), loiBull, loiBear)) //-----------------------------------------------------------------------------} //Ranges Of Interest //-----------------------------------------------------------------------------{ var float roi_upper = na var line roi_avg = na var float roi_lower = na var roi_os = 0 rhv = ta.highest(v, roiLength) if showRoi if rhv == v roi_avg := line.new(n, hl2, n, hl2, color = roiAvg, style = line.style_dashed) else roi_avg.set_x2(n) roi_upper := rhv == v and showRoi ? high : roi_upper roi_lower := rhv == v and showRoi ? low : roi_lower //-----------------------------------------------------------------------------} //Impulses //-----------------------------------------------------------------------------{ imp_upv = ta.highest(v, impLength) imp_up = ta.highest(impLength) imp_dn = ta.lowest(impLength) bull_imp = imp_upv > imp_upv[1] and imp_up > imp_up[1] and showImp bear_imp = imp_upv > imp_upv[1] and imp_dn < imp_dn[1] and showImp //-----------------------------------------------------------------------------} //Volume Divergences //-----------------------------------------------------------------------------{ var ph_y1 = 0., var pl_y1 = 0., var phv_y1 = 0., var x1 = 0 ph = ta.pivothigh(divLength, divLength) pl = ta.pivotlow(divLength, divLength) phv = ta.pivothigh(volume, divLength, divLength) if phv and showDiv if phv < phv_y1 and high[divLength] > ph_y1 and ph line.new(n - divLength, high[divLength], x1, ph_y1, color = divBull) else if phv < phv_y1 and low[divLength] < pl_y1 and pl line.new(n - divLength, low[divLength], x1, pl_y1, color = divBear) phv_y1 := phv ph_y1 := high[divLength] pl_y1 := low[divLength] x1 := n - divLength //-----------------------------------------------------------------------------} //Plots //-----------------------------------------------------------------------------{ //ROI plot(roi_upper, 'Upper', rhv == v ? na : roiCss) plot(roi_lower, 'Lower', rhv == v ? na : roiCss) //Impulses plotcandle(high, high, low, low , color = color(na) , wickcolor = color(na) , bordercolor = bull_imp ? impBull : color(na) , display = display.all - display.status_line) plotcandle(high, high, low, low , color = color(na) , wickcolor = color(na) , bordercolor = bear_imp ? impBear : color(na) , display = display.all - display.status_line) //-----------------------------------------------------------------------------}
Enio_SPX_Accumulation/Distribution
https://www.tradingview.com/script/f08K4GfI-Enio-SPX-Accumulation-Distribution/
Point-Blank-Trading
https://www.tradingview.com/u/Point-Blank-Trading/
87
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/ // © Point-Blank-Trading //@version=5 indicator("Enio SPX Accumulation/Distribution") lengthAD = input.int(3, "AccDist_MA_length", minval=1, maxval=200, step=1) //input.string("Histogram", "Plot style", ["Histogram", "Candlesticks"]) aVol_open = request.security("USI:UVOL",timeframe.period , open) aVol_high = request.security("USI:UVOL", timeframe.period , high) aVol_low = request.security("USI:UVOL", timeframe.period , low) aVol_close = request.security("USI:UVOL",timeframe.period ,close) aIs_open = request.security("USI:ADV",timeframe.period , open) aIs_high = request.security("USI:ADV", timeframe.period , high) aIs_low = request.security("USI:ADV", timeframe.period , low) aIs_close = request.security("USI:ADV", timeframe.period , close) dVol_open = request.security("USI:DVOL", timeframe.period , open) dVol_high = request.security("USI:DVOL", timeframe.period , high) dVol_low = request.security("USI:DVOL", timeframe.period , low) dVol_close = request.security("USI:DVOL", timeframe.period , close) dIs_open = request.security("USI:DECL", timeframe.period , open) dIs_high = request.security("USI:DECL", timeframe.period , high) dIs_low = request.security("USI:DECL", timeframe.period , low) dIs_close = request.security("USI:DECL", timeframe.period , close) ind_open = request.security("SP:SPX", timeframe.period , open) ind_high = request.security("SP:SPX", timeframe.period , high) ind_low = request.security("SP:SPX", timeframe.period ,low) ind_close = request.security("SP:SPX", timeframe.period , close) AccDis_open = (aVol_open * aIs_open - dVol_open * dIs_open) / ind_open AccDis_high = (aVol_open *aIs_high - dVol_high * dIs_high) / ind_high AccDis_low = (aVol_open * aIs_low - dVol_low * dIs_low) / ind_low AccDis_close = (aVol_close * aIs_close - dVol_close * dIs_close) / ind_close AD_MA = ta.sma(AccDis_close, lengthAD) hist_color = if AccDis_close > 0 AccDis_close > AD_MA ? color.rgb(3, 119, 7) : color.rgb(51, 172, 113) else AccDis_close <AD_MA ? color.rgb(250, 1, 1, 5) : color.rgb(224, 138, 138, 20) //candle_color = if(AccDis_close > AccDis_open) //color.green //else //if(AccDis_close < AccDis_open) //color.red //else //color.white plot(AccDis_close , style=plot.style_histogram, linewidth=4, color=hist_color)
90 Minute Cycles
https://www.tradingview.com/script/MBeCQZ4G-90-Minute-Cycles/
sunwoo101
https://www.tradingview.com/u/sunwoo101/
68
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/ // © sunwoo101 //@version=5 indicator("90 Minute Cycles, MOP, DTCC", overlay = true, max_boxes_count = 500, max_labels_count = 500, max_lines_count = 500) markLast20Candles = input(true, "Last 20 Candles Box Outline", group = "Candle Range") last20CandlesColor = input(color.yellow, "Last 20 Candles Box Outline Color", group = "Candle Range") markLast40Candles = input(true, "Last 40 Candles Box Outline", group = "Candle Range") last40CandlesColor = input(color.orange, "Last 40 Candles Box Outline Color", group = "Candle Range") show90mCycles = input(true, "Show 90m Cycles", group = "Cycles") miniCyclesColor = input(color.white, "Mini Cycles Color", group = "Cycles") _6_00Cycle = input(true, "Q1 (6-7:30)", group = "Cycles") _6_00CycleColor = input(color.purple, "Q1 (6-7:30) Color", group = "Cycles") _7_30Cycle = input(true, "Q2 (7:30-9)", group = "Cycles") _7_30CycleColor = input(color.yellow, "Q2 (7:30-9) Color", group = "Cycles") _9_00Cycle = input(true, "Q3 (9-10:30)", group = "Cycles") _9_00CycleColor = input(color.green, "Q3 (9-10:30) Color", group = "Cycles") _10_30Cycle = input(true, "Q4 (10:30-12)", group = "Cycles") _10_30CycleColor = input(color.blue, "Q4 (10:30-12) Color", group = "Cycles") showFVG = input(true, "Show FVG", group = "FVG") FVGOnlyInSession = input(true, "FVG Only In Session", group = "FVG") _6_00FVG = input(true, "6-7:30", group = "FVG") _7_30FVG = input(true, "7:30-9", group = "FVG") _9_00FVG = input(true, "9-10:30", group = "FVG") _10_30FVG = input(true, "10:30-12", group = "FVG") FVGColor = input(color.new(color.white, 50), "FVG Color", group = "FVG") showMidnightStart = input(true, "Show Midnight Start", group = "Midnight") midnightStartColor = input(color.black, "Midnight Start Color", group = "Midnight") showMidnightPrice = input(true, "Show Midnight Opening Price", group = "Midnight") midnightPriceColor = input(color.black, "Midnight Opening Price Line Color", group = "Midnight") showNYTrueOpenStart = input(true, "Show NY True Open Start", group = "NY True Open") NYTrueOpenStartColor = input(color.blue, "NY True Open Start Color", group = "NY True Open") showNYTrueOpenPrice = input(true, "Show NY True Open Price", group = "NY True Open") NYTrueOpenPriceColor = input(color.blue, "NY True Open Price Color", group = "NY True Open") showICTMacros = input(true, "Show ICT Macros", group = "ICT Macros") ICTMacrosColor = input(color.new(color.black, 50), "ICT Macros Color", group = "ICT Macros") IsTime(h, m) => s = 0 not na(time) and hour(time, "America/New_York") == h and minute(time, "America/New_York") == m and second(time, "America/New_York") == s IsSession(sess) => not na(time(timeframe.period, sess, "America/New_York")) is6_00Session = IsSession("0600-0730") is7_30Session = IsSession("0730-0900") is9_00Session = IsSession("0900-1030") is10_30Session = IsSession("1030-1200") // Last 20 candles highest20 = ta.highest(high, 20) lowest20 = ta.lowest(low, 20) var _20CandlesBox = box.new(na, na, na, na, bgcolor=na, border_color = last20CandlesColor) box.set_left(_20CandlesBox, bar_index[19]) box.set_right(_20CandlesBox, bar_index) box.set_top(_20CandlesBox, highest20) box.set_bottom(_20CandlesBox, lowest20) box.set_border_color(_20CandlesBox, markLast20Candles ? last20CandlesColor : na) // Last 40 candles highest40 = ta.highest(high, 40) lowest40 = ta.lowest(low, 40) var _40CandlesBox = box.new(na, na, na, na, bgcolor=na, border_color = last40CandlesColor) box.set_left(_40CandlesBox, bar_index[39]) box.set_right(_40CandlesBox, bar_index) box.set_top(_40CandlesBox, highest40) box.set_bottom(_40CandlesBox, lowest40) box.set_border_color(_40CandlesBox, markLast40Candles ? last40CandlesColor : na) // Cycles if show90mCycles if _6_00Cycle if IsTime(6, 0) // LQ run (Q1 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _6_00CycleColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(6, 12) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(6, 30) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(6, 42) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(7, 0) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(7, 12) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(7, 30) // LQ run (Q3 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _7_30CycleColor, width = 1, extend = extend.both, style = line.style_solid) if _7_30Cycle if IsTime(7, 30) // LQ run (Q2 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _7_30CycleColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(7, 42) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(8, 0) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(8, 12) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(8, 30) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(8, 42) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(9, 0) // LQ run (Q3 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _9_00CycleColor, width = 1, extend = extend.both, style = line.style_solid) if _9_00Cycle if IsTime(9, 0) // LQ run (Q3 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _9_00CycleColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(9, 12) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(9, 30) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(9, 42) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(10, 0) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(10, 12) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(10, 30) // LQ run (Q4 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _10_30CycleColor, width = 1, extend = extend.both, style = line.style_solid) if _10_30Cycle if IsTime(10, 30) // LQ run (Q4 start) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = _10_30CycleColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(10, 42) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(11, 0) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(11, 12) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(11, 30) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) if IsTime(11, 42) // Trade entry line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_dashed) if IsTime(12, 0) // LQ run line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = miniCyclesColor, width = 1, extend = extend.both, style = line.style_solid) // FVG if showFVG and (not FVGOnlyInSession or (_6_00FVG and is6_00Session or _7_30FVG and is7_30Session or _9_00FVG and is9_00Session or _10_30FVG and is10_30Session)) // Bullish FVG if low > high[2] and close[1] > open[1] box.new(left=bar_index[2], top=low, right=bar_index, bottom=high[2], bgcolor=FVGColor, border_color = FVGColor) // Bearish FVG if high < low[2] and close[1] < open[1] box.new(left=bar_index[2], top=high, right=bar_index, bottom=low[2], bgcolor=FVGColor, border_color = FVGColor) // MOP var MOPLine = line.new(na, na, na, na, color = showMidnightPrice ? midnightPriceColor : na, width = 2, style = line.style_solid) if IsTime(0, 0) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = showMidnightStart ? midnightStartColor : na, width = 2, extend = extend.both, style = line.style_solid) line.set_xy1(MOPLine, bar_index, open) line.set_xy2(MOPLine, bar_index, open) if barstate.islast line.set_x2(MOPLine, bar_index) // NY True Open var NYTrueOpenLine = line.new(na, na, na, na, color = showNYTrueOpenPrice ? NYTrueOpenPriceColor : na, width = 2, style = line.style_solid) if IsTime(7, 30) line.new(x1 = bar_index, y1 = low, x2 = bar_index, y2 = high, color = showNYTrueOpenStart ? NYTrueOpenStartColor : na, width = 2, extend = extend.both, style = line.style_solid) line.set_xy1(NYTrueOpenLine, bar_index, open) line.set_xy2(NYTrueOpenLine, bar_index, open) if barstate.islast line.set_x2(NYTrueOpenLine, bar_index) // ICT Macros is8_50Macro = IsSession("0850-0910") is9_50Macro = IsSession("0950-1010") is10_50Macro = IsSession("1050-1110") is13_50Macro = IsSession("1350-1410") is14_50Macro = IsSession("1450-1510") is15_00Macro = IsSession("1500-1600") bgcolor(showICTMacros and (is8_50Macro or is9_50Macro or is10_50Macro or is13_50Macro or is14_50Macro or is15_00Macro) ? ICTMacrosColor : na)
IchimokuBuy Sell With Stoch RSI
https://www.tradingview.com/script/qqxK1UvB-IchimokuBuy-Sell-With-Stoch-RSI/
aliyilmazov
https://www.tradingview.com/u/aliyilmazov/
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/ // © aliyilmazov //@version=5 indicator(title="Ichimoku Kumo Cloud Crossover", shorttitle="IKCC", overlay=true) // Ichimoku Kumo Cloud hesaplama donchian(length) => h = ta.highest(high, length) l = ta.lowest(low, length) (h + l) / 2 conversionPeriod = input(9, title="Conversion Line Period") basePeriod = input(26, title="Base Line Period") lead1Period = input(52, title="Leading Span 1 Period") lead2Period = input(104, title="Leading Span 2 Period") conversionLine = ta.sma(donchian(conversionPeriod), conversionPeriod) baseLine = ta.sma(donchian(basePeriod), basePeriod) lead1 = ta.sma(hlc3, lead1Period) lead2 = donchian(lead2Period) // MACD göstergesi hesaplamaları fastLength = input(12, title="Fast EMA Length") slowLength = input(26, title="Slow EMA Length") signalSMA = input(9, title="Signal Line SMA Length") // MACD Osilatör [macdLine, signalLine, macdHistogram] = ta.macd(close, fastLength, slowLength, signalSMA) // MACD Osilatör hesaplaması macdOscillator = macdLine - signalLine // EMA 200 hesaplama lengthEMA200 = input(200, title="EMA 200 Period") ema200 = ta.ema(close, lengthEMA200) // RSI hesaplama lengthRSI = input(14, title="RSI Period") rsi = ta.rsi(close, lengthRSI) // Calculate RSI for Stoch RSI rsiLength = input(14, title="Stoch RSI Length") rsiStoch = ta.rsi(close, rsiLength) // Calculate Stoch RSI stochKLength = input(3, title="Stoch K Length") stochDLength = input(3, title="Stoch D Length") k = ta.sma(rsiStoch - ta.lowest(rsiStoch, rsiLength), stochKLength) / ta.sma(ta.highest(rsiStoch, rsiLength) - ta.lowest(rsiStoch, rsiLength), stochKLength) d = ta.sma(k, stochDLength) // Kumo Cloud renkleri cloudColor = baseLine > conversionLine ? color.green : color.red plot(lead1, title="Leading Span 1", color=color.blue) plot(lead2, title="Leading Span 2", color=color.orange) plot(conversionLine, title="Conversion Line", color=color.purple) plot(baseLine, title="Base Line", color=color.red) plot(0, title="Zero Line", color=color.gray) // Kumo Cloud fill(plot(baseLine, title="Kumo Cloud", color=cloudColor), plot(conversionLine)) // Sinyal üretimi crossOverUp = ta.crossover(conversionLine, baseLine) and close > ema200 and rsi > 50 and rsi < 70 and macdHistogram > 0 and high >= (ema200 + 0.25 * (high - ema200)) and k < d crossOverDown = ta.crossunder(conversionLine, baseLine) and close < ema200 and rsi < 50 and rsi > 20 and macdHistogram < 0 and low <= (ema200 + 0.25 * (low - ema200)) and k > d plotshape(crossOverUp, title="Alış Sinyali", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small, text="Buy") plotshape(crossOverDown, title="Satış Sinyali", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small, text="Sell") // EMA 200 çizgisini grafiğe ekleyin plot(ema200, title="EMA 200", color=color.blue, linewidth=2)
libKageMisc
https://www.tradingview.com/script/54lpjR14-libKageMisc/
marcelokg
https://www.tradingview.com/u/marcelokg/
10
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/ // © marcelokg //@version=5 // @description Kage's Miscelaneous library library("libKageMisc", overlay = true) ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Debug // @function Print a numerical value in a label at last historical bar. // @param _value (float) The value to be printed. // @returns Nothing. export print(float _value) => if barstate.islastconfirmedhistory label.new(x = bar_index + 2, y = hl2, style = label.style_label_upper_left, color = color.silver, size = size.large, text = str.tostring(_value) ) //#endregion Debug ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Bars // @function Get the number of bars we have to go back to get data from a specific date. // @param _year (int) Year of the specific date. // @param _month (int) Month of the specific date. Optional. Default = 1. // @param _day (int) Day of the specific date. Optional. Default = 1. // @returns (int) Number of bars to go back until reach the specific date. export barsBackToDate(int _year, int _month = 1, int _day = 1) => dayStamp = timestamp(_year, _month, _day) int barsBack = (time - dayStamp) / (1000 * timeframe.in_seconds(timeframe.period)) + 1 // @function Calculates the size of the bar's body. // @param _index (simple int) The historical index of the bar. Optional. Default = 0. // @returns (float) The size of the bar's body in price units. export bodySize(simple int _index = 0) => float bodySize = math.abs(close[_index] - open[_index]) // @function Calculates the size of the bar with both shadows. // @param _index (simple int) The historical index of the bar. Optional. Default = 0. // @returns (float) The size of the bar in price units. export barSize(simple int _index = 0) => float barSize = high[_index] - low[_index] // @function Proportion of chosen bar size to the body size // @param _index (simple int) The historical index of the bar. Optional. Default = 0. // @returns (float) Percent ratio of the body size per close price. export bodyBarRatio(simple int _index = 0) => float bodyBarRatio = bodySize(_index) * 100.0 / barSize(_index) // @function Proportion of chosen bar body size to the close price // @param _index (simple int) The historical index of the bar. Optional. Default = 0. // @returns (float) Percent ratio of the body size per close price. export bodyCloseRatio(simple int _index = 0) => float bodyCloseRatio = bodySize(_index) * 100.0 / close[_index] // @function A stochastic meassure for the the body size // @param _index (simple int) The historical index of the bar. Optional. Default = 0. // @param _length (simple int) How many bars look back to stochastic calculus. Default = 144. // @returns (float) Percent ratio of the body stochastic measure. export bodyStoch(simple int _index = 0, simple int _length = 144) => float bodySize = math.abs(close - open) float bodyMin = ta.lowest(bodySize, _length + _index) float bodyMax = ta.highest(bodySize, _length + _index) float bodyStoch = 100.0 * (bodySize(_index) - bodyMin) / (bodyMax - bodyMin) // @function Size of the current bar shadow. Either "top" or "bottom". // @param _direction (string) Direction of the desired shadow. // @returns (float) The size of the chosen bar's shadow in price units. export shadowSize(string _direction) => float thisShadowSize = 0.00 if _direction == "top" //if green bar if close > open thisShadowSize := high - close //if red... else thisShadowSize := high - open else if _direction == "bottom" //if green bar if close > open thisShadowSize := open - low //if red... else thisShadowSize := close - low else thisShadowSize := float(na) thisShadowSize // @function Proportion of current bar shadow to the bar size // @param _direction (string) Direction of the desired shadow. // @returns (float) Ratio of the shadow size per body size. export shadowBodyRatio(string _direction) => float thisShadowBodyRatio = shadowSize(_direction) / bodySize() //#endregion Bars ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Dates // @function Returns the last day of a month. // @param _month (int) Month number. // @returns (int) The number (28, 30 or 31) of the last day of a given month. export lastDayOfMonth(int _month) => int last = switch _month 2 => 28 4 => 30 6 => 30 9 => 30 11 => 30 => 31 // @function Return the short name of a month. // @param _month (int) Month number. // @returns (string) The short name ("Jan", "Feb"...) of a given month. export nameOfMonth(int _month) => string name = switch _month 1 => "Jan" 2 => "Feb" 3 => "Mar" 4 => "Apr" 5 => "May" 6 => "Jun" 7 => "Jul" 8 => "Aug" 9 => "Sep" 10 => "Oct" 11 => "Nov" 12 => "Dec" => "ERROR" //#endregion Dates ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Math // @function Calculate Profit/Loss between two values. // @param _initialValue (float) Initial value. // @param _finalValue (float) Final value = Initial value + delta. // @returns (float) Profit/Loss as a percentual change. export pl(float _initialValue, float _finalValue) => float percentPL = 100.00 * (_finalValue - _initialValue) / _initialValue // @function Generalist Moving Average (GMA). // @param _Type (string) Type of average to be used. Either "EMA", "HMA", "RMA", "SMA", "SWMA", "WMA" or "VWMA". // @param _Source (series float) Series of values to process. // @param _Length (simple int) Number of bars (length). // @returns (float) The value of the chosen moving average. export gma(string _Type, series float _Source, simple int _Length) => ema = ta.ema(_Source, _Length) hma = ta.hma(_Source, _Length) rma = ta.rma(_Source, _Length) sma = ta.sma(_Source, _Length) swma = ta.swma(_Source) wma = ta.wma(_Source, _Length) vwma = ta.vwma(_Source, _Length) float returnMA = switch _Type "EMA" => ema "HMA" => hma "RMA" => rma "SMA" => sma "SWMA" => swma "WMA" => wma "VWMA"=> vwma returnMA //#endregion Math ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Text // @function Transform a percentual value in a X Factor value. // @param _percentValue (float) Percentual value to be transformed. // @param _minXFactor (float) Minimum X Factor to that the conversion occurs. Optional. Default = 10. // @returns (string) A formated string. export xFormat(float _percentValue, float _minXFactor = 10.00) => float xFactor = 1.00 + ( _percentValue / 100.00 ) string returnValue = "" if xFactor >= _minXFactor returnValue := str.tostring(xFactor, "###,##0.0X") else if xFactor < _minXFactor returnValue := str.tostring(_percentValue, "###,##0.0") + "%" //#endregion Text ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Strategy // @function Check if the open trade direction is long. // @returns (bool) True if the open position is long. export isLong() => strategy.position_size > 0 // @function Check if the open trade direction is short. // @returns (bool) True if the open position is short. export isShort() => strategy.position_size < 0 // @function Returns the entry price of the last openned trade. // @returns (float) The last entry price. export lastPrice() => strategy.opentrades.entry_price(strategy.opentrades - 1) // @function Returns the number of bars since last trade was oppened. // @returns (series int) export barsSinceLastEntry() => strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1) : na // @function Returns the number of bars since the chosen trade's entry // @param _tradeIndex (int) Trade index from wich the information is wanted // @param _type (string) Type of trade. "O" for open trade or "C" for closed trade. Optional. Default is "O" // @returns (series int) Number of bars export barsSinceTradeEntry(int _tradeIndex = 0, string _type = "O") => int barsSinceTradeEntry = switch _type "O" => strategy.opentrades > 0 ? bar_index - strategy.opentrades.entry_bar_index(_tradeIndex) : int(na) "C" => strategy.closedtrades > 0 ? bar_index - strategy.closedtrades.entry_bar_index(_tradeIndex) : int(na) => int(na) //#endregion Strategy ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Bot //Bot strings BOT_NAME_FROSTY = "FrostyBot" BOT_NAME_ZIG = "Zignaly" // @function Return the name of the FrostyBot Bot. // @returns (string) A string containing the name. export getBotNameFrosty() => BOT_NAME_FROSTY // @function Return the name of the FrostyBot Bot. // @returns (string) A string containing the name. export getBotNameZig() => BOT_NAME_ZIG //#endregion Bot ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Symbol // @function Converts currency value to ticks // @param _currencyValue (float) Value to be converted. // @returns (float) Value converted to minticks. export getTicksValue(float _currencyValue) => float ticksValue = _currencyValue / ( syminfo.mintick * syminfo.pointvalue ) // math.round_to_mintick() ??? // @function Formats the symbol string to be used with a bot // @param _botName (string) Bot name constant. Either BOT_NAME_FROSTY or BOT_NAME_ZIG. Optional. Default is empty string. // @param _botCustomSymbol (string) Custom string. Optional. Default is empy string. // @returns (string) A string containing the symbol for the bot. If all arguments are empty, the current symbol is returned in Binance format. export getSymbol(string _botName = "", string _botCustomSymbol = "") => string returnSymbol = _botCustomSymbol if returnSymbol == "" returnSymbol := switch _botName BOT_NAME_FROSTY => str.upper(syminfo.basecurrency) + "/" + str.upper(syminfo.currency) BOT_NAME_ZIG => str.lower(syminfo.basecurrency) + str.lower(syminfo.currency) => str.upper(syminfo.basecurrency) + str.upper(syminfo.currency) returnSymbol //#endregion Symbol ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#region Info // @function Calculates and shows a board of Profit/Loss through the years. // @returns Nothing. export showProfitLossBoard() => /////////////////////////////////////////////////////// //#region Bar on bar int MATRIX_COLS = 14 var int currentYear = 0 var float yEquity = strategy.equity var mPL = matrix.new<float>(0, MATRIX_COLS) //Populate de matrix as long as the historical bars are processed if strategy.closedtrades + strategy.opentrades > 0 if year > currentYear matrix.add_row(mPL) currentYear := year matrix.set(mPL, matrix.rows(mPL) - 1, 0, currentYear) yEquity := strategy.equity lastMonthDay = lastDayOfMonth(month) if dayofmonth == lastMonthDay barsBack = barsBackToDate(year, month, 1) calcMPL = pl(strategy.equity[barsBack], strategy.equity) matrix.set(mPL, matrix.rows(mPL) - 1, month, calcMPL) calcYPL = pl(yEquity, strategy.equity) matrix.set(mPL, matrix.rows(mPL) - 1, MATRIX_COLS -1, calcYPL) //#endregion Bar on bar /////////////////////////////////////////////////////// //#region Last Bar //Only populate the table on the last historiacal bar if barstate.islastconfirmedhistory /////////////////////////////////////////////////////// //#region Constants //Period of data int FIRST_YEAR = int(matrix.get(mPL, 0, 0)) int LAST_YEAR = int(matrix.get(mPL, matrix.rows(mPL) - 1, 0)) //Table dimensions are based on the matrix dimensions int TABLE_COLS_HEADER = 1 int TABLE_COLS_MONTHS = MATRIX_COLS - 2 int TABLE_COLS_TOTAL = MATRIX_COLS int TABLE_ROWS_HEADER = 2 int TABLE_ROWS_FOOTER = 1 int TABLE_ROWS_DETAIL = (LAST_YEAR - FIRST_YEAR + 1) int TABLE_ROWS_TOTAL = TABLE_ROWS_HEADER + TABLE_ROWS_DETAIL + TABLE_ROWS_FOOTER int TABLE_ROW_FIRST_YEAR = TABLE_ROWS_HEADER int TABLE_ROW_LAST_YEAR = TABLE_ROWS_HEADER + TABLE_ROWS_DETAIL - 1 int TABLE_ROW_FOOTER = TABLE_ROWS_TOTAL - TABLE_ROWS_FOOTER //#endregion /////////////////////////////////////////////////////// //#region Variables and Calculations //Self explained currentRow = 0 currentCol = 0 //Last bar data lastBarDay = dayofmonth(time) barsBack = barsBackToDate(year, month, 1) calcLastMPL = pl(strategy.equity[barsBack], strategy.equity) matrix.set(mPL, matrix.rows(mPL) - 1, month, calcLastMPL) calcLastYPL = pl(yEquity, strategy.equity) matrix.set(mPL, matrix.rows(mPL) - 1, MATRIX_COLS -1, calcLastYPL) //#endregion var plBoard = table.new(position.bottom_center, columns = TABLE_COLS_TOTAL, rows = TABLE_ROWS_TOTAL, bgcolor = color.new(color.white, 95)) /////////////////////////////////////////////////////// //#region Header //Board title currentRow := 0 currentCol := 0 table.cell(table_id = plBoard, column = currentCol, row = currentRow, text = "Monthly Profit/Loss", text_color = color.white) table.merge_cells(plBoard, 0, 0, TABLE_COLS_TOTAL - 1, 0) //Months header line currentRow += 1 for mCol = 1 to TABLE_COLS_MONTHS table.cell(table_id = plBoard, column = mCol, row = currentRow, text = nameOfMonth(mCol), text_color = color.white) //Annual column reader currentRow := 1 currentCol := TABLE_COLS_TOTAL - 1 table.cell(table_id = plBoard, column = currentCol, row = currentRow, text = "In the Year", text_color = color.white) //Footer header currentRow := TABLE_ROW_FOOTER currentCol := TABLE_COLS_TOTAL - 2 table.cell(table_id = plBoard, column = currentCol, row = currentRow, text = "TOTAL", text_color = color.white) //#endregion Header /////////////////////////////////////////////////////// //#region Data //yRow stands for both year and row for yRow = TABLE_ROW_FIRST_YEAR to TABLE_ROW_LAST_YEAR //Column of years yCol = 0 yValue = matrix.get(mPL, yRow - TABLE_ROWS_HEADER, yCol) yText = str.tostring(yValue, "#") table.cell(table_id = plBoard, column = yCol, row = yRow, text = yText, text_color = color.white, text_halign = text.align_right) //Columns of months: mCol stands for both month and column for mCol = 1 to TABLE_COLS_MONTHS calcMPL = matrix.get(mPL, yRow - TABLE_ROWS_HEADER, mCol) textMPL = xFormat(calcMPL) table.cell(table_id = plBoard, column = mCol, row = yRow, text = textMPL, text_color = calcMPL >= 0.00 ? color.green : (calcMPL < 0.00 ? color.red : na), text_halign = text.align_right) //Column of annual P/Ls yCol := TABLE_COLS_TOTAL - 1 calcYPL = matrix.get(mPL, yRow - TABLE_ROWS_HEADER, yCol) textYPL = xFormat(calcYPL) table.cell(table_id = plBoard, column = yCol, row = yRow, text = textYPL, text_color = calcYPL >= 0.00 ? color.green : (calcYPL < 0.00 ? color.red : na), text_halign = text.align_right) //TOTAL data currentRow := TABLE_ROWS_TOTAL - 1 currentCol := TABLE_COLS_TOTAL - 1 calcTotal = pl(strategy.initial_capital, strategy.equity) textTotal = xFormat(calcTotal) table.cell(table_id = plBoard, column = currentCol, row = currentRow, text = textTotal, text_color = calcTotal >= 0.00 ? color.green : (calcTotal < 0.00 ? color.red : na), text_halign = text.align_right) //#endregion Data //#endregion Last Bar //#endregion Info
ulib
https://www.tradingview.com/script/xMjvvE8L-ulib/
culturalStar54759
https://www.tradingview.com/u/culturalStar54759/
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/ // © culturalStar54759 //@version=5 library("ulib" ) // stochastic calculator export Stochastic(simple int length,simple int smoothing_period,simple int k_period,simple int d_period ) => hh = ta.highest(close, length) ll = ta.lowest(close, length) k = 100 * (close - ll) / (hh - ll) float d = ta.sma(k_period, smoothing_period) float d2 = ta.sma(d_period,smoothing_period ) [k,d,d2] export bull_stoch_condition(float k, float d) => if ta.crossover(k,d) bool bull_stoch_condition = true export ema_condition(float ema_1,float ema_2,float ema_3 ) => if ta.crossover(ema_1, ema_2) bool ema_condition = true else if ta.crossover(ema_1 , ema_3) bool ema_condition = true else if ta.crossover(ema_2, ema_3) bool ema_condition = true export bull_fractal_condition(int n)=> // downFractal bool downflag = true bool downflag_0 = true bool downflag_1 = true bool downflag_2 = true bool downflag_3 = true bool downflag_4 = true for i = 1 to n downflag := downflag and (low[n-i] > low[n]) downflag_0 := downflag_0 and (low[n+i] > low[n]) downflag_1 := downflag_1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n]) downflag_2 := downflag_2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n]) downflag_3 := downflag_3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n]) downflag_4 := downflag_4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n]) flagdown = downflag_0 or downflag_1 or downflag_2 or downflag_3 or downflag_4 bool df = (downflag and flagdown) export bear_fractal_condition(int n)=> bool upflag = true bool upflag_0 = true bool upflag_1 = true bool upflag_2 = true bool upflag_3 = true bool upflag_4 = true for i = 1 to n upflag := upflag and (high[n-i] < high[n]) upflag_0 := upflag_0 and (high[n+i] < high[n]) upflag_1 := upflag_1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n]) upflag_2 := upflag_2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n]) upflag_3 := upflag_3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n]) upflag_4 := upflag_4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n]) flagUp = upflag_0 or upflag_1 or upflag_2 or upflag_3 or upflag_4 bool uf = (upflag and flagUp) export Bull( bool Fractal,bool ema,bool stochastic_osc ) => if Fractal == true and ema == true and stochastic_osc == true bool Bull_condition = true
price_a
https://www.tradingview.com/script/zRScUb2y/
gtgpsa
https://www.tradingview.com/u/gtgpsa/
1
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/ // © gtgpsa //@version=5 library('price_a', true) a=(close-close[1])/close[1]*100 export sinh(float X) => a + X
Markdown: The Pine Editor's Hidden Gem
https://www.tradingview.com/script/b6aw56xH-Markdown-The-Pine-Editor-s-Hidden-Gem/
HoanGhetti
https://www.tradingview.com/u/HoanGhetti/
65
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/ // © nsadeghi //@version=5 library("MarkdownLib", overlay = true) //---------------------------------------------------------------------------------------------------------------------------------------------------- // // Markdown is a portable, lightweight markup language that can be used for everything // whether you're building a website, documentation, or even presentations. // // Platforms like Discord, Reddit and GitHub support Markdown, and is the widely go to // option for text formatting due to its simplicity. Pine Script is a language that also // utilizes Markdown, specifically in the Pine Editor is where it can really be used to some extent. // // Since the release of libraries, user-defined types, and methods, Pine Script is entering an // age where developers will be highly dependent on libraries due to the capabilities // Pine has inherited recently. It would be no surprise if a few people got together and took // their time to thoroughly develop an entire library centered around improving Pine Script's // built-in functions and providing developers easier ways of achieving things than they thought // they could. // // As you're all aware, hovering over functions (and more) in the editor pops up a prompt that specifies // the parameters, types, and what the function returns. Pine Script uses Markdown for that, so I figured // let's go ahead and push that feature to its limits and see what we can do. // // Today we'll go over how we can utilize Markdown in Pine Script, and how you can make your library's // built-in functions stand out more than they did previously. // // For more information, visit https://www.markdownguide.org/ // //---------------------------------------------------------------------------------------------------------------------------------------------------- // GENERAL NOTES // ----------------------- // Markdown syntax only works on functions and methods. // Using arrays as parameters as of 2/21/2023 breaks the Markdown system. // The prompt window holds a max of 166 characters on one line before overflowing. // ----------------------- // HEADINGS // --------------- // If you have experience in HTML, Markdown, or even Microsoft Word you already have a grasp of how Headings work and look. // To simplify it, headings make the given text either massive, or tiny depending on how many number symbols are provided. // When defining headings, you must have a space between the number (#) symbol, and the text. This is typical syntax throughout the language. // Pine Script's built-ins use Heading Level 4 (####) as their main headers. // --------------- // @function # A confirmation function // # Heading Level 1 // ## Heading Level 2 // ### Heading Level 3 // #### Heading Level 4 // ##### Heading Level 5 // ###### Heading Level 6 // // # Works. // #Won't Work. // @returns Confirmation confirmFunction() => barstate.isconfirmed // PARAGRAPHS & LINE BREAKS // ----------------------------------------- // You may want to provide extensive details and examples relating to one function, in this case // you could create line breaks. Creating line breaks skips to the next line so you can keep things organized as a result. // To achieve a valid line break and create a new paragraph, you must end the line with two or more spaces. // If you want to have an empty line in between, apply a back slash (\). // Back slashes (\) are generally not recommended for every line break. In this case, I only recommend using them for empty lines. // ------------------------------------------ // @function A confirmation function // \ // First Paragraph with two spaces at the end. // Second Paragraph with two spaces at the end. // Third Paragraph with a backslash at the end.\ // Random Text. // @returns Confirmation confirmFunction2() => barstate.isconfirmed // TEXT FORMATTING // -------------------------- // Markdown provides text formatting such as bold, italics, and strikethrough. // For bolding text, you can do (**) or (__) as an open and closer. // For italicizing text, you can do (*) or (_) as an open and closer. // For bolding and italicizing text, you can do (***) or (___) as an open and closer. // For strikethrough you need to use (~~) as an open and closer. // See examples below. // -------------------------- // @function **A confirmation function** // *Italic Text* // _Italic_ Text // **Bold Text** // __Bold__ Text // ~~Strikethrough~~ Text // ~~***All***~~ // @returns Confirmation confirmFunction3() => barstate.isconfirmed // BLOCKQUOTES // -------------------------------------------------------- // Blockquotes in Pine Script can be visualized as a built-in indentation system. // They are declared using greater than (>) and everything will be auto-aligned and indented until closed. // By convention you generally want to include the greater than (>) on every line that's included in the block quote. Even when not needed. // If you would like to indent even more (nested blockquotes), you can apply multiple greater than symbols (>). For example, (>>) // Blockquotes can be closed by ending the next line with only one greater than (>) symbol, or by using a horizontal rule. // --------------------------------------------------------- // @function A confirmation function // \ // Random Text // > #### Blockquote as a Header // > // >> ##### Information inside block quote. // > // End Blockquote // @returns Confirmation confirmFunction4() => barstate.isconfirmed // HORIZONTAL RULES // --------------------------------------------- // Horizontal rules in Pine Script are what you see at the very top of the prompt. // When hovering, you can see the top of the prompt provides a line, and we can actually reproduce these lines. // These are extremely useful for separating information into their own parts, and are accessed by applying // three underscores (___), or three asterisks (***). // Horizontal rules were mentioned above, when we were discussing block quotes. These can also be used to close blockquotes as well. // Horizontal rules require minimum 3 underscores (___). // @function A confirmation function // ___ // Text in-between two lines. // ___ // @returns Confirmation confirmFunction5() => barstate.isconfirmed // LISTS // --------- // Lists give us a way to structure data in a neat fashion. There are multiple ways to start a list, such as // 1. First Item (number followed by a period) // - First Item (dash) // + First Item (plus sign) // * First Item (asterisk) // Using number-based lists provide an ordered list, whereas using (-), (+), or (*) will provide an unordered list (bullet points). // If you want to begin an unordered list with a number that ends with a period, you must use an escape sequence (\) after the number. // Standard indentation (tab-width) list detection isn't supported, so to nest lists you have to use block quotes. (>) // --------- // @function A confirmation function // - First List // > - First item // > - Second item // 1. First List // 2. Second Item // 3. Third Item // ___ // - 2000. Won't Work. // ___ // - 2000\. Will Work // @returns Confirmation confirmFunction6() => barstate.isconfirmed // CODE BLOCKS // ------------------- // Using code blocks allows you to write actual Pine Script code inside the prompt. // It's a game changer that can potentially help people understand how to execute functions quickly. // To use code blocks, apply three backquotes (```) as an opener, and a closer. // Considering that indentation isn't detected properly, use (-) and three spaces as an indentation reference. // ------------------- // @function The `drawLabel` function draws a label based on a condition. // #### Usage // ___ // ``` // if barstate.isconfirmed // - drawLabel(bar_index, high) // ``` // ___ // @returns A Label drawLabel(int x, float y) => label.new(x, y) // DENOTATION // -------------- // Denoting can also be seen as highlighting a background layer behind text. They're basically code blocks, but without the "block". // Similar to how code blocks work, we apply one backquote (`) as an opener and closer. // Make sure to only use this on important keywords. There isn't really a conventional way of applying this. // It's up to you to decide what people should have their eyes tracked onto when they hover over your functions. // If needed, look at how Pine Script's built-in variables and functions utilize this. // -------------- // @function A confirmation function // \ // `Denote` a phrase/word. // @returns Confirmation confirmFunction7() => barstate.isconfirmed // TABLES // ----------- // Tables are possible in Markdown, although it may look a bit different in the Pine Editor. // They are made by separating text with vertical bars (|). // The headers are detected when there is a minimum of one dash (-) below them. // Tables aren't ideal to use in the editor, but is there if anyone wants to give it a go. // @function A confirmation function // | Left Columns │ | │ Right Columns | // | ----------------: | :--------------- | // | left val │ | │ right val | // | left val2 │ | │ right val2 | // ___ // @returns Confirmation confirmFunction8() => barstate.isconfirmed // LINKS & IMAGES // ------------------------ // Markdown supports images and hyperlinks, which means we can also do that here in the Pine Editor. Cool right? // If you want to create a hyper link, surround the displayed text in open and close brackets []. // The syntax should look like this [Display Text](URL) // If you want to load a photo into your prompt, it's the same syntax as the hyperlink, except it uses a (!) // Image syntax should look like this ![Logo Name](URL.png) // @function A confirmation function // ___ // [A Fancy Youtube Link](https://www.youtube.com/watch?v=dQw4w9WgXcQ) // ___ // ![Pine Script Logo](https://i.postimg.cc/qvsJqNT6/Pine-Script-logo-text-1.png) confirmFunction9() => barstate.isconfirmed // USAGE EXAMPLES // ------------------------ // @function Gets the total decimal count of the current symbol. // // #### Usage // ___ // ``` // table = table.new(position.middle_right, 20, 20) // table.cell(table, 0, 0, str.tostring(getDecimals())) // ``` // ___ // @returns The `amount` of existing numbers `after` the decimal point of the current symbol. export getDecimals() => mintickToArray = str.split(str.tostring(syminfo.mintick), '') result = array.new<string>() for i in mintickToArray switch i '0' => array.push(result, '0') '.' => array.push(result, '.') if array.size(result) > 1 for i = 0 to array.size(result) - 1 array.remove(mintickToArray, 0) joinTick = array.join(mintickToArray, '') getDecimals = math.log10(str.tonumber(joinTick)/syminfo.mintick) thenConvert = math.round(getDecimals) // @function Creates bollinger bands out of any specified moving average // // #### Usage // ___ // ``` // input_len = input.int(defval = 50, title = 'Moving Average Length') // SMA = ta.sma(close, input_len) // [bb_up, bb_mid, bb_dn] = bb(close, SMA, input_len, 4) // ‎ // plot(bb_up) // plot(bb_mid) // plot(bb_dn) // ``` // ___ // @param src The source of the standard deviation. The default is `close` `Optional` // @param movingAverage A pre-defined moving average `Required` // @param maLength The `length` of the moving average. `Required` // @param mult The multiplier of both `up` and `dn` moving average offsets. `Required` // @returns `Bollinger bands` of the specified moving average. export bb(series float src, series float movingAverage, series int maLength, series float mult) => dev = mult * ta.stdev(src, maLength) [movingAverage, movingAverage + dev, movingAverage - dev] // @function Parses `time` into a `date` string with optional time parameters. // // #### Usage // ___ // ``` // table = table.new(position.middle_right, 20, 20) // table.cell(table, 0, 0, str.tostring(getCurrentDate(true, 'America/Chicago'))) // ``` // *Visit https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for zones* // ___ // @param includeTime Specifies Timestamp `Optional` // @param time_zone The specified time zone. The default is `syminfo.timezone` `Optional` // @returns A `timestamp` of the current date. export getCurrentDate(simple bool includeTime = true, string time_zone = syminfo.timezone) => includeTime ? str.format_time(time, "MM-dd-yyyy HH:mm:ss", time_zone) : not includeTime ? str.format_time(time, "MM-dd-yyyy", time_zone) : na
Vector2Array
https://www.tradingview.com/script/yAf9dBk5-Vector2Array/
RicardoSantos
https://www.tradingview.com/u/RicardoSantos/
17
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/ // © RicardoSantos //@version=5 // @description functions to handle vector2 Array operations. // . // references: // https://docs.unity3d.com/ScriptReference/Vector2.html // https://gist.github.com/winduptoy/a1aa09c3499e09edbd33 // https://github.com/dogancoruh/Javascript-Vector2/blob/master/js/vector2.js // https://gist.github.com/Dalimil/3daf2a0c531d7d030deb37a7bfeff454 // https://gist.github.com/jeantimex/7fa22744e0c45e5df770b532f696af2d // https://gist.github.com/volkansalma/2972237 // . library(title='Vector2Array') //#region ~~~ Imports and Helpers: import RicardoSantos/CommonTypesMath/1 as TMath import RicardoSantos/Vector2/1 as Vector2 //#endregion //#region -> Constructor: // from () { // @function Generate array of vector2 from string. // @param source string Source string of the vectors. // @param prop_sep string Separator character of the vector properties (x`,`y). // @param vect_sep string Separator character of the vectors ((x,y)`;`(x,y)). // @returns array<Vector2>. export from (string source, string prop_sep=',', string vect_sep=';') => array<string> _s = str.split(source, vect_sep) int _size = _s.size() if _size > 0 _output = array.new<TMath.Vector2>(_size) for [_i, _e] in _s _output.set(_i, Vector2.from(_e, prop_sep)) _output // TEST: 20230221 RS // if barstate.islast // _V = from('1.2,3;2.0,3.0;(1,2.0);4,3') // _str = '' // for _e in _V // _str += ':' + _e.to_string() // label.new(bar_index, 0.0, _str) // } //#endregion //#region ~~~ Array Methods: // max () { // @function Combination of the highest elements in column of a array of vectors. // @param vectors array<Vector2.Vector2>, Array of Vector2 objects. // @returns Vector2.Vector2, Vector2 object. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = max(array.from(a, b, c)) , plot(d.x)` export method max (array<TMath.Vector2> vectors) => int _size = array.size(vectors) if _size > 0 TMath.Vector2 _min = array.get(vectors, 0) for _e in vectors if _e.x > _min.x _min.x := _e.x if _e.y > _min.y _min.y := _e.y _min else Vector2.nan() // } // min () { // @function Combination of the lowest elements in column of a array of vectors. // @param vectors array<Vector2.Vector2>, Array of Vector2 objects. // @returns Vector2.Vector2, Vector2 object. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = min(array.from(a, b, c)) , plot(d.x)` export min (array<TMath.Vector2> vectors) => int _size = array.size(vectors) if _size > 0 TMath.Vector2 _min = array.get(vectors, 0) for _e in vectors if _e.x < _min.x _min.x := _e.x if _e.y < _min.y _min.y := _e.y _min else Vector2.nan() // } // sum () { // @function Total sum of all vectors. // @param vectors array<Vector2.Vector2>, ID of the vector2 array. // @returns Vector2.Vector2, vector2 object. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = sum(array.from(a, b, c)) , plot(d.x)` export sum (array<TMath.Vector2> vectors) => TMath.Vector2 _sum = Vector2.zero() for _e in vectors _sum.x += _e.x _sum.y += _e.y _sum // } // center () { // @function Finds the vector center of the array. // @param vectors array<Vector2.Vector2>, ID of the vector2 array. // @returns Vector2.Vector2, vector2 object. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = center(array.from(a, b, c)) , plot(d.x)` export center (array<TMath.Vector2> vectors) => int _size = array.size(vectors) TMath.Vector2 _sum = sum(vectors) Vector2.new(_sum.x / _size, _sum.y / _size) // } // rotate () { // @function Rotate Array vectors around origin vector by a angle. // @param vectors array<Vector2.Vector2>, ID of the vector2 array. // @param center Vector2.Vector2 , Vector2 object. Center of the rotation. // @param degree float , Angle value. // @returns rotated points array. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = rotate(array.from(a, b, c), b, 45.0)` export rotate (array<TMath.Vector2> vectors, TMath.Vector2 center, float degree) => array<TMath.Vector2> _vectors = array.new<TMath.Vector2>(0, Vector2.nan()) int _size = array.size(vectors) for _e in vectors array.push(_vectors, Vector2.rotate_around(_e, center, degree)) _vectors // TEST: 20230206 RS // va = Vector2.from(300.0) , vb = Vector2.from(200.0), vc = Vector2.from(100.0)//, vd = rotate(array.from(va, vb, vc), vb, 45.0) // if barstate.islast // label.new(bar_index+int(vc.x), vc.y, vc.to_string()) // for _d = 0 to 360 by 20 // vd = rotate(array.from(va, vb), vc, _d) // line.new(bar_index+int(vd.get(0).x), vd.get(0).y, bar_index+int(vd.get(1).x), vd.get(1).y) // } // scale () { // @function Scale Array vectors based on a origin vector perspective. // @param vectors array<Vector2.Vector2>, ID of the vector2 array. // @param center Vector2.Vector2 , Vector2 object. Origin center of the transformation. // @param rate float , Rate to apply transformation. // @returns rotated points array. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = scale(array.from(a, b, c), b, 1.25)` export method scale (array<TMath.Vector2> vectors, TMath.Vector2 center, float rate) => array<TMath.Vector2> _vectors = array.new<TMath.Vector2>(0, Vector2.from(0.0)) for _oldvector in vectors // Vector2.Vector2 _newvector = add(center, scale(subtract(_oldvector, center), 1.0 + rate)) TMath.Vector2 _newvector = Vector2.new(center.x + (_oldvector.x - center.x) * (1.0 + rate), center.y + (_oldvector.y - center.y) * (1.0 + rate)) array.push(_vectors, _newvector) _vectors // TEST: 20230221 RS // float _r = input.float(0.0, step=0.05) // if barstate.islast // _a = Vector2.new(bar_index + 000.0, 000.0) // _b = Vector2.new(bar_index + 100.0, 100.0) // _c = Vector2.new(bar_index + 150.0, 050.0) // _center = Vector2.new(bar_index + 100.0, 050.0) // _before = array.from(_a, _b, _c) // line.new(int(_before.get(0).x), _before.get(0).y, int(_before.get(1).x), _before.get(1).y) // line.new(int(_before.get(1).x), _before.get(1).y, int(_before.get(2).x), _before.get(2).y) // _after = _before.scale(_center, _r) // line.new(int(_after.get(0).x), _after.get(0).y, int(_after.get(1).x), _after.get(1).y) // line.new(int(_after.get(1).x), _after.get(1).y, int(_after.get(2).x), _after.get(2).y) // } // move () { // @function Move Array vectors by a rate of the distance to center position (LERP). // @param vectors array<Vector2.Vector2>, ID of the vector2 array. // @param value Vector2.Vector2 , Vector2 object. Value of the transformation. // @returns Moved points array. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = move(array.from(a, b, c), b, 1.25)` export method move (array<TMath.Vector2> vectors, TMath.Vector2 center, float rate) => array<TMath.Vector2> _vectors = array.new<TMath.Vector2>(0, Vector2.from(0.0)) for _oldvector in vectors // Vector2.Vector2 _newvector = add(center, scale(subtract(_oldvector, center), 1.0 + rate)) TMath.Vector2 _newvector = Vector2.new(center.x + (_oldvector.x - center.x) * (1.0 + rate), center.y + (_oldvector.y - center.y) * (1.0 + rate)) array.push(_vectors, _newvector) _vectors // TEST: 20230221 RS // float _r = input.float(0.0, step=0.05) // _center = Vector2.from(input.string('100,50')) // _center.x += bar_index // if barstate.islast // _a = Vector2.new(bar_index + 000.0, 000.0) // _b = Vector2.new(bar_index + 100.0, 100.0) // _c = Vector2.new(bar_index + 150.0, 050.0) // _before = array.from(_a, _b, _c) // line.new(int(_before.get(0).x), _before.get(0).y, int(_before.get(1).x), _before.get(1).y) // line.new(int(_before.get(1).x), _before.get(1).y, int(_before.get(2).x), _before.get(2).y) // _after = _before.move(_center, _r) // line.new(int(_after.get(0).x), _after.get(0).y, int(_after.get(1).x), _after.get(1).y) // line.new(int(_after.get(1).x), _after.get(1).y, int(_after.get(2).x), _after.get(2).y) // } //#region ~~~ ~~~ Translate: // to_string () { // @function Reads a array of vectors into a string, of the form `[ (x, y), ... ]`. // @param id array<Vector2.Vector2>, ID of the vector2 array. // @param separator string separator for cell splitting. // @returns string Translated complex array into string. // -> usage: // `a = Vector2.from(1.0) , b = Vector2.from(2.0), c = Vector2.from(3.0), d = to_string(array.from(a, b, c))` export to_string (array<TMath.Vector2> id, string separator='') => string _separator = na(separator) ? ', ' : separator string _str = '[ ' for _e in id _str += Vector2.to_string(_e) + _separator int _size = str.length(_str) if _size > 2 str.substring(_str, 0, _size - 2) + ' ]' else _str + ' ]' // } // to_string () { // @function Reads a array of vectors into a string, of the form `[ (x, y), ... ]`. // @param id array<Vector2.Vector2>, ID of the vector2 array. // @param format string , Format to apply transformation. // @param separator string , Separator for cell splitting. // @returns string Translated complex array into string. // -> usage: // `a = Vector2.from(1.234) , b = Vector2.from(2.23), c = Vector2.from(3.1234), d = to_string(array.from(a, b, c), "#.##")` export to_string (array<TMath.Vector2> id, string format, string separator = '') => string _separator = na(separator) ? ', ' : separator string _str = '[ ' for _e in id _str += Vector2.to_string(_e, format) + _separator int _size = str.length(_str) if _size > 2 str.substring(_str, 0, _size - 2) + ' ]' else _str + ' ]' // } //#endregion //#endregion // rotation = input(0) // origin = input(0.0) // triangle_scale = input(0.0) // if barstate.ishistory[1] and (barstate.isrealtime or barstate.islast) // TMath.Vector2 a = Vector2.new(0.10, -0.25) // TMath.Vector2 b = Vector2.new(0.66, float(na)) // TMath.Vector2 c = Vector2.add(a, Vector2.one()) // TMath.Vector2 d = Vector2.subtract(c, Vector2.one()) // array<TMath.Vector2> L = array.new<TMath.Vector2>(4, Vector2.new(0, 0)) // array.set(L, 0, a) // array.set(L, 1, b) // array.set(L, 2, c) // array.set(L, 3, d) // _text = '' // _text := _text + 'Array Methods:\n' // _text := _text + 'array L: ' + to_string(L, string(na)) + '\n' // _text := _text + 'center of L: ' + Vector2.to_string(center(L)) + '\n' // array.unshift(L, Vector2.from(1.111)) // array.push(L, Vector2.from(2.222)) // _text := _text + 'Sum of L: ' + Vector2.to_string(sum(L)) + '\n' // _text := _text + 'Top of L: ' + Vector2.to_string(max(L)) + '\n' // _text := _text + 'Bottom of L: ' + Vector2.to_string(min(L)) + '\n' // array<TMath.Vector2> _triangle = array.new<TMath.Vector2>(3, Vector2.from(0.0)) // array.set(_triangle, 1, Vector2.from(bar_index/2)) // array.set(_triangle, 2, Vector2.new(bar_index/2, 0.0)) // array<TMath.Vector2> _new_triangle = scale(_triangle, Vector2.from(origin), triangle_scale) // T = table.new(position.bottom_right, 1, 1, #000000) // table.cell(T, 0, 0, _text, text_color = #ffffff, text_size = size.small) // console.update(__T, __C)