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
[PlayBit]Correlation-Co _OI
https://www.tradingview.com/script/rPNPvxmK-PlayBit-Correlation-Co-OI/
FFriZz
https://www.tradingview.com/u/FFriZz/
98
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/ // © FFriZz inspired by © mortdiggiddy //@version=5 indicator('[PlayBit]Correlation-Co _OI', shorttitle='[PlayBit]Cor-Co _OI',format = format.price) //sym1 = input.symbol('Binance:BTCUSDT', 'sym₿ol 1') autoSym = input.bool(true,'Auto Change to Chart Open Interest | On/Off?',group='Read Tooltip') sym2 = input.symbol('BTCUSDTPERP', 'Crypto/Stock/Future(Read Tooltip)',group='Read Tooltip',inline='a',tooltip='If indicator moves up it means the 2 assets are correlating(moving together) and it goes down it means the 2 assets are diverging(moving differently). If comparing a Stock or Future to Crypto chart the Stock or Future and change indicator to the Crypto you want to compare. The reason is Crypto is open 24/7 and will have more bars than an asset with closed hours causing the indicator to produce gaps in the data, if comparing crypto to crypto disreguard this information.') length = input.int(14, 'Ammount of bars data is correlated(Similar to length of a MA)', minval=1) length2 = input.int(14, 'Length of MA', minval=1) sym = syminfo.ticker//+'PERP_OI' symm = str.replace(sym,'USDT.P','USDTPERP') symmm = str.replace(symm,'_OI','') sym33 = symmm + '_OI' sym3 = 'Binance:'+ sym33 symTable = autoSym ? sym33 : sym2 src1 = input.source(close,'Source of Chart Asset') src2ind = input.source(close,'Source of symbol of indicator Asset') //TF = input.timeframe('D','TimeFrame') //src1 = request.security(sym1,timeframe.period, src1ind ,gaps=barmerge.gaps_off) src3 = request.security(sym2,timeframe.period, src2ind ,gaps=barmerge.gaps_off) src4 = request.security(sym3,timeframe.period, src2ind ,gaps=barmerge.gaps_off) maof = input(true,'MA on/off') float src2 = na if autoSym src2 := src4 else src2 := src3 var a1 = array.new_float(0) var a2 = array.new_float(0) var a1_sorted = array.new_float(0) var a2_sorted = array.new_float(0) var a1_ranked = array.new_float(length, 0) var a2_ranked = array.new_float(length, 0) var diff = array.new_float(length, 0) // initially the array sizes are zero at the very first bar // index, they grow to 'length' as the chart data is traversed if array.size(a1) <= length array.unshift(a1, src1) array.unshift(a2, src2) // pop off last value if a.size > 'length' if array.size(a1) > length array.pop(a1) if array.size(a2) > length array.pop(a2) // update arrays with the current values at the array head array.set(a1, 0, src1) array.set(a2, 0, src2) rank(a, sorted, ranked) => dupe = array.new_float(0) size = array.size(a) // re-populate and re-sort array.clear(sorted) array.concat(sorted, a) array.sort(sorted, order.ascending) for i = 0 to (size - 1) v = array.get(sorted, i) if not array.includes(dupe, v) // locate the original index of the sorted value at index 'i' index = array.indexof(a, v) lastIndex = array.lastindexof(a, v) if index >= 0 // we have to check for duplicate entries // // ex) a = [1 5 3 7 5 9 8] // a_ranked = [1 3.5 2 5 3.5 6 7] rank = if index != lastIndex array.push(dupe, v) total = array.lastindexof(sorted, v) - i + 1 mod = i for j = 1 to (total - 1) mod := mod + i + j rank = mod / total else rank = i // assign the rank to all occurrences of the value for j = index to lastIndex if array.get(a, j) == v array.set(ranked, j, rank) tie = array.size(dupe) corr(tie) => // https://i.imgur.com/W6yPFGk.png size = array.size(a1) d2_sum = 0.0 corr = if tie == 0 for i = 0 to (size - 1) v1 = array.get(a1_ranked, i) v2 = array.get(a2_ranked, i) d2_sum := d2_sum + (v1 - v2) * (v1 - v2) corr = 1 - (6 * d2_sum / (size * (size * size - 1))) else // Tied Ranks (Full calc): https://i.imgur.com/iVieah3.png r1_avg = array.avg(array.slice(a1_ranked, 0, size)) r2_avg = array.avg(array.slice(a2_ranked, 0, size)) covar = 0.0 r1_sq_sum = 0.0 r2_sq_sum = 0.0 for i = 0 to (size - 1) v1 = array.get(a1_ranked, i) - r1_avg v2 = array.get(a2_ranked, i) - r2_avg covar := covar + v1 * v2 r1_sq_sum := r1_sq_sum + v1 * v1 r2_sq_sum := r2_sq_sum + v2 * v2 corr = covar / math.sqrt(r1_sq_sum * r2_sq_sum) corr tie1 = rank(a1, a1_sorted, a1_ranked) tie2 = rank(a2, a2_sorted, a2_ranked) correlation = corr(tie1 + tie2) //HOURSP= hours ? PL : ZL //HOURSN= hours ? NL : ZL var table Tbl = table.new(position.top_right,columns = 1 ,rows = 1, bgcolor = color.new(chart.bg_color,100), frame_color = color.new(chart.fg_color,0), frame_width = 1, border_color = color.new(chart.fg_color, 0), border_width = 1) if barstate.islast table.cell(Tbl,0,0,symTable,text_color = chart.fg_color,text_size = size.small) colorUp = 1 colorDn = -1 cu=input.color(color.new(#00FF00FF,0),'Color Up Correlation') cd=input.color(color.new(#FF0000FF,0),'Color Down Correlation') ccu=input.color(color.new(#000000,0),'Color MA') bgc=input.color(color.new(color.black,100),'Background Color') colorg=color.from_gradient(correlation,colorDn,colorUp,cd,cu) c=correlation * src2 plot(correlation * src2, 'P₿ Correlation', color=colorg, style=plot.style_columns) bgcolor(color=bgc, title= 'BG Color') ComCp = maof ? ta.sma(correlation,length) * ta.sma(src2, length2) : na plot(ComCp,'Asset Selected MA',color=ccu,style=plot.style_line,linewidth=2)
Nadaraya-Watson: Envelope (Non-Repainting)
https://www.tradingview.com/script/WeLssFxl-Nadaraya-Watson-Envelope-Non-Repainting/
jdehorty
https://www.tradingview.com/u/jdehorty/
1,372
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/ // © jdehorty // @version=5 indicator(title="Nadaraya-Watson: Envelope (Non-Repainting)", overlay=true, timeframe='') // In technical analysis, an "envelope" typically refers to a pair of upper and lower bounds that surrounds price action to help characterize extreme overbought and oversold conditions. Envelopes are often derived from a simple moving average (SMA) and are placed at a predefined distance above and below the SMA from which they were generated. // However, envelopes do not necessarily need to be derived from a moving average. In fact, they can be derived from any estimator, including a kernel density estimator (KDE) such as Nadaraya-Watson (NW). Nadaraya-Watson Estimation is a non-parametric regression technique that uses a kernel function to estimate the value of a function at a given point. // In this indicator, the Rational Quadratic (RQ) Kernel is used to estimate the value of the price at each bar. From this estimation, the upper and lower bounds of the envelope are calculated based on ATR and a user-defined multiplier. // Libraries import jdehorty/KernelFunctions/2 as kernels // Helper Functions getBounds(_atr, _nearFactor, _farFactor, _yhat) => _upper_far = _yhat + _farFactor*_atr _upper_near = _yhat + _nearFactor*_atr _lower_near = _yhat - _nearFactor*_atr _lower_far = _yhat - _farFactor*_atr _upper_avg = (_upper_far + _upper_near) / 2 _lower_avg = (_lower_far + _lower_near) / 2 [_upper_near, _upper_far, _upper_avg, _lower_near, _lower_far, _lower_avg] kernel_atr(length, _high, _low, _close) => trueRange = na(_high[1])? _high-_low : math.max(math.max(_high - _low, math.abs(_high - _close[1])), math.abs(_low - _close[1])) ta.rma(trueRange, length) // Kernel Settings h = input.int(8, 'Lookback Window', tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50', group='Kernel Settings') alpha = input.float(8., 'Relative Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25', group='Kernel Settings') x_0 = input.int(25, "Start Regression at Bar", tooltip='Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25', group='Kernel Settings') // Envelope Calculations yhat_close = kernels.rationalQuadratic(close, h, alpha, x_0) yhat_high = kernels.rationalQuadratic(high, h, alpha, x_0) yhat_low = kernels.rationalQuadratic(low, h, alpha, x_0) yhat = yhat_close atr_length = input.int(60, 'ATR Length', minval=1, tooltip='The number of bars associated with the Average True Range (ATR).') ktr = kernel_atr(atr_length, yhat_high, yhat_low, yhat_close) nearFactor = input.float(1.5, 'Near ATR Factor', minval=0.5, step=0.25, tooltip='The factor by which to multiply the ATR to calculate the near bound of the envelope. Recommended range: 0.5-2.0') farFactor = input.float(8.0, 'Far ATR Factor', minval=1.0, step=0.25, tooltip='The factor by which to multiply the ATR to calculate the far bound of the envelope. Recommended range: 6.0-8.0') [upper_near, upper_far, upper_avg, lower_near, lower_far, lower_avg] = getBounds(ktr, nearFactor, farFactor, yhat_close) // Colors red_far = input.color(color.new(color.red, 60), title='Upper Boundary Color: Far', tooltip='The color of the farmost upper boundary of the envelope.', group='Color Settings') red_near = input.color(color.new(color.red, 80), title='Upper Boundary Color: Near', tooltip='The color of the nearmost upper boundary of the envelope.', group='Color Settings') yhat_green = input.color(color.new(color.green, 50), title='Bullish Estimator Color', tooltip='The Bullish color of the Nadaraya-Watson estimator.', group='Color Settings') yhat_red = input.color(color.new(color.red, 50), title='Bearish Estimator Color', tooltip='The Bearish color of the Nadaraya-Watson estimator.', group='Color Settings') green_near = input.color(color.new(color.green, 80), title='Lower Boundary Color: Near', tooltip='The color of the nearmost lower boundary of the envelope.', group='Color Settings') green_far = input.color(color.new(color.green, 60), title='Lower Boundary Color: Far', tooltip='The color of the farmost lower boundary of the envelope.', group='Color Settings') // Plots p_upper_far = plot(upper_far, color=red_far, title='Upper Boundary: Far') p_upper_avg = plot(upper_avg, color=red_near,title='Upper Boundary: Average') p_upper_near = plot(upper_near, color=red_near, title='Upper Boundary: Near') p_yhat = plot(yhat_close, color=yhat > yhat[1] ? yhat_green : yhat_red, linewidth=2, title='Nadaraya-Watson Estimation') p_lower_near = plot(lower_near, color=green_near, title='Lower Boundary: Near') p_lower_avg = plot(lower_avg, color=green_near, title='Lower Boundary: Average') p_lower_far = plot(lower_far, color=green_far, title='Lower Boundary: Far') // Fills fill(p_upper_far, p_upper_avg, color=red_far, title='Upper Boundary: Farmost Region') fill(p_upper_near, p_upper_avg, color=red_near, title='Upper Boundary: Nearmost Region') fill(p_lower_near, p_lower_avg, color=green_near, title='Lower Boundary: Nearmost Region') fill(p_lower_far, p_lower_avg, color=green_far, title='Lower Boundary: Farmost Region')
Rolling MACD
https://www.tradingview.com/script/vzTUAvsR/
chervolino
https://www.tradingview.com/u/chervolino/
71
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/ // © chervolino //@version=5 indicator("Rolling MACD", "RMACD") // Rolling MACD // v1.1 // ———————————————————— Constants and Inputs { // ————— Constants int MS_IN_MIN = 60 * 1000 int MS_IN_HOUR = MS_IN_MIN * 60 int MS_IN_DAY = MS_IN_HOUR * 24 string TT_SRC = "The source used to calculate the MACD." string TT_WINDOW = "By default, the time period used to calculate the RMACD automatically adjusts with the chart's timeframe. Check this to use a fixed-size time period instead, which you define with the following three values." string TT_MINBARS = "The minimum number of last values to keep in the moving window, even if these values are outside the time period. This avoids situations where a large time gap between two bars would cause the time window to be empty." string TT_TABLE = "Displays the time period of the rolling window." // ————— Inputs float srcInput = input.source(close, "Source", tooltip = TT_SRC) string GRP2 = '═══════════   Time Period   ═══════════' bool fixedTfInput = input.bool(false, "Use a fixed time period", group = GRP2, tooltip = TT_WINDOW) int daysInput = input.int(1, "Days", group = GRP2, minval = 0, maxval = 90) * MS_IN_DAY int hoursInput = input.int(0, "Hours", group = GRP2, minval = 0, maxval = 23) * MS_IN_HOUR int minsInput = input.int(0, "Minutes", group = GRP2, minval = 0, maxval = 59) * MS_IN_MIN bool showInfoBoxInput = input.bool(true, "Show time period", group = GRP2) string infoBoxSizeInput = input.string("small", "Size ", inline = "21", group = GRP2, options = ["tiny", "small", "normal", "large", "huge", "auto"]) string infoBoxYPosInput = input.string("bottom", "↕", inline = "21", group = GRP2, options = ["top", "middle", "bottom"]) string infoBoxXPosInput = input.string("left", "↔", inline = "21", group = GRP2, options = ["left", "center", "right"]) color infoBoxColorInput = input.color(color.black, "", inline = "21", group = GRP2) color infoBoxTxtColorInput = input.color(color.white, "T", inline = "21", group = GRP2) string GRP4 = '════════  Minimum Window Size  ════════' int minBarsInput = input.int(10, "Bars", group = GRP4, tooltip = TT_MINBARS) // } // ———————————————————— Functions { // @function Determines a time period from the chart's timeframe. // @returns (int) A value of time in milliseconds that is appropriate for the current chart timeframe. To be used in the RMACD calculation. timeStep() => int tfInMs = timeframe.in_seconds() * 1000 float step = switch tfInMs <= MS_IN_MIN => MS_IN_HOUR tfInMs <= MS_IN_MIN * 5 => MS_IN_HOUR * 4 tfInMs <= MS_IN_HOUR => MS_IN_DAY * 1 tfInMs <= MS_IN_HOUR * 4 => MS_IN_DAY * 3 tfInMs <= MS_IN_HOUR * 12 => MS_IN_DAY * 7 tfInMs <= MS_IN_DAY => MS_IN_DAY * 30.4375 tfInMs <= MS_IN_DAY * 7 => MS_IN_DAY * 90 => MS_IN_DAY * 365 int result = int(step) totalForTimeWhen(src, ms, cond, minBars) => var float[] sources = array.new_float(0) var int[] times = array.new_int(0) if cond array.push(sources, src) array.push(times, time) if array.size(sources) > 0 while time - array.get(times, 0) >= ms and array.size(sources) > minBars array.shift(sources) array.shift(times) float result = array.sum(sources) // @function Produces a string corresponding to the input time in days, hours, and minutes. // @param (series int) A time value in milliseconds to be converted to a string variable. // @returns (string) A string variable reflecting the amount of time from the input time. tfString(int timeInMs) => int s = timeInMs / 1000 int m = s / 60 int h = m / 60 int tm = math.floor(m % 60) int th = math.floor(h % 24) int d = math.floor(h / 24) string result = switch d == 30 and th == 10 and tm == 30 => "1M" d == 7 and th == 0 and tm == 0 => "1W" => string dStr = d ? str.tostring(d) + "D " : "" string hStr = th ? str.tostring(th) + "H " : "" string mStr = tm ? str.tostring(tm) + "min" : "" dStr + hStr + mStr // } // ———————————————————— Calculations and Plots { // Stop the indicator on charts with no volume. if barstate.islast and ta.cum(nz(volume)) == 0 runtime.error("No volume is provided by the data vendor.") int timeInMs = fixedTfInput ? minsInput + hoursInput + daysInput : timeStep() z = input.int(45, title='Inventory Retracement Percentage %', maxval=100) rv = math.abs(close - open) < z / 100 * math.abs(high - low) x = low + z / 100 * math.abs(high - low) y = high - z / 100 * math.abs(high - low) x_1 = totalForTimeWhen(x, timeInMs, true, minBarsInput) y_1 = totalForTimeWhen(y, timeInMs, true, minBarsInput) sl = rv == 1 and high > y_1 and close < y_1 and open < y_1 ss = rv == 1 and low < x_1 and close > x_1 and open > x_1 li = sl ? y_1 : ss ? x_1 : (x_1 + y_1) / 2 clo_1=totalForTimeWhen(srcInput, timeInMs, true, minBarsInput) macd = clo_1 - li macd_pre = clo_1[1] - li[1] msignal = ta.ema(macd, 9) signal = ta.ema(msignal, 9) plotColor = macd > 0 ? macd > macd_pre ? color.lime : color.green : macd < macd_pre ? color.maroon : color.red plot(msignal,color=plotColor, style = plot.style_columns) plot(signal, color=color.white, style = plot.style_line) is_long_short_text = msignal > signal? "Long" : "Short" is_bullish_bearish_text = msignal > 0 ? "Bullish" : "Bearish" is_long_short_css = msignal > signal? color.green : color.red is_bullish_bearish_css = msignal > signal? color.green : color.red // Display of time period. var table tfDisplay = table.new(infoBoxYPosInput + "_" + infoBoxXPosInput, 3, 3) if showInfoBoxInput and barstate.islastconfirmedhistory table.cell(tfDisplay, 1, 0, tfString(timeInMs), bgcolor = infoBoxColorInput, text_color = infoBoxTxtColorInput, text_size = infoBoxSizeInput) table.cell(tfDisplay, 1, 1, is_long_short_text, bgcolor = infoBoxColorInput, text_color = is_long_short_css, text_size = infoBoxSizeInput) table.cell(tfDisplay, 1, 2, is_bullish_bearish_text, bgcolor = infoBoxColorInput, text_color = is_bullish_bearish_css, text_size = infoBoxSizeInput) // }
LazyScalp Board
https://www.tradingview.com/script/rMVnXgGN-lazyscalp-board/
Aleksandr400
https://www.tradingview.com/u/Aleksandr400/
488
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/ // © Aleksandr400 //@version=5 indicator("LazyScalp Board", overlay = true) avgVolLength = input.int(title="Avg Vol length", defval = 30, minval = 3, maxval=100, step=1) natrLength = input.int(title="NATR length", defval = 14) avgType = input.string("EMA", "Avg type", options = ["SMA", "EMA", "RMA", "WMA"]) position = input.string("Right bottom", "Board position", options = ["Right top", "Right bottom", "Center bottom", "Left bottom", "Left top"]) cellWidth = input.int(8, "Cell width", 1, 20, 1) backColor = input.color(#434651, "Cell Background color") textColor = input.color(color.white, "Cell Text color") backColorAlert = input.color(#FBC02D, "Cell Background color alert") textColorAlert = input.color(color.black, "Cell Text color alert") showTitles = input.bool(true, "Show titles") showDayVol = input.bool(true, "Show Day Volume") showAvgVol = input.bool(true, "Show Avg Volume") showNatr = input.bool(true, "Show NATR") showCorr = input.bool(true, "Show Correlation") corrTicker = input.symbol("BINANCE:BTCUSDT.P", "Correlation symbol") corrPeriod = input.int(title = "Correlation period", defval = 20, step = 1) thresholdDayVol = input.int(title = "Day VOL threshold ($)", defval = 100000000, step = 1000000) thresholdAvgVol = input.int(title = "Avg VOL threshold ($)", defval = 3000000, step = 100000) thresholdNatr = input.float(title = "NATR threshold", defval = 1, step = 0.1) // Titles dv = "" av = "" n = "" c = "" if showTitles dv := "DV " av := "AV " n := "N " c := "C " // FORMATTER formater(data) => if str.length(data) > 11 str.substring(data, 0, 3) + " B" else if str.length(data) > 10 str.substring(data, 0, 2) + " B" else if str.length(data) > 9 str.substring(data, 0, 1) + " B" else if str.length(data) > 8 str.substring(data, 0, 3) + " M" else if str.length(data) > 7 str.substring(data, 0, 2) + " M" else if str.length(data) > 6 str.substring(data, 0, 1) + " M" else if str.length(data) > 5 str.substring(data, 0, 3) + " K" else if str.length(data) > 4 str.substring(data, 0, 2) + " K" else if str.length(data) > 3 str.substring(data, 0, 1) + " K" // NART natr = ta.ema(ta.tr(true), natrLength) / close * 100 if avgType == "RMA" natr := ta.rma(ta.tr(true), natrLength) / close * 100 if avgType == "SMA" natr := ta.sma(ta.tr(true), natrLength) / close * 100 if avgType == "WMA" natr := ta.wma(ta.tr(true), natrLength) / close * 100 natrFormated = str.tostring(math.round(natr, 2)) // DAY VOLUME from different timeframe d1 = request.security(syminfo.tickerid, "60", volume * close) d2 = request.security(syminfo.tickerid, "60", volume[1] * close[1]) d3 = request.security(syminfo.tickerid, "60", volume[2] * close[2]) d4 = request.security(syminfo.tickerid, "60", volume[3] * close[3]) d5 = request.security(syminfo.tickerid, "60", volume[4] * close[4]) d6 = request.security(syminfo.tickerid, "60", volume[5] * close[5]) d7 = request.security(syminfo.tickerid, "60", volume[6] * close[6]) d8 = request.security(syminfo.tickerid, "60", volume[7] * close[7]) d9 = request.security(syminfo.tickerid, "60", volume[8] * close[8]) d10 = request.security(syminfo.tickerid, "60", volume[9] * close[9]) d11 = request.security(syminfo.tickerid, "60", volume[10] * close[10]) d12 = request.security(syminfo.tickerid, "60", volume[11] * close[11]) d13 = request.security(syminfo.tickerid, "60", volume[12] * close[12]) d14 = request.security(syminfo.tickerid, "60", volume[13] * close[13]) d15 = request.security(syminfo.tickerid, "60", volume[14] * close[14]) d16 = request.security(syminfo.tickerid, "60", volume[15] * close[15]) d17 = request.security(syminfo.tickerid, "60", volume[16] * close[16]) d18 = request.security(syminfo.tickerid, "60", volume[17] * close[17]) d19 = request.security(syminfo.tickerid, "60", volume[18] * close[18]) d20 = request.security(syminfo.tickerid, "60", volume[19] * close[19]) d21 = request.security(syminfo.tickerid, "60", volume[20] * close[20]) d22 = request.security(syminfo.tickerid, "60", volume[21] * close[21]) d23 = request.security(syminfo.tickerid, "60", volume[22] * close[22]) d24 = request.security(syminfo.tickerid, "60", volume[23] * close[23]) dayVolNumber = math.round(d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + d9 + d10 + d11 + d12 + d13 + d14 + d15 + d16 + d17 + d18 + d19 + d20 + d21 + d22 + d23 + d24) dayVol = str.tostring(dayVolNumber) dayVol := formater(dayVol) // AVG VOLUME avgVolArr = array.new_float(1, volume * close) for i = 1 to avgVolLength - 1 array.push(avgVolArr, volume[i] * close[i]) avgVolNumber = math.round(array.avg(avgVolArr)) avgVol = str.tostring(avgVolNumber) avgVol := formater(avgVol) // CORRELATION corrTickerData = request.security(corrTicker, "1", close) corr = math.round(ta.correlation(corrTickerData, close, corrPeriod), 2) // Styles backColorDayVol = backColor textColorDayVol = textColor backColorAvgVol = backColor textColorAvgVol = textColor backColorNatr = backColor textColorNatr = textColor if dayVolNumber >= thresholdDayVol backColorDayVol := backColorAlert textColorDayVol := textColorAlert if avgVolNumber >= thresholdAvgVol backColorAvgVol := backColorAlert textColorAvgVol := textColorAlert if natr >= thresholdNatr backColorNatr := backColorAlert textColorNatr := textColorAlert var tablePosition = position.top_right if position == "Right top" tablePosition := position.top_right if position == "Right bottom" tablePosition := position.bottom_right if position == "Center bottom" tablePosition := position.bottom_center if position == "Left bottom" tablePosition := position.bottom_left if position == "Left top" tablePosition := position.top_left // Render table var infoTable = table.new(tablePosition, 1, 4, border_width = 1) if barstate.islast if showDayVol table.cell(infoTable, 0, 0, text = dv + str.tostring(dayVol), width = cellWidth, bgcolor = backColorDayVol, text_color = textColorDayVol) if showAvgVol table.cell(infoTable, 0, 1, text = av + str.tostring(avgVol), width = cellWidth, bgcolor = backColorAvgVol, text_color = textColorAvgVol) if showNatr table.cell(infoTable, 0, 2, text = n + natrFormated + " %", width = cellWidth, bgcolor = backColorNatr, text_color = textColorNatr) if showCorr table.cell(infoTable, 0, 3, text = c + " " + str.tostring(corr), width = cellWidth, bgcolor = backColor, text_color = textColor)
Pinbar by BirdCoin
https://www.tradingview.com/script/LqhKo2kK-Pinbar-by-BirdCoin/
BirdCoin11
https://www.tradingview.com/u/BirdCoin11/
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/ // © BirdCoin11 //@version=5 indicator('Pinbar by BirdCoin', overlay=true) candle = math.abs(high - low) body = math.abs(open - close) upshadow = open>close?(high-open):(high-close) downshadow = open>close?(close-low):(open-low) minspread = input.float(defval = 0.15, title = "Min Spread, %", minval = 0.01, maxval = 100, step=0.01, tooltip="Percentage of Min Spread compared to Price", group="Pinbar Condition") maxspread = input.float(defval = 1.5, title = "Max Spread, %", minval = 0.01, maxval = 100, step=0.01, tooltip="Percentage of Max Spread compared to Price", group="Pinbar Condition") longwick = input.float(defval = 50, title = "Min Long Wick, %", minval = 25, maxval = 100, step=1, tooltip="Percent longer than the total candle", group="Pinbar Condition") shortwick = input.float(defval = 20, title = "Max Short Wick, %", minval = 0, maxval = 50, step=1, tooltip="Percent shorter than the total candle", group="Pinbar Condition") realbody = input.float(defval = 33, title = "Max Body, %", minval = 0, maxval = 50, step=1, tooltip="Percent shorter than the total candle", group="Pinbar Condition") minvol = input.float(defval = 500, title = "Min Volume", minval = 1, step=1, group="Pinbar Condition") hunt = input.int(defval = 1, title = "Hunt?", minval = 0, step=1, tooltip = "How many previous candles were hunted?", group="Pinbar Condition") hunt1 = hunt > 0 ? hunt : 1 upperbound = input.float(defval = 0, title = "Upper Bound", minval = 0, tooltip = "Alert when pinbar appear in range", group="Alert in Range") lowerbound = input.float(defval = 0, title = "Lower Bound", minval = 0, tooltip = "Alert when pinbar appear in range", group="Alert in Range") //Pinbar condition check? l1 = candle > close * minspread / 100 l2 = candle < close * maxspread / 100 l3 = high > ta.highest (high,hunt1)[1] l4 = downshadow < candle * shortwick / 100 l5 = upshadow > candle * longwick / 100 l6 = volume > minvol l7 = close < open l8 = body < candle * realbody / 100 //bearish pin bar bearishpin = hunt > 0 ? l1 and l2 and l3 and l4 and l5 and l6 and l7 and l8 : l1 and l2 and l4 and l5 and l6 and l7 and l8 plotshape(bearishpin, title = "Pinbar Down", style=shape.triangledown, color=color.new(color.red, 0), size=size.tiny, location=location.abovebar) //Pinbar condition check? h1 = candle > close * minspread / 100 h2 = candle < close * maxspread / 100 h3 = low < ta.lowest (low,hunt1)[1] h4 = downshadow > candle * longwick / 100 h5 = upshadow < candle * shortwick / 100 h6 = volume > minvol h7 = close > open h8 = body < candle * realbody / 100 //bullish pin bar bullishpin = hunt > 0 ? h1 and h2 and h3 and h4 and h5 and h6 and h7 and h8 : h1 and h2 and h4 and h5 and h6 and h7 and h8 plotshape(bullishpin, title = "Pinbar Up", style=shape.triangleup, color=color.new(color.green, 0), size=size.tiny, location=location.belowbar) //pin bar in range inrange_up_alert = high[1] >= lowerbound and low[1] <= upperbound and bullishpin inrange_down_alert = high[1] >= lowerbound and low[1] <= upperbound and bearishpin //================================= Alerts =================================== NewPinbar = bullishpin[1] or bearishpin[1] alertcondition(bullishpin, title='Pinbar Up', message='Pinbar Up') alertcondition(bearishpin, title='Pinbar Down', message='Pinbar Down') alertcondition(bullishpin, title='New Pinbar', message='New Pinbar') alertcondition(inrange_up_alert, title='Pinbar Up in Range', message='Pinbar Up in Range') alertcondition(inrange_down_alert, title='Pinbar Down in Range', message='Pinbar Down in Range')
Times-Revenue (Fundamental Metric)
https://www.tradingview.com/script/qFDCH1Ng-Times-Revenue-Fundamental-Metric/
jcode773
https://www.tradingview.com/u/jcode773/
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/ // © jcode773 //@version=5 indicator("Times Revenue") TSO = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ") MarketCap = TSO * close TRY = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FY") TRQ = request.financial(syminfo.tickerid, "TOTAL_REVENUE", "FQ") TVY = MarketCap / TRY plot(TVY, "Annual", color.red) qftBarTime = timeframe.change('3M') counter = 0 number = 1 max = 4 total= 0.0 latest = TRQ[0] prices = array.new_float(4,-1) array.set(prices, 0, latest) while number < max if (na(TRQ[counter])) break else if TRQ[counter] != latest array.set(prices, number, TRQ[counter]) number:= number + 1 latest := TRQ[counter] counter := counter + 1 TVQ = MarketCap / (array.get(prices,0) + array.get(prices,1) + array.get(prices,2) + array.get(prices,3)) plot(TVQ, "Past 4 Quarters", color.black) //test = str.tostring(array.get(prices,3)) //test = str.tostring(bar_index) //if (barstate.islast) // label.new(bar_index, 0, "ex: " + test) sTV = str.tostring(TVQ[0]) sTY = str.tostring(TVY[0]) if barstate.islast var label = label.new(x=bar_index, y=TVQ[0], yloc = yloc.price, color=color.black, textcolor=color.white, text=sTV) label.set_style(label, label.style_label_lower_left) var red = label.new(x=bar_index, y=TVY[0], yloc = yloc.price, color=color.black, textcolor=color.red, text=sTY) label.set_style(red, label.style_label_upper_right)
ema20-50-200
https://www.tradingview.com/script/z9z37NZ9/
rakanishux
https://www.tradingview.com/u/rakanishux/
6
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © rakanishux //@version=5 indicator("Conjunto",overlay=true) ema20 = ta.ema(close, 20) ema50 = ta.ema(close, 50) ema200 = ta.ema(close, 200) plot( ema20, color=color.red, title="ema20", linewidth=1) plot( ema50, color=color.green, title="ema50", linewidth=1) plot( ema200, color=color.white, title="ema200", linewidth=1)
Automatic Closest FVG with BPR
https://www.tradingview.com/script/W2DlVs8C-Automatic-Closest-FVG-with-BPR/
Texmoonbeam
https://www.tradingview.com/u/Texmoonbeam/
1,183
study
5
MPL-2.0
// // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // // © Texmoonbeam //@version=5 indicator("Auto Closest FVG with BPR", overlay = true, max_boxes_count = 100, max_lines_count = 100, max_labels_count = 500, max_bars_back = 5000) bullfvg = input.color(defval=color.new(color.teal,25), title='Bull FVG') bearfvg = input.color(defval=color.new(color.maroon,25), title='Bear FVG') style = input.string(line.style_solid, 'Line Style', options=[line.style_solid, line.style_dotted, line.style_dashed]) width = input.int(1, 'Line Width', minval=0) lookback = input.int(defval=50, title='Bars to look back') mit = input.string(defval="full fill high/low", title = "Mitigation Type", options = ["full fill high/low","full fill open/close","half fill high/low","half fill open/close","no mitigation"], tooltip="Defines when an FVG will be mitigated and not used/displayed. This can be when full or half filled, by a high/low value or open/close value. When using no mitigation the nearest FVG will be shown always.") gap = input.float(defval = 0.0, minval = 0.0, title = "Minimum Price Gap of FVGs", tooltip = "When the price gap for an FVG is less than this, it will not be used in the nearest selection", step=0.1) bprs = input.bool(defval=true, title='Show when nearest FVGs create a BPR ▼', tooltip="BPR refers to balanced price range, and an overlapped bull/bear FVG pair.") //Convert a given string resolution into seconds ResolutionToSec(res)=> mins = res == "1" ? 1 : res == "3" ? 3 : res == "5" ? 5 : res == "10" ? 10 : res == "15" ? 15 : res == "30" ? 30 : res == "45" ? 45 : res == "60" ? 60 : res == "120" ? 120 : res == "180" ? 180 : res == "240" ? 240 : res == "D" or res == "1D" ? 1440 : res == "W" or res == "1W" ? 10080 : res == "M" or res == "1M" ? 43200 : res == "" ? int(str.tonumber(timeframe.period)) : int(str.tonumber(res)) ms = mins * 60 * 1000 bar = ResolutionToSec(timeframe.period) //addition = ResolutionToSec(timeframe == "" ? timeframe.period : timeframe) var n = 0 var m = 0 var bullmit = false var bearmit = false var float bullhigh = na var float bearlow = na var float prevnearbull = high var float prevnearbear = high var line bullhighline = na var line bearhighline = na var line bulllowline = na var line bearlowline = na var label bearbpr = na var label bullbpr = na var bullfvghight = array.new_int() var bullfvglowt= array.new_int() var bearfvghight = array.new_int() var bearfvglowt = array.new_int() var bullfvghighttemp = array.new_int() var bullfvglowttemp= array.new_int() var bearfvghighttemp = array.new_int() var bearfvglowttemp = array.new_int() //array.copy var bullfvghigh = array.new_float() var bullfvglow = array.new_float() var bearfvghigh = array.new_float() var bearfvglow = array.new_float() var bullfvghightemp = array.new_float() var bullfvglowtemp = array.new_float() var bearfvghightemp = array.new_float() var bearfvglowtemp = array.new_float() nearest(prev, curr, target) => if (math.abs(prev-target) < math.abs(curr-target)) prev else curr arrayadd(n, arr1, arr2) => array.push(arr2, array.get(arr1, n)) if (high[2] < low and (math.abs(high[2] - low) / high[2]) * 100 > gap) array.push(bullfvghigh, high[2]) array.push(bullfvglow, low) array.push(bullfvghight, time[2]) array.push(bullfvglowt, time) if (array.size((bullfvglow)) > 0) for x = array.size((bullfvglow))-1 to 0 if (mit == "full fill high/low") if (not(low <= array.get(bullfvghigh, x)) and array.get(bullfvghight, x) >= time - lookback*(bar+2)) arrayadd(x, bullfvghigh, bullfvghightemp) arrayadd(x, bullfvghight, bullfvghighttemp) arrayadd(x, bullfvglow, bullfvglowtemp) arrayadd(x, bullfvglowt, bullfvglowttemp) if (mit == "half fill high/low") if (not(low <= array.get(bullfvglow, x)-(array.get(bullfvglow, x)-array.get(bullfvghigh, x))/2) and array.get(bullfvghight, x) >= time - lookback*(bar+2)) arrayadd(x, bullfvghigh, bullfvghightemp) arrayadd(x, bullfvghight, bullfvghighttemp) arrayadd(x, bullfvglow, bullfvglowtemp) arrayadd(x, bullfvglowt, bullfvglowttemp) if (mit == "full fill open/close") if ((close<open ? close : open) >= array.get(bullfvghigh, x) and array.get(bullfvghight, x) >= time - lookback*(bar+2)) arrayadd(x, bullfvghigh, bullfvghightemp) arrayadd(x, bullfvghight, bullfvghighttemp) arrayadd(x, bullfvglow, bullfvglowtemp) arrayadd(x, bullfvglowt, bullfvglowttemp) if (mit == "half fill open/close") if ((close<open ? close : open) >= array.get(bullfvglow, x)-(array.get(bullfvglow, x)-array.get(bullfvghigh, x))/2) and array.get(bullfvghight, x) >= time - lookback*(bar+2) arrayadd(x, bullfvghigh, bullfvghightemp) arrayadd(x, bullfvghight, bullfvghighttemp) arrayadd(x, bullfvglow, bullfvglowtemp) arrayadd(x, bullfvglowt, bullfvglowttemp) if (mit == "no mitigation") if (array.get(bullfvghight, x) >= time - lookback*(bar+2)) arrayadd(x, bullfvghigh, bullfvghightemp) arrayadd(x, bullfvghight, bullfvghighttemp) arrayadd(x, bullfvglow, bullfvglowtemp) arrayadd(x, bullfvglowt, bullfvglowttemp) bullfvghigh := array.copy(bullfvghightemp) bullfvghight := array.copy(bullfvghighttemp) bullfvglow := array.copy(bullfvglowtemp) bullfvglowt := array.copy(bullfvglowttemp) array.clear(bullfvghightemp) array.clear(bullfvghighttemp) array.clear(bullfvglowtemp) array.clear(bullfvglowttemp) if (low[2] > high and (math.abs(high - low[2]) / high) * 100 > gap) array.push(bearfvghigh, high) array.push(bearfvglow, low[2]) array.push(bearfvghight, time) array.push(bearfvglowt, time[2]) if (array.size((bearfvglow)) > 0) for x = array.size((bearfvglow))-1 to 0 if (mit == "full fill high/low") if (not(high >= array.get(bearfvglow, x)) and array.get(bearfvglowt, x) >= time - lookback*(bar+2)) arrayadd(x, bearfvghigh, bearfvghightemp) arrayadd(x, bearfvghight, bearfvghighttemp) arrayadd(x, bearfvglow, bearfvglowtemp) arrayadd(x, bearfvglowt, bearfvglowttemp) if (mit == "half fill high/low") if (not(high >= array.get(bearfvglow, x)-(array.get(bearfvglow, x)-array.get(bearfvghigh, x))/2) and array.get(bearfvglowt, x) >= time - lookback*(bar+2)) arrayadd(x, bearfvghigh, bearfvghightemp) arrayadd(x, bearfvghight, bearfvghighttemp) arrayadd(x, bearfvglow, bearfvglowtemp) arrayadd(x, bearfvglowt, bearfvglowttemp) if (mit == "full fill open/close") if ((close>open ? close : open) < array.get(bearfvglow, x) and array.get(bearfvglowt, x) >= time - lookback*(bar+2)) arrayadd(x, bearfvghigh, bearfvghightemp) arrayadd(x, bearfvghight, bearfvghighttemp) arrayadd(x, bearfvglow, bearfvglowtemp) arrayadd(x, bearfvglowt, bearfvglowttemp) if (mit == "half fill open/close") if ((close>open ? close : open) < array.get(bearfvglow, x)-(array.get(bearfvglow, x)-array.get(bearfvghigh, x))/2 and array.get(bearfvglowt, x) >= time - lookback*(bar+2)) arrayadd(x, bearfvghigh, bearfvghightemp) arrayadd(x, bearfvghight, bearfvghighttemp) arrayadd(x, bearfvglow, bearfvglowtemp) arrayadd(x, bearfvglowt, bearfvglowttemp) if (mit == "no mitigation") if (array.get(bearfvglowt, x) >= time - lookback*(bar+2)) arrayadd(x, bearfvghigh, bearfvghightemp) arrayadd(x, bearfvghight, bearfvghighttemp) arrayadd(x, bearfvglow, bearfvglowtemp) arrayadd(x, bearfvglowt, bearfvglowttemp) bearfvghigh := array.copy(bearfvghightemp) bearfvghight := array.copy(bearfvghighttemp) bearfvglow := array.copy(bearfvglowtemp) bearfvglowt := array.copy(bearfvglowttemp) array.clear(bearfvghightemp) array.clear(bearfvghighttemp) array.clear(bearfvglowtemp) array.clear(bearfvglowttemp) var bullhighlinearr = array.new_line() var bulllowlinearr = array.new_line() var bearhighlinearr = array.new_line() var bearlowlinearr = array.new_line() if (bar_index == last_bar_index) if (array.size(bullfvghigh) > 0) n:=0 prevnearbull := high for x = array.size((bullfvghigh))-1 to 0 if (math.abs(close-(array.get(bullfvglow, x)-(array.get(bullfvglow, x)-array.get(bullfvghigh, x))/2)) < prevnearbull) prevnearbull := math.abs(close-(array.get(bullfvglow, x)-(array.get(bullfvglow, x)-array.get(bullfvghigh, x))/2)) n := x bullhighline := line.new(x1=array.get(bullfvghight, n), y1=array.get(bullfvghigh, n), x2=time+(bar*2), y2 = array.get(bullfvghigh, n), xloc=xloc.bar_time, color = bullfvg, style=style, width=width) bulllowline := line.new(x1=array.get(bullfvglowt, n), y1=array.get(bullfvglow, n), x2=time+(bar*2), y2 = array.get(bullfvglow, n), xloc=xloc.bar_time, color = bullfvg, style=style, width=width) line.set_x2(bullhighline, time+(bar*2)) line.set_x2(bulllowline, time+(bar*2)) array.push(bullhighlinearr, bullhighline) array.push(bulllowlinearr, bulllowline) if (array.size(bullhighlinearr) > 1) delline1 = array.remove(bullhighlinearr, 0) line.delete(delline1) delline2 = array.remove(bulllowlinearr, 0) line.delete(delline2) if (array.size(bearfvghigh) > 0) m:=0 prevnearbear := high for x = array.size((bearfvghigh))-1 to 0 if (math.abs(close-(array.get(bearfvglow, x)-(array.get(bearfvglow, x)-array.get(bearfvghigh, x))/2)) < prevnearbear) prevnearbear := math.abs(close-(array.get(bearfvglow, x)-(array.get(bearfvglow, x)-array.get(bearfvghigh, x))/2)) m := x bearhighline := line.new(x1=array.get(bearfvghight, m), y1=array.get(bearfvghigh, m), x2=time+(bar*2), y2 = array.get(bearfvghigh, m), xloc=xloc.bar_time, color = bearfvg, style=style, width=width) bearlowline := line.new(x1=array.get(bearfvglowt, m), y1=array.get(bearfvglow, m), x2=time+(bar*2), y2 = array.get(bearfvglow, m), xloc=xloc.bar_time, color = bearfvg, style=style, width=width) line.set_x2(bearhighline, time+(bar*2)) line.set_x2(bearlowline, time+(bar*2)) array.push(bearhighlinearr, bearhighline) array.push(bearlowlinearr, bearlowline) if (array.size(bearhighlinearr) > 1) delline3 = array.remove(bearhighlinearr, 0) line.delete(delline3) delline4 = array.remove(bearlowlinearr, 0) line.delete(delline4) label.delete(bearbpr) label.delete(bullbpr) if (array.size(bulllowlinearr) > 0 and array.size(bearlowlinearr) > 0) if (line.get_y1(array.get(bulllowlinearr, 0)) < line.get_y1(array.get(bearlowlinearr, 0)) and line.get_y1(array.get(bullhighlinearr, 0)) > line.get_y1(array.get(bearhighlinearr, 0)) and bprs) bearbpr := label.new(x=time, y=high, text=str.tostring("▼"), xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=bearfvg, size=size.normal, textalign=text.align_right) if (line.get_y1(array.get(bearlowlinearr, 0)) < line.get_y1(array.get(bulllowlinearr, 0)) and line.get_y1(array.get(bearhighlinearr, 0)) > line.get_y1(array.get(bullhighlinearr, 0)) and bprs) bearbpr := label.new(x=time, y=high, text=str.tostring("▼"), xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=bullfvg, size=size.normal, textalign=text.align_right) // debug label.new(x=time, y=high, text=str.tostring(prevnearbear), xloc=xloc.bar_time, color=color.white, style=label.style_none, textcolor=color.green, size=size.normal, textalign=text.align_right)
[ENT] Indicators
https://www.tradingview.com/script/D1GOg8p4-ent-indicators/
Lancelot6303
https://www.tradingview.com/u/Lancelot6303/
32
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Edgar Ovsepyan/Lancelot6303/ENT //@version=5 indicator('[ENT] Indicators', overlay=true) var grp23 = 'NewYorkMidnight по NY GTM -4. Стандарт 00:00' //NYM// sess2Show = input.bool(true, title='', inline='2', group=grp23) sess2Hour = input.int(0, title='', minval=0, maxval=0, inline='2', group=grp23) sess2Minute = input.int(0, title='', minval=0, maxval=0, inline='2', group=grp23) sess2Text = input.string("NYM ", title='', inline='2', group=grp23) sess2Col = input.color(color.rgb(81, 19, 138), title='', inline="2", group=grp23) inSession2 = hour == sess2Hour and minute == sess2Minute and second == 0 var grp24 = 'Настройки NYM' MAX_LINES = input.int(1, title='История открытий', minval=1, maxval=1, group=grp24) extendHours = input.int(16, title='Длина линии в часах', minval=16, maxval=16, group=grp24) linesWidth = input.int(2, title='Ширина линии', minval=1, maxval=2, group=grp24) _labelSize = input.string("Normal", title='Размер текста', options=['Small', 'Normal'], group=grp24) labelSize = _labelSize == "Small" ? size.small : _labelSize == "Normal" ? size.normal : size.huge var line[] l1 = array.new_line(0) var line[] l2 = array.new_line(0) var line[] l3 = array.new_line(0) var label[] la1 = array.new_label(0) var label[] la2 = array.new_label(0) var label[] la3 = array.new_label(0) _extend = extendHours * 3600000 if inSession2 and not inSession2[1] and sess2Show array.push(l2, line.new(time, open, time + _extend, open, xloc=xloc.bar_time, color=sess2Col, width=linesWidth)) array.push(la2, label.new(time + _extend, open, sess2Text, xloc=xloc.bar_time, style=label.style_none, size=labelSize, textcolor=sess2Col)) // Delete lines if more than max if array.size(l1) > MAX_LINES line.delete(array.shift(l1)) label.delete(array.shift(la1)) if array.size(l2) > MAX_LINES line.delete(array.shift(l2)) label.delete(array.shift(la2)) if array.size(l3) > MAX_LINES line.delete(array.shift(l3)) label.delete(array.shift(la3)) //DO// daily_time = request.security(syminfo.tickerid, 'D', time, lookahead=barmerge.lookahead_on) daily_open = request.security(syminfo.tickerid, 'D', open, lookahead=barmerge.lookahead_on) daily_close = request.security(syminfo.tickerid, 'D', close, lookahead=barmerge.lookahead_on) var dailyopen = input(defval=true, title='Daily Open') var extend_right = 20 var show_open = dailyopen and timeframe.isintraday and timeframe.multiplier <= 60 DOcolor = close >= daily_open daily_color = DOcolor ? color.rgb(0, 0, 0, 53) : color.rgb(0, 0, 0, 53) rightbar(bars) => time_close + (time - time[1]) * bars if barstate.islast if show_open and DOcolor and not barstate.isconfirmed and barstate.isrealtime var open_line = line.new(x1=daily_time, x2=rightbar(extend_right), y1=daily_open, y2=daily_open, color = daily_color, width=1, xloc = xloc.bar_time) var open_label = label.new(x=rightbar(extend_right), y=daily_open, text='Open ' + str.tostring(daily_open), style = label.style_none, textcolor = #ff0000, size = size.small, xloc = xloc.bar_time) line.set_x1(open_line, daily_time) line.set_x2(open_line, rightbar(extend_right)) line.set_y1(open_line, daily_open) line.set_y2(open_line, daily_open) label.set_x(open_label, rightbar(extend_right)) label.set_y(open_label, daily_open) if show_open and not DOcolor and not barstate.isconfirmed and barstate.isrealtime var open_line = line.new(x1=daily_time, x2=rightbar(extend_right), y1=daily_open, y2=daily_open, color = daily_color, width=1, xloc = xloc.bar_time) var open_label = label.new(x=rightbar(extend_right), y=daily_open, text='Open ' + str.tostring(daily_open), style = label.style_none, textcolor = #ff0000, size = size.small, xloc = xloc.bar_time) line.set_x1(open_line, daily_time) line.set_x2(open_line, rightbar(extend_right)) line.set_y1(open_line, daily_open) line.set_y2(open_line, daily_open) label.set_x(open_label, rightbar(extend_right)) label.set_y(open_label, daily_open) //weeklyOpen weekly_time = request.security(syminfo.tickerid, 'W', time, lookahead=barmerge.lookahead_on) weekly_open = request.security(syminfo.tickerid, 'W', open, lookahead=barmerge.lookahead_on) weekly_close = request.security(syminfo.tickerid, 'W', close, lookahead=barmerge.lookahead_on) var weeklyopen = input(defval=true, title='Weekly Open') var extend_right1 = 20 var showweekly_open = weeklyopen and timeframe.isintraday and timeframe.multiplier <= 60 WOcolor = close >= weekly_open weekly_color = WOcolor ? color.rgb(0, 0, 0, 53) : color.rgb(0, 0, 0, 53) rightbar1(bars) => time_close + (time - time[1]) * bars if barstate.islast if showweekly_open and WOcolor and not barstate.isconfirmed and barstate.isrealtime var open_line = line.new(x1=weekly_time, x2=rightbar1(extend_right1), y1=weekly_open, y2=weekly_open, color = weekly_color, width=1, xloc = xloc.bar_time) var open_label = label.new(x=rightbar1(extend_right1), y=weekly_open, text='Weekly Open ' + str.tostring(weekly_open), style = label.style_none, textcolor = #ff0000, size = size.small, xloc = xloc.bar_time) line.set_x1(open_line, weekly_time) line.set_x2(open_line, rightbar1(extend_right1)) line.set_y1(open_line, weekly_open) line.set_y2(open_line, weekly_open) label.set_x(open_label, rightbar1(extend_right1)) label.set_y(open_label, weekly_open) if showweekly_open and not WOcolor and not barstate.isconfirmed and barstate.isrealtime var open_line = line.new(x1=weekly_time, x2=rightbar1(extend_right1), y1=weekly_open, y2=weekly_open, color = weekly_color, width=1, xloc = xloc.bar_time) var open_label = label.new(x=rightbar1(extend_right1), y=weekly_open, text='Weekly Open ' + str.tostring(weekly_open), style = label.style_none, textcolor = #ff0000, size = size.small, xloc = xloc.bar_time) line.set_x1(open_line, weekly_time) line.set_x2(open_line, rightbar1(extend_right1)) line.set_y1(open_line, weekly_open) line.set_y2(open_line, weekly_open) label.set_x(open_label, rightbar1(extend_right1)) label.set_y(open_label, weekly_open) //MonthlyOpen monthly_time = request.security(syminfo.tickerid, 'M', time, lookahead=barmerge.lookahead_on) monthly_open = request.security(syminfo.tickerid, 'M', open, lookahead=barmerge.lookahead_on) monthly_close = request.security(syminfo.tickerid, 'M', close, lookahead=barmerge.lookahead_on) var monthlyopen = input(defval=true, title='Monthly Open') var extend_right2 = 20 var showmonthly_open = monthlyopen and timeframe.isintraday and timeframe.multiplier <= 60 MOcolor = close >= monthly_open monthly_color = MOcolor ? color.rgb(0, 0, 0, 53) : color.rgb(0, 0, 0, 53) rightbar2(bars) => time_close + (time - time[1]) * bars if barstate.islast if showmonthly_open and MOcolor and not barstate.isconfirmed and barstate.isrealtime var open_line = line.new(x1=monthly_time, x2=rightbar2(extend_right2), y1=monthly_open, y2=monthly_open, color = monthly_color, width=1, xloc = xloc.bar_time) var open_label = label.new(x=rightbar2(extend_right2), y=monthly_open, text='Monthly Open ' + str.tostring(monthly_open), style = label.style_none, textcolor = #ff0000, size = size.small, xloc = xloc.bar_time) line.set_x1(open_line, monthly_time) line.set_x2(open_line, rightbar2(extend_right2)) line.set_y1(open_line, monthly_open) line.set_y2(open_line, monthly_open) label.set_x(open_label, rightbar2(extend_right2)) label.set_y(open_label, monthly_open) if showmonthly_open and not MOcolor and not barstate.isconfirmed and barstate.isrealtime var open_line = line.new(x1=monthly_time, x2=rightbar2(extend_right2), y1=monthly_open, y2=monthly_open, color = monthly_color, width=1, xloc = xloc.bar_time) var open_label = label.new(x=rightbar2(extend_right2), y=monthly_open, text='Monthly Open ' + str.tostring(monthly_open), style = label.style_none, textcolor = #ff0000, size = size.small, xloc = xloc.bar_time) line.set_x1(open_line, monthly_time) line.set_x2(open_line, rightbar2(extend_right2)) line.set_y1(open_line, monthly_open) line.set_y2(open_line, monthly_open) label.set_x(open_label, rightbar2(extend_right2)) label.set_y(open_label, monthly_open) //PDH&PDL disp_dp = input(true, title='PDH/PDL') firstbar(resolution) => ch = 0 if resolution == 'Y' t = year(time('D')) ch := ta.change(t) != 0 ? 1 : 0 ch else t = time(resolution) ch := ta.change(t) != 0 ? 1 : 0 ch ch pp_res = 'D' bars_sinse = 0 bars_sinse := firstbar(pp_res) ? 0 : bars_sinse[1] + 1 phigh_d = request.security(syminfo.tickerid, 'D', high[1], barmerge.gaps_off, barmerge.lookahead_on) plow_d = request.security(syminfo.tickerid, 'D', low[1], barmerge.gaps_off, barmerge.lookahead_on) y_th = line.new(bar_index[math.min(bars_sinse, 300)], disp_dp ? phigh_d : na, bar_index, disp_dp ? phigh_d : na, color=color.rgb(0, 0, 0, 56), style=line.style_solid, width=1, extend=extend.none) y_tl = line.new(bar_index[math.min(bars_sinse, 300)], disp_dp ? plow_d : na, bar_index, disp_dp ? plow_d : na, color=color.rgb(0, 0, 0, 60), style=line.style_solid, width=1, extend=extend.none) line.delete(y_th[1]) line.delete(y_tl[1]) label_yh = label.new(bar_index, disp_dp ? phigh_d : na, text='PDH', textcolor = color.rgb(0, 0, 0, 52), style=label.style_none) label_yl = label.new(bar_index, disp_dp ? plow_d : na, text='PDL', textcolor = #00000063,style=label.style_none) label.delete(label_yh[1]) label.delete(label_yl[1]) // -------------------- INPUTS -------------------- var GRP0 = "=============== Часовой пояс ===============" hoursOffsetInput = input.string(title='Часовой пояс NY', defval='-4', options=['-4'], group=GRP0) newDayHr = input.int(17, title='Начало дня по NY 17 не менять!', minval=0, maxval=23, group=GRP0) // --- CONSTANTS --- TIMEZONE = "GMT"+hoursOffsetInput ISNEWDAY = dayofweek != dayofweek[1] TRANSPARENT = color.new(color.white, 100) exchangeOffset = hour(timenow, TIMEZONE) - hour(timenow, syminfo.timezone) HOUR = hour + exchangeOffset <= 23 ? hour + exchangeOffset : (hour + exchangeOffset) - 24 // --- CONSTANTS --- var grp1 = '-------------------- Сессии - выставить время по NY --------------' session1Text = input.string('London Open', title='', inline='1', group=grp1) session1Time = input.session(title='', defval='0400-0700', inline='1', group=grp1) session1Color = input.color(color.new(color.blue, 0), title='', inline='1', group=grp1) session1Show = input.bool(true, title='', inline='1', group=grp1) session2Text = input.string('NY Open', title='', inline='2', group=grp1) session2Time = input.session(title='', defval='0900-1100', inline='2', group=grp1) session2Color = input.color(color.new(color.red, 0), title='', inline='2', group=grp1) session2Show = input.bool(true, title='', inline='2', group=grp1) session3Text = input.string('London Close', title='', inline='3', group=grp1) session3Time = input.session(title='', defval='1100-1300', inline='3', group=grp1) session3Color = input.color(color.new(color.lime, 0), title='', inline='3', group=grp1) session3Show = input.bool(true, title='', inline='3', group=grp1) session4Text = input.string('Tokyo', title='', inline='4', group=grp1) session4Time = input.session(title='', defval='1900-0300', inline='4', group=grp1) session4Color = input.color(color.new(#d89b19, 0), title='', inline='4', group=grp1) session4Show = input.bool(true, title='', inline='4', group=grp1) bgType = input.string(title='Type', defval='Line', options=['Line'], inline='5', group=grp1) linePosition = input.string(title='Lines Position', defval='Bottom', options=['Top', 'Bottom'], inline='5', group=grp1) var grp2 = "-------------------- Табло сессий --------------------" showTable = input.bool(true, title='Показать табло', inline='1', group=grp2) showNextSession = input.bool(true, title='Показать следующую сессию', inline='1', group=grp2) theme = input.string(title='Цвет темы табло', defval='Light', options=['Dark', 'Light'], inline='2', group = grp2) position = input.string(title='Позиция табло', defval='Top Right', options=['Top Right'], inline='2', group = grp2) alignment = input.string(title='Позиция сессий', defval='Horizontal', options=['Vertical', 'Horizontal'], inline='3', group = grp2) noSessionText = input.string('Нет сессий', title='Нет сессий', inline='3', group=grp2) var grp3 = "-------------------- Daily Dividers --------------------" showDailyDividers = input(title='Show Daily Dividers ?', defval=true, inline='1', group=grp3) showDOW = input(true, title='Show days of week', inline='1', group=grp3) divider_text_color = input(color.blue, 'Divider and Text Color', group=grp3) dayLabelOffset = input.int(4, title='Days label offset', minval=1, maxval=15, group=grp3) // -------------------- INPUTS -------------------- // -------------------- FUNCTIONS -------------------- _color1 = theme == "Dark" ? color.white : color.black vline(BarIndex, Color, LineStyle, LineWidth) => LineLengthMult = 10 LineLength = ta.atr(100) * 100 line.new(BarIndex, low-LineLength, BarIndex, high+LineLength, extend=extend.both, color=Color, style=LineStyle, width=LineWidth) // return_1 = line.new(BarIndex, low - ta.tr, BarIndex, high + ta.tr, xloc.bar_index, extend=extend.both, color=Color, style=LineStyle, width=LineWidth) // return_1 timeTillPeriodEnd(sess, _type = 1) => sessionEnd = array.get(str.split(sess, '-'), _type) int endHour = math.round(str.tonumber(str.substring(sessionEnd, 0, 2))) int endMinute = math.round(str.tonumber(str.substring(sessionEnd, 2, 4))) tsNow = timestamp(TIMEZONE, year(time, TIMEZONE), month(time, TIMEZONE), dayofmonth(time, TIMEZONE), hour(time, TIMEZONE), minute(time, TIMEZONE)) tsEnd = timestamp(TIMEZONE, year(time, TIMEZONE), month(time, TIMEZONE), dayofmonth(time, TIMEZONE), endHour, endMinute) timeRemaining = tsEnd - tsNow < 0 ? math.round(((tsEnd+86400000) - tsNow) / 1000) : math.round((tsEnd - tsNow) / 1000) days = math.floor(timeRemaining / 86400) hours = math.floor((timeRemaining % 86400) / 3600) minutes = math.floor((timeRemaining % 3600) / 60) seconds = timeRemaining % 60 [hours, minutes, seconds] resolutionInMinutes() => resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na) int(resInMinutes) // -------------------- FUNCTIONS -------------------- // -------------------- SESSIONS -------------------- sess1 = session1Show ? time(timeframe.period, session1Time, TIMEZONE) : na sess2 = session2Show ? time(timeframe.period, session2Time, TIMEZONE) : na sess3 = session3Show ? time(timeframe.period, session3Time, TIMEZONE) : na sess4 = session4Show ? time(timeframe.period, session4Time, TIMEZONE) : na // -------------------- SESSIONS -------------------- // -------------------- PLOT -------------------- _linPos = linePosition == 'Top' ? location.top : location.bottom plotshape(not na(sess1) and bgType == 'Line' and timeframe.isintraday == true, title='London', style=shape.square, location=_linPos, color=session1Color, size=size.auto) plotshape(not na(sess2) and bgType == 'Line' and timeframe.isintraday == true, title='NY', style=shape.square, location=_linPos, color=session2Color, size=size.auto) plotshape(not na(sess3) and bgType == 'Line' and timeframe.isintraday == true, title='LC', style=shape.square, location=_linPos, color=session3Color, size=size.auto) plotshape(not na(sess4) and bgType == 'Line' and timeframe.isintraday == true, title='Asia', style=shape.square, location=_linPos, color=session4Color, size=size.auto) // -------------------- PLOT -------------------- // -------------------- SESSIONS LOGIC -------------------- sessions_arr = array.new_string(0) if session1Show array.push(sessions_arr, '1') if session2Show array.push(sessions_arr, '2') if session3Show array.push(sessions_arr, '3') if session4Show array.push(sessions_arr, '4') _findSess(_i) => arr_size = array.size(sessions_arr) - 1 _index = array.indexof(sessions_arr, _i) _next = _i if _index < arr_size _next := array.get(sessions_arr, _index + 1) else _next := array.get(sessions_arr, 0) _next _currentSess = noSessionText _currentSessCol = _color1 var _nextSess = noSessionText var _nextSessCol = _color1 var _ni = '0' end_hours = 0 end_minutes = 0 end_seconds = 0 start_hours = 0 start_minutes = 0 start_seconds = 0 // Current Sessions if(sess1) _currentSess := session1Text _currentSessCol := session1Color _ni := _findSess('1') [_h, _m, _s] = timeTillPeriodEnd(session1Time) end_hours := _h end_minutes := _m end_seconds := _s else if(sess2) _currentSess := session2Text _currentSessCol := session2Color _ni := _findSess('2') [_h, _m, _s] = timeTillPeriodEnd(session2Time) end_hours := _h end_minutes := _m end_seconds := _s else if(sess3) _currentSess := session3Text _currentSessCol := session3Color _ni := _findSess('3') [_h, _m, _s] = timeTillPeriodEnd(session3Time) end_hours := _h end_minutes := _m end_seconds := _s else if(sess4) _currentSess := session4Text _currentSessCol := session4Color _ni := _findSess('4') [_h, _m, _s] = timeTillPeriodEnd(session4Time) end_hours := _h end_minutes := _m end_seconds := _s else _currentSess := noSessionText _currentSessCol := _color1 end_hours := 0 end_minutes := 0 end_seconds := 0 // Next Session if _ni == '1' _nextSess := session1Text _nextSessCol := session1Color [_h, _m, _s] = timeTillPeriodEnd(session1Time, 0) start_hours := _h start_minutes := _m start_seconds := _s else if _ni == '2' _nextSess := session2Text _nextSessCol := session2Color [_h, _m, _s] = timeTillPeriodEnd(session2Time, 0) start_hours := _h start_minutes := _m start_seconds := _s else if _ni == '3' _nextSess := session3Text _nextSessCol := session3Color [_h, _m, _s] = timeTillPeriodEnd(session3Time, 0) start_hours := _h start_minutes := _m start_seconds := _s else if _ni == '4' _nextSess := session4Text _nextSessCol := session4Color [_h, _m, _s] = timeTillPeriodEnd(session4Time, 0) start_hours := _h start_minutes := _m start_seconds := _s else _nextSess := noSessionText _nextSessCol := _color1 start_hours := 0 start_minutes := 0 start_seconds := 0 // -------------------- SESSIONS LOGIC -------------------- // -------------------- TABLE -------------------- _position = switch position "Top Left" => position.top_left "Top Right" => position.top_right "Bottom Left" => position.bottom_left => position.bottom_right end_txt = str.tostring(end_hours) + "h " + str.tostring(end_minutes) + "m" start_txt = str.tostring(start_hours) + "h " + str.tostring(start_minutes) + "m" var table _table = table.new(_position, columns = 2, rows = 4, border_width=3) _vert = alignment == 'Vertical' if showTable table.cell(_table, column = 0, row = 0, text = _currentSess, text_color=color.new(_currentSessCol, 0), bgcolor=color.new(_currentSessCol, 90)) table.cell(_table, column = _vert ? 0 : 1, row = _vert ? 1 : 0, text = end_txt, text_color=color.new(_currentSessCol, 0)) if showNextSession table.cell(_table, column = 0, row = 2, text = _nextSess, text_color=color.new(_nextSessCol, 0), bgcolor=color.new(_nextSessCol, 90)) table.cell(_table, column = _vert ? 0 : 1, row = _vert ? 3 : 2, text = start_txt, text_color=color.new(_nextSessCol, 0)) // -------------------- TABLE -------------------- // -------------------- DAILY DIVIDERS -------------------- tickerExchangeOffset = 5 int dayLabelStartTime = 1 _rin = resolutionInMinutes() if syminfo.timezone == 'Etc/UTC' dayLabelStartTime += tickerExchangeOffset dayLabelStartTime isStartTime = HOUR == newDayHr and HOUR[1] != newDayHr //and minute == 0 _inTimeframe = _rin <= 180 and timeframe.isintraday isMon() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.monday : false isTue() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.tuesday : false isWed() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.wednesday : false isThu() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.thursday : false isFri() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.friday : false isSat() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.saturday : false isSun() => _inTimeframe ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.sunday : false if isStartTime and showDailyDividers vline(bar_index, divider_text_color, line.style_dashed, 1) _offset = _rin <= 7 ? math.round(dayLabelOffset * 12) : _rin <= 14 ? math.round(dayLabelOffset * 6) : _rin <= 20 ? math.round(dayLabelOffset * 4) : _rin <= 30 ? math.round(dayLabelOffset * 2) : _rin <= 60 ? math.round(dayLabelOffset * 1) : math.round(dayLabelOffset * 0.2) txtMonH = "Понедельник" txtTueH = "Вторник" txtWedH = "Среда" txtThuH = "Четверг" txtFriH = "Пятница" txtSatH = "Суббота" txtSunH = "Воскресенье" // Days Label plotshape(showDOW and isMon(), text=txtMonH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) plotshape(showDOW and isTue(), text=txtTueH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) plotshape(showDOW and isWed(), text=txtWedH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) plotshape(showDOW and isThu(), text=txtThuH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) plotshape(showDOW and isFri(), text=txtFriH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) plotshape(showDOW and isSat(), text=txtSatH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) plotshape(showDOW and isSun(), text=txtSunH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=divider_text_color, size=size.tiny, editable=false) // -------------------- DAILY DIVIDERS -------------------- // Watermark ENT ///////////////////////////////////////////////// // FONTS ///////////////////////////////////////////////// //{ var FONT1 = array.new<string>(0) if barstate.isfirst array.push(FONT1, "░█████╗░,██████╗░,░█████╗░,██████╗░,███████╗,███████╗,░██████╗░,██╗░░██╗,██╗,░░░░░██╗,██╗░░██╗,██╗░░░░░,███╗░░░███╗,███╗░░██╗,░█████╗░,██████╗░,░██████╗░,██████╗░,░██████╗,████████╗,██╗░░░██╗,██╗░░░██╗,░██╗░░░░░░░██╗,██╗░░██╗,██╗░░░██╗,███████╗,░█████╗░,░░███╗░░,██████╗░,██████╗░,░░██╗██╗,███████╗,░█████╗░,███████╗,░█████╗░,░█████╗░,░░░░") array.push(FONT1, "██╔══██╗,██╔══██╗,██╔══██╗,██╔══██╗,██╔════╝,██╔════╝,██╔════╝░,██║░░██║,██║,░░░░░██║,██║░██╔╝,██║░░░░░,████╗░████║,████╗░██║,██╔══██╗,██╔══██╗,██╔═══██╗,██╔══██╗,██╔════╝,╚══██╔══╝,██║░░░██║,██║░░░██║,░██║░░██╗░░██║,╚██╗██╔╝,╚██╗░██╔╝,╚════██║,██╔══██╗,░████║░░,╚════██╗,╚════██╗,░██╔╝██║,██╔════╝,██╔═══╝░,╚════██║,██╔══██╗,██╔══██╗,░░░░") array.push(FONT1, "███████║,██████╦╝,██║░░╚═╝,██║░░██║,█████╗░░,█████╗░░,██║░░██╗░,███████║,██║,░░░░░██║,█████═╝░,██║░░░░░,██╔████╔██║,██╔██╗██║,██║░░██║,██████╔╝,██║██╗██║,██████╔╝,╚█████╗░,░░░██║░░░,██║░░░██║,╚██╗░██╔╝,░╚██╗████╗██╔╝,░╚███╔╝░,░╚████╔╝░,░░███╔═╝,██║░░██║,██╔██║░░,░░███╔═╝,░█████╔╝,██╔╝░██║,██████╗░,██████╗░,░░░░██╔╝,╚█████╔╝,╚██████║,░░░░") array.push(FONT1, "██╔══██║,██╔══██╗,██║░░██╗,██║░░██║,██╔══╝░░,██╔══╝░░,██║░░╚██╗,██╔══██║,██║,██╗░░██║,██╔═██╗░,██║░░░░░,██║╚██╔╝██║,██║╚████║,██║░░██║,██╔═══╝░,╚██████╔╝,██╔══██╗,░╚═══██╗,░░░██║░░░,██║░░░██║,░╚████╔╝░,░░████╔═████║░,░██╔██╗░,░░╚██╔╝░░,██╔══╝░░,██║░░██║,╚═╝██║░░,██╔══╝░░,░╚═══██╗,███████║,╚════██╗,██╔══██╗,░░░██╔╝░,██╔══██╗,░╚═══██║,░░░░") array.push(FONT1, "██║░░██║,██████╦╝,╚█████╔╝,██████╔╝,███████╗,██║░░░░░,╚██████╔╝,██║░░██║,██║,╚█████╔╝,██║░╚██╗,███████╗,██║░╚═╝░██║,██║░╚███║,╚█████╔╝,██║░░░░░,░╚═██╔═╝░,██║░░██║,██████╔╝,░░░██║░░░,╚██████╔╝,░░╚██╔╝░░,░░╚██╔╝░╚██╔╝░,██╔╝╚██╗,░░░██║░░░,███████╗,╚█████╔╝,███████╗,███████╗,██████╔╝,╚════██║,██████╔╝,╚█████╔╝,░░██╔╝░░,╚█████╔╝,░█████╔╝,░░░░") array.push(FONT1, "╚═╝░░╚═╝,╚═════╝░,░╚════╝░,╚═════╝░,╚══════╝,╚═╝░░░░░,░╚═════╝░,╚═╝░░╚═╝,╚═╝,░╚════╝░,╚═╝░░╚═╝,╚══════╝,╚═╝░░░░░╚═╝,╚═╝░░╚══╝,░╚════╝░,╚═╝░░░░░,░░░╚═╝░░░,╚═╝░░╚═╝,╚═════╝░,░░░╚═╝░░░,░╚═════╝░,░░░╚═╝░░░,░░░╚═╝░░░╚═╝░░,╚═╝░░╚═╝,░░░╚═╝░░░,╚══════╝,░╚════╝░,╚══════╝,╚══════╝,╚═════╝░,░░░░░╚═╝,╚═════╝░,░╚════╝░,░░╚═╝░░░,░╚════╝░,░╚════╝░,░░░░") var FONT_REF = array.from("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"," ") //} ///////////////////////////////////////////////// // SETTINGS ///////////////////////////////////////////////// //{ var watermarkent = input(defval=true, title='Watermark') WATERMARK_TEXT = input.string("ENT", "Text") WATERMARK_STYLE = input.string("Type1", "Style", options=["Type1"]) WATERMARK_COLOR = input.color(color.new(color.gray,85), "Color") WATERMARK_SIZE_OPT = input.string("Normal", "Size", options=["Large","Normal"]) WATERMARK_POS_OPT = input.string("Middle-Center", "Position", options=["Middle-Center"]) WATERMARK_REP_ROW = input.int(1, "Количество: Vertical ", inline="repetition") WATERMARK_REP_COL = input.int(1, "Horizontal ", inline="repetition") WATERMARK_SIZE = switch WATERMARK_SIZE_OPT "Large" => size.large "Normal" => size.normal WATERMARK_POS = switch WATERMARK_POS_OPT "Middle-Center" => position.middle_center FONT = switch WATERMARK_STYLE "Type1" => FONT1 //} ///////////////////////////////////////////////// // MAIN ///////////////////////////////////////////////// var watermark_table = table.new(WATERMARK_POS, WATERMARK_REP_COL, WATERMARK_REP_ROW, na, na) gen_watermark(message) => msg = str.split(str.upper(message), "") idx_list = array.new<int>(0) for ii=0 to array.size(msg)-1 for jj=0 to array.size(FONT_REF)-1 if array.get(msg, ii) == array.get(FONT_REF, jj) array.push(idx_list, jj) break watermark_width = 0 watermark_msg = "" for ii=0 to array.size(FONT)-1 watermark_msg := watermark_msg font_line = str.split(array.get(FONT,ii), ",") for jj=0 to array.size(idx_list)-1 idx = array.get(idx_list, jj) watermark_msg := watermark_msg + array.get(font_line, idx) watermark_width := ( ii == 0 )? watermark_width + str.length(array.get(font_line, idx)) : watermark_width watermark_msg := watermark_msg + "\n" for mm=0 to WATERMARK_REP_COL-1 for nn=0 to WATERMARK_REP_ROW-1 table.cell(watermark_table, mm, nn, watermark_msg, text_color=WATERMARK_COLOR, text_halign=text.align_left, text_size=WATERMARK_SIZE) if barstate.islastconfirmedhistory and watermarkent == true gen_watermark(WATERMARK_TEXT)
Support Bands indicator
https://www.tradingview.com/script/sUnZhmup-Support-Bands-indicator/
RCBInvestments
https://www.tradingview.com/u/RCBInvestments/
27
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © RCBInvestments //@version=5 indicator("Support Bands",overlay=true) ema8= ta.ema(close,8) sma10= ta.sma(close,10) ema8_c=plot (ema8, "EMA8",color=color.rgb(89, 238, 109)) sma10_c=plot (sma10, "SMA 10",color=color.rgb(91, 158, 221)) MA8Index= ema8 MA10Index=sma10 plotshape(ta.crossover(MA8Index,MA10Index), style=shape.arrowup, color=color.green) plotshape(ta.crossover(MA10Index,MA8Index), style=shape.arrowdown, color=color.rgb(190, 10, 10)) fill(ema8_c,sma10_c, title="Support Band 1",color = ema8 > sma10? color.new(color.green,50): ema8 < sma10 ? color.new(color.red,50):na) ema21= ta.ema(close,21) sma30= ta.sma(close,30) ema21_c=plot(ema21,"EMA 21",color=color.orange) sma30_c=plot(sma30,"SMA 30",color=color.rgb(70, 61, 61)) MA21Index= ema21 MA30Index=sma30 plotshape(ta.crossover(MA21Index,MA30Index), style=shape.arrowup, color=color.rgb(107, 188, 241)) plotshape(ta.crossover(MA30Index,MA21Index), style=shape.arrowdown, color=color.rgb(250, 169, 76)) fill(ema21_c,sma30_c, title="Support Band 2", color = ema21 > sma30? color.new(color.green,50): ema21 < sma30 ? color.new(color.red,50):na) a=ta.sma(close,5) j=ta.sma(close,195) c=ta.sma(close,130) h=ta.sma(close,65) i=ta.sma(close,30) b=ta.sma(close,40) src1 = input(close, "SMA Source") len1 = input(50, "SMA") out1 =ta.sma(src1, len1) plot(out1, title="SMA 50", color=close >= out1 ? color.rgb(31, 167, 14, 42) : color.rgb(155, 32, 32)) d=ta.sma(close,100) e=ta.sma(close,150) f=ta.sma(close,200) g=ta.sma(close,300) plot(a, "B Shannon 5 SMA",color=color.rgb(212, 141, 208)) plot(j,"10 Min 5 SMA", color= color.rgb(212, 141, 208)) plot(c,"15 Min 5 SMA", color= color.rgb(212, 141, 208)) plot(h,"30 Min 5 SMA", color= color.rgb(212, 141, 208)) plot(i,"65 Min 5 SMA", color= color.rgb(212, 141, 208)) plot(b, "SMA 40", color=color.rgb(97,97,97)) plot(d,"SMA 100",color=color.rgb(252, 251, 251)) plot(e, "SMA 150",color=color.rgb(243, 33, 233)) plot(f,"SMA 200",color=color.yellow) plot(g,"SMA 300",color=color.rgb (112,2,2))
Pivot Points
https://www.tradingview.com/script/7Pe5Jf5I-Pivot-Points/
bandelier
https://www.tradingview.com/u/bandelier/
118
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/ // © bandelier //@version=5 indicator("Pivot Points", overlay = true) prevClose = request.security(syminfo.tickerid, "D", close[1], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on) prevHigh = request.security(syminfo.tickerid, "D", high[1], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on) prevLow = request.security(syminfo.tickerid, "D", low[1], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on) pivot = (prevClose + prevHigh + prevLow) / 3 R1 = (pivot * 2) - prevLow R2 = pivot + (prevHigh - prevLow) R3 = prevHigh + (2*(pivot - prevLow)) S1 = (pivot * 2) - prevHigh S2 = pivot - (prevHigh - prevLow) S3 = prevLow - (2*(prevHigh - pivot)) plot(pivot, color = color.white) plot(R1, color = color.red) plot(R2, color = color.red) plot(R3, color = color.red) plot(S1, color = color.green) plot(S2, color = color.green) plot(S3, color = color.green) PivotLabel = label.new(bar_index, pivot, text = "P", color = color.white) R1Label = label.new(bar_index, R1, text = "R1", color = color.red) R2Label = label.new(bar_index, R2, text = "R2", color = color.red) R3Label = label.new(bar_index, R3, text = "R3", color = color.red) S1Label = label.new(bar_index, S1, text = "S1", color = color.green) S2Label =label.new(bar_index, S2, text = "S2", color = color.green) S3Label = label.new(bar_index, S3, text = "S3", color = color.green) label.delete(PivotLabel[1]) label.delete(R1Label[1]) label.delete(R2Label[1]) label.delete(R3Label[1]) label.delete(S1Label[1]) label.delete(S2Label[1]) label.delete(S3Label[1])
Yield Curve (1-10yr)
https://www.tradingview.com/script/7J1QerZA-Yield-Curve-1-10yr/
capriole_charles
https://www.tradingview.com/u/capriole_charles/
119
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/ // © charles edwards //@version=4 study("Yield Curve (1-10yr)", overlay=false) OneYear = security("DGS1", "D", close) TenYear = security("DGS10", "D", close) YC = (TenYear - OneYear) curveO = plot(YC) lineO = plot(0, color=color.gray) fill(plot1=curveO, plot2=lineO, color= YC<0 ? color.new(color.red,70): na, title="Inverted") // Sourcing var table_source = table(na) table_source := table.new(position=position.bottom_left, columns=1, rows=1, bgcolor=color.white, border_width=1) table.cell(table_source, 0, 0, text="Source: Capriole Investments Limited", bgcolor=color.white, text_color=color.black, width=20, height=7, text_size=size.normal, text_halign=text.align_left)
PDs - MID ADVANCE RANGE
https://www.tradingview.com/script/2Gjgtw1w-PDs-MID-ADVANCE-RANGE/
tejedawx
https://www.tradingview.com/u/tejedawx/
6
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © tejedawx //@version=5 // // Pine Script v4 // @author BigBitsIO // Script Library: https://www.tradingview.com/u/BigBitsIO/#published-scripts // indicator('PDs - MID ADVANCE RANGE', overlay=true, timeframe="") //len = input.int(2, minval=2, title='Length') //SMlen = input.int(10, minval=2, title='HMA Smoothing') //MULT = input.int(2, minval=1, title="Multiplier") col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above") col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above") col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below") col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below") // I have consolidated some of this code from a prior example o = open c = close h = high l = low //so = ta.hma(o, SMlen) //sc = ta.hma(c, SMlen) //sh = ta.hma(h, SMlen) //sl = ta.hma(l, SMlen) //Initial Price Average Data //ohlcFour = ta.hma(ohlc4, len) //ohlcFourSMT = ta.ema(ohlcFour, 4) //Close Data //Close = ta.hma(close, len) //CloseSMT = ta.hma(Close, 3) //MID OPEN-CLOSE OC = (o+c)/2 //FIRST AVERAGES UA_ONE= if o < c //VERDE (h+c)/2 else (h+o)/2 LA_ONE = if o > c // ROJA (l+c)/2 else (l+o)/2 MID = (UA_ONE+LA_ONE)/2 EMA1 = ta.ema(UA_ONE, 1) EMA2 = ta.ema(LA_ONE, 1) //SECOND AVERAGES UA_TWO = (OC+UA_ONE)/2 LA_TWO = (OC+LA_ONE)/2 EMA10 = ta.ema(UA_TWO, 1) EMA20 = ta.ema(LA_TWO, 1) MID2 = (UA_TWO+LA_TWO)/2 MID3 = (MID2+MID2[1])/2 //RANGE //UPA = UPPER_AVE+((MID-LOWER_AVE)*MULT) //LWA = LOWER_AVE-((UPPER_AVE-MID)*MULT) DIFF = EMA1-EMA2 //ta.ema(((EMA1) - (EMA2)), 1) DIFF2 = MID3-MID3[1] LRANGE = if MID3 > MID3[1] MID3-(MID3 - ((l+l[1]+l[2])/3)) else MID3-(MID3-l) URANGE = if MID3 < MID3[1] MID3+(((h+h[1]+h[2])/3)- MID3) else MID3+(h-MID3) //MIDAVE = (ta.ema(MID, SMlen) + ohlcFourSMT)/2 //DIFFMIDAVE= ta.ema(MIDAVE - (ta.ema(MID, SMlen)), 2) //colorBody = sc > so[1] ? color.lime : color.red //plotcandle(so, sh, sl, sc, color=colorBody, title='Hull Candles') //plot(ohlcFourSMT, color=color.new(color.black, 0)) //plot(EMA1, color=color.blue) //plot(EMA2, color=color.maroon) //plot(EMA10, color=color.green) //plot(EMA20, color=color.lime) //plot(MID, color=color.yellow) plot(MID3, color=color.black) plot(LRANGE, color=color.blue) plot(URANGE, color=color.purple) // //plot(RES, color=color.blue) //plot(LWA, color=color.maroon) //plot(ta.ema(EMA0, 3), color=color.blue) //plot(ta.ema(EMA01, 3), color=color.purple) //plot(DIFF, title="Power+ Histogram", style=plot.style_columns, color=(DIFF>=0 ? (DIFF[1] < DIFF ? col_grow_above : col_fall_above) : (DIFF[1] < DIFF ? col_grow_below : col_fall_below))) //plot(SDIFF, color=color.black) //plot(ta.hma(DIFF, 10)) //plot(DIFF, color=color.green) //plot(DIFF2, color=color.purple) //plot(LAST, color=color.black) //plot(DIFFMIDAVE, color=color.blue) //plot(c, color=color.blue) //plot(so, color=color.new(color.blue, 0)) //plot(sc, color=color.new(color.purple, 0)) //plot(sh, color=color.new(color.red, 0)) //plot(sl, color=color.new(color.lime, 0))
PDs - MID ADVANCE DIRECTION
https://www.tradingview.com/script/ZlOGkJr8-PDs-MID-ADVANCE-DIRECTION/
tejedawx
https://www.tradingview.com/u/tejedawx/
6
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © tejedawx //@version=5 // // Pine Script v4 // @author BigBitsIO // Script Library: https://www.tradingview.com/u/BigBitsIO/#published-scripts // indicator('PDs - MID ADVANCE DIRECTION', overlay=true, timeframe="") //len = input.int(2, minval=2, title='Length') //SMlen = input.int(10, minval=2, title='HMA Smoothing') //MULT = input.int(2, minval=1, title="Multiplier") col_grow_above = input(#26A69A, "Above Grow", group="Histogram", inline="Above") col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above") col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below") col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below") // I have consolidated some of this code from a prior example o = open c = close h = high l = low //so = ta.hma(o, SMlen) //sc = ta.hma(c, SMlen) //sh = ta.hma(h, SMlen) //sl = ta.hma(l, SMlen) //Initial Price Average Data //ohlcFour = ta.hma(ohlc4, len) //ohlcFourSMT = ta.ema(ohlcFour, 4) //Close Data //Close = ta.hma(close, len) //CloseSMT = ta.hma(Close, 3) //MID OPEN-CLOSE OC = (o+c)/2 //FIRST AVERAGES UA_ONE= if o < c //VERDE (h+c)/2 else (h+o)/2 LA_ONE = if o > c // ROJA (l+c)/2 else (l+o)/2 MID = (UA_ONE+LA_ONE)/2 EMA1 = ta.ema(UA_ONE, 1) EMA2 = ta.ema(LA_ONE, 1) //SECOND AVERAGES UA_TWO = (OC+UA_ONE)/2 LA_TWO = (OC+LA_ONE)/2 EMA10 = ta.ema(UA_TWO, 1) EMA20 = ta.ema(LA_TWO, 1) MID2 = (UA_TWO+LA_TWO)/2 MID3 = (MID2+MID2[1])/2 //RANGE //UPA = UPPER_AVE+((MID-LOWER_AVE)*MULT) //LWA = LOWER_AVE-((UPPER_AVE-MID)*MULT) DIFF = EMA1-EMA2 //ta.ema(((EMA1) - (EMA2)), 1) DIFF2 = MID3-MID3[1] LRANGE = if MID3 > MID3[1] MID3-(MID3 - ((l+l[1]+l[2])/3)) else MID3-(MID3-l) URANGE = if MID3 < MID3[1] MID3+(((h+h[1]+h[2])/3)- MID3) else MID3+(h-MID3) //MIDAVE = (ta.ema(MID, SMlen) + ohlcFourSMT)/2 //DIFFMIDAVE= ta.ema(MIDAVE - (ta.ema(MID, SMlen)), 2) //colorBody = sc > so[1] ? color.lime : color.red //plotcandle(so, sh, sl, sc, color=colorBody, title='Hull Candles') //plot(ohlcFourSMT, color=color.new(color.black, 0)) //plot(EMA1, color=color.blue) //plot(EMA2, color=color.maroon) //plot(EMA10, color=color.green) //plot(EMA20, color=color.lime) //plot(MID, color=color.yellow) plot(MID3, color=color.black) //plot(LRANGE, color=color.blue) //plot(URANGE, color=color.purple) //plot(UPA, color=color.blue) //plot(LWA, color=color.maroon) //plot(ta.ema(EMA0, 3), color=color.blue) //plot(ta.ema(EMA01, 3), color=color.purple) //plot(DIFF, title="Power+ Histogram", style=plot.style_columns, color=(DIFF>=0 ? (DIFF[1] < DIFF ? col_grow_above : col_fall_above) : (DIFF[1] < DIFF ? col_grow_below : col_fall_below))) //plot(SDIFF, color=color.black) //plot(ta.hma(DIFF, 10)) //plot(DIFF, color=color.green) //plot(DIFF2, color=color.purple) //plot(LAST, color=color.black) //plot(DIFFMIDAVE, color=color.blue) //plot(c, color=color.blue) //plot(so, color=color.new(color.blue, 0)) //plot(sc, color=color.new(color.purple, 0)) //plot(sh, color=color.new(color.red, 0)) //plot(sl, color=color.new(color.lime, 0))
PADR
https://www.tradingview.com/script/w2yd0JvH-PADR/
Andrew_Yong
https://www.tradingview.com/u/Andrew_Yong/
0
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/ // © Andrew_Yong //@version=5 indicator("PADR", overlay=true) lengthInput = input.int(14, title="Length") smaHigh = ta.sma(high, lengthInput) smaLow = ta.sma(low, lengthInput) i_res = input.timeframe('D', "Resolution") s = request.security("FCPO1!", i_res, smaHigh - smaLow) plot(s ? s : na, style=plot.style_line, linewidth=2, color=color.rgb(0, 255, 0))
Relative Bi-Directional Volatility Range
https://www.tradingview.com/script/86VHetM6/
metka183
https://www.tradingview.com/u/metka183/
66
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © metka183 //@version=5 indicator(title="Relative Bi-Directional Volatility Range", shorttitle="RBVR2.1", overlay=false, max_bars_back=3000, timeframe="", timeframe_gaps=false) //Input ---------------------------------- category = "Moving Average Control" ma_type = input.string("Relative", title="Type", options=["Median", "Simple", "Relative", "Exponential", "Weighted", "Volume Weighted", "Hull 2xL Weighted"], group=category) ma_len = input.int(8, "Length", minval=1, group=category) ma_lohi = input.bool(false, "Activate Moving Averages for Volatility Lows and Highs", group=category) category2 = "Trend Signal Separation" ma_pow = input.float(0, "Power", minval=0, step=0.5, group=category2, tooltip="This factor potentiates the separation of strong and weak signals. Background color will become brighter for weaker signals. A too high factor can wipe out the weaker signals and therefore make trend indication maybe useless.") [curO, curC, curH, curL] = request.security(syminfo.tickerid, timeframe.period, [open, close, high, low]) curG = not na(curC[1]) ? curO-curC[1] : 0. //---------------------------------------- //Volatility ----------------------------- volaC = 0., volaL = 0., volaH = 0., divisor = 1., nrg = 1. if bar_index > 0 divisor := math.abs(curC[1]) > 0 ? math.abs(curC[1]) : 0.00000001 volaC := (curC-curC[1])/divisor nrg := ma_pow > 0 ? math.pow(1-1/(1+volaC*volaC), ma_pow) : 1. if volaC > 0 volaL := (curL-curG-curH[1])/divisor volaH := (curH-curL[1])/divisor else volaL := (curL-curH[1])/divisor volaH := (curH-curG-curL[1])/divisor volaC := volaC > 0 ? 1-1/(1+volaC) : 1/(1-volaC)-1 volaL := volaL > 0 ? 1-1/(1+volaL) : 1/(1-volaL)-1 volaH := volaH > 0 ? 1-1/(1+volaH) : 1/(1-volaH)-1 volaC *= 100, volaL *= 100, volaH *= 100 //---------------------------------------- //Moving Average ------------------------- ma = 0., ma_nrg = 0., ma_low = 0., ma_high = 0. dL = bar_index >= ma_len ? ma_len : bar_index+1 //limitation for insufficient data history if ma_type == "Relative" or ma_type == "Exponential" len = ma_type == "Relative" ? 1/ma_len : 2/(ma_len+1) //does not need a limitation ma := (1-len)*nz(ma[1]) + len*volaC ma_nrg := (1-len)*nz(ma_nrg[1]) + len*volaC*nrg ma_low := (1-len)*nz(ma_low[1]) + len*volaL ma_high := (1-len)*nz(ma_high[1]) + len*volaH else if ma_type == "Median" ma := ta.median(volaC, dL) ma_nrg := ta.median(volaC*nrg, dL) ma_low := ta.median(volaL, dL) ma_high := ta.median(volaH, dL) else if ma_type == "Simple" ma := ta.sma(volaC, dL) ma_nrg := ta.sma(volaC*nrg, dL) ma_low := ta.sma(volaL, dL) ma_high := ta.sma(volaH, dL) else if ma_type == "Weighted" ma := ta.wma(volaC, dL) ma_nrg := ta.wma(volaC*nrg, dL) ma_low := ta.wma(volaL, dL) ma_high := ta.wma(volaH, dL) else if ma_type == "Volume Weighted" ma := ta.vwma(volaC, dL) ma_nrg := ta.vwma(volaC*nrg, dL) ma_low := ta.vwma(volaL, dL) ma_high := ta.vwma(volaH, dL) else if ma_type == "Hull 2xL Weighted" dL := bar_index >= 2*ma_len ? 2*ma_len : bar_index+1 //make Hull more comparable to Weighted Moving Average len = math.round(math.sqrt(dL)) len2 = math.round(dL/2) len2 := dL != 2 ? len2 : 2 //small correction to avoid overshooting wma = ta.wma(volaC, dL), wma_nrg = ta.wma(volaC*nrg, dL) wma_low = ta.wma(volaL, dL), wma_high = ta.wma(volaH, dL) wma2 = 2*ta.wma(volaC, len2), wma2_nrg = 2*ta.wma(volaC*nrg, len2) wma2_low = 2*ta.wma(volaL, len2), wma2_high = 2*ta.wma(volaH, len2) ma := ta.wma(wma2-wma, len) ma_nrg := ta.wma(wma2_nrg-wma_nrg, len) ma_low := ta.wma(wma2_low-wma_low, len) ma_high := ta.wma(wma2_high-wma_high, len) //---------------------------------------- //Status and Color ----------------------- var ma_status = 0 var ma_color = color.gray var ma_color_up = color.purple var ma_color_down = color.yellow var fill_color_up = color.rgb(76, 175, 79, 100) var fill_color_down = color.rgb(255, 82, 82, 100) var volaH_color = color.rgb(50, 115, 50, 40) var volaL_color = color.rgb(175, 50, 50, 40) ma_sum = 0. if not na(ma[1]) if ma_nrg < 0 and ma < 0 ma_sum -= 1 else if ma_nrg > 0 and ma < 0 ma_sum -= 0.5 else if ma_nrg > 0 and ma > 0 ma_sum += 1 else if ma_nrg < 0 and ma > 0 ma_sum += 0.5 if ma_status >= 0 and ma_sum < -0.5 ma_status := -1 else if ma_status <= 0 and ma_sum > 0.5 ma_status := 1 if ma_sum <= -1 ma_color := ma_color_down fill_color_up := color.rgb(76, 175, 79, 100) fill_color_down := color.rgb(255, 82, 82, 65) volaH_color := color.rgb(50, 115, 50, 40) volaL_color := color.rgb(175, 50, 50, 0) else if ma_sum < 0 ma_color := ma_color_down fill_color_up := color.rgb(76, 175, 79, 100) fill_color_down := color.rgb(255, 82, 82, 85) volaH_color := color.rgb(50, 115, 50, 40) volaL_color := color.rgb(175, 50, 50, 40) else if ma_sum >= 1 ma_color := ma_color_up fill_color_up := color.rgb(76, 175, 79, 65) fill_color_down := color.rgb(255, 82, 82, 100) volaH_color := color.rgb(50, 115, 50, 0) volaL_color := color.rgb(175, 50, 50, 40) else if ma_sum > 0 ma_color := ma_color_up fill_color_up := color.rgb(76, 175, 79, 85) fill_color_down := color.rgb(255, 82, 82, 100) volaH_color := color.rgb(50, 115, 50, 40) volaL_color := color.rgb(175, 50, 50, 40) else ma_color := color.gray if ma_status > 0 fill_color_up := color.rgb(120, 123, 134, 85) fill_color_down := color.rgb(255, 82, 82, 100) else if ma_status < 0 fill_color_up := color.rgb(76, 175, 79, 100) fill_color_down := color.rgb(120, 123, 134, 85) else fill_color_up := color.rgb(76, 175, 79, 100) fill_color_down := color.rgb(255, 82, 82, 100) volaH_color := color.rgb(50, 115, 50, 40) volaL_color := color.rgb(175, 50, 50, 40) var volaC_color = color.gray if volaC > 0 volaC_color := ma_status > 0 ? color.rgb(76, 175, 79, 0) : color.rgb(76, 175, 79, 40) else volaC_color := ma_status < 0 ? color.rgb(255, 82, 82, 0) : color.rgb(255, 82, 82, 40) //---------------------------------------- //Trend Shift Signal --------------------- signal = 0. if ma_status > 0 and nz(ma_status[1]) <= 0 signal := 1.0 else if ma_status < 0 and nz(ma_status[1]) >= 0 signal := -1.0 //---------------------------------------- //Output --------------------------------- line_center = hline(0, "Center Line", color=color.new(#000000, 30), linestyle=hline.style_solid, linewidth=1) line_max = hline(100, "Max Line", color=color.new(#000000, 30), linestyle=hline.style_solid, linewidth=1, display=display.none) line_min = hline(-100, "Min Line", color=color.new(#000000, 30), linestyle=hline.style_solid, linewidth=1, display=display.none) plot(volaC, "Vola", color=volaC_color, linewidth=2, style=plot.style_columns) //Volatility plot(volaH, "Vola High", color=volaH_color, linewidth=2, display=ma_lohi ? display.none : display.all) //Volatility High plot(volaL, "Vola Low", color=volaL_color, linewidth=2, display=ma_lohi ? display.none : display.all) //Volatility Low plot(ma, "VMA", color=ma_color, linewidth=2) //Volatility Moving Average plot(ma_high, "VMA Heigh", color=volaH_color, linewidth=2, display=ma_lohi ? display.all : display.none) //Volatility High Moving Average plot(ma_low, "VMA Low", color=volaL_color, linewidth=2, display=ma_lohi ? display.all : display.none) //Volatility Low Moving Average plot(ma_nrg, "PVMA", color=ma_color, linewidth=2, display=display.none) //Powered Volatility Moving Average plot(signal, "TSS", color=color.new(color.black, 100), linewidth=1, display=display.none) //Trend Shift Signal fill(line_center, line_max, color=fill_color_up, title="Background High") fill(line_center, line_min, color=fill_color_down, title="Background Low") //----------------------------------------
Donchian Channels Multitimeframe Jaime
https://www.tradingview.com/script/aiKZI8oz/
jaimecruz3
https://www.tradingview.com/u/jaimecruz3/
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/ // © jaimecruz3 // Create the popular Donchian Chanels in Multiframe periods //@version=5 indicator('Donchian Channels Multitimeframe Jaime', overlay=true) // GET TIMEFRAMES TimeframeU = input.string(defval='Auto', title='Higher Time Frame', options=['Auto', '1', '3', '5', '10', '15', '30', '60', '120', '180', '240', '360', '480', '720', 'D', 'W', '2W', 'M', '3M', '6M', '12M']) higher_tf = TimeframeU == 'Auto' ? timeframe.period == '1' ? '60' : timeframe.period == '2' ? '60' : timeframe.period == '3' ? '60' : timeframe.period == '5' ? '60' : timeframe.period == '10' ? '120' : timeframe.period == '15' ? '120' : timeframe.period == '30' ? 'D' : timeframe.period == '45' ? 'D' : timeframe.period == '60' ? 'D' : timeframe.period == '120' ? 'D' : timeframe.period == '180' ? 'D' : timeframe.period == '240' ? 'D' : timeframe.period == 'D' ? 'W' : timeframe.period == 'W' ? 'M' : timeframe.period : TimeframeU actual_tf = timeframe.period donchian_period = input.int(defval=20, minval=1, title="Donchian Periods", group="General options") var bool_bullish_donchian_trend = false donchian(highSource, lowSource, rangeLength)=> top = ta.highest(highSource, rangeLength) bottom = ta.lowest(lowSource, rangeLength) middle = (top+bottom)/2 [middle, top, bottom] [donchian_middle, donchian_upper, donchian_lower] = request.security(syminfo.tickerid, actual_tf, donchian(high, low, donchian_period), lookahead=barmerge.lookahead_off) [donchian_middle_HTF, donchian_upper_HTF, donchian_lower_HTF] = request.security(syminfo.tickerid, higher_tf, donchian(high, low, donchian_period), lookahead=barmerge.lookahead_off) plot(donchian_upper, color=color.new(color.gray, 0), editable=false) mdonchian = plot(donchian_middle, color=color.new(color.yellow, 0), editable=false) plot(donchian_lower, color=color.new(color.gray, 0), editable=false) plot(donchian_upper_HTF, color=color.new(color.blue, 0), editable=false) mdonchian_HTF = plot(donchian_middle_HTF, color=color.new(color.orange, 0), editable=false) plot(donchian_lower_HTF, color=color.new(color.blue, 0), editable=false) // See trend if close >= donchian_upper[1] bool_bullish_donchian_trend := true if close <= donchian_lower[1] bool_bullish_donchian_trend := false // plotshape(bool_bullish_donchian_trend, style=shape.triangleup, location=location.abovebar, color=color.green) // plotshape(not bool_bullish_donchian_trend, style=shape.triangledown, location=location.belowbar, color=color.red) fill(mdonchian, mdonchian_HTF, color=color.yellow, title='Middle donchian')
Adaptive Fisherized Stochastic Center of Gravity
https://www.tradingview.com/script/wAwgiNjD-Adaptive-Fisherized-Stochastic-Center-of-Gravity/
simwai
https://www.tradingview.com/u/simwai/
168
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © simwai //@version=5 indicator('Adaptive Fisherized Stochastic Center of Gravity', 'AF_SCG', overlay=false) // -- Input -- // Gradient color schemes var string SH1 = 'Red ⮀ Green' var string SH2 = 'Purple ⮀ Blue' var string SH3 = 'Yellow ⮀ Dark Green' var string SH4 = 'White ⮀ Black' var string SH5 = 'White ⮀ Blue' var string SH6 = 'White ⮀ Red' var string SH7 = 'Rainbow' string stochResolution = input.timeframe(defval='', title='Resolution', group='Stochastic/CG', inline='1') float source = input.source(close, 'Source', group='Stochastic/CG', inline='2') int min = input.int(5, 'Min. Period', minval=1, group='Stochastic/CG', inline='3', tooltip='Used as min length for adaptive mode') int length = input.int(20, 'Period', minval=1, group='Stochastic/CG', inline='4', tooltip='Used as length or max length when adaptive mode is enabled') bool isStoch = input.bool(false, 'Use Stochastic Instead Of CG', tooltip='For overbought/oversold and cross Signals', group='Stochastic/CG', inline='5') bool isFisherized = input.bool(true, 'Enable Inverse Fisher Transform (IFT)', group='Stochastic/CG', inline='6') string signalMode = input.string('Fast Overbought/Oversold', 'Choose Signal Mode', options=['Fast Overbought/Oversold', 'Overbought/Oversold', 'Cross', 'Stoch/CG Cross', 'None'], tooltip='Upper and lower lines are the overbought/oversold trigger lines', group='Stochastic/CG', inline='7') var bool isGradientEnabled = input.bool(true, 'Enable Gradient', group='Gradient', inline='1') var bool isGradientInverted = input.bool(true, 'Invert Colors', group='Gradient', inline='1') var string gradientScheme = input.string(SH2, 'Choose Color Scheme', options = [SH1, SH2, SH3, SH4, SH5, SH6, SH7], group='Gradient', inline='2') string adaptiveMode = input.string('Hilbert Transform', 'Choose Adaptive Mode', options=['Hilbert Transform', 'Inphase-Quadrature Transform', 'Median', 'Homodyne Discriminator', 'None'], group='Adaptiveness', inline='1') bool isLengthPlotEnabled = input.bool(false, 'Enable Length Plot', tooltip='Interesting to see the adaptive length', group='Adaptiveness', inline='2') string smoothingMode = input.timeframe('T3', 'Choose Smoothing Mode', options=['T3', 'Hann Window', 'None'], group='Smoothing', inline='1', tooltip='Smooths the price') int smoothingLength = input.int(3, 'Smoothing Length', minval=2, group='Smoothing', inline='2') float t3Hot = input.float(title='T3 Smoothing Factor', defval=0.5, minval=0.00001, maxval=1, step=0.1, group='Smoothing', inline='3', tooltip='Called hot in code') string t3Type = input.string(title='T3 Type', defval='T3 Normal', options=['T3 Normal', 'T3 New'], group='Smoothing', inline='3') bool isNetEnabled = input.bool(false, 'Enable NET', group='Smoothing', inline='3', tooltip='Ehlers Noise Elmimination Technique') int netLength = input.int(9, 'NET Length', minval=2, group='Smoothing', inline='4') // -- Global States -- [_high, _low, src] = request.security(syminfo.tickerid, stochResolution, [high[1], low[1], source[1]], barmerge.gaps_off, barmerge.lookahead_on) bool areBuySellLabelsEnabled = signalMode != 'None' // -- Colors -- color maximumYellowRed = color.rgb(255, 203, 98) // yellow color rajah = color.rgb(242, 166, 84) // orange color magicMint = color.rgb(171, 237, 198) color lightPurple = color.rgb(193, 133, 243) color languidLavender = color.rgb(232, 215, 255) color maximumBluePurple = color.rgb(181, 161, 226) color skyBlue = color.rgb(144, 226, 244) color lightGray = color.rgb(214, 214, 214) color quickSilver = color.rgb(163, 163, 163) color mediumAquamarine = color.rgb(104, 223, 153) color transpLightGray = color.new(lightGray, 50) // -- Functions -- // Get highest val in period getHighest(src, len) => H = src[len] for i = 0 to len by 1 if src[i] > H H := src[i] H H // Get lowest val in period getLowest(src, len) => L = src[len] for i = 0 to len by 1 if src[i] < L L := src[i] L L // Get normal stochastic stoch(src, len) => 100 * (src - getLowest(_low, len)) / (getHighest(_high, len) - getLowest(_low, len)) // Apply normalization normalize(float _src, int _min, int _max) => var float _historicMin = 1.0 var float _historicMax = -1.0 _historicMin := math.min(nz(_src, _historicMin), _historicMin) _historicMax := math.max(nz(_src, _historicMax), _historicMax) _min + (_max - _min) * (_src - _historicMin) / math.max(_historicMax - _historicMin, 1) // Inverse Fisher Transformation (IFT) fisherize(float _value) => (math.exp(2 * _value) - 1) / (math.exp(2 * _value) + 1) // Convert length to alpha getAlpha(float _length) => 2 / (_length + 1) // Get dominant cyber cycle – Median – Credits to @blackcat1402 getMedianDc(float Price, float alpha=0.07, simple float CycPart=0.5) => Smooth = 0.00 Cycle = 0.00 Q1 = 0.00 I1 = 0.00 DeltaPhase = 0.00 MedianDelta = 0.00 DC = 0.00 InstPeriod = 0.00 Period = 0.00 I2 = 0.00 Q2 = 0.00 IntPeriod = 0 Smooth := (Price + 2 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 6 Cycle := (1 - .5 * alpha) * (1 - .5 * alpha) * (Smooth - 2 * nz(Smooth[1]) + nz(Smooth[2])) + 2 * (1 - alpha) * nz(Cycle[1]) - (1 - alpha) * (1 - alpha) * nz(Cycle[2]) Cycle := bar_index < 7 ? (Price - 2 * nz(Price[1]) + nz(Price[2])) / 4 : Cycle Q1 := (.0962 * Cycle + .5769 * nz(Cycle[2]) - .5769 * nz(Cycle[4]) - .0962 * nz(Cycle[6])) * (.5 + .08 * nz(InstPeriod[1])) I1 := nz(Cycle[3]) DeltaPhase := Q1 != 0 and nz(Q1[1]) != 0 ? (I1 / Q1 - nz(I1[1]) / nz(Q1[1])) / (1 + I1 * nz(I1[1]) / (Q1 * nz(Q1[1]))) : DeltaPhase DeltaPhase := DeltaPhase < 0.1 ? 0.1 : DeltaPhase DeltaPhase := DeltaPhase > 1.1 ? 1.1 : DeltaPhase MedianDelta := ta.median(DeltaPhase, 5) DC := MedianDelta == 0.00 ? 15.00 : 6.28318 / MedianDelta + .5 InstPeriod := .33 * DC + .67 * nz(InstPeriod[1]) Period := .15 * InstPeriod + .85 * nz(Period[1]) IntPeriod := math.round(Period * CycPart) < 1 ? 1 : math.round(Period * CycPart) IntPeriod // Get dominant cyber cycle – Inphase-Quadrature -- Credits to @DasanC getIQ(float src, int min, int max) => PI = 3.14159265359 P = src - src[7] lenIQ = 0.0 lenC = 0.0 imult = 0.635 qmult = 0.338 inphase = 0.0 quadrature = 0.0 re = 0.0 im = 0.0 deltaIQ = 0.0 instIQ = 0.0 V = 0.0 inphase := 1.25 * (P[4] - imult * P[2]) + imult * nz(inphase[3]) quadrature := P[2] - qmult * P + qmult * nz(quadrature[2]) re := 0.2 * (inphase * inphase[1] + quadrature * quadrature[1]) + 0.8 * nz(re[1]) im := 0.2 * (inphase * quadrature[1] - inphase[1] * quadrature) + 0.8 * nz(im[1]) if re != 0.0 deltaIQ := math.atan(im / re) deltaIQ for i = 0 to max by 1 V += deltaIQ[i] if V > 2 * PI and instIQ == 0.0 instIQ := i instIQ if instIQ == 0.0 instIQ := nz(instIQ[1]) instIQ lenIQ := 0.25 * instIQ + 0.75 * nz(lenIQ[1], 1) length = lenIQ < min ? min : lenIQ > max ? max : lenIQ math.round(length) // Get dominant cyber cycle – Hilbert Transform -- Credits to @DasanC getHT(float src) => Imult = .635 Qmult = .338 PI = 3.14159 InPhase = 0.0 Quadrature = 0.0 Phase = 0.0 DeltaPhase = 0.0 InstPeriod = 0.0 Period = 0.0 Value4 = 0.0 if bar_index > 5 // Detrend src Value3 = src - src[7] // Compute InPhase and Quadrature components InPhase := 1.25 * (Value3[4] - Imult * Value3[2]) + Imult * nz(InPhase[3]) Quadrature := Value3[2] - Qmult * Value3 + Qmult * nz(Quadrature[2]) // Use ArcTangent to compute the current phase if math.abs(InPhase + InPhase[1]) > 0 Phase := 180 / PI * math.atan(math.abs((Quadrature + Quadrature[1]) / (InPhase + InPhase[1]))) Phase // Resolve the ArcTangent ambiguity if InPhase < 0 and Quadrature > 0 Phase := 180 - Phase Phase if InPhase < 0 and Quadrature < 0 Phase := 180 + Phase Phase if InPhase > 0 and Quadrature < 0 Phase := 360 - Phase Phase // Compute a differential phase, resolve phase wraparound, and limit delta phase errors DeltaPhase := Phase[1] - Phase if Phase[1] < 90 and Phase > 270 DeltaPhase := 360 + Phase[1] - Phase DeltaPhase if DeltaPhase < 1 DeltaPhase := 1 DeltaPhase if DeltaPhase > 60 DeltaPhase := 60 DeltaPhase // Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous period. for i = 0 to 50 by 1 Value4 += DeltaPhase[i] if Value4 > 360 and InstPeriod == 0 InstPeriod := i InstPeriod // Resolve Instantaneous Period errors and smooth if InstPeriod == 0 nz(InstPeriod[1]) Period := .25 * InstPeriod + .75 * Period[1] math.round(Period) // Get Dominant Cyber Cycle - Homodyne Discriminator With Hilbert Dominant Cycle – Credits to @blackcat1402 getHdDc(float Price, int min, int max, simple float CycPart = 0.5) => Smooth = 0.00 Detrender = 0.00 I1 = 0.00 Q1 = 0.00 jI = 0.00 jQ = 0.00 I2 = 0.00 Q2 = 0.00 Re = 0.00 Im = 0.00 Period = 0.00 SmoothPeriod = 0.00 pi = 2 * math.asin(1) DomCycle = 0.0 // Hilbert Transform Smooth := bar_index > 7 ? (4 * Price + 3 * nz(Price[1]) + 2 * nz(Price[2]) + nz(Price[3])) / 10 : Smooth Detrender := bar_index > 7 ? (.0962 * Smooth + .5769 * nz(Smooth[2]) - .5769 * nz(Smooth[4]) - .0962 * nz(Smooth[6])) * (.075 * nz(Period[1]) + .54) : Detrender // Compute InPhase and Quadrature components Q1 := bar_index > 7 ? (.0962 * Detrender + .5769 * nz(Detrender[2]) - .5769 * nz(Detrender[4]) - .0962 * nz(Detrender[6])) * (.075 * nz(Period[1]) + .54) : Q1 I1 := bar_index > 7 ? nz(Detrender[3]) : I1 // Advance the phase of I1 and Q1 by 90 degrees jI := (.0962 * I1 + .5769 * nz(I1[2]) - .5769 * nz(I1[4]) - .0962 * nz(I1[6])) * (.075 * nz(Period[1]) + .54) jQ := (.0962 * Q1 + .5769 * nz(Q1[2]) - .5769 * nz(Q1[4]) - .0962 * nz(Q1[6])) * (.075 * nz(Period[1]) + .54) // Phasor addition for 3 bar averaging I2 := I1 - jQ Q2 := Q1 + jI // Smooth the I and Q components before applying the discriminator I2 := .2 * I2 + .8 * nz(I2[1]) Q2 := .2 * Q2 + .8 * nz(Q2[1]) // Homodyne Discriminator Re := I2 * nz(I2[1]) + Q2 * nz(Q2[1]) Im := I2 * nz(Q2[1]) - Q2 * nz(I2[1]) Re := .2 * Re + .8 * nz(Re[1]) Im := .2 * Im + .8 * nz(Im[1]) Period := Im != 0 and Re != 0 ? 2 * pi / math.atan(Im / Re) : Period Period := Period > 1.5 * nz(Period[1]) ? 1.5 * nz(Period[1]) : Period Period := Period < .67 * nz(Period[1]) ? .67 * nz(Period[1]) : Period Period := Period < min ? min : Period Period := Period > max ? max : Period Period := .2 * Period + .8 * nz(Period[1]) SmoothPeriod := .33 * Period + .67 * nz(SmoothPeriod[1]) DomCycle := math.ceil(CycPart * SmoothPeriod) < 1 ? 1 : math.ceil(CycPart * SmoothPeriod) // Limit dominant cycle DomCycle := DomCycle < min ? min : DomCycle > max ? max : DomCycle math.round(DomCycle) // Noise Elimination Technology (NET) – Credits to @blackcat1402 doNet(float _series, simple int _netLength, int _lowerBand=-1, int _upperBand=1) => var netX = array.new_float(102) var netY = array.new_float(102) num = 0.00 denom = 0.00 net = 0.00 trigger = 0.00 for count = 1 to _netLength array.set(netX, count, nz(_series[count - 1])) array.set(netY, count, -count) num := 0 for count = 2 to _netLength for k = 1 to count - 1 num := num - math.sign(nz(array.get(netX, count)) - nz(array.get(netX, k))) denom := 0.5 * _netLength * (_netLength - 1) net := num / denom trigger := 0.05 + 0.9 * nz(net[1]) trigger := normalize(trigger, _lowerBand, _upperBand) // Hann Window Smoothing – Credits to @cheatcountry doHannWindow(float _series, float _hannWindowLength) => sum = 0.0, coef = 0.0 for i = 1 to _hannWindowLength cosine = 1 - math.cos(2 * math.pi * i / (_hannWindowLength + 1)) sum := sum + (cosine * nz(_series[i - 1])) coef := coef + cosine h = coef != 0 ? sum / coef : 0 var color[] colors = array.new_color(na) // T3 - Credits to @loxx t3(float _src, float _length, float hot=1, string clean='T3 Normal')=> a = hot _c1 = -a * a * a _c2 = 3 * a * a + 3 * a * a * a _c3 = -6 * a * a - 3 * a - 3 * a * a * a _c4 = 1 + 3 * a + a * a * a + 3 * a * a alpha = 0. if (clean == 'T3 New') alpha := 2.0 / (2.0 + (_length - 1.0) / 2.0) else alpha := 2.0 / (1.0 + _length) _t30 = _src, _t31 = _src _t32 = _src, _t33 = _src _t34 = _src, _t35 = _src _t30 := nz(_t30[1]) + alpha * (_src - nz(_t30[1])) _t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1])) _t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1])) _t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1])) _t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1])) _t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1])) out = _c1 * _t35 + _c2 * _t34 + _c3 * _t33 + _c4 * _t32 out // Credits to @LucF, https://www.pinecoders.com/faq_and_code/#how-can-i-rescale-an-indicator-from-one-scale-to-another // Rescales series with known min/max to the color array size. rescale(_src, _min, _max) => var int _size = array.size(colors) - 1 int _colorStep = int(_size * (_src - _min)) / int(math.max(_max - _min, 10e-10)) _colorStep := _colorStep > _size ? _size : _colorStep < 0 ? 0 : _colorStep int(_colorStep) colGrad(_src, _min, _max) => array.get(colors, rescale(_src, _min, _max)) // -- Calculation -- // Price Smoothing if (smoothingMode == 'Hann Window') src := doHannWindow(src, smoothingLength) if (smoothingMode == 'T3') src := t3(src, smoothingLength, t3Hot, t3Type) // Adaptiveness float alpha = getAlpha(length) float cyclePart = 0.5 // Cannot override input length variable int _length = length switch adaptiveMode 'Hilbert Transform' => _length := getHT(src) 'Inphase-Quadrature Transform' => _length := getIQ(src, min, _length) 'Median' => _length := getMedianDc(src, alpha, cyclePart), 'Homodyne Discriminator' => _length := getHdDc(src, min, _length) if (_length < min and adaptiveMode != 'None') _length := min plot(isLengthPlotEnabled ? getHT(src) / 2 : na, 'HT', color=skyBlue) plot(isLengthPlotEnabled ? getIQ(src, min, _length) / 2 : na, 'IQ', color=maximumBluePurple) plot(isLengthPlotEnabled ? getMedianDc(src, alpha, cyclePart) / 2 : na, 'M', color=languidLavender) plot(isLengthPlotEnabled ? getHdDc(src, min, _length) : na, 'HD', color=lightPurple) plot(isLengthPlotEnabled ? _length : na, 'CG/Stoch Length', color=maximumYellowRed) // CoG/CG Num = 0.0 Denom = 0.0 CG = 0.0 MaxCG = 0.0 MinCG = 0.0 Value1 = 0.0 Value2 = 0.0 Value3 = 0.0 for i = 0 to _length - 1 by 1 Num += (1 + i) * src[i] Denom += src[i] if (Denom != 0) CG := -Num / Denom + (_length + 1) / 2 MaxCG := getHighest(CG, _length) MinCG := getLowest(CG, _length) if (MaxCG != MinCG) Value1 := (CG - MinCG) / (MaxCG - MinCG) Value2 := (4 * Value1 + 3 * Value1[1] + 2 * Value1[2] + Value1[3]) / 10 Value3 := .5 * math.log((1 + 1.98 * (Value2 - .5)) / (1 - 1.98 * (Value2 - .5))) // Stoch int topBand = 1 int bottomBand = -1 float upperBand = 0.9 float lowerBand = -0.9 int zeroLine = 0 float _stoch = stoch(src, _length) if (isStoch and (not isFisherized) and (signalMode != 'Stoch/CG Cross')) topBand := 100 bottomBand := 0 upperBand := 80 lowerBand := 20 zeroLine := 50 if ((not isStoch) and (not isFisherized)) // topBand := math.round(getHighest(Value3, 20)) // bottomBand := math.round(getLowest(Value3, 20)) topBand := 3 bottomBand := -3 lowerBand := -2.5 upperBand := 2.5 zeroLine := 0 if (isNetEnabled or isFisherized) topBand := 1 bottomBand := -1 upperBand := 0.9 lowerBand := -0.9 zeroLine := 0 // Normalization and Fisherization if (isFisherized or (signalMode == 'Stoch/CG Cross')) Value3 := fisherize(Value3) _stoch := fisherize(0.1 * (_stoch - 50)) // _stoch := fisherize(normalize(_stoch, lowerBand, upperBand)) // Indicator Smoothing if (isNetEnabled) Value3 := doNet(Value3, smoothingLength) _stoch := doNet(_stoch, smoothingLength) // Gradient - Credits @e2e4mfck // Fill the array with colors only on the first iteration of the script if barstate.isfirst if gradientScheme == SH1 array.push(colors, #ff0000), array.push(colors, #ff2c00), array.push(colors, #fe4200), array.push(colors, #fc5300), array.push(colors, #f96200), array.push(colors, #f57000), array.push(colors, #f07e00), array.push(colors, #ea8a00), array.push(colors, #e39600), array.push(colors, #dca100), array.push(colors, #d3ac00), array.push(colors, #c9b600), array.push(colors, #bfc000), array.push(colors, #b3ca00), array.push(colors, #a6d400), array.push(colors, #97dd00), array.push(colors, #86e600), array.push(colors, #71ee00), array.push(colors, #54f700), array.push(colors, #1eff00) else if gradientScheme == SH2 array.push(colors, #ff00d4), array.push(colors, #f71fda), array.push(colors, #ef2ee0), array.push(colors, #e63ae5), array.push(colors, #de43ea), array.push(colors, #d44bee), array.push(colors, #cb52f2), array.push(colors, #c158f6), array.push(colors, #b75df9), array.push(colors, #ac63fb), array.push(colors, #a267fe), array.push(colors, #966bff), array.push(colors, #8b6fff), array.push(colors, #7e73ff), array.push(colors, #7276ff), array.push(colors, #6479ff), array.push(colors, #557bff), array.push(colors, #437eff), array.push(colors, #2e80ff), array.push(colors, #0082ff) else if gradientScheme == SH3 array.push(colors, #fafa6e), array.push(colors, #e0f470), array.push(colors, #c7ed73), array.push(colors, #aee678), array.push(colors, #97dd7d), array.push(colors, #81d581), array.push(colors, #6bcc86), array.push(colors, #56c28a), array.push(colors, #42b98d), array.push(colors, #2eaf8f), array.push(colors, #18a48f), array.push(colors, #009a8f), array.push(colors, #00908d), array.push(colors, #008589), array.push(colors, #007b84), array.push(colors, #0c707d), array.push(colors, #196676), array.push(colors, #215c6d), array.push(colors, #275263), array.push(colors, #2a4858) else if gradientScheme == SH4 array.push(colors, #ffffff), array.push(colors, #f0f0f0), array.push(colors, #e1e1e1), array.push(colors, #d2d2d2), array.push(colors, #c3c3c3), array.push(colors, #b5b5b5), array.push(colors, #a7a7a7), array.push(colors, #999999), array.push(colors, #8b8b8b), array.push(colors, #7e7e7e), array.push(colors, #707070), array.push(colors, #636363), array.push(colors, #575757), array.push(colors, #4a4a4a), array.push(colors, #3e3e3e), array.push(colors, #333333), array.push(colors, #272727), array.push(colors, #1d1d1d), array.push(colors, #121212), array.push(colors, #000000) else if gradientScheme == SH5 array.push(colors, #ffffff), array.push(colors, #f4f5fa), array.push(colors, #e9ebf5), array.push(colors, #dee1f0), array.push(colors, #d3d7eb), array.push(colors, #c8cde6), array.push(colors, #bdc3e1), array.push(colors, #b2b9dd), array.push(colors, #a7b0d8), array.push(colors, #9ca6d3), array.push(colors, #919dce), array.push(colors, #8594c9), array.push(colors, #7a8bc4), array.push(colors, #6e82bf), array.push(colors, #6279ba), array.push(colors, #5570b5), array.push(colors, #4768b0), array.push(colors, #385fab), array.push(colors, #2557a6), array.push(colors, #004fa1) else if gradientScheme == SH6 array.push(colors, #ffffff), array.push(colors, #fff4f1), array.push(colors, #ffe9e3), array.push(colors, #ffded6), array.push(colors, #ffd3c8), array.push(colors, #fec8bb), array.push(colors, #fdbdae), array.push(colors, #fbb2a1), array.push(colors, #f8a794), array.push(colors, #f69c87), array.push(colors, #f3917b), array.push(colors, #f0856f), array.push(colors, #ec7a62), array.push(colors, #e86e56), array.push(colors, #e4634a), array.push(colors, #df563f), array.push(colors, #db4933), array.push(colors, #d63a27), array.push(colors, #d0291b), array.push(colors, #cb0e0e) else if gradientScheme == SH7 array.push(colors, #E50000), array.push(colors, #E6023B), array.push(colors, #E70579), array.push(colors, #E908B7), array.push(colors, #E00BEA), array.push(colors, #A70DEB), array.push(colors, #6E10ED), array.push(colors, #3613EE), array.push(colors, #162DEF), array.push(colors, #1969F1), array.push(colors, #1CA4F2), array.push(colors, #1FDFF4), array.push(colors, #22F5D2), array.push(colors, #25F69C), array.push(colors, #28F867), array.push(colors, #2CF933), array.push(colors, #5DFA2F), array.push(colors, #96FC32), array.push(colors, #CDFD35), array.push(colors, #FFF938) // Invert colors in array if isGradientInverted array.reverse(colors) // Colorize the bounded source color stochGradient = isGradientEnabled ? colGrad(_stoch, bottomBand, topBand) : skyBlue color stochTriggerGradient = isGradientEnabled ? colGrad(_stoch[1], bottomBand, topBand) : color.new(skyBlue, 50) color cgGradient = isGradientEnabled ? colGrad(Value3, bottomBand, topBand) : maximumBluePurple color cgTriggerGradient = isGradientEnabled ? colGrad(Value3[1], bottomBand, topBand) : color.new(maximumBluePurple, 50) bool isCgPlotEnabled = (not isStoch) or (signalMode == 'Stoch/CG Cross') bool isStochPlotEnabled = isStoch or (signalMode == 'Stoch/CG Cross') stochPlot = plot(isStochPlotEnabled ? _stoch : na, 'Stoch', stochGradient, editable=false) stochTriggerPlot = plot((isStochPlotEnabled and (signalMode != 'Stoch/CG Cross')) ? _stoch[1] :na, 'Stoch Trigger', stochTriggerGradient, editable=false) cgPlot = plot(isCgPlotEnabled ? Value3 : na, 'CG', cgGradient, editable=false) cgTriggerPlot = plot((isCgPlotEnabled and (signalMode != 'Stoch/CG Cross')) ? Value3[1] : na, 'CG Trigger', cgTriggerGradient, editable=false) plot(zeroLine, 'Zero Line', color=transpLightGray) plot(upperBand, 'Upper Band', color=transpLightGray) plot(lowerBand, 'Lower Band', color=transpLightGray) plot(topBand, 'Top Band', color=transpLightGray) plot(bottomBand, 'Bottom Band', color=transpLightGray) fill(stochPlot, stochTriggerPlot, color=isGradientEnabled ? stochTriggerGradient : color.new(skyBlue, 50), editable=false) fill(cgPlot, cgTriggerPlot, color=isGradientEnabled ? cgTriggerGradient : color.new(languidLavender, 50), editable=false) // -- Signals -- bool longSignal = false bool shortSignal = false if (areBuySellLabelsEnabled) float baseLine = isStoch ? _stoch : Value3 // Check slope int lookback = 2 float slope = (baseLine[lookback] - baseLine) / (ta.lowest(baseLine, lookback) - ta.highest(baseLine, lookback)) slope := (not slope) ? 0 : slope if (signalMode == 'Overbought/Oversold') longSignal := ta.crossover(baseLine, lowerBand) shortSignal := ta.crossunder(baseLine, upperBand) if (signalMode == 'Fast Overbought/Oversold') // longSignal := (math.round(slope[1]) == 0) and (ta.crossover(baseLine, lowerBand) or ta.crossover(baseLine, lowerBand)[1] and math.round(slope) > 0) // shortSignal := (math.round(slope[1]) == 0) and (ta.crossunder(baseLine, upperBand) or ta.crossover(baseLine, upperBand)[1] and math.round(slope) < 0) longSignal := (math.round(baseLine[2], 3) == math.round(baseLine[1], 3)) and baseLine > baseLine[1] and baseLine < lowerBand shortSignal := (math.round(baseLine[2], 3) == math.round(baseLine[1], 3)) and baseLine < baseLine[1] and baseLine > upperBand if (signalMode == 'Stoch/CG Cross') longSignal := ta.cross(Value3, _stoch) and _stoch < zeroLine and Value3 < zeroLine shortSignal := ta.cross(Value3, _stoch) and _stoch > zeroLine and Value3 > zeroLine if ((signalMode == 'Cross') and (not isStoch)) longSignal := ta.crossover(Value3, Value3[1]) and Value3 < zeroLine shortSignal := ta.crossunder(Value3, Value3[1]) and Value3 > zeroLine if ((signalMode == 'Cross') and isStoch) longSignal := ta.crossover(_stoch[1], _stoch) and _stoch < zeroLine shortSignal := ta.crossunder(_stoch[1], _stoch) and _stoch > zeroLine plotshape(longSignal ? bottomBand - 0.5 : na, title='BUY', style=shape.triangleup, color=magicMint, size=size.tiny, location=location.absolute) plotshape(shortSignal ? topBand + 0.5: na, title='SELL', style=shape.triangledown, color=rajah, size=size.tiny, location=location.absolute) // -- Alerts -- alertcondition(longSignal, title='BUY', message='Adaptive Fisherized Center of Gravity -> BUY') alertcondition(shortSignal, title='SELL', message='Adaptive Fisherized Center of Gravity -> SELL')
1stDay_3rdFriday of Month by RM
https://www.tradingview.com/script/qt9VK6Tp-1stDay-3rdFriday-of-Month-by-RM/
raul3429
https://www.tradingview.com/u/raul3429/
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/ // by © raul3429, with thanks to @StaticNoise et all. // This script is meant for use on a daily chart on indices like SPY to set a line in the sand for Bullish/Bearish trends // This indicator marks the 1st and 3rd Friday of current month in the chart with: Vertical, High-Low lines // //@version=5 indicator('1stDay_3rdFriday of Month by RM', '1stDay_3rdFri by RM', true) gr9 = '***** 1st Day and 3rd Friday of the Month ******' // --------- Colors c_orange = #f17f17 //Orange c_green = #006400 //Green c_green100 = #006400FF//Green 100% c_greenLight= #388e3c //Green Light c_red = #8B0000 //Red c_red100 = #8B0000FF//Red 100% c_redLight = #b71c1c //Red Light c_white = #ffffff //White c_grey = #808080 //Grey c_navy = #000080 //Navy c_yellow = #FFFF00 //Yellow c_teal = #008080 //Teal Clr = input.color(title='Color 1stMo', defval=c_orange, group=gr9) Clr2 = input.color(title='Color 3rdFri', defval=c_yellow, group=gr9) line_Style = input.string(defval = 'Dashed', title = "Line Style" , options = ['Solid', 'Dotted', 'Dashed']) Lst = line_Style == 'Solid' ? line.style_solid : line_Style == 'Dashed' ? line.style_dashed : line_Style == 'Dotted' ? line.style_dotted : line.style_solid LB = input.bool(title='Show Date', defval=true, group=gr9) days_in_month = 30 + month % 2 if month == 2 leap_day = year % 4 == 0 ? 1 : 0 days_in_month := 28 + leap_day days_in_month bar_date_ts = timestamp(year(time),month(time),dayofmonth(time),0,0,0) is_new_date = ta.change(bar_date_ts) is_newbar(timeframe.period) => ta.change(time(timeframe.period)) != 0 high_rangeL = ta.valuewhen(is_newbar('D'),high,0) low_rangeL = ta.valuewhen(is_newbar('D'),low,0) if (is_new_date) and dayofmonth == 1 thisMonth = month (time) isMon = dayofweek == dayofweek.monday isFri = dayofweek == dayofweek.friday isSat = dayofweek == dayofweek.saturday isSun = dayofweek == dayofweek.sunday isWeekend = isSun or isSat ? true:false isWeekDay = not isWeekend w1 = isFri and dayofmonth(time) >= 1 and dayofmonth(time) <= 7 ? true : false w2 = isFri and dayofmonth(time) > 7 and dayofmonth(time) <= 14 ? true : false w3 = isFri and dayofmonth(time) > 14 and dayofmonth(time) <= 21 ? true : false w4 = isFri and dayofmonth(time) > 21 and dayofmonth(time) <= 28 ? true : false w5 = isFri and dayofmonth(time) > 28 and dayofmonth(time) <= days_in_month ? true : false //firstOfMonth = firstOfMonthWeekday ? true : firstOfMonthSat and dayofmonth == 3 ? true : firstOfMonthSun and dayofmonth == 2 ? true : false //firstOfMonth = (is_new_date) and dayofmonth(time) == 1 and not isWeekend ? true : dayofmonth(time) == 2 and dayofweek.monday ? true : dayofmonth(time) == 3 and dayofweek.monday ? true : false var line l1 = na var line l2 = na var line l3 = na var line l4 = na var line V = na var label lbl = na bool is3rdFri = na bool is1sMonWkDay = na bool is1sMonSat = na bool is1sMonSun = na if (is_new_date) is3rdFri := w3 ? true : na is1sMonWkDay := dayofmonth(time) == 1 and isWeekDay ? true : na is1sMonSat := not is1sMonWkDay and isMon and dayofmonth(time) == 2 ? true : na is1sMonSun := not is1sMonWkDay and isMon and dayofmonth(time) == 3 ? true : na if is3rdFri or is1sMonWkDay or is1sMonSat or is1sMonSun line.delete(l1) line.delete(l2) line.delete(V) line.delete(l3) line.delete(l4) V := line.new (x1=bar_index, x2=bar_index, y1=1, y2=2, extend=extend.both, color=Clr2, style=line.style_dashed, width=1) l1 := line.new (x1=bar_index, y1=high , x2=bar_index+10, y2=high , extend=extend.right, color = Clr2, style = Lst, width=1) l2 := line.new (x1=bar_index, y1=low , x2=bar_index+10, y2=low , extend=extend.right, color = Clr2, style = Lst, width=1) linefill.new(l1, l2, color=color.new(c_white,90)) if LB label.delete(lbl[1]) lbl := label.new(bar_index, low, xloc = xloc.bar_index , yloc=yloc.belowbar , text = str.format("{0, date, full}", time), color= c_yellow , size = size.normal, style = label.style_label_up)
Range Slicer
https://www.tradingview.com/script/EfZDkukX-Range-Slicer/
melodicfish
https://www.tradingview.com/u/melodicfish/
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/ // © melodicfish //@version=5 indicator("Range Slicer",overlay = true) p1=input.price(100.0,title="Price Level One",tooltip = "Select Price Level Point 1 on Chart ",confirm = true) p2=input.price(50.0,title="Price Level Two",tooltip = "Select Price Level Point 2 on Chart ",confirm = true) slices=input.int(5,title="Number of slices") pr_col=input.color(color.teal,title="Price Range Line Color",inline = "+") pr_lw=input.int(2,title="Price Range Line Width",inline = "+") slice_col=input.color(color.purple,title="Slice Line Color",inline = "=") slice_lw=input.int(1,title="Slice Line Width",inline = "=") ext=input.string(defval = "To Right",options = ["To Right","Both"],title="Extend lines: ", inline="c") var p1Line=line.new(1,1,1,1,color=pr_col,extend=ext=="Both"?extend.both:extend.right,width=pr_lw) var p2Line=line.new(1,1,1,1,color=pr_col,extend=ext=="Both"?extend.both:extend.right,width = pr_lw) var sliceLines = array.new<line>(slices) topVal=math.max(p1,p2) bottomVal=math.min(p1,p2) priceRange=topVal-bottomVal sliceSize=priceRange/slices line.set_xy1(p1Line,bar_index,p1),line.set_xy2(p1Line,bar_index+1,p1) line.set_xy1(p2Line,bar_index,p2),line.set_xy2(p2Line,bar_index+1,p2) line.set_extend(p1Line,ext=="Both"?extend.both:extend.right), line.set_extend(p2Line,ext=="Both"?extend.both:extend.right) if array.size(sliceLines)>0 and barstate.isconfirmed for i=0 to array.size(sliceLines)-1 line.delete(array.get(sliceLines,i)) array.clear(sliceLines) sliceLines:=array.new<line>(slices) if barstate.isconfirmed for i=1 to slices-1 level=(sliceSize*i)+bottomVal line=line.new(bar_index,level,bar_index+6,level,color=slice_col,extend=ext=="Both"?extend.both:extend.right,width = slice_lw) array.insert(sliceLines,i,line)
Nadaraya-Watson Envelope Alternative [CHE] Super Envelope
https://www.tradingview.com/script/TKWJDDoj/
chervolino
https://www.tradingview.com/u/chervolino/
274
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/ // © chervolino //@version=5 indicator("Nadaraya-Watson Envelope Alternative [CHE] Super Envelope", shorttitle="Super Envelope [CHE]", overlay=true, max_bars_back=1000, max_lines_count=500, max_labels_count=500) // ———————————————————— Constants and Inputs { // ————— Constants string TT_len = "Length for John Ehlers’ 2-pole Butterworth filter “Super Smoother”" string TT_mult = "Multiplier for the bands" string TT_showMiddle = "On and off center line" string TT_showdisclaimer = "Uncheck to hide the disclaimer" string GRP2 = '═══════════   Settings   ═══════════' // ————— Inputs int len = input(50, "smoothing length" , tooltip = TT_len , group = GRP2) float mult = input(5.0,"Adjustable multiplier", tooltip = TT_mult , group = GRP2) bool showMiddle = input(false, "Show middle band" , tooltip = TT_showMiddle , group = GRP2) bool disclaimer = input(false, 'Hide Disclaimer' , tooltip = TT_showdisclaimer, group = GRP2) up_col = input.color(#39ff14,'Colors',inline='col') dn_col = input.color(#ff1100,'',inline='col') // ———————————————————— Functions { super(float src, int len) => f = (1.414 * math.pi)/len a = math.exp(-f) c2 = 2 * a * math.cos(f) c3 = -a*a c1 = 1-c2-c3 smooth = 0.0 smooth := c1*(src+src[1])*0.5+c2*nz(smooth[1])+c3*nz(smooth[2]) // ———————————————————— Calculations and Plots { // Stop the indicator on charts with no volume. if barstate.islast and ta.cum(nz(volume)) == 0 runtime.error("No volume is provided by the data vendor.") a=super(high,len) b=super(low,len) c=(a-b)/2*mult d=b+(a-b)/2 plotcolor = d>d[1]? up_col : dn_col bullish_bearish = d>d[1]? true : false plot(a+c, color=up_col) plot(b-c, color=dn_col) plot(showMiddle? d:na, color=plotcolor) plotchar(ta.crossover(high,a+c),char = "💰", location = location.abovebar, size = size.tiny) plotchar(ta.crossunder(low,b-c),char = "🛒",location = location.belowbar , size = size.tiny) // ———————————————————— Alerts alertcondition(bullish_bearish == true ,title='Bearish Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bearish ▼') alertcondition(bullish_bearish == false, title='Bullish Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bullish ▲') alertcondition(ta.crossunder(high,a+c) , title='Price close under lower band', message='Nadaraya-Watson: {{ticker}} ({{interval}}) crossed under lower band 💰') alertcondition(ta.crossover(low,b-c) , title='Price close above upper band', message='Nadaraya-Watson: {{ticker}} ({{interval}}) Crossed above upper band 🛒') //---- var tb = table.new(position.top_right, 1, 1 , bgcolor = #35202b) if barstate.isfirst and not disclaimer table.cell(tb, 0, 0, 'Super Envelope [CHE] non repaiting' , text_size = size.small , text_color = #cc2f3c)
Multi-Indicator Divergence Screener
https://www.tradingview.com/script/dA0l6tFx-Multi-Indicator-Divergence-Screener/
DoctaBot
https://www.tradingview.com/u/DoctaBot/
290
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/ // © DoctaBot //@version=5 indicator('Divergence Screener', shorttitle = 'Div. Screener', overlay = true) /////////////////////Indicators/////////////////////// // Macd [macd, signal, hist] = ta.macd(close, 12, 26, 9) // Mfi mfi = ta.mfi(hlc3, 14) // Stoch k = ta.sma(ta.stoch(close, high, low, 14), 1) stoch = ta.sma(k, 3) OBV = ta.obv RSI = ta.rsi(close, 14) rsidelta = ta.mom(RSI, 9) rsisma = ta.sma(ta.rsi(close, 3), 3) FSR = rsidelta+rsisma IndSel1 = input.string('RSI', title = 'Indicator 1', group = 'Indicators', options = ['MACD', 'MFI', 'Stoch', 'OBV', 'RSI', 'FSR']) IndSel2 = input.string('OBV', title = 'Indicator 2', group = 'Indicators', options = ['MACD', 'MFI', 'Stoch', 'OBV', 'RSI', 'FSR']) IndSel3 = input.string('MACD', title = 'Indicator 3', group = 'Indicators', options = ['MACD', 'MFI', 'Stoch', 'OBV', 'RSI', 'FSR']) Ind1 = switch IndSel1 'MACD' => macd, 'MFI' => mfi, 'Stoch' => stoch, 'OBV' => OBV, 'FSR' => FSR, => RSI Ind2 = switch IndSel2 'MACD' => macd, 'MFI' => mfi, 'Stoch' => stoch, 'OBV' => OBV, 'FSR' => FSR, => RSI Ind3 = switch IndSel3 'MACD' => macd, 'MFI' => mfi, 'Stoch' => stoch, 'OBV' => OBV, 'FSR' => FSR, => RSI ////////////////////////////////////////////////////// plotBull = input.bool(defval = true, title = 'Regular Bullish   ', group = 'Alert Options', inline = 'Divs1') plotBear = input.bool(defval = true, title = 'Regular Bearish', group = 'Alert Options', inline = 'Divs1') plotHiddenBull = input.bool(defval = false, title = 'Hidden Bullish   ', group = 'Alert Options', inline = 'Divs2') plotHiddenBear = input.bool(defval = false, title = 'Hidden Bearish', group = 'Alert Options', inline = 'Divs2') PotAlerts = input.bool(defval = false, title = 'Potential Divergences', group = 'Alert Options', inline = 'Divs3') AlertFilt = input.string('All', title = 'Alert Confluence Filter', group = 'Alert Options', inline = 'Divs4', options = ['All', 'Min 2', 'Triple Only']) rangeLower = input.int(defval = 2, title = 'Min/Max of Lookback Range', group = 'Divergence Settings', inline = 'Divs5', minval = 2) rangeUpper = input.int(defval = 20, title = '', group = 'Divergence Settings', inline = 'Divs5') lbR = 1 lbL = 1 CustAsset1 = input.symbol(defval='BTCUSDT', group = 'Assets', inline = 'Assets4', title ='Custom 1 & 2') CustAsset2 = input.symbol(defval='ETHUSDT', group = 'Assets', inline = 'Assets4', title ='') CustAsset3 = input.symbol(defval='BNBUSDT', group = 'Assets', inline = 'Assets5', title ='Custom 3 & 4') CustAsset4 = input.symbol(defval='ADAUSDT', group = 'Assets', inline = 'Assets5', title ='') CustAsset5 = input.symbol(defval='SOLUSDT', group = 'Assets', inline = 'Assets6', title ='Custom 5 & 6') CustAsset6 = input.symbol(defval='XRPUSDT', group = 'Assets', inline = 'Assets6', title ='') //----------//COLOR OPTIONS//----------// DispTab = input.bool(true, title = 'Table', group = 'Table', inline = 'Table0') TabLocOpt = input.string(defval = 'Bottom Right', group = 'Table', inline = 'Table0', title ='', options =['Bottom Right', 'Bottom Left', 'Top Right', 'Top Left', 'Top Center', 'Bottom Center']) LightMode = input.bool(defval=false, group = 'Table', inline = 'Table1', title = 'Invert Text Colors', tooltip='Useful if you view charts in Light Mode') BullBaseCol = input.color(defval = color.green, group = 'Table', inline = 'Table2', title = 'Bull/Bear Colors') BearBaseCol = input.color(defval = color.red, group = 'Table', inline = 'Table2', title = '') BullColor1 = color.new(BullBaseCol, 25) BullColor2 = color.new(BullBaseCol, 75) BearColor1 = color.new(BearBaseCol, 25) BearColor2 = color.new(BearBaseCol, 75) noneColor = color.new(color.white, 100) //Load Pivots{ //Check Arrays are even to ensure Price and Bar values have been added properly f_checkPivArrays(float[] PriceArr, float[] OscArr, int[] BarsArr) => if array.size(PriceArr) != array.size(OscArr) or array.size(PriceArr) != array.size(BarsArr) or array.size(OscArr) != array.size(BarsArr) runtime.error('Array sizes are not equal!') //Load new Price, Osc, and Bar values into their respective arrays f_loadNewPivValues(float[] PriceArr, Price, float[] OscArr, Osc, int[] BarsArr, Bars) => f_checkPivArrays(PriceArr, OscArr, BarsArr) array.unshift(PriceArr, Price) array.unshift(OscArr, Osc) array.unshift(BarsArr, Bars) f_loadPivArrays(_osc) => phFound = na(ta.pivothigh(_osc, lbL, lbR)) ? false : true plFound = na(ta.pivotlow(_osc, lbL, lbR)) ? false : true //Declare Pivot High Arrays var PricePHArr = array.new_float() var OscPHArr = array.new_float() var BarPHArr = array.new_int() //Declare Pivot Low Arrays var PricePLArr = array.new_float() var OscPLArr = array.new_float() var BarPLArr = array.new_int() //Declare Pivot Values PricePH = math.max(open[lbR], close[lbR]) //ta.highest(close, lbR + 2) PricePL = math.min(open[lbR], close[lbR]) //ta.lowest(close, lbR + 2) //Load Pivot High Values into Arrays and remove pivots outside range lookback if phFound f_loadNewPivValues(PricePHArr, PricePH, OscPHArr, _osc[lbR], BarPHArr, bar_index - lbR) if bar_index - array.min(BarPHArr) > rangeUpper array.pop(PricePHArr) array.pop(OscPHArr) array.pop(BarPHArr) //Load Pivot Low Values into Arrays and remove pivots outside range lookback if plFound f_loadNewPivValues(PricePLArr, PricePL, OscPLArr, _osc[lbR], BarPLArr, bar_index - lbR) if bar_index - array.min(BarPLArr) > rangeUpper array.pop(PricePLArr) array.pop(OscPLArr) array.pop(BarPLArr) [PricePH, PricePL, phFound, plFound, PricePHArr, OscPHArr, BarPHArr, PricePLArr, OscPLArr, BarPLArr] //} //Get Divergences{ f_getDivergence(_osc, _plotOn, _divType, _divDir, _conf)=> [PricePH, PricePL, phFound, plFound, PricePHArr, OscPHArr, BarPHArr, PricePLArr, OscPLArr, BarPLArr] = f_loadPivArrays(_osc) _OscArr = _divDir == 'Bull' ? OscPLArr : OscPHArr _PriceArr = _divDir == 'Bull' ? PricePLArr : PricePHArr _BarArr = _divDir == 'Bull' ? BarPLArr : BarPHArr IntLBStart = _conf ? lbR + 1 : 1 DivCount = 0 OscEnd = _conf ? _osc[lbR] : _osc PriceEnd = _conf ? _divDir == 'Bull' ? PricePL : PricePH : close BarEnd = _conf ? bar_index - lbR : bar_index if array.size(_OscArr) > 0 for i = array.size(_OscArr) - 1 to 0 OscStart = array.get(_OscArr, i) PriceStart = array.get(_PriceArr, i) BarStart = array.get(_BarArr, i) oscH = OscEnd > OscStart oscL = OscEnd < OscStart PriceH = PriceEnd > PriceStart PriceL = PriceEnd < PriceStart DivLen = BarEnd - BarStart Divergence = (_conf ? _divDir == 'Bull' ? plFound : phFound : true) and (((_divType == 'Regular' and _divDir == 'Bull') or (_divType == 'Hidden' and _divDir == 'Bear')) ? (oscH and PriceL) : (oscL and PriceH)) if DivLen >= rangeLower and Divergence and _plotOn NoIntersect = true OscSlope = (OscEnd - OscStart)/(BarEnd - BarStart) PriceSlope = (PriceEnd - PriceStart)/(BarEnd - BarStart) OscLine = OscEnd - OscSlope PriceLine = PriceEnd - PriceSlope for x = IntLBStart to DivLen - 1 if (_divDir == 'Bull' and (_osc[x] < OscLine or nz(close[x]) < PriceLine)) or (_divDir == 'Bear' and (_osc[x] > OscLine or nz(close[x]) > PriceLine)) NoIntersect := false break OscLine -= OscSlope PriceLine -= PriceSlope NoIntersect if NoIntersect DivCount := DivCount + 1 DivCount DivCount ////////////////////////////////Screener//////////////////////////////////////////// f_getAllDivs() => //Indicator 1 //Confirmed Ind1RegBullDiv = f_getDivergence(Ind1, plotBull, 'Regular', 'Bull', true) Ind1HidBullDiv = f_getDivergence(Ind1, plotHiddenBull, 'Hidden', 'Bull', true) Ind1RegBearDiv = f_getDivergence(Ind1, plotBear, 'Regular', 'Bear', true) Ind1HidBearDiv = f_getDivergence(Ind1, plotHiddenBear, 'Hidden', 'Bear', true) Ind1BullDivCount = Ind1RegBullDiv + Ind1HidBullDiv Ind1BearDivCount = Ind1RegBearDiv + Ind1HidBearDiv Ind1BullDiv = Ind1BullDivCount > 0 Ind1BearDiv = Ind1BearDivCount > 0 //Potentials PotInd1RegBullDiv = f_getDivergence(Ind1, PotAlerts and plotBull, 'Regular', 'Bull', false) PotInd1HidBullDiv = f_getDivergence(Ind1, PotAlerts and plotHiddenBull, 'Hidden', 'Bull', false) PotInd1RegBearDiv = f_getDivergence(Ind1, PotAlerts and plotBear, 'Regular', 'Bear', false) PotInd1HidBearDiv = f_getDivergence(Ind1, PotAlerts and plotHiddenBear, 'Hidden', 'Bear', false) PotInd1BullDivCount = PotInd1RegBullDiv + PotInd1HidBullDiv PotInd1BearDivCount = PotInd1RegBearDiv + PotInd1HidBearDiv PotInd1BullDiv = PotInd1BullDivCount > 0 PotInd1BearDiv = PotInd1BearDivCount > 0 //Indicator 2 //Confirmed Ind2RegBullDiv = f_getDivergence(Ind2, plotBull, 'Regular', 'Bull', true) Ind2HidBullDiv = f_getDivergence(Ind2, plotHiddenBull, 'Hidden', 'Bull', true) Ind2RegBearDiv = f_getDivergence(Ind2, plotBear, 'Regular', 'Bear', true) Ind2HidBearDiv = f_getDivergence(Ind2, plotHiddenBear, 'Hidden', 'Bear', true) Ind2BullDivCount = Ind2RegBullDiv + Ind2HidBullDiv Ind2BearDivCount = Ind2RegBearDiv + Ind2HidBearDiv Ind2BullDiv = Ind2BullDivCount > 0 Ind2BearDiv = Ind2BearDivCount > 0 //Potentials PotInd2RegBullDiv = f_getDivergence(Ind2, PotAlerts and plotBull, 'Regular', 'Bull', false) PotInd2HidBullDiv = f_getDivergence(Ind2, PotAlerts and plotHiddenBull, 'Hidden', 'Bull', false) PotInd2RegBearDiv = f_getDivergence(Ind2, PotAlerts and plotBear, 'Regular', 'Bear', false) PotInd2HidBearDiv = f_getDivergence(Ind2, PotAlerts and plotHiddenBear, 'Hidden', 'Bear', false) PotInd2BullDivCount = PotInd2RegBullDiv + PotInd2HidBullDiv PotInd2BearDivCount = PotInd2RegBearDiv + PotInd2HidBearDiv PotInd2BullDiv = PotInd2BullDivCount > 0 PotInd2BearDiv = PotInd2BearDivCount > 0 //Indicator 3 //Confirmed Ind3RegBullDiv = f_getDivergence(Ind3, plotBull, 'Regular', 'Bull', true) Ind3HidBullDiv = f_getDivergence(Ind3, plotHiddenBull, 'Hidden', 'Bull', true) Ind3RegBearDiv = f_getDivergence(Ind3, plotBear, 'Regular', 'Bear', true) Ind3HidBearDiv = f_getDivergence(Ind3, plotHiddenBear, 'Hidden', 'Bear', true) Ind3BullDivCount = Ind3RegBullDiv + Ind3HidBullDiv Ind3BearDivCount = Ind3RegBearDiv + Ind3HidBearDiv Ind3BullDiv = Ind3BullDivCount > 0 Ind3BearDiv = Ind3BearDivCount > 0 //Potentials PotInd3RegBullDiv = f_getDivergence(Ind3, PotAlerts and plotBull, 'Regular', 'Bull', false) PotInd3HidBullDiv = f_getDivergence(Ind3, PotAlerts and plotHiddenBull, 'Hidden', 'Bull', false) PotInd3RegBearDiv = f_getDivergence(Ind3, PotAlerts and plotBear, 'Regular', 'Bear', false) PotInd3HidBearDiv = f_getDivergence(Ind3, PotAlerts and plotHiddenBear, 'Hidden', 'Bear', false) PotInd3BullDivCount = PotInd3RegBullDiv + PotInd3HidBullDiv PotInd3BearDivCount = PotInd3RegBearDiv + PotInd3HidBearDiv PotInd3BullDiv = PotInd3BullDivCount > 0 PotInd3BearDiv = PotInd3BearDivCount > 0 ColInd1 = Ind1BullDiv ? BullColor1 : Ind1BearDiv ? BearColor1 : PotInd1BullDiv ? BullColor2 : PotInd1BearDiv ? BearColor2 : noneColor ColInd2 = Ind2BullDiv ? BullColor1 : Ind2BearDiv ? BearColor1 : PotInd2BullDiv ? BullColor2 : PotInd2BearDiv ? BearColor2 : noneColor ColInd3 = Ind3BullDiv ? BullColor1 : Ind3BearDiv ? BearColor1 : PotInd3BullDiv ? BullColor2 : PotInd3BearDiv ? BearColor2 : noneColor ColorArr = array.from(ColInd1, ColInd2, ColInd3) DivArr = array.from(Ind1BullDivCount, Ind1BearDivCount, PotInd1BullDivCount, PotInd1BearDivCount, Ind2BullDivCount, Ind2BearDivCount, PotInd2BullDivCount, PotInd2BearDivCount, Ind3BullDivCount, Ind3BearDivCount, PotInd3BullDivCount, PotInd3BearDivCount) [ColorArr, DivArr] //////////////////////////////////////////////////////////////////////////////// // Securities // //////////////////////////////////////////////////////////////////////////////// [Ass1ColorArr, Ass1DivArr] = request.security(CustAsset1 ,timeframe.period, f_getAllDivs()) [Ass2ColorArr, Ass2DivArr] = request.security(CustAsset2 ,timeframe.period, f_getAllDivs()) [Ass3ColorArr, Ass3DivArr] = request.security(CustAsset3 ,timeframe.period, f_getAllDivs()) [Ass4ColorArr, Ass4DivArr] = request.security(CustAsset4 ,timeframe.period, f_getAllDivs()) [Ass5ColorArr, Ass5DivArr] = request.security(CustAsset5 ,timeframe.period, f_getAllDivs()) [Ass6ColorArr, Ass6DivArr] = request.security(CustAsset6 ,timeframe.period, f_getAllDivs()) ColorMatrix = matrix.new<color>() DivMatrix = matrix.new<int>() if barstate.islast //Load Color Matrix matrix.add_row(ColorMatrix, 0, Ass1ColorArr) matrix.add_row(ColorMatrix, 1, Ass2ColorArr) matrix.add_row(ColorMatrix, 2, Ass3ColorArr) matrix.add_row(ColorMatrix, 3, Ass4ColorArr) matrix.add_row(ColorMatrix, 4, Ass5ColorArr) matrix.add_row(ColorMatrix, 5, Ass6ColorArr) //Load Div Matrix matrix.add_row(DivMatrix, 0, Ass1DivArr) matrix.add_row(DivMatrix, 1, Ass2DivArr) matrix.add_row(DivMatrix, 2, Ass3DivArr) matrix.add_row(DivMatrix, 3, Ass4DivArr) matrix.add_row(DivMatrix, 4, Ass5DivArr) matrix.add_row(DivMatrix, 5, Ass6DivArr) Asset1 = array.get(str.split(CustAsset1, ':'), 1) Asset2 = array.get(str.split(CustAsset2, ':'), 1) Asset3 = array.get(str.split(CustAsset3, ':'), 1) Asset4 = array.get(str.split(CustAsset4, ':'), 1) Asset5 = array.get(str.split(CustAsset5, ':'), 1) Asset6 = array.get(str.split(CustAsset6, ':'), 1) AssetArr = array.from(Asset1, Asset2, Asset3, Asset4, Asset5, Asset6) TabLoc = TabLocOpt == 'Bottom Right' ? position.bottom_right : TabLocOpt == 'Bottom Left' ? position.bottom_left : TabLocOpt == 'Top Right' ? position.top_right : TabLocOpt == 'Top Left' ? position.top_left : TabLocOpt == 'Top Center' ? position.top_center : position.bottom_center var table DivTable = table.new(TabLoc, columns = 4, rows = 7, border_width = 1) //----------//Early Alert Arrays//----------// if barstate.islast and DispTab //Table Headers HeaderBGCol = LightMode ? color.black : color.white HeaderTextCol = LightMode ? color.white : color.black table.cell(DivTable, 0, 0, 'Asset', text_halign = text.align_center, bgcolor = HeaderBGCol, text_color = HeaderTextCol, text_size = size.normal) table.cell(DivTable, 1, 0, IndSel1, text_halign = text.align_center, bgcolor = HeaderBGCol, text_color = HeaderTextCol, text_size = size.normal) table.cell(DivTable, 2, 0, IndSel2, text_halign = text.align_center, bgcolor = HeaderBGCol, text_color = HeaderTextCol, text_size = size.normal) table.cell(DivTable, 3, 0, IndSel3, text_halign = text.align_center, bgcolor = HeaderBGCol, text_color = HeaderTextCol, text_size = size.normal) //Populate Table for i = 0 to 5 //Colors Ind1Col = matrix.get(ColorMatrix, i, 0) Ind2Col = matrix.get(ColorMatrix, i, 1) Ind3Col = matrix.get(ColorMatrix, i, 2) Ind1Bull = Ind1Col == BullColor1 or Ind1Col == BullColor2 Ind2Bull = Ind2Col == BullColor1 or Ind2Col == BullColor2 Ind3Bull = Ind3Col == BullColor1 or Ind3Col == BullColor2 Ind1Bear = Ind1Col == BearColor1 or Ind1Col == BearColor2 Ind2Bear = Ind2Col == BearColor1 or Ind2Col == BearColor2 Ind3Bear = Ind3Col == BearColor1 or Ind3Col == BearColor2 AllBull = Ind1Bull and Ind2Bull and Ind3Bull AllBear = Ind1Bear and Ind3Bear and Ind3Bear symBGColor = AllBull ? BullColor1 : AllBear ? BearColor1 : HeaderBGCol symColor = symBGColor != HeaderBGCol ? HeaderBGCol : HeaderTextCol Ind1Mess = Ind1Col == BullColor1 ? str.tostring(matrix.get(DivMatrix, i, 0)) : Ind1Col == BearColor1 ? str.tostring(matrix.get(DivMatrix, i, 1)) : Ind1Col == BullColor2 ? str.tostring(matrix.get(DivMatrix, i, 2)) : Ind1Col == BearColor2 ? str.tostring(matrix.get(DivMatrix, i, 3)): '' Ind2Mess = Ind2Col == BullColor1 ? str.tostring(matrix.get(DivMatrix, i, 4)) : Ind2Col == BearColor1 ? str.tostring(matrix.get(DivMatrix, i, 5)) : Ind2Col == BullColor2 ? str.tostring(matrix.get(DivMatrix, i, 6)) : Ind2Col == BearColor2 ? str.tostring(matrix.get(DivMatrix, i, 7)): '' Ind3Mess = Ind3Col == BullColor1 ? str.tostring(matrix.get(DivMatrix, i, 8)) : Ind3Col == BearColor1 ? str.tostring(matrix.get(DivMatrix, i, 9)) : Ind3Col == BullColor2 ? str.tostring(matrix.get(DivMatrix, i, 10)) : Ind3Col == BearColor2 ? str.tostring(matrix.get(DivMatrix, i, 11)): '' //Values table.cell(DivTable, 0, i + 1, array.get(AssetArr, i) , text_halign = text.align_center, bgcolor = symBGColor, text_color = symColor, text_size = size.normal) table.cell(DivTable, 1, i + 1, Ind1Mess , text_halign = text.align_center, bgcolor = Ind1Col , text_color = HeaderBGCol, text_size = size.normal) table.cell(DivTable, 2, i + 1, Ind2Mess , text_halign = text.align_center, bgcolor = Ind2Col, text_color = HeaderBGCol, text_size = size.normal) table.cell(DivTable, 3, i + 1, Ind3Mess , text_halign = text.align_center, bgcolor = Ind3Col, text_color = HeaderBGCol, text_size = size.normal) // //Alerts // BullDivArr = array.new_bool(0) //Oversold // BearDivArr = array.new_bool(0) //Overbought // PotBullDivArr = array.new_bool(0) //Oversold V2 // PotBearDivArr = array.new_bool(0) //Overbought V2 f_convertTFtoString(_TF)=> TFConv = _TF == '' ? timeframe.isminutes ? timeframe.multiplier >= 60 ? str.tostring(timeframe.multiplier / 60) + 'H' : str.tostring(timeframe.multiplier) + 'm' : timeframe.period == "D" ? '1D' : timeframe.period : str.endswith(_TF, 'D') or str.endswith(_TF, 'M') ? _TF : str.tonumber(_TF) >= 60 ? str.tostring(str.tonumber(_TF) / 60) + 'H' : _TF + 'm' TFConv TFConv = f_convertTFtoString('') AlertFiltText = AlertFilt == 'Min 2' ? ' Double' : AlertFilt == 'Triple Only' ? ' Triple' : na BullDivText = TFConv + AlertFiltText + ' Bull Div \n' BearDivText = TFConv + AlertFiltText + ' Bear Div \n' if barstate.islast for i = 0 to 5 Ind1Col = matrix.get(ColorMatrix, i, 0) Ind2Col = matrix.get(ColorMatrix, i, 1) Ind3Col = matrix.get(ColorMatrix, i, 2) Ind1Bull = Ind1Col == BullColor1 or Ind1Col == BullColor2 Ind2Bull = Ind2Col == BullColor1 or Ind2Col == BullColor2 Ind3Bull = Ind3Col == BullColor1 or Ind3Col == BullColor2 Ind1Bear = Ind1Col == BearColor1 or Ind1Col == BearColor2 Ind2Bear = Ind2Col == BearColor1 or Ind2Col == BearColor2 Ind3Bear = Ind3Col == BearColor1 or Ind3Col == BearColor2 AnyBull = Ind1Bull or Ind2Bull or Ind3Bull AnyBear = Ind1Bear or Ind2Bear or Ind3Bear Min2Bull = (Ind1Bull and Ind2Bull) or (Ind1Bull and Ind3Bull) or (Ind2Bull and Ind3Bull) Min2Bear = (Ind1Bear and Ind2Bear) or (Ind1Bear and Ind3Bear) or (Ind2Bear and Ind3Bear) AllBull = Ind1Bull and Ind2Bull and Ind3Bull AllBear = Ind1Bear and Ind3Bear and Ind3Bear if (AnyBull and AlertFilt == 'All') or (Min2Bull and AlertFilt == 'Min 2') or (AllBull and AlertFilt == 'Triple Only') BullDivText := BullDivText + str.tostring(array.get(AssetArr, i)) + ': ' if Ind1Col == BullColor1 BullDivText := BullDivText + str.tostring(matrix.get(DivMatrix, i, 0)) + 'x ' + IndSel1 if Ind1Col == BullColor2 BullDivText := BullDivText + str.tostring(matrix.get(DivMatrix, i, 2)) + 'x Pot ' + IndSel1 if Ind1Bull and (Ind2Bull or Ind3Bull) BullDivText := BullDivText + ', ' if Ind2Col == BullColor1 BullDivText := BullDivText + str.tostring(matrix.get(DivMatrix, i, 4)) + 'x ' + IndSel2 if Ind2Col == BullColor2 BullDivText := BullDivText + str.tostring(matrix.get(DivMatrix, i, 6)) + 'x Pot ' + IndSel2 if Ind2Bull and Ind3Bull BullDivText := BullDivText + ', ' if Ind3Col == BullColor1 BullDivText := BullDivText + str.tostring(matrix.get(DivMatrix, i, 8)) + 'x ' + IndSel3 if Ind3Col == BullColor2 BullDivText := BullDivText + str.tostring(matrix.get(DivMatrix, i, 10)) + 'x Pot ' + IndSel3 BullDivText := BullDivText + '\n' if (AnyBear and AlertFilt == 'All') or (Min2Bear and AlertFilt == 'Min 2') or (AllBear and AlertFilt == 'Triple Only') BearDivText := BearDivText + str.tostring(array.get(AssetArr, i)) + ': ' if Ind1Col == BearColor1 BearDivText := BearDivText + str.tostring(matrix.get(DivMatrix, i, 1)) + 'x ' + IndSel1 if Ind1Col == BearColor2 BearDivText := BearDivText + str.tostring(matrix.get(DivMatrix, i, 3)) + 'x Pot ' + IndSel1 if Ind1Bear and (Ind2Bear or Ind3Bear) BearDivText := BearDivText + ', ' if Ind2Col == BearColor1 BearDivText := BearDivText + str.tostring(matrix.get(DivMatrix, i, 5)) + 'x ' + IndSel2 if Ind2Col == BearColor2 BearDivText := BearDivText + str.tostring(matrix.get(DivMatrix, i, 7)) + 'x Pot ' + IndSel2 if Ind2Bear and Ind3Bear BearDivText := BearDivText + ', ' if Ind3Col == BearColor1 BearDivText := BearDivText + str.tostring(matrix.get(DivMatrix, i, 9)) + 'x ' + IndSel3 if Ind3Col == BearColor2 BearDivText := BearDivText + str.tostring(matrix.get(DivMatrix, i, 11)) + 'x Pot' + IndSel3 BearDivText := BearDivText + '\n' if BullDivText != TFConv + AlertFiltText + ' Bull Div \n' alert(BullDivText, alert.freq_once_per_bar_close) if BearDivText != TFConv + AlertFiltText + ' Bear Div \n' alert(BearDivText, alert.freq_once_per_bar_close)
Support & Resistance Trendlines with PP + Fib. Channel
https://www.tradingview.com/script/q3EHsmuK-Support-Resistance-Trendlines-with-PP-Fib-Channel/
Yatagarasu_
https://www.tradingview.com/u/Yatagarasu_/
1,001
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("S&R • Yata", overlay = true, max_bars_back = 5000) // --------------------- groupPP = "Pivot Points" groupPL = "Pivot Labels & Lines" groupSR = "Support & Resistance" groupFR = "Fibonacci Retracement" groupFE = "Fibonacci Extension" // --------------------- length = input (21 , title="Length" , inline="PP1", group=groupPP) //max_h_pivot_points = input.float (5, minval=2, title="Lookback: High" , inline="PP2", group=groupPP) //max_l_pivot_points = input.float (5, minval=2, title="Low" , inline="PP2", group=groupPP) max_pivot_points = input.float (5, minval=2, title="Pivot Points Lookback" , inline="PP2", group=groupPP) max_h_pivot_points = max_pivot_points max_l_pivot_points = max_pivot_points //min_difference = input.float (0.0 , title="" , inline="", group=groupPP) min_difference = 0.0 channel_ext_length = input (14 , title="Lines Extension" , inline="EXT", group=groupPP) source = input (close , title="Source" , inline="PP1", group=groupPP) // --------------------- show_plabels = input.bool(true, title="Show Pivot Labels", inline="PP4", group=groupPL) //d_lbl_pivh = input.bool(true, title="Draw Pivot High Labels", inline="", group=groupPL) //d_lbl_pivl = input.bool(true, title="Draw Pivot Low Labels", inline="", group=groupPL) d_lbl_pivh = show_plabels ? true : false d_lbl_pivl = show_plabels ? true : false ALB1 = input.color(color.new(#99D31B, 25), title="Active" , inline="PP4A", group=groupPL) // Active Pivot High Labels ALB2 = input.color(color.new(#FA5032, 25), title="" , inline="PP4A", group=groupPL) // Active Pivot Low Labels ILB1 = input.color(color.new(#99D31B, 75), title="| Inactive",inline="PP4A", group=groupPL) // Inactive Pivot High Labels ILB2 = input.color(color.new(#FF4500, 75), title="" , inline="PP4A", group=groupPL) // Inactive Pivot Low Labels // --------------------- show_plines = input.bool(true, title="Show Pivot Lines" , inline="PP5", group=groupPL) //d_pivh = input.bool(true, title="Draw Pivot High Lines", inline="", group=groupPL) //d_pivl = input.bool(true, title="Draw Pivot Low Lines" , inline="", group=groupPL) d_pivh = show_plines ? true : false d_pivl = show_plines ? true : false ALN1 = input.color(color.new(#99D31B, 50), title="Active" , inline="PP5A", group=groupPL) // Active Pivot High Lines ALN2 = input.color(color.new(#FA5032, 50), title="" , inline="PP5A", group=groupPL) // Active Pivot Low Lines ILN1 = input.color(color.new(#99D31B, 50), title="Inactive" , inline="PP5B", group=groupPL) // Inactive Pivot High Lines ILN2 = input.color(color.new(#FF4500, 50), title="" , inline="PP5B", group=groupPL) // Inactive Pivot Low Lines // --------------------- show_chan = input.bool(true, title="Show Channel Lines" , inline="CH1", group=groupSR) //d_chanh = input.bool(true, title="Draw Channel High" , inline="", group=groupSR) //d_chanl = input.bool(true, title="Draw Channel Low" , inline="", group=groupSR) d_chanh = show_chan ? true : false d_chanl = show_chan ? true : false show_extendL = input.bool(false, title="Extend Channel Lines" , inline="CH1B", group=groupSR) extendL = show_extendL ? extend.left : extend.none RLN = input.color(color.new(#99D31B, 25), title="High" , inline="CH1A", group=groupSR) // Resistance Line SLN = input.color(color.new(#FA5032, 25), title="Low" , inline="CH1A", group=groupSR) // Support Line // --------------------- d_fib = input.bool(true, title="Draw Fib. Retr. Lines", inline="CH2", group=groupFR) FRH = input.color(color.new(#99D31B, 25), title="High" , inline="CH2A", group=groupFR) // Fibonacci Retracement High FRL = input.color(color.new(#FA5032, 25), title="Low" , inline="CH2A", group=groupFR) // Fibonacci Retracement Low sfib_R01 = input.bool(true , title="01" , inline="CH21", group=groupFR) sfib_R02 = input.bool(true , title="02" , inline="CH22", group=groupFR) sfib_R03 = input.bool(true , title="03" , inline="CH23", group=groupFR) sfib_R04 = input.bool(true , title="04" , inline="CH24", group=groupFR) sfib_R05 = input.bool(true , title="05" , inline="CH25", group=groupFR) fib_R01 = sfib_R01 ? input.float(0.236 , title="" , inline="CH21", group=groupFR) : na fib_R02 = sfib_R02 ? input.float(0.382 , title="" , inline="CH22", group=groupFR) : na fib_R03 = sfib_R03 ? input.float(0.5 , title="" , inline="CH23", group=groupFR) : na fib_R04 = sfib_R04 ? input.float(0.618 , title="" , inline="CH24", group=groupFR) : na fib_R05 = sfib_R05 ? input.float(0.786 , title="" , inline="CH25", group=groupFR) : na sfib_R06 = input.bool(false , title="06" , inline="CH21", group=groupFR) sfib_R07 = input.bool(false , title="07" , inline="CH22", group=groupFR) sfib_R08 = input.bool(false , title="08" , inline="CH23", group=groupFR) sfib_R09 = input.bool(false , title="09" , inline="CH24", group=groupFR) sfib_R10 = input.bool(false , title="10" , inline="CH25", group=groupFR) fib_R06 = sfib_R06 ? input.float(0.09 , title="" , inline="CH21", group=groupFR) : na fib_R07 = sfib_R07 ? input.float(0.146 , title="" , inline="CH22", group=groupFR) : na fib_R08 = sfib_R08 ? input.float(0.35 , title="" , inline="CH23", group=groupFR) : na fib_R09 = sfib_R09 ? input.float(0.65 , title="" , inline="CH24", group=groupFR) : na fib_R10 = sfib_R10 ? input.float(0.886 , title="" , inline="CH25", group=groupFR) : na // --------------------- d_fib2 = input.bool(true, title="Draw Fib. Ext. Lines", inline="CH3", group=groupFE) FEH = input.color(color.new(#99D31B, 25), title="High" , inline="CH3A", group=groupFE) // Fibonacci Extension High FEL = input.color(color.new(#FA5032, 25), title="Low" , inline="CH3A", group=groupFE) // Fibonacci Extension Low sfib_E01 = input.bool(true , title="01" , inline="CH31", group=groupFE) sfib_E02 = input.bool(false , title="02" , inline="CH32", group=groupFE) sfib_E03 = input.bool(true , title="03" , inline="CH33", group=groupFE) sfib_E04 = input.bool(false , title="04" , inline="CH34", group=groupFE) fib_E01 = sfib_E01 ? input.float(1.618 , title="" , inline="CH31", group=groupFE) : na fib_E02 = sfib_E02 ? input.float(2 , title="" , inline="CH32", group=groupFE) : na fib_E03 = sfib_E03 ? input.float(-0.618 , title="" , inline="CH33", group=groupFE) : na fib_E04 = sfib_E04 ? input.float(-1 , title="" , inline="CH34", group=groupFE) : na sfib_E05 = input.bool(false , title="05" , inline="CH31", group=groupFE) sfib_E06 = input.bool(false , title="06" , inline="CH32", group=groupFE) sfib_E07 = input.bool(false , title="07" , inline="CH33", group=groupFE) sfib_E08 = input.bool(false , title="08" , inline="CH34", group=groupFE) fib_E05 = sfib_E05 ? input.float(1.13 , title="" , inline="CH31", group=groupFE) : na fib_E06 = sfib_E06 ? input.float(1.272 , title="" , inline="CH32", group=groupFE) : na fib_E07 = sfib_E07 ? input.float(1.41 , title="" , inline="CH33", group=groupFE) : na fib_E08 = sfib_E08 ? input.float(1.786 , title="" , inline="CH34", group=groupFE) : na // --------------------- f_bg = input.bool(true, title="Fill Channel Background" , inline="CH4", group=groupSR) GF2 = input.color(color.new(#99D31B, 0) , title="Rising" , inline="CH4A", group=groupSR) // Falling Fill GF1 = input.color(color.new(#FF4500, 0) , title="Falling" , inline="CH4A", group=groupSR) // Rising Fill f_transp = input.float(97 , title="| Tra." , inline="CH4A", group=groupSR) // --------------------- lwidth_piv = input.int(1, minval=0, title="| Width", inline="PP5", group=groupPL) lwidth_chan = input.int(2, minval=0, title="| Width", inline="CH1", group=groupSR) lwidth_FR = input.int(1, minval=0, title="| Width", inline="CH2", group=groupFR) lwidth_FE = input.int(1, minval=0, title="| Width", inline="CH3", group=groupFE) i_line0 = "Solid" i_line1 = "Dotted" i_line2 = "Dashed" ppstyleAHL_input = input.string(i_line2, title="|", options=[i_line0, i_line1, i_line2], inline="PP5A", group=groupPL) // Active Pivot Lines ppstyleIHL_input = input.string(i_line1, title="|", options=[i_line0, i_line1, i_line2], inline="PP5B", group=groupPL) // Inactive Pivot Lines ppstyleSRL_input = input.string(i_line0, title="|", options=[i_line0, i_line1, i_line2], inline="CH1A", group=groupSR) // Support and Resistance Lines ppstyleFRL_input = input.string(i_line1, title="|", options=[i_line0, i_line1, i_line2], inline="CH2A", group=groupFR) // Fibonacci Retracement Lines ppstyleFEL_input = input.string(i_line1, title="|", options=[i_line0, i_line1, i_line2], inline="CH3A", group=groupFE) // Fibonacci Extension Lines f_getLineStyle(_inputStyle) => _return = _inputStyle == i_line1 ? line.style_dotted : _inputStyle == i_line2 ? line.style_dashed : line.style_solid _return // --------------------- var ph_index = array.new_int() var pl_index = array.new_int() var ph_value = array.new_float() var pl_value = array.new_float() interp(l, h, s) => l + (h - l) * s // --------------------- ph = ta.pivothigh(source, length, length) if ph ok = true ph := high[length] if array.size(ph_index) > 0 if array.size(ph_index) >= max_h_pivot_points array.shift(ph_index) array.shift(ph_value) for i = 0 to array.size(ph_value) - 1 if math.abs(ph - array.get(ph_value, i)) < min_difference ok := false if ph > array.get(ph_value, i) array.set(ph_value, i , ph) array.set(ph_index, i , bar_index[length]) if ok array.push(ph_index, bar_index[length]) array.push(ph_value, ph) // --------------------- pl = ta.pivotlow(source, length, length) if pl ok = true pl := low[length] if array.size(pl_index) > 0 if array.size(pl_index) >= max_l_pivot_points array.shift(pl_index) array.shift(pl_value) for i = 0 to array.size(pl_value) - 1 if math.abs(pl - array.get(pl_value, i)) < min_difference ok := false if pl < array.get(pl_value, i) array.set(pl_value, i , pl) array.set(pl_index, i , bar_index[length]) if ok array.push(pl_index, bar_index[length]) array.push(pl_value, pl) // --------------------- var lines = array.new_line() var labels = array.new_label() var fibs = array.new_line() var line line_fc_up = line(na) var line line_fc_down = line(na) var linefill fill_fc = linefill(na) // --------------------- if barstate.isconfirmed ph_count = array.size(ph_index) pl_count = array.size(pl_index) for i = 0 to array.size(lines) if array.size(lines) > 0 line.delete(array.shift(lines)) for i = 0 to array.size(labels) if array.size(labels) > 0 label.delete(array.shift(labels)) if ph_count > 0 for i = 0 to ph_count - 1 // alpha = 80//math.min(100 - int((i / (ph_count - 1)) * 100), 80) // clr = color.from_gradient(100 - alpha, 0, 100, #E8E965, #99D31B) if d_lbl_pivh array.push(labels, label.new(array.get(ph_index, i), array.get(ph_value, i), "", style=label.style_label_down, color=ILB1, size=size.tiny)) if d_pivh array.push(lines, line.new(array.get(ph_index, i), array.get(ph_value, i), bar_index + channel_ext_length, array.get(ph_value, i), color=ILN1, width=lwidth_piv, style=f_getLineStyle(ppstyleIHL_input), extend=extend.none)) if pl_count > 0 for i = 0 to pl_count - 1 // alpha = 80//math.min(100 - int((i / (pl_count - 1)) * 100), 80) // clr = color.from_gradient(100 - alpha, 0, 100, #64C5C7, #FA5032) if d_lbl_pivl array.push(labels, label.new(array.get(pl_index, i), array.get(pl_value, i), "", style=label.style_label_up, color=ILB2, size=size.tiny)) if d_pivl array.push(lines, line.new(array.get(pl_index, i), array.get(pl_value, i), bar_index + channel_ext_length, array.get(pl_value, i), color=ILN2, width=lwidth_piv, style=f_getLineStyle(ppstyleIHL_input), extend=extend.none)) // --------------------- if d_chanh if ph_count > 1 tmp_arr = array.new_line() for i = 0 to ph_count - 1 for j = 0 to ph_count - 1 h0 = array.get(ph_value, i) h1 = array.get(ph_value, j) h0i = array.get(ph_index, i) //array.indexof(ph_value, h0)) h1i = array.get(ph_index, j) //array.indexof(ph_value, h1)) if h0i < h1i array.push(tmp_arr, line.new(h0i, h0, h1i, h1, color=RLN, width=lwidth_chan, extend=extend.none, style=f_getLineStyle(ppstyleSRL_input))) if h0i > h1i array.push(tmp_arr, line.new(h1i, h1, h0i, h0, color=RLN, width=lwidth_chan, extend=extend.none, style=f_getLineStyle(ppstyleSRL_input))) int min_ind = na float min_val = 100000.0 for i = 0 to array.size(tmp_arr) - 1 lp = line.get_price(array.get(tmp_arr, i), bar_index) if lp > high if min_val > math.abs(lp - close) min_val := math.abs(lp - close) min_ind := i if not na(min_ind) line.delete(line_fc_up[1]) best_line = array.get(tmp_arr, min_ind) line_fc_up := line.new(line.get_x1(best_line), line.get_y1(best_line), line.get_x2(best_line), line.get_y2(best_line), color=RLN, width=lwidth_chan, extend=extendL, style=f_getLineStyle(ppstyleSRL_input)) for i = 0 to array.size(tmp_arr) - 1 if array.size(tmp_arr) > 0 line.delete(array.shift(tmp_arr)) for l in labels if label.get_x(l) == line.get_x1(line_fc_up) or label.get_x(l) == line.get_x2(line_fc_up) label.set_color(l, ALB1) for l in lines if line.get_x1(l) == line.get_x1(line_fc_up) or line.get_x1(l) == line.get_x2(line_fc_up) line.set_color(l, ALN1) line.set_style(l, f_getLineStyle(ppstyleAHL_input)) line.set_width(l, lwidth_piv) line.set_y2(line_fc_up, line.get_price(line_fc_up, bar_index + channel_ext_length)) line.set_x2(line_fc_up, bar_index + channel_ext_length) // --------------------- if d_chanl if pl_count > 1 tmp_arr = array.new_line() for i = 0 to pl_count - 1 for j = 0 to pl_count - 1 l0 = array.get(pl_value, i) l1 = array.get(pl_value, j) l0i = array.get(pl_index, i) //array.indexof(pl_value, l0)) l1i = array.get(pl_index, j) //array.indexof(pl_value, l1)) if l0i < l1i array.push(tmp_arr, line.new(l0i, l0, l1i, l1, color=SLN, width=lwidth_chan, extend=extend.none, style=f_getLineStyle(ppstyleSRL_input))) if l0i > l1i array.push(tmp_arr, line.new(l1i, l1, l0i, l0, color=SLN, width=lwidth_chan, extend=extend.none, style=f_getLineStyle(ppstyleSRL_input))) int min_ind = na float min_val = 100000.0 for i = 0 to array.size(tmp_arr) - 1 lp = line.get_price(array.get(tmp_arr, i), bar_index) if lp < low if min_val > math.abs(lp - close) min_val := math.abs(lp - close) min_ind := i if not na(min_ind) line.delete(line_fc_down[1]) best_line = array.get(tmp_arr, min_ind) line_fc_down := line.new(line.get_x1(best_line), line.get_y1(best_line), line.get_x2(best_line), line.get_y2(best_line), color=SLN, width=lwidth_chan, extend=extendL, style=f_getLineStyle(ppstyleSRL_input)) for i = 0 to array.size(tmp_arr) - 1 if array.size(tmp_arr) > 0 line.delete(array.shift(tmp_arr)) for l in labels if label.get_x(l) == line.get_x1(line_fc_down) or label.get_x(l) == line.get_x2(line_fc_down) label.set_color(l, ALB2) for l in lines if line.get_x1(l) == line.get_x1(line_fc_down) or line.get_x1(l) == line.get_x2(line_fc_down) line.set_color(l, ALN2) line.set_style(l, f_getLineStyle(ppstyleAHL_input)) line.set_width(l, lwidth_piv) line.set_y2(line_fc_down, line.get_price(line_fc_down, bar_index + channel_ext_length)) line.set_x2(line_fc_down, bar_index + channel_ext_length) // --------------------- if not na(line_fc_up) and not na(line_fc_down) and f_bg linefill.delete(fill_fc[1]) fill_color = color.new(color.from_gradient(ta.rsi(close, 14), 30, 70, GF1, GF2), f_transp) fill_fc := linefill.new(line_fc_up, line_fc_down, fill_color) if not na(line_fc_up) and not na(line_fc_down) and d_fib for i = 0 to array.size(fibs) - 1 if array.size(fibs) > 0 line.delete(array.shift(fibs)) left = math.min(line.get_x1(line_fc_up), line.get_x1(line_fc_down)) right = bar_index + channel_ext_length left_val = interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R01) right_val = interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R01) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R02) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R02) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R03) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R03) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R04) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R04) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R05) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R05) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R06) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R06) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R07) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R07) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R08) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R08) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R09) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R09) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_R10) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_R10) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFRL_input), width=lwidth_FR, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FRL, FRH))) if d_fib2 left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E01) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E01) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E02) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E02) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E03) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E03) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E04) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E04) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E05) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E05) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E06) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E06) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E07) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E07) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH))) left_val := interp(line.get_price(line_fc_down, left), line.get_price(line_fc_up, left) , fib_E08) right_val := interp(line.get_price(line_fc_down, right), line.get_price(line_fc_up, right) , fib_E08) array.push(fibs, line.new(left, left_val, right, right_val, style=f_getLineStyle(ppstyleFEL_input), width=lwidth_FE, color=color.from_gradient(right_val, line.get_price(line_fc_down, right), line.get_price(line_fc_up, right), FEL, FEH)))
Advanced Donchian Channels
https://www.tradingview.com/script/TRYeJZDd-Advanced-Donchian-Channels/
SamRecio
https://www.tradingview.com/u/SamRecio/
211
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("Advanced Donchian Channels", shorttitle = "[ADC]",overlay = true, max_lines_count = 500) len = input.int(20, title ="Len", minval = 1, maxval = 166, group = "Advanced Donchian Channel") fut_tog = input.bool(true, title = "Plot Future Lines?") color1 = input.color(color.rgb(38,208,124), title = "", inline = "1", group = "Colors") color2 = input.color(color.rgb(0,150,255), title = "", inline = "1", group = "Colors") color3 = input.color(color.rgb(255,3,62), title = "", inline = "1", group = "Colors") highst = ta.highest(high,len) lowst = ta.lowest(low,len) mean = math.avg(highst,lowst) highbar = ta.barssince(high == highst) lowbar = ta.barssince(low == lowst) dir = highbar>lowbar?2:lowbar>highbar?1:0 var fut_lines = array.new_line(na) if array.size(fut_lines) > 0 for i = 0 to array.size(fut_lines) - 1 line.delete(array.get(fut_lines, i)) array.clear(fut_lines) if fut_tog for i = len to 2 low1 = ta.lowest(low,i) low2 = ta.lowest(low,i-1) high1 = ta.highest(high,i) high2 = ta.highest(high,i-1) array.push(fut_lines,line.new(bar_index + (len-i), high1,(bar_index +(len-i))+ 1,high2, color = color1, style = line.style_dotted)) array.push(fut_lines,line.new(bar_index + (len-i), math.avg(high1,low1),(bar_index +(len-i))+ 1,math.avg(high2,low2), color = color2, style = line.style_dotted)) array.push(fut_lines,line.new(bar_index + (len-i), low1,(bar_index +(len-i))+ 1,low2, color = color3, style = line.style_dotted)) //PLOTS plot(highst, title = "Highest", color = color1, linewidth = 2, editable = false) plot(mean,title = "Mean", color = color2, linewidth = 1, editable = false) plot(lowst, title = "Lowest", color = color3, linewidth = 2, editable = false) //ALERTS//////////////////////////////////////////////////////////////////////// up = (close<=mean)[1] and (close>mean) down = (close>=mean)[1] and (close<mean) alertcondition(up, "Close Over Mean") alertcondition(down, "Close Under Mean")
EMA Gradient
https://www.tradingview.com/script/D3Kif6lU-EMA-Gradient/
m_b_round
https://www.tradingview.com/u/m_b_round/
30
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © m_b_round //@version=5 indicator("EMA Gradient", precision=5, overlay=true) emaLength = input.int(200, "EMA Length", group="EMA Inputs") emaSource = input.source(close, "Source", group="EMA Inputs") sampleLength = input.int(10, "Linreg length", group="Linear Regression") showLine = input.bool(true, "Show best fit line", group="Linear Regression") linregColor = input.color(color.purple, "Best fit line colour", group="Linear Regression") gradientThreshold = input.float(75, "Gradient Threshold", group="Gradient Comparison") gradientComparison = input.int(200, "Gradient Lookback", group="Gradient Comparison") emaLine = ta.ema(emaSource, emaLength) gradient = (ta.linreg(emaLine,sampleLength,-10) - ta.linreg(emaLine,sampleLength,10)) / 20 var line li = na if showLine line.delete(li) // Use sampleLength as the plot length of the line to show how many data points it refers to. li := line.new(bar_index-sampleLength, ta.linreg(emaLine, sampleLength, sampleLength), bar_index, ta.linreg(emaLine, sampleLength, 0), xloc=xloc.bar_index, color=linregColor, style=line.style_dashed, width=2) percRank = ta.percentrank(math.abs(gradient), gradientComparison) plot(percRank, "Percentage Rank", display=display.data_window) plot(emaLine, color= percRank >= gradientThreshold ? gradient > 0 ? color.green : color.red : color.yellow) plot(gradient/close*100, "Gradient (%)", display=display.data_window) // plot(ta.atr(emaLength) / close * 100, "ATRP", display=display.data_window)
Bandas de Bollinger + 3 Medias Moviles Simples
https://www.tradingview.com/script/Bgxp3png/
jeanjara77
https://www.tradingview.com/u/jeanjara77/
34
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © jeanjara77 //@version=5 indicator(shorttitle="BB+3MA", title="Bollinger Bands + Medias Moviles Simples", overlay=true, timeframe="", timeframe_gaps=true) length = input.int(20, minval=1) src = input(close, title="Source") mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev") basis = ta.sma(src, length) dev = mult * ta.stdev(src, length) upper = basis + dev lower = basis - dev offset = input.int(0, "Offset", minval = -500, maxval = 500) plot(basis, "Basis", color=#2962FF, offset = offset) p1 = plot(upper, "Upper", color=#bbbdc2, offset = offset) p2 = plot(lower, "Lower", color=#bbbdc2, offset = offset) fill(p1, p2, title = "Background", color=color.rgb(76, 169, 245, 96)) //Evaluation Bear = high >= upper Bull = low <= lower //Plots plotshape(Bear, style=shape.triangledown, location=location.abovebar, color=color.rgb(255, 82, 82, 66), size=size.tiny) plotshape(Bull, style=shape.triangleup, location=location.belowbar, color=color.rgb(76, 175, 79, 64), size=size.tiny) // Alert Functionality alertcondition(Bear or Bull, title="Any Signal", message="{{exchange}}:{{ticker}}" + " {{interval}}") alertcondition(Bear, title="Bearish Signal", message="{{exchange}}:{{ticker}}" + " {{interval}}") alertcondition(Bull, title="Bullish Signal", message="{{exchange}}:{{ticker}}" + " {{interval}}") //3SMA plot(ta.sma(close, 200), color=#f00808, title="SMA200") plot(ta.sma(close, 100), color=color.rgb(238, 215, 4), title="SMA100") plot(ta.sma(close, 50), color=#099b2d, title="SMA50")
First Derivative
https://www.tradingview.com/script/ADm7Ar4M-First-Derivative/
jas9360
https://www.tradingview.com/u/jas9360/
2
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/ // © jas9360 //@version=5 indicator("First Derivative", shorttitle="ROC", format=format.price, precision=2, timeframe="", timeframe_gaps=true) roc = 100* ((close - hl2)/hl2) plot(roc, color=#2962FF, title="ROC", linewidth=2, style=plot.style_circles) hline(0, color=#787B86, title="Zero Line")
Divergence Backtester
https://www.tradingview.com/script/vNAFeZFR-Divergence-Backtester/
Trendoscope
https://www.tradingview.com/u/Trendoscope/
655
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/ // © HeWhoMustNotBeNamed // __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __ // / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / | // $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ | // $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ | // $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ | // $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ | // $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ | // $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ | // $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/ // // // //@version=5 indicator("Divergence Backtester", overlay=true, max_lines_count = 500, max_labels_count = 500) import HeWhoMustNotBeNamed/mZigzag/10 as zg import HeWhoMustNotBeNamed/enhanced_ta/14 as eta import HeWhoMustNotBeNamed/arrays/1 as pa //*********************** Debug method *************************// i_start = 0 i_page = 100 i_maxLogSize = 1000 i_showHistory = false i_showBarIndex = false var DebugArray = array.new_string(0) var DebugBarArray = array.new_string(0) add_to_debug_array(arr, val, maxItems) => array.unshift(arr, str.tostring(val)) if array.size(arr) > maxItems array.pop(arr) debug(debugMsg) => if barstate.islast or i_showHistory barTimeString = str.tostring(year, '0000') + '/' + str.tostring(month, '00') + '/' + str.tostring(dayofmonth, '00') + (timeframe.isintraday ? '-' + str.tostring(hour, '00') + ':' + str.tostring(minute, '00') + ':' + str.tostring(second, '00') : '') add_to_debug_array(DebugBarArray, i_showBarIndex ? str.tostring(bar_index) : barTimeString, i_maxLogSize) add_to_debug_array(DebugArray, debugMsg, i_maxLogSize) //*********************** Debug method *************************// length = input.int(8, 'Length', group='Zigzag') oscillatorType = input.string("rsi", title="Oscillator", inline="osc", options=["cci", "cmo", "cog", "mfi", "roc", "rsi"], group='Oscillator') oscLength = input.int(14, title="", inline="osc", group='Oscillator') supertrendLength = input.int(5, 'History', inline='st', group='Supertrend') drawSupertrend = input.bool(true, "Draw Zigzag Supertrend", inline='st2', group='Supertrend') txtSize = input.string(size.tiny, 'Text Size', [size.tiny, size.small, size.normal, size.large, size.huge], inline='txt') txtColor = input.color(color.white, '', inline='txt') getPivotLowDivergenceIndex(divergence)=> switch(divergence) 4 => 0 //Bullish Continuation - Uptrend HL, HL 3 => 1 //Bullish Hidden Divergence - Uptrend HL, LL 2 => 2 //Bullish Divergence - Downtrend LL, HL 1 => 3 //Bullish Against Trend - Downtrend HL, HL -4 => 4 //Bearish Continuation - Downtrend LL, LL -1 => 5 //Bearish Against Trend - Uptrend LL, LL => 6 //Indeterminate - Uptrend LL, HL and Downtrend HL, LL getPivotHighDivergenceIndex(divergence)=> switch(divergence) -4 => 0 //Bearish Continuation - Downtrend LH, LH -3 => 1 //Bearish Hidden Divergence - Downtrend LH, HH -2 => 2 //Bearish Divergence - Uptrend HH, LH -1 => 3 //Bearish Against Trend - Uptrend LH, LH 4 => 4 //Bullish Continuation - Uptrend HH, HH 1 => 5 //Bullish Against Trend - Downtrend HH, HH => 6 //Indeterminate - Downtrend HH, HL and Uptrend LH, HH getPivotLowDivergenceColor(index)=> switch(index) 0=> color.green 1=> color.green 2=> color.lime 3=> color.lime 4=> color.red 5=> color.orange 6=> color.silver getPivotHighDivergenceColor(index)=> switch(index) 0=> color.red 1=> color.orange 2=> color.orange 3=> color.orange 4=> color.green 5=> color.lime 6=> color.silver getPivotLowDivergenceLabel(index)=> switch(index) 0 => "Bullish Continuation (Uptrend - HL/HL)" 1 => "Bullish Hidden Divergence (Uptrend - HL/LL)" 2 => "Bullish Divergence (Downtrend - LL/HL)" 3 => "Bullish Against Trend (Downtrend - HL/HL)" 4 => "Bearish Continuation (Downtrend - LL/LL)" 5 => "Bearish Against Trend (Uptrend - LL/LL)" 6 => "Indeterminate (Uptrend - LL/HL, Downtrend - HL/LL)" => "None" getPivotHighDivergenceLabel(index)=> switch(index) 0 => "Bearish Continuation (Downtrend - LH/LH)" 1 => "Bearish Hidden Divergence (Downtrend - LH/HH)" 2 => "Bearish Divergence (Uptrend - HH/LH)" 3 => "Bearish Against Trend (Uptrend - LH/LH)" 4 => "Bullish Continuation (Uptrend - HH/HH)" 5 => "Bullish Against Trend (Downtrend - HH/HH)" 6 => "Indeterminate (Downtrend - HH/LH, Uptrend - LH/HH)" => "None" draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, lineColor, lineWidth, lineStyle) => if matrix.rows(valueMatrix) > 2 idxLen1 = matrix.rows(valueMatrix)-idx1 idxLen2 = matrix.rows(valueMatrix)-idx2 lastValues = matrix.row(valueMatrix, idxLen1) llastValues = matrix.row(valueMatrix, idxLen2) lastDirections = matrix.row(directionMatrix, idxLen1) lastRatios = matrix.row(ratioMatrix, idxLen1) lastDivergence = matrix.row(divergenceMatrix, idxLen1) lastDoubleDivergence = matrix.row(doubleDivergenceMatrix, idxLen1) y1 = array.get(lastValues, 0) y2 = array.get(llastValues, 0) x1 = array.get(barArray, idxLen1) x2 = array.get(barArray, idxLen2) zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=lineColor, width=lineWidth, style=lineStyle) currentDir = y1 > y2? 1 : -1 lastDivergenceLabel = currentDir > 0? getPivotHighDivergenceLabel(getPivotHighDivergenceIndex(array.get(lastDivergence, 1))) : getPivotLowDivergenceLabel(getPivotLowDivergenceIndex(array.get(lastDivergence, 1))) labelStyle = currentDir > 0? label.style_label_down : label.style_label_up lblColor = currentDir > 0? getPivotHighDivergenceColor(getPivotHighDivergenceIndex(array.get(lastDivergence, 1))) : getPivotLowDivergenceColor(getPivotLowDivergenceIndex(array.get(lastDivergence, 1))) zlabel = label.new(x=x1, y=y1, yloc=yloc.price, color=lblColor, style=labelStyle, text=lastDivergenceLabel, textcolor=color.black, size = size.small, tooltip=lastDivergenceLabel) if array.size(zigzaglines) > 0 lastLine = array.get(zigzaglines, array.size(zigzaglines)-1) if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1 pa.pop(zigzaglines) pa.pop(zigzaglabels) pa.push(zigzaglines, zline, 500) pa.push(zigzaglabels, zlabel, 500) draw(matrix<float> valueMatrix, matrix<int> directionMatrix, matrix<float> ratioMatrix, matrix<int> divergenceMatrix, matrix<int> doubleDivergenceMatrix, array<int> barArray, bool newZG, bool doubleZG, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid)=> var zigzaglines = array.new_line(0) var zigzaglabels = array.new_label(0) if(newZG) if doubleZG draw_zg_line(2, 3, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, lineColor, lineWidth, lineStyle) if matrix.rows(valueMatrix) >= 2 draw_zg_line(1, 2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, lineColor, lineWidth, lineStyle) [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, zigzaglines, zigzaglabels] increment(matrix<int> mtx, row, col)=>matrix.set(mtx, row, col, matrix.get(mtx, row, col)+1) indicatorHigh = array.new_float() indicatorLow = array.new_float() indicatorLabels = array.new_string() [oscHigh, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, high) [oscLow, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, low) array.push(indicatorHigh, math.round(oscHigh,2)) array.push(indicatorLow, math.round(oscLow,2)) array.push(indicatorLabels, oscillatorType+str.tostring(oscLength)) [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, supertrendDir, supertrend, newZG, doubleZG] = zg.calculate(length, array.from(high, low), indicatorHigh, indicatorLow, supertrendLength = supertrendLength) lastDirection = matrix.rows(directionMatrix) > 1? matrix.row(directionMatrix, matrix.rows(directionMatrix)-2) : array.new_int() lastRatio = matrix.rows(ratioMatrix) > 1? matrix.row(ratioMatrix, matrix.rows(ratioMatrix)-2) : array.new_float() lastDivergence = matrix.rows(divergenceMatrix) > 1? matrix.row(divergenceMatrix, matrix.rows(divergenceMatrix)-2) : array.new_int() lastDoubleDivergence = matrix.rows(doubleDivergenceMatrix) > 1? matrix.row(doubleDivergenceMatrix, matrix.rows(doubleDivergenceMatrix)-2) : array.new_int() llastRatio = matrix.rows(ratioMatrix) > 2? matrix.row(ratioMatrix, matrix.rows(ratioMatrix)-3) : array.new_float() llastDivergence = matrix.rows(divergenceMatrix) > 2? matrix.row(divergenceMatrix, matrix.rows(divergenceMatrix)-3) : array.new_int() llastDoubleDivergence = matrix.rows(doubleDivergenceMatrix) > 2? matrix.row(doubleDivergenceMatrix, matrix.rows(doubleDivergenceMatrix)-3) : array.new_int() lllastRatio = matrix.rows(ratioMatrix) > 3? matrix.row(ratioMatrix, matrix.rows(ratioMatrix)-4) : array.new_float() lllastDivergence = matrix.rows(divergenceMatrix) > 3? matrix.row(divergenceMatrix, matrix.rows(divergenceMatrix)-4) : array.new_int() lllastDoubleDivergence = matrix.rows(doubleDivergenceMatrix) > 3? matrix.row(doubleDivergenceMatrix, matrix.rows(doubleDivergenceMatrix)-4) : array.new_int() var bullishPivotCount = 0 var bearishPivotCount = 0 var pivotHighDivergenceStats = matrix.new<int>(4, 7, 0) var pivotLowDivergenceStats = matrix.new<int>(4, 7, 0) if(array.size(lllastRatio) > 0) priceDirection = array.get(lastDirection, 0) lastPriceDivergence = array.get(llastDivergence, 1) llastPriceDivergence = array.get(lllastDivergence,1) if(math.abs(priceDirection) > 2 or math.abs(priceDirection) < 1) runtime.error('Incorrect direction :'+str.tostring(priceDirection)) if(math.sign(priceDirection) > 0) lastIndex = getPivotLowDivergenceIndex(lastPriceDivergence) llastIndex = getPivotHighDivergenceIndex(llastPriceDivergence) rowLast = math.abs(priceDirection) %2 rowLLast = 2 + rowLast increment(pivotHighDivergenceStats, rowLast, lastIndex) increment(pivotHighDivergenceStats, rowLLast, llastIndex) bullishPivotCount+=1 else lastIndex = getPivotHighDivergenceIndex(lastPriceDivergence) llastIndex = getPivotLowDivergenceIndex(llastPriceDivergence) rowLast = math.abs(priceDirection) %2 rowLLast = 2 + rowLast increment(pivotLowDivergenceStats, rowLast, lastIndex) increment(pivotLowDivergenceStats, rowLLast, llastIndex) bearishPivotCount+=1 draw(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, newZG, doubleZG) var statsTable = table.new(position=position.top_right, columns=6, rows=20, border_color = color.black, border_width = 2) table.cell(statsTable, 0, 0, 'Piot High', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.merge_cells(statsTable, 0, 0, 5, 0) table.cell(statsTable, 0, 1, 'Last Pivot Trend', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 1, 1, 'HH Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 2, 1, 'LH Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 3, 1, 'Previous Last Pivot Trend', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 4, 1, 'HH Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 5, 1, 'LH Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 0, 9, '', bgcolor = color.silver, text_color = txtColor, text_size = size.tiny) table.merge_cells(statsTable, 0, 9, 5, 9) table.cell(statsTable, 0, 10, 'Piot Low', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.merge_cells(statsTable, 0, 10, 5, 10) table.cell(statsTable, 0, 11, 'Last Pivot Trend', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 1, 11, 'LL Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 2, 11, 'HL Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 3, 11, 'Previous Last Pivot Trend', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 4, 11, 'LL Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 5, 11, 'HL Count', bgcolor = color.maroon, text_color = txtColor, text_size = txtSize) if(barstate.islast) for i=0 to matrix.columns(pivotHighDivergenceStats)-1 hhStatLPivot = matrix.get(pivotHighDivergenceStats, 0, i) lhStatLPivot = matrix.get(pivotHighDivergenceStats, 1, i) hhStatLLPivot = matrix.get(pivotHighDivergenceStats, 2, i) lhStatLLPivot = matrix.get(pivotHighDivergenceStats, 3, i) table.cell(statsTable, 0, 2+i, getPivotLowDivergenceLabel(i), bgcolor = color.teal, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 3, 2+i, getPivotHighDivergenceLabel(i), bgcolor = color.teal, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 1, 2+i, str.tostring(hhStatLPivot), bgcolor = color.new(color.green, 70), text_color = txtColor, text_size = txtSize) table.cell(statsTable, 2, 2+i, str.tostring(lhStatLPivot), bgcolor = color.new(color.red, 70), text_color = txtColor, text_size = txtSize) table.cell(statsTable, 4, 2+i, str.tostring(hhStatLLPivot), bgcolor = color.new(color.green, 70), text_color = txtColor, text_size = txtSize) table.cell(statsTable, 5, 2+i, str.tostring(lhStatLLPivot), bgcolor = color.new(color.red, 70), text_color = txtColor, text_size = txtSize) for i=0 to matrix.columns(pivotLowDivergenceStats)-1 llStatLPivot = matrix.get(pivotLowDivergenceStats, 0, i) hlStatLPivot = matrix.get(pivotLowDivergenceStats, 1, i) llStatLLPivot = matrix.get(pivotLowDivergenceStats, 2, i) hlStatLLPivot = matrix.get(pivotLowDivergenceStats, 3, i) table.cell(statsTable, 0, 12+i, getPivotHighDivergenceLabel(i), bgcolor = color.teal, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 3, 12+i, getPivotLowDivergenceLabel(i), bgcolor = color.teal, text_color = txtColor, text_size = txtSize) table.cell(statsTable, 1, 12+i, str.tostring(llStatLPivot), bgcolor = color.new(color.red, 70), text_color = txtColor, text_size = txtSize) table.cell(statsTable, 2, 12+i, str.tostring(hlStatLPivot), bgcolor = color.new(color.green, 70), text_color = txtColor, text_size = txtSize) table.cell(statsTable, 4, 12+i, str.tostring(llStatLLPivot), bgcolor = color.new(color.red, 70), text_color = txtColor, text_size = txtSize) table.cell(statsTable, 5, 12+i, str.tostring(hlStatLLPivot), bgcolor = color.new(color.green, 70), text_color = txtColor, text_size = txtSize) plot(drawSupertrend? supertrend:na, color=supertrendDir>0? color.green:color.red, style=plot.style_linebr) //************************************************************ Print debug message on table ********************************************************/ var debugTable = table.new(position=position.bottom_right, columns=2, rows=i_page + 1, border_width=1) if array.size(DebugArray) > 0 table.cell(table_id=debugTable, column=0, row=0, text=i_showBarIndex ? 'Bar Index' : 'Bar Time', bgcolor=color.teal, text_color=txtColor, text_size=size.normal) table.cell(table_id=debugTable, column=1, row=0, text='Debug Message', bgcolor=color.teal, text_color=txtColor, text_size=size.normal) for i = 0 to math.min(array.size(DebugArray) - 1 - i_start, i_page - 1) by 1 table.cell(table_id=debugTable, column=0, row=i + 1, text=array.get(DebugBarArray, i + i_start), bgcolor=color.black, text_color=txtColor, text_size=size.normal) table.cell(table_id=debugTable, column=1, row=i + 1, text=array.get(DebugArray, i + i_start), bgcolor=color.black, text_color=txtColor, text_size=size.normal) //************************************************************ Finish Printing ********************************************************/
Williams Fractals + SMMA
https://www.tradingview.com/script/aEddme3o-Williams-Fractals-SMMA/
rangu9101994
https://www.tradingview.com/u/rangu9101994/
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/ // © rangu9101994 //@version=5 indicator("Williams Fractals", shorttitle="Williams fractail + Moving average", format=format.price, precision=0, overlay=true) // Define "n" as the number of periods and keep a minimum value of 2 for error handling. n = input.int(title="Periods", defval=2, minval=2) // UpFractal bool upflagDownFrontier = true bool upflagUpFrontier0 = true bool upflagUpFrontier1 = true bool upflagUpFrontier2 = true bool upflagUpFrontier3 = true bool upflagUpFrontier4 = true for i = 1 to n upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n]) upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n]) upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n]) upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n]) upflagUpFrontier3 := upflagUpFrontier3 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]) upflagUpFrontier4 := upflagUpFrontier4 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]) flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4 upFractal = (upflagDownFrontier and flagUpFrontier) // downFractal bool downflagDownFrontier = true bool downflagUpFrontier0 = true bool downflagUpFrontier1 = true bool downflagUpFrontier2 = true bool downflagUpFrontier3 = true bool downflagUpFrontier4 = true for i = 1 to n downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n]) downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n]) downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n]) downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n]) downflagUpFrontier3 := downflagUpFrontier3 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]) downflagUpFrontier4 := downflagUpFrontier4 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]) flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4 downFractal = (downflagDownFrontier and flagDownFrontier) plotshape(downFractal, style=shape.triangledown, location=location.belowbar, offset=-n, color=#F44336, size = size.small) plotshape(upFractal, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size = size.small) len = input.int(7, minval=1, title="Length") src = input(close, title="Source") smma = 0.0 smma := na(smma[1]) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len plot(smma, color=#673AB7)
Williams Fractals + SMMA
https://www.tradingview.com/script/xeNH5BUA-Williams-Fractals-SMMA/
rangu9101994
https://www.tradingview.com/u/rangu9101994/
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/ // © rangu9101994 //@version=5 indicator("Williams Fractals", shorttitle="Williams fractail + SMMA", format=format.price, precision=0, overlay=true) // Define "n" as the number of periods and keep a minimum value of 2 for error handling. n = input.int(title="Periods", defval=2, minval=2) // UpFractal bool upflagDownFrontier = true bool upflagUpFrontier0 = true bool upflagUpFrontier1 = true bool upflagUpFrontier2 = true bool upflagUpFrontier3 = true bool upflagUpFrontier4 = true for i = 1 to n upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n]) upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n]) upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n]) upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n]) upflagUpFrontier3 := upflagUpFrontier3 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]) upflagUpFrontier4 := upflagUpFrontier4 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]) flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4 upFractal = (upflagDownFrontier and flagUpFrontier) // downFractal bool downflagDownFrontier = true bool downflagUpFrontier0 = true bool downflagUpFrontier1 = true bool downflagUpFrontier2 = true bool downflagUpFrontier3 = true bool downflagUpFrontier4 = true for i = 1 to n downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n]) downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n]) downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n]) downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n]) downflagUpFrontier3 := downflagUpFrontier3 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]) downflagUpFrontier4 := downflagUpFrontier4 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]) flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4 downFractal = (downflagDownFrontier and flagDownFrontier) plotshape(downFractal, style=shape.triangledown, location=location.belowbar, offset=-n, color=#F44336, size = size.small) plotshape(upFractal, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size = size.small) len = input.int(7, minval=1, title="Length") src = input(close, title="Source") smma = 0.0 smma := na(smma[1]) ? ta.sma(src, len) : (smma[1] * (len - 1) + src) / len plot(smma, color=#673AB7)
RSI Phi Phi
https://www.tradingview.com/script/5gZ58KRU/
galaxys10mmo
https://www.tradingview.com/u/galaxys10mmo/
45
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/ // © galaxys10mmo //@version=5 indicator(title="RSI Su Phu PhiPhi") // Get user input rsiLength = input(title="Độ dài RSI", defval=7) rsiOB = input.float(title="Điểm quán mua", defval=70) rsiOS = input.float(title="Điểm quá bán", defval=30) timeframe1 = input.timeframe(title="Khung thời gian #1", defval="1") timeframe2 = input.timeframe(title="Khung thời gian #2", defval="5") timeframe3 = input.timeframe(title="Khung thời gian #3", defval="15") // Declare custom security function f_sec(_market, _res, _exp) => request.security(_market, _res, _exp[barstate.isrealtime ? 1 : 0]) // Get RSI on all timeframes rsi_timeframe1 = f_sec(syminfo.tickerid, timeframe1, ta.rsi(close, rsiLength)) rsi_timeframe2 = f_sec(syminfo.tickerid, timeframe2, ta.rsi(close, rsiLength)) rsi_timeframe3 = f_sec(syminfo.tickerid, timeframe3, ta.rsi(close, rsiLength)) // Check OB levels rsi_ob1 = rsi_timeframe1 >= rsiOB rsi_ob2 = rsi_timeframe2 >= rsiOB rsi_ob3 = rsi_timeframe3 >= rsiOB // Check OS levels rsi_os1 = rsi_timeframe1 <= rsiOS rsi_os2 = rsi_timeframe2 <= rsiOS rsi_os3 = rsi_timeframe3 <= rsiOS // Plot RSIs plot(rsi_timeframe1, color=rsi_ob1 or rsi_os1 ? color.purple : color.green, title="RSI Timeframe #1") plot(rsi_timeframe2, color=rsi_ob2 or rsi_os2 ? color.purple : color.red, title="RSI Timeframe #2") plot(rsi_timeframe3, color=rsi_ob3 or rsi_os3 ? color.purple : color.orange, title="RSI Timeframe #3") hline(rsiOB, color=color.gray, title="RSI quán mua") hline(rsiOS, color=color.gray, title="RSI quá bán") hline(50, color=color.new(color.gray,50), title="Thanh giữa") // Change color based on superstack condition obTrigger = rsi_ob1 and rsi_ob2 and rsi_ob3 osTrigger = rsi_os1 and rsi_os2 and rsi_os3 bgcolor(obTrigger ? color.red : osTrigger ? color.green : na, title="Màu thông báo tín hiệu") // Trigger alert alertcondition(obTrigger or osTrigger, title="RSI Superstack Alert", message="{{ticker}} has 3 RSI values at extreme levels!")
SUPER Alligator[Gabbo]
https://www.tradingview.com/script/S0Ttroab-SUPER-Alligator-Gabbo/
Gabbo1064
https://www.tradingview.com/u/Gabbo1064/
93
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © Gabbo1064 //@version=5 indicator("SUPER Alligator[Gabbo]", "Alligator", true, precision=2) // ══════════════════════════ Input { jawLength = input.int( 13, "Jaw Length", 1, 100, 1, inline="1", group="Alligator") jawOffset = input.int( 8, "Jaw Offset", 1, 100, 1, inline="1", group="Alligator") teethLength = input.int( 8, "Teeth Length", 1, 100, 1, inline="2", group="Alligator") teethOffset = input.int( 5, "Teeth Offset", 1, 100, 1, inline="2", group="Alligator") lipsLength = input.int( 5, "Lips Length", 1, 100, 1, inline="3", group="Alligator") lipsOffset = input.int( 3, "Lips Offset", 1, 100, 1, inline="3", group="Alligator") sourceAllig = input.source( hl2, "Source", inline="4", group="Alligator") maSlowType = input.string( "EMA", "Type Line", ["SMA", "EMA", "WMA", "RMA", "HMA", "JMA", "DEMA", "TEMA", "LSMA", "VWMA", "SMMA", "KAMA", "ALMA", "FRAMA", "VIDYA"], inline="4", group="Alligator") phaseSlow = input.int( 50, "Phase", 1, 1000, 1, inline="5", group="Alligator", tooltip="FOR JMA") powerSlow = input.int( 2, "Power", 1, 1000, 1, inline="5", group="Alligator", tooltip="FOR JMA") offsetSlow = input.float( 0.85, "Offset", 0, 1000, 1, inline="6", group="Alligator", tooltip="FOR ALMA") sigmaSlow = input.float( 6, "Sigma", 0, 1000, 1, inline="6", group="Alligator", tooltip="FOR ALMA") FCSlow = input.int( 1, "Lower shift (FC)", 1, 1000, 1, inline="7", group="Alligator", tooltip="FOR FRAMA") SCSlow = input.int( 198, "Upper shift (SC)", 1, 1000, 1, inline="7", group="Alligator", tooltip="FOR FRAMA") fixCMOSlow = input.bool( true, "Fixed CMO Length (9)?", inline="8", group="Alligator", tooltip="FOR VIDYA") selectSlow = input.bool( true, "Calculation Method: CMO/StDev?", inline="8", group="Alligator", tooltip="FOR VIDYA") timeCandles = input( "", "Timeframe", inline="9", group="Alligator") alligStrong = input.bool( false, "Use Different Source???", inline="9", group="Alligator") Alligsource1 = input.bool( true, "Source 1", inline="10", group="Alligator") alligsource1 = input.source( close, "", inline="10", group="Alligator") Alligsource2 = input.bool( true, "Source 2", inline="10", group="Alligator") alligsource2 = input.source( open, "", inline="10", group="Alligator") Alligsource3 = input.bool( true, "Source 3", inline="11", group="Alligator") alligsource3 = input.source( hl2, "", inline="11", group="Alligator") Alligsource4 = input.bool( true, "Source 4", inline="11", group="Alligator") alligsource4 = input.source( ohlc4, "", inline="11", group="Alligator") Alligsource5 = input.bool( false, "Source 5", inline="12", group="Alligator") alligsource5 = input.source( hlcc4, "", inline="12", group="Alligator") plotLine = input.bool( true, "Jaw/ Teeth/ Lips ???", inline="1", group="Plot") fillLine = input.bool( true, "Fill Line???", inline="1", group="Plot") fillBack = input.bool( false, "Fill Background???", inline="1", group="Plot") fillLineLong = input.color( color.new(#58E600, 90), "Fill Line Long", inline="2", group="Plot") fillLineShort = input.color( color.new(#FA2878, 90), "Fill Line Short", inline="2", group="Plot") fillLineNeut = input.color( color.new(color.yellow, 90), "Fill Line Neutral", inline="2", group="Plot") fillBackLong = input.color( color.new(#58E600, 96), "BG Long", inline="3", group="Plot") fillBackShort = input.color( color.new(#FA2878, 96), "BG Short", inline="3", group="Plot") fillBackNeut = input.color( color.new(color.yellow, 96), "BG Neutral", inline="3", group="Plot") // } // ══════════════════════════ Calculations { sourceNum1 = Alligsource1? 1: 0 sourceNum2 = Alligsource2? 1: 0 sourceNum3 = Alligsource3? 1: 0 sourceNum4 = Alligsource4? 1: 0 sourceNum5 = Alligsource5? 1: 0 sourceNum = sourceNum1 + sourceNum2 + sourceNum3 + sourceNum4 + sourceNum5 sourceSomm = (Alligsource1? alligsource1: 0) + (Alligsource2? alligsource2: 0) + (Alligsource3? alligsource3: 0) + (Alligsource4? alligsource4: 0) + (Alligsource5? alligsource5: 0) source = alligStrong? sourceSomm / sourceNum: sourceAllig hma(source, lenght) => ta.wma(2 * ta.wma(source, lenght / 2) -ta.wma(source, lenght), math.round(math.sqrt(lenght))) jma(phase, lenght, power, source) => phaseRatio = phase < -100 ? 0.5 : phase > 100 ? 2.5 : phase / 100 + 1.5 beta = 0.45 * (lenght - 1) / (0.45 * (lenght - 1) + 2) alpha = math.pow(beta, power) jma = 0.0 e0 = 0.0 e0 := (1 - alpha) * source + alpha * nz(e0[1]) e1 = 0.0 e1 := (source - e0) * (1 - beta) + beta * nz(e1[1]) e2 = 0.0 e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1]) jma := e2 + nz(jma[1]) dema(source, lenght) => 2 * (ta.ema(source, lenght)) - (ta.ema(ta.ema(source, lenght), lenght)) tema(source, lenght) => 3 * ((ta.ema(source, lenght)) - (ta.ema(ta.ema(source, lenght), lenght))) + (ta.ema(ta.ema(ta.ema(source, lenght), lenght), lenght)) smma(source, lenght) => smma1 = 0.0000 smma11 = ta.sma(source, lenght) smma1 := na(smma1[1]) ? smma11 : ((smma1[1] * (lenght - 1) + source) / lenght) kama(source, lenght) => xvnoise = math.abs(source - source[1]) nAMA = 0.0 nfastend = 0.666 nslowend = 0.0645 nsignal = math.abs(source - source[lenght]) nnoise = math.sum(xvnoise, lenght) nefratio = nnoise != 0? nsignal / nnoise: 0 nsmooth = math.pow(nefratio * (nfastend - nslowend) + nslowend, 2) nAMA := nz(nAMA[1]) + nsmooth * (source - nz(nAMA[1])) frama(source, length, FC, SC) => HL = (ta.highest(high, length) - ta.lowest(low, length)) / length HL1 = (ta.highest(high, length/2) - ta.lowest(low, length/2)) / (length/2) HL2 = (ta.highest(high, length/2)[length/2] - ta.lowest(low, length/2)[length/2]) / (length/2) D = (math.log(HL1+HL2) - math.log(HL)) / math.log(2) dim = HL1>0 and HL2>0 and HL>0? D: nz(D[1]) w = math.log(2/(SC+1)) alpha = math.exp(w*(dim-1)) alpha1 = alpha>1 ? 1 : (alpha<0.01 ? 0.01 : alpha) oldN = (2-alpha1) / alpha1 newN = (((SC-FC) * (oldN-1)) / (SC-1)) + FC newalpha = 2/(newN+1) newalpha1 = newalpha<2/(SC+1) ? 2/(SC+1) : (newalpha>1 ? 1 : newalpha) frama = 0.0 frama := (1-newalpha1) * nz(frama[1]) + newalpha1*source vidya(source, lenght, bool1, bool2) => alpha = 2/(lenght+1) momm = ta.change(source) m1 = momm >= 0.0 ? momm : 0.0 m2 = momm >= 0.0 ? 0.0 : -momm sm1 = bool1 ? math.sum(m1, 9) : math.sum(m1, lenght) sm2 = bool1 ? math.sum(m2, 9) : math.sum(m2, lenght) chandeMO = nz(100 * (sm1 - sm2) / (sm1 + sm2)) k = bool2 ? math.abs(chandeMO)/100 : ta.stdev(source,lenght) VIDYA = 0.0 VIDYA := nz(alpha*k*source)+(1-alpha*k)*nz(VIDYA[1]) jawInput = maSlowType == "SMA"? ta.sma(source, jawLength): maSlowType == "EMA"? ta.ema(source, jawLength): maSlowType == "WMA"? ta.wma(source, jawLength): maSlowType == "DEMA"? dema(source, jawLength): maSlowType == "TEMA"? tema(source, jawLength): maSlowType == "VWMA"? ta.vwma(source, jawLength): maSlowType == "RMA"? ta.rma(source, jawLength): maSlowType == "LSMA"? ta.linreg(source, jawLength, 0): maSlowType == "SMMA"? smma(source, jawLength): maSlowType == "HMA"? hma(source, jawLength): maSlowType == "ALMA"? ta.alma(source, jawLength, offsetSlow, sigmaSlow): maSlowType == "JMA"? jma(phaseSlow, jawLength, powerSlow, source): maSlowType == "KAMA"? kama(source, jawLength): maSlowType == "VIDYA"? vidya(source, jawLength, fixCMOSlow, selectSlow): frama(source, jawLength, FCSlow, SCSlow) jaw = request.security(syminfo.tickerid, timeCandles, jawInput) teethInput = maSlowType == "SMA"? ta.sma(source, teethLength): maSlowType == "EMA"? ta.ema(source, teethLength): maSlowType == "WMA"? ta.wma(source, teethLength): maSlowType == "DEMA"? dema(source, teethLength): maSlowType == "TEMA"? tema(source, teethLength): maSlowType == "VWMA"? ta.vwma(source, teethLength): maSlowType == "RMA"? ta.rma(source, teethLength): maSlowType == "LSMA"? ta.linreg(source, teethLength, 0): maSlowType == "SMMA"? smma(source, teethLength): maSlowType == "HMA"? hma(source, teethLength): maSlowType == "ALMA"? ta.alma(source, teethLength, offsetSlow, sigmaSlow): maSlowType == "JMA"? jma(phaseSlow, teethLength, powerSlow, source): maSlowType == "KAMA"? kama(source, teethLength): maSlowType == "VIDYA"? vidya(source, teethLength, fixCMOSlow, selectSlow): frama(source, teethLength, FCSlow, SCSlow) teeth = request.security(syminfo.tickerid, timeCandles, teethInput) lipsInput = maSlowType == "SMA"? ta.sma(source, lipsLength): maSlowType == "EMA"? ta.ema(source, lipsLength): maSlowType == "WMA"? ta.wma(source, lipsLength): maSlowType == "DEMA"? dema(source, lipsLength): maSlowType == "TEMA"? tema(source, lipsLength): maSlowType == "VWMA"? ta.vwma(source, lipsLength): maSlowType == "RMA"? ta.rma(source, lipsLength): maSlowType == "LSMA"? ta.linreg(source, lipsLength, 0): maSlowType == "SMMA"? smma(source, lipsLength): maSlowType == "HMA"? hma(source, lipsLength): maSlowType == "ALMA"? ta.alma(source, lipsLength, offsetSlow, sigmaSlow): maSlowType == "JMA"? jma(phaseSlow, lipsLength, powerSlow, source): maSlowType == "KAMA"? kama(source, lipsLength): maSlowType == "VIDYA"? vidya(source, lipsLength, fixCMOSlow, selectSlow): frama(source, lipsLength, FCSlow, SCSlow) lips = request.security(syminfo.tickerid, timeCandles, lipsInput) // } // ══════════════════════════ Plot { alligatorLong = jaw[jawOffset] <= teeth[teethOffset] and jaw[jawOffset] <= lips[lipsOffset] and teeth[teethOffset] <= lips[lipsOffset] alligatorShort = jaw[jawOffset] > teeth[teethOffset] and jaw[jawOffset] > lips[lipsOffset] and teeth[teethOffset] > lips[lipsOffset] jawPlot = plot(jaw[jawOffset], "Jaw", #2962FF, display=plotLine? display.all: display.none) teethPlot = plot(teeth[teethOffset], "Teeth", #E91E63, display=plotLine? display.all: display.none) lipsPlot = plot(lips[lipsOffset], "Lips", #66BB6A, display=plotLine? display.all: display.none) fill(jawPlot, lipsPlot, alligatorLong? fillLineLong: alligatorShort? fillLineShort: fillLineNeut, title="Fill Line", display=fillLine? display.all: display.none) bgcolor(alligatorLong? fillBackLong: alligatorShort? fillBackShort: fillBackNeut, display=fillBack? display.all: display.none) // }
Ichimoku MA Up & Down
https://www.tradingview.com/script/mAvrK6du/
Feel_Long_KIM
https://www.tradingview.com/u/Feel_Long_KIM/
36
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/ // © Feel_Long_KIM // // Ichimoku and MA use the default. // // It is repainted because it uses a moving average line. // A marker is only true if it was created after the candle closed. // The principle is too simple. // Please enjoy using it. // // [Trend] // - Up : Conversion Line > MA #1 and Base Line > MA #2 // It is an uptrend. The short-term moving average should be above the conversion line. And the long-term should be above the Base Line. // - Down : Conversion Line < MA #1 and Base Line < MA #2 // It's a downtrend. The short-term moving average should be below the conversion line. And the long-term should be below the Base Line. // // You can get better results if you use a momentum indicator like RSI. // Thank you. //@version=5 indicator("Ichimoku MA Up & Down", shorttitle="Ichimoku MA Up & Down", overlay=true, timeframe="", timeframe_gaps=true) // Ichimoku conversionPeriods = input.int(9, minval=1, title="Conversion Line Length", group="Ichimoku Cloud") basePeriods = input.int(26, minval=1, title="Base Line Length", group="Ichimoku Cloud") laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length", group="Ichimoku Cloud") displacement = input.int(26, minval=1, title="Lagging Span", group="Ichimoku Cloud") donchian(len) => math.avg(ta.lowest(len), ta.highest(len)) conversionLine = donchian(conversionPeriods) baseLine = donchian(basePeriods) leadLine1 = math.avg(conversionLine, baseLine) leadLine2 = donchian(laggingSpan2Periods) plot(conversionLine, color=#2962FF, title="Conversion Line") plot(baseLine, color=#B71C1C, title="Base Line") plot(close, offset = -displacement + 1, color=#43A047, title="Lagging Span") p1 = plot(leadLine1, offset = displacement - 1, color=#A5D6A7, title="Leading Span A") p2 = plot(leadLine2, offset = displacement - 1, color=#EF9A9A, title="Leading Span B") fill(p1, p2, color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 90) : color.rgb(244, 67, 54, 90)) // MA 1 len = input.int(10, minval=1, title="Length", group="MA #1") src = input(close, title="Source", group="MA #1") out = ta.sma(src, len) plot(out, color=color.red, title="MA #1") // MA 2 len2 = input.int(20, minval=1, title="Length", group="MA #2") src2 = input(close, title="Source", group="MA #2") out2 = ta.sma(src2, len2) plot(out2, color=color.blue, title="MA #2") // Function conversionUpMa1(period) => conversionLine[period] > out[period] conversionUpMa2(period) => baseLine[period] > out2[period] conversionDownMa1(period) => conversionLine[period] < out[period] conversionDownMa2(period) => baseLine[period] < out2[period] conversionUpMk(period) => conversionLine[period] > out[0] and baseLine[period] > out2[0] conversionDownMk(period) => conversionLine[period] < out[0] and baseLine[period] < out2[0] // Background conversionBgUp = false conversionBgDn = false if conversionUpMa1(0) and conversionUpMa2(0) conversionBgUp := true if conversionDownMa1(0) and conversionDownMa2(0) conversionBgDn := true bgcolor(conversionBgUp ? color.new(#33CCFF, 95) : color.new(#33CCFF, 100)) bgcolor(conversionBgDn ? color.new(#EE0D59, 95) : color.new(#EE0D59, 100)) // Marker upMk = false dnMk = false if conversionDownMk(1) and conversionUpMk(0) upMk := true if conversionUpMk(1) and conversionDownMk(0) dnMk := true bgTrend = false if upMk == true bgTrend := true if dnMk == true bgTrend := false plotshape(upMk ? upMk : na, title='Up Marker', location=location.belowbar, style=shape.square, color=color.new(#2962FF, 0), size=size.auto, text='UP', textcolor=color.new(#2962FF, 0)) plotshape(dnMk ? dnMk : na, title='Down Marker', location=location.abovebar, style=shape.square, color=color.new(#B71C1C, 0), size=size.auto, text='DOWN', textcolor=color.new(#B71C1C, 0)) // Alert alertcondition(upMk, title="Up Alert",message="Up") alertcondition(dnMk, title="Down Alert",message="Down")
UFO + Realtime Divergences (UO x MFI)
https://www.tradingview.com/script/ahPVdZQY-UFO-Realtime-Divergences-UO-x-MFI/
tvenn
https://www.tradingview.com/u/tvenn/
164
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/ // © tvenn //@version=5 indicator("UFO + Realtime Divergences", shorttitle="UFO+", overlay=false, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400, precision=3) pulldatafromtimeframe = input.string("Chart", title="Select alternate timeframe in mins", options=["Chart", "1", "2", "3", "4", "5", "10", "15", "30", "45", "60", "120", "240"]) customOscColor = input.color(color.new(color.blue, 0), title="Oscillator color") green = color.new(#95BD5F, 30) red = color.new(#EA1889, 30) //UO grp_UOS = "UO Settings" length1 = input.int(7, minval=1, title = "Fast Length", group=grp_UOS) length2 = input.int(14, minval=1, title = "Middle Length", group=grp_UOS) length3 = input.int(28, minval=1, title = "Slow Length", group=grp_UOS) //MFI grp_MFIS = "MFI Settings" mfilength1 = input(10, title="MFI Length", group=grp_MFIS) mfisrc = input(hlc3, title="MFI Source", group=grp_MFIS) mfi = ta.mfi(mfisrc, mfilength1) //MFI end //Divergence Settings grp_DivS = "Divergence Settings" showlines = input(defval = true, title = "Show Divergence Lines", group=grp_DivS) showlast = input(defval = true, title = "Show Only Last Divergence", group=grp_DivS) dontconfirm = input(defval = true, title = "Don't Wait for Confirmation", group=grp_DivS) //Detail grp_Detail = "Details" centerline = input(true, title="Centerline", group=grp_Detail, inline="0") showBands = input(false, title="Range bands", group=grp_Detail, inline="1") obosHighlightEnabled= input(false, title="Highlight overbought & oversold", group=grp_Detail, inline="2") fadeOutOsc = input(false, title="Fade out oscillator", group=grp_Detail, tooltip="Face out the oscillator leaving only the most recent periods prominent for a clearer chart.") flipOsc = input(false, title="Flip Oscillator", group=grp_Detail, tooltip="This will flip the oscillator upside down. The purpose is for use with the flip chart feature of Tradingview (Alt+i), which does not also flip the oscillator. This may help those with a particular long/short bias to see the other side of things. Divergence lines will not be drawn.") showMTFRibbon = input(true, title="Enable MTF ribbon", group=grp_Detail) showLabel = input(true, title="Show MTF OB/OS label", group=grp_Detail, tooltip="This will show a text label in the bottom left of the panel to notify when the MTF CCI or MTF Stoch RSI is either overbought or oversold, for clarity, or colour blind users.") showMTFVals = input(false, title="Show MTF table for", group=grp_Detail, inline="table") MTFTableType = input.string("MTF Stoch RSI", options=["MTF Stoch RSI", "MTF CCI", "Both"], title="", group=grp_Detail, inline="table") MTFTableTheme = input.string("Dark", options=["Dark", "Light"], title="", group=grp_Detail, inline="table") // MTFOBOSDivSignal = input(true, title="Show MTF OB/OS + Div", group=grp_Detail, tooltip="Places label to indicate where MTF Stoch RSI / MTF CCI oversold AND recent bullish divergence, and where MTF Stoch RSI / MTF CCI overbought AND recent bearish divergence.\n\nYou can alert these using the alert called 'MTF OB/OS + Div on RF+'") grp_BG = "Background styles" backgroundColor = input(color.new(color.white, 97), title = "", group=grp_BG, inline='clc') showBackground = input(false, title="Background", group=grp_BG, inline='clc') centerlineXBgColor = input(color.new(red, 90), title='', group=grp_BG, inline='clc1') backgroundSignalOn = input(false, title="Centerline crossunder background color", group=grp_BG, tooltip="This will colour the background according to whether the RSI is above or below the 50 level.", inline='clc1') centerlineXOscColor = input(color.new(red, 10), title='', group=grp_BG, inline='clc2') oscSignalOn = input(false, title="Centerline crossunder oscillator color", group=grp_BG, tooltip="This will colour the oscillator according to whether the RSI is above or below the 50 level.", inline='clc2') //UO 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) uo_val = 100 * (4*avg7 + 2*avg14 + avg28)/7 //UO end ufo_val = (uo_val + mfi) / 2 osc = (flipOsc ? 100-ufo_val : ufo_val) ultimate_value = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, osc, barmerge.gaps_on) oscColor = ((obosHighlightEnabled and ultimate_value > 75) ? red : ((obosHighlightEnabled and ultimate_value < 25) ? red : (oscSignalOn and ultimate_value > 50 ? customOscColor : (oscSignalOn and ultimate_value < 50 ? centerlineXOscColor : customOscColor)))) distanceTransparency = (bar_index > (last_bar_index - 30) ? 10 : (bar_index > last_bar_index - 60 ? 20 : (bar_index > last_bar_index - 80 ? 30 : (bar_index > last_bar_index - 100 ? 40 : (bar_index > last_bar_index - 120 ? 50 : (bar_index > last_bar_index - 140 ? 60 : (bar_index > last_bar_index - 160 ? 70 : 80))))))) plot(ultimate_value, color=(fadeOutOsc ? color.new(oscColor, distanceTransparency) : oscColor), linewidth=2, title="Ultimate Oscillator") //MTF confluences //=============================================================================================================================== grp_SRSI = "MTF Stoch RSI for ribbon" srsiribbonPos= input.string(title="MTF Stoch RSI ribbon position", defval='Absolute', options=['Top', 'Bottom', 'Absolute'], group=grp_SRSI) smoothK = input.int(3, "K line", minval=1, group=grp_SRSI) smoothD = input.int(3, "D line", minval=1, group=grp_SRSI) lengthRSI = input.int(14, "RSI Length", minval=1, group=grp_SRSI) lengthStoch = input.int(14, "Stochastic Length", minval=1, group=grp_SRSI) src = input(close, title="RSI Source", group=grp_SRSI) rsi1 = ta.rsi(src, lengthRSI) k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = ta.sma(k, smoothD) k1 = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, k, barmerge.gaps_off) d1 = request.security(syminfo.tickerid, pulldatafromtimeframe == "Chart" ? "" : pulldatafromtimeframe, d, barmerge.gaps_off) //Bands bandColor = showBands ? color.new(#777777, 30) : color.new(#777777, 100) band1 = hline(75, color=bandColor, linestyle=hline.style_dotted, title="Band high", linewidth=1) band2 = hline(50, color=(centerline ? color.new(#777777, 0) : na), linestyle=hline.style_dotted, title="Centerline", linewidth=1) band0 = hline(25, color=bandColor, linestyle=hline.style_dotted, title="Band low", linewidth=1) //Primary timeframes confluences grp_MTFSRSI1 = "MTF Stoch RSI for ribbon" overboughtColor_1 = input.color(color.new(red, 0), title="MTF Stoch RSI OB color", group=grp_MTFSRSI1) oversoldColor_1 = input.color(color.new(green, 0), title="MTF Stoch RSI OS color", group=grp_MTFSRSI1) useBgColorMTFStochOBOS_1 = input(true, title="Color ribbon where MTF Stoch RSI OB/OS", group=grp_MTFSRSI1, tooltip="This will signal the overbought / oversold state of the Stochastic RSI on all 3x selected timeframes together at the same time.") useBarColorMTFStochOBOS_1 = input(false, title="Color candles where MTF Stoch RSI OB/OS", group=grp_MTFSRSI1, tooltip="This will signal the overbought / oversold state of the Stochastic RSI on all 3x selected timeframes together at the same time.") grp_CTFSRSI1 = "Show Current Timeframe OB/OS in Ribbon" includeCurrentTFOBOS = input(false, title="Show selected timeframe OB/OS in ribbon", group=grp_CTFSRSI1, tooltip="this will include in the ribbon indications where the Stoch RSI is overbought or oversold on the current timeframe") CTF_1 = input.string("Chart", title="CTF", options=["Chart"], group=grp_CTFSRSI1, inline="tf1") CTF_OSTHRESH_1 = input(20, title="", group=grp_CTFSRSI1, inline="tf1") CTF_OBTHRESH_1 = input(80, title="", group=grp_CTFSRSI1, inline="tf1") grp_MTFSRSI1Conf = "MTF Stoch RSI confluences [Timeframe] [OS level] [OB level]" TF_1_1 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1Conf, inline="mtf1") TF_2_1 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1Conf, inline="mtf2") TF_3_1 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1Conf, inline="mtf3") MTF_OSTHRESH_1_1 = input(20, title="", group=grp_MTFSRSI1Conf, inline="mtf1") MTF_OSTHRESH_2_1 = input(20, title="", group=grp_MTFSRSI1Conf, inline="mtf2") MTF_OSTHRESH_3_1 = input(20, title="", group=grp_MTFSRSI1Conf, inline="mtf3") MTF_OBTHRESH_1_1 = input(80, title="", group=grp_MTFSRSI1Conf, inline="mtf1") MTF_OBTHRESH_2_1 = input(80, title="", group=grp_MTFSRSI1Conf, inline="mtf2") MTF_OBTHRESH_3_1 = input(80, title="", group=grp_MTFSRSI1Conf, inline="mtf3") MTF1_1 = request.security(syminfo.tickerid, TF_1_1 == "Chart" ? "" : TF_1_1, k, barmerge.gaps_off) MTF2_1 = request.security(syminfo.tickerid, TF_2_1 == "Chart" ? "" : TF_2_1, k, barmerge.gaps_off) MTF3_1 = request.security(syminfo.tickerid, TF_3_1 == "Chart" ? "" : TF_3_1, k, barmerge.gaps_off) allMTFStochOB_1 = (MTF1_1 > MTF_OBTHRESH_1_1 and MTF2_1 > MTF_OBTHRESH_2_1 and MTF3_1 > MTF_OBTHRESH_3_1) allMTFStochOS_1 = (MTF1_1 < MTF_OSTHRESH_1_1 and MTF2_1 < MTF_OSTHRESH_2_1 and MTF3_1 < MTF_OSTHRESH_3_1) allOBColor_1 = (allMTFStochOB_1 ? overboughtColor_1 : na) allOSColor_1 = (allMTFStochOS_1 ? oversoldColor_1 : na) isCTFOB_1 = (k > CTF_OBTHRESH_1 ? true : false) isCTFOS_1 = (k < CTF_OSTHRESH_1 ? true : false) ctfOBColor_1 = (k > CTF_OBTHRESH_1+10 ? color.new(overboughtColor_1, 60) : k > CTF_OBTHRESH_1+10 ? color.new(overboughtColor_1, 80) : na) ctfOSColor_1 = (k < CTF_OSTHRESH_1-10 ? color.new(oversoldColor_1, 60) : k < CTF_OSTHRESH_1 ? color.new(oversoldColor_1, 80) : na) //Secondary timeframes confluences grp_CCI = "MTF CCI settings for ribbon" cciribbonPos= input.string(title="MTF CCI ribbon position", defval='Top', options=['Top', 'Bottom', 'Absolute'], group=grp_CCI) ccilength = input.int(20, minval=1, title="CCI source", group=grp_CCI) ccisrc = input(hlc3, title="CCI source", group=grp_CCI) ma = ta.sma(src, ccilength) cci_value = (src - ma) / (0.015 * ta.dev(src, ccilength)) grp_MTFCCI2 = "MTF CCI for ribbon" overboughtColor_2 = input.color(color.new(color.red, 50), title="MTF CCI OB color", group=grp_MTFCCI2) oversoldColor_2 = input.color(color.new(color.green, 50), title="MTF CCI OS color", group=grp_MTFCCI2) useBgColorMTFCCIOBOS_2 = input(true, title="Color ribbon where MTF CCI OB/OS", group=grp_MTFCCI2, tooltip="This will signal the overbought / oversold state of the CCI on all 3x selected timeframes together at the same time.") useBarColorMTFCCIOBOS_2 = input(false, title="Color candles where MTF CCI OB/OS", group=grp_MTFCCI2, tooltip="This will signal the overbought / oversold state of the CCI on all 3x selected timeframes together at the same time.") grp_MTFCCI2Conf = "MTF CCI confluences 2 [Timeframe] [OS level] [OB level]" TF_1_2 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFCCI2Conf, inline="mtf1") TF_2_2 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFCCI2Conf, inline="mtf2") TF_3_2 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFCCI2Conf, inline="mtf3") MTF_OSTHRESH_1_2 = input(-150, title="", group=grp_MTFCCI2Conf, inline="mtf1") MTF_OSTHRESH_2_2 = input(-150, title="", group=grp_MTFCCI2Conf, inline="mtf2") MTF_OSTHRESH_3_2 = input(-150, title="", group=grp_MTFCCI2Conf, inline="mtf3") MTF_OBTHRESH_1_2 = input(150, title="", group=grp_MTFCCI2Conf, inline="mtf1") MTF_OBTHRESH_2_2 = input(150, title="", group=grp_MTFCCI2Conf, inline="mtf2") MTF_OBTHRESH_3_2 = input(150, title="", group=grp_MTFCCI2Conf, inline="mtf3") MTF1_2 = request.security(syminfo.tickerid, TF_1_2 == "Chart" ? "" : TF_1_2, cci_value, barmerge.gaps_off) MTF2_2 = request.security(syminfo.tickerid, TF_2_2 == "Chart" ? "" : TF_2_2, cci_value, barmerge.gaps_off) MTF3_2 = request.security(syminfo.tickerid, TF_3_2 == "Chart" ? "" : TF_3_2, cci_value, barmerge.gaps_off) allMTFCCIOB_2 = (MTF1_2 > MTF_OBTHRESH_1_2 and MTF2_2 > MTF_OBTHRESH_2_2 and MTF3_2 > MTF_OBTHRESH_3_2) allMTFCCIOS_2 = (MTF1_2 < MTF_OSTHRESH_1_2 and MTF2_2 < MTF_OSTHRESH_2_2 and MTF3_2 < MTF_OSTHRESH_3_2) allOBColor_2 = (allMTFCCIOB_2 ? overboughtColor_2 : na) allOSColor_2 = (allMTFCCIOS_2 ? oversoldColor_2 : na) _srsiribbonLocation = switch srsiribbonPos "Absolute" => location.absolute "Top" => location.top "Bottom" => location.bottom _cciribbonLocation = switch cciribbonPos "Absolute" => location.absolute "Top" => location.top "Bottom" => location.bottom plotshape(showMTFRibbon and useBgColorMTFStochOBOS_1 and allMTFStochOB_1, title="OB/OS", location=_srsiribbonLocation, color=allOBColor_1, style=shape.circle, size=size.auto) plotshape(showMTFRibbon and useBgColorMTFStochOBOS_1 and allMTFStochOS_1, title="OB/OS", location=_srsiribbonLocation, color=allOSColor_1, style=shape.circle, size=size.auto) plotshape(showMTFRibbon and useBgColorMTFCCIOBOS_2 and allMTFCCIOB_2, title="OB/OS", location=_cciribbonLocation, color=allOBColor_2, style=shape.circle, size=size.auto) plotshape(showMTFRibbon and useBgColorMTFCCIOBOS_2 and allMTFCCIOS_2, title="OB/OS", location=_cciribbonLocation, color=allOSColor_2, style=shape.circle, size=size.auto) barcolor(useBarColorMTFStochOBOS_1 and allMTFStochOB_1 ? allOBColor_1 : (useBarColorMTFStochOBOS_1 and allMTFStochOS_1 ? allOSColor_1 : na)) barcolor(useBarColorMTFCCIOBOS_2 and allMTFCCIOB_2 ? allOBColor_2 : (useBarColorMTFCCIOBOS_2 and allMTFCCIOS_2 ? allOSColor_2 : na)) plotshape(showMTFRibbon and includeCurrentTFOBOS and isCTFOB_1, title="Current TF SRSI overbought", color=(showMTFRibbon and includeCurrentTFOBOS ? ctfOBColor_1 : na), location=_srsiribbonLocation, style=shape.circle, size=size.auto) plotshape(showMTFRibbon and includeCurrentTFOBOS and isCTFOS_1, title="Current TF SRSI oversold", color=(showMTFRibbon and includeCurrentTFOBOS ? ctfOSColor_1 : na), location=_srsiribbonLocation, style=shape.circle, size=size.auto) //Pivot settings grp_PPS = "Pivot Point Settings" pp = input.int(defval = 12, title = "Pivot period", minval = 1, maxval = 50, group=grp_PPS) maxpp = input.int(defval = 5, title = "Maximum Pivot periods to check for divs", minval = 1, maxval = 100, group=grp_PPS) maxbars = input.int(defval = 100, title = "Maximum Bars to Check", minval = 1, maxval = 300, group=grp_PPS) source = "Close" searchdiv = input.string(defval = "Regular/Hidden", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group=grp_DivS) prd = pp //Styles grp_STY = "Styles" MTFTableColor = input.color(color.new(color.black, 100), title="Table Color", group=grp_STY) pos_reg_div_col = input(defval = green, title = "Positive Regular Divergence", group=grp_STY) neg_reg_div_col = input(defval = red, title = "Negative Regular Divergence", group=grp_STY) pos_hid_div_col = input(defval = green, title = "Positive Hidden Divergence", group=grp_STY) neg_hid_div_col = input(defval = red, title = "Negative Hidden Divergence", group=grp_STY) reg_div_l_style_= input.string(defval = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STY) hid_div_l_style_= input.string(defval = "Dotted", title = "Hdden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group=grp_STY) reg_div_l_width = input.int(defval = 2, title = "Regular Divergence Line Width", minval = 1, maxval = 2, group=grp_STY) hid_div_l_width = input.int(defval = 2, title = "Hidden Divergence Line Width", minval = 1, maxval = 2, group=grp_STY) //background fill options fill(band0, band1, backgroundSignalOn and ultimate_value > 50 ? na : backgroundSignalOn and ultimate_value < 50 ? centerlineXBgColor : na, title="Centerline crossover background color", editable=1) fill(band0, band1, showBackground ? backgroundColor : na, title="Centerline crossover background color", editable=1) // set line styles var reg_div_l_style = reg_div_l_style_ == "Solid" ? line.style_solid : reg_div_l_style_ == "Dashed" ? line.style_dashed : line.style_dotted var hid_div_l_style = hid_div_l_style_ == "Solid" ? line.style_solid : hid_div_l_style_ == "Dashed" ? line.style_dashed : line.style_dotted // get indicators uo = ultimate_value // keep indicator colors in arrays var indicators_name = array.new_string(11) var div_colors = array.new_color(4) if barstate.isfirst //colors array.set(div_colors, 0, pos_reg_div_col) array.set(div_colors, 1, neg_reg_div_col) array.set(div_colors, 2, pos_hid_div_col) array.set(div_colors, 3, neg_hid_div_col) // Check if we get new Pivot High Or Pivot Low float ph = ta.pivothigh(close, prd, prd) float pl = ta.pivotlow(close, prd, prd) // keep values and positions of Pivot Highs/Lows in the arrays var int maxarraysize = 20 var ph_positions = array.new_int(maxarraysize, 0) var pl_positions = array.new_int(maxarraysize, 0) var ph_vals = array.new_float(maxarraysize, 0.) var pl_vals = array.new_float(maxarraysize, 0.) // add PHs to the array if ph array.unshift(ph_positions, bar_index) array.unshift(ph_vals, ph) if array.size(ph_positions) > maxarraysize array.pop(ph_positions) array.pop(ph_vals) // add PLs to the array if pl array.unshift(pl_positions, bar_index) array.unshift(pl_vals, pl) if array.size(pl_positions) > maxarraysize array.pop(pl_positions) array.pop(pl_vals) // functions to check Regular Divergences and Hidden Divergences // function to check positive regular or negative hidden divergence // cond == 1 => positive_regular, cond == 2=> negative_hidden positive_regular_positive_hidden_divergence(src, cond)=> divlen = 0 prsc = close // if indicators higher than last value and close price is higher than las close if dontconfirm or src > src[1] or close > close[1] startpoint = dontconfirm ? 0 : 1 // don't check last candle // we search last 15 PPs for x = 0 to maxpp - 1 len = bar_index - array.get(pl_positions, x) + prd // if we reach non valued array element or arrived 101. or previous bars then we don't search more if array.get(pl_positions, x) == 0 or len > maxbars break if len > 5 and ((cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x))) or (cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))) slope1 = (src[startpoint] - src[len]) / (len - startpoint) virtual_line1 = src[startpoint] - slope1 slope2 = (close[startpoint] - close[len]) / (len - startpoint) virtual_line2 = close[startpoint] - slope2 arrived = true for y = 1 + startpoint to len - 1 if src[y] < virtual_line1 or nz(close[y]) < virtual_line2 arrived := false break virtual_line1 := virtual_line1 - slope1 virtual_line2 := virtual_line2 - slope2 if arrived divlen := len break divlen // function to check negative regular or positive hidden divergence // cond == 1 => negative_regular, cond == 2=> positive_hidden negative_regular_negative_hidden_divergence(src, cond)=> divlen = 0 prsc = close // if indicators higher than last value and close price is higher than las close if dontconfirm or src < src[1] or close < close[1] startpoint = dontconfirm ? 0 : 1 // don't check last candle // we search last 15 PPs for x = 0 to maxpp - 1 len = bar_index - array.get(ph_positions, x) + prd // if we reach non valued array element or arrived 101. or previous bars then we don't search more if array.get(ph_positions, x) == 0 or len > maxbars break if len > 5 and ((cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x))) or (cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))) slope1 = (src[startpoint] - src[len]) / (len - startpoint) virtual_line1 = src[startpoint] - slope1 slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint) virtual_line2 = close[startpoint] - slope2 arrived = true for y = 1 + startpoint to len - 1 if src[y] > virtual_line1 or nz(close[y]) > virtual_line2 arrived := false break virtual_line1 := virtual_line1 - slope1 virtual_line2 := virtual_line2 - slope2 if arrived divlen := len break divlen // calculate 4 types of divergence if enabled in the options and return divergences in an array calculate_divs(cond, indicator)=> divs = array.new_int(4, 0) array.set(divs, 0, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 1) : 0) array.set(divs, 1, cond and (searchdiv == "Regular" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 1) : 0) array.set(divs, 2, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? positive_regular_positive_hidden_divergence(indicator, 2) : 0) array.set(divs, 3, cond and (searchdiv == "Hidden" or searchdiv == "Regular/Hidden") ? negative_regular_negative_hidden_divergence(indicator, 2) : 0) divs // array to keep all divergences var all_divergences = array.new_int(4) // 1 indicator * 4 divergence = 4 elements // set related array elements array_set_divs(div_pointer, index)=> for x = 0 to 3 array.set(all_divergences, index * 4 + x, array.get(div_pointer, x)) // set divergences array array_set_divs(calculate_divs(true, uo), 0) // keep line in an array var pos_div_lines = array.new_line(0) var neg_div_lines = array.new_line(0) var pos_div_labels = array.new_label(0) var neg_div_labels = array.new_label(0) // remove old lines and labels if showlast option is enabled delete_old_pos_div_lines()=> if array.size(pos_div_lines) > 0 for j = 0 to array.size(pos_div_lines) - 1 line.delete(array.get(pos_div_lines, j)) array.clear(pos_div_lines) delete_old_neg_div_lines()=> if array.size(neg_div_lines) > 0 for j = 0 to array.size(neg_div_lines) - 1 line.delete(array.get(neg_div_lines, j)) array.clear(neg_div_lines) delete_old_pos_div_labels()=> if array.size(pos_div_labels) > 0 for j = 0 to array.size(pos_div_labels) - 1 label.delete(array.get(pos_div_labels, j)) array.clear(pos_div_labels) delete_old_neg_div_labels()=> if array.size(neg_div_labels) > 0 for j = 0 to array.size(neg_div_labels) - 1 label.delete(array.get(neg_div_labels, j)) array.clear(neg_div_labels) // delete last creted lines and labels until we met new PH/PV delete_last_pos_div_lines_label(n)=> if n > 0 and array.size(pos_div_lines) >= n asz = array.size(pos_div_lines) for j = 1 to n line.delete(array.get(pos_div_lines, asz - j)) array.pop(pos_div_lines) if array.size(pos_div_labels) > 0 label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1)) array.pop(pos_div_labels) delete_last_neg_div_lines_label(n)=> if n > 0 and array.size(neg_div_lines) >= n asz = array.size(neg_div_lines) for j = 1 to n line.delete(array.get(neg_div_lines, asz - j)) array.pop(neg_div_lines) if array.size(neg_div_labels) > 0 label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1)) array.pop(neg_div_labels) // variables for Alerts pos_reg_div_detected = false neg_reg_div_detected = false pos_hid_div_detected = false neg_hid_div_detected = false // to remove lines/labels until we met new // PH/PL var last_pos_div_lines = 0 var last_neg_div_lines = 0 var remove_last_pos_divs = false var remove_last_neg_divs = false if pl remove_last_pos_divs := false last_pos_div_lines := 0 if ph remove_last_neg_divs := false last_neg_div_lines := 0 // draw divergences lines and labels divergence_text_top = "" divergence_text_bottom = "" distances = array.new_int(0) dnumdiv_top = 0 dnumdiv_bottom = 0 top_label_col = color.white bottom_label_col = color.white old_pos_divs_can_be_removed = true old_neg_divs_can_be_removed = true startpoint = dontconfirm ? 0 : 1 // used for don't confirm option for x = 0 to 0 div_type = -1 for y = 0 to 3 if array.get(all_divergences, x * 4 + y) > 0 // any divergence? div_type := y if (y % 2) == 1 dnumdiv_top := dnumdiv_top + 1 top_label_col := array.get(div_colors, y) if (y % 2) == 0 dnumdiv_bottom := dnumdiv_bottom + 1 bottom_label_col := array.get(div_colors, y) if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ? array.push(distances, array.get(all_divergences, x * 4 + y)) new_line = (showlines and not flipOsc) ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y), y1 = (source == "Close" ? uo[array.get(all_divergences, x * 4 + y)] : (y % 2) == 0 ? low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4 + y)]), x2 = bar_index - startpoint, y2 = (source == "Close" ? uo[startpoint] : (y % 2) == 0 ? low[startpoint] : high[startpoint]), color = array.get(div_colors, y), style = y < 2 ? reg_div_l_style : hid_div_l_style, width = y < 2 ? reg_div_l_width : hid_div_l_width ) : na if (y % 2) == 0 if old_pos_divs_can_be_removed old_pos_divs_can_be_removed := false if not showlast and remove_last_pos_divs delete_last_pos_div_lines_label(last_pos_div_lines) last_pos_div_lines := 0 if showlast delete_old_pos_div_lines() array.push(pos_div_lines, new_line) last_pos_div_lines := last_pos_div_lines + 1 remove_last_pos_divs := true if (y % 2) == 1 if old_neg_divs_can_be_removed old_neg_divs_can_be_removed := false if not showlast and remove_last_neg_divs delete_last_neg_div_lines_label(last_neg_div_lines) last_neg_div_lines := 0 if showlast delete_old_neg_div_lines() array.push(neg_div_lines, new_line) last_neg_div_lines := last_neg_div_lines + 1 remove_last_neg_divs := true // set variables for alerts if y == 0 pos_reg_div_detected := true if y == 1 neg_reg_div_detected := true if y == 2 pos_hid_div_detected := true if y == 3 neg_hid_div_detected := true alertcondition(pos_reg_div_detected and not pos_reg_div_detected[1], title='Bullish Regular Divergence in UFO', message='Bullish Regular Divergence in UFO') alertcondition(pos_hid_div_detected and not pos_hid_div_detected[1], title='Bullish Hidden Divergence in UFO', message='Bullish Hidden Divergence in UFO') alertcondition(neg_reg_div_detected and not neg_reg_div_detected[1], title='Bearish Regular Divergence in UFO', message='Bearish Regular Divergence in UFO') alertcondition(neg_hid_div_detected and not neg_hid_div_detected[1], title='Bearish Hidden Divergence in UFO', message='Bearish Hidden Divergence in UFO') alertcondition((pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]), title='Bullish Divergence in UFO', message='Bullish Divergence in UFO') alertcondition((neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]), title='Bearish Divergence in UFO', message='Bearish Divergence in UFO') alertcondition((neg_reg_div_detected and not neg_reg_div_detected[1]) or (neg_hid_div_detected and not neg_hid_div_detected[1]) or (pos_reg_div_detected and not pos_reg_div_detected[1]) or (pos_hid_div_detected and not pos_hid_div_detected[1]), title='Divergence in UFO', message='Divergence in UFO') alertcondition((allMTFStochOB_1 and not allMTFStochOB_1[1]) or (allMTFCCIOB_2 and not allMTFCCIOB_2[1]), title='MTF Overbought on UFO', message='MTF Overbought on UFO') alertcondition((allMTFStochOS_1 and not allMTFStochOS_1[1]) or (allMTFCCIOS_2 and not allMTFCCIOS_2[1]), title='MTF Oversold on UFO', message='MTF Oversold on UFO') alertcondition((allMTFStochOS_1 and not allMTFStochOS_1[1]) or (allMTFStochOB_1 and not allMTFStochOB_1[1]) or (allMTFCCIOB_2 and not allMTFCCIOB_2[1]) or (allMTFCCIOS_2 and not allMTFCCIOS_2[1]), title='MTF OB/OS on UFO', message='MTF OB/OS on UFO') //Oscillator name label var table label = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.black, 100), frame_width = 0, frame_color = color.new(#000000, 100)) // var table flippedLabel = table.new(position.bottom_left, 1, 1, bgcolor = color.new(color.black, 100), frame_width = 0, frame_color = color.new(#000000, 100)) if barstate.islast and flipOsc // We only populate the table on the last bar. table.cell(label, 0, 0, text="Flipped", text_color=color.gray, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) if barstate.islast and (not flipOsc) and allMTFStochOB_1 and showLabel table.cell(label, 0, 0, text="MTF Stoch RSI Overbought", text_color=overboughtColor_1, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) if barstate.islast and (not flipOsc) and allMTFStochOS_1 and showLabel table.cell(label, 0, 0, text="MTF Stoch RSI Oversold", text_color=oversoldColor_1, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) if barstate.islast and (not flipOsc) and allMTFCCIOB_2 and showLabel table.cell(label, 0, 0, text="MTF CCI Overbought", text_color=overboughtColor_2, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) if barstate.islast and (not flipOsc) and allMTFCCIOS_2 and showLabel table.cell(label, 0, 0, text="MTF CCI Oversold", text_color=oversoldColor_2, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) if barstate.islast and (not flipOsc and not allMTFStochOB_1 and not allMTFStochOS_1 and not allMTFCCIOB_2 and not allMTFCCIOS_2) table.cell(label, 0, 0, text="", text_color=color.black, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) // We use `var` to only initialize the table on the first bar. var table dashboard = table.new(position.top_right, 4, 4, bgcolor = MTFTableColor, frame_width = 0, frame_color = na) LabelColor = MTFTableTheme=="Dark" ? color.new(color.white, 70) : color.new(color.black, 70) ValueColor = MTFTableTheme=="Dark" ? color.new(color.white, 20) : color.new(color.black, 20) _CCIlabelColor(val, ob, os) => val > ob ? overboughtColor_2 : (val < os ? oversoldColor_2 : ValueColor) _SRSIlabelColor(val, ob, os) => val > ob ? overboughtColor_1 : (val < os ? oversoldColor_1 : ValueColor) // We call functions like `ta.atr()` outside the `if` block so it executes on each bar. if barstate.islast and showMTFVals // We only populate the table on the last bar. if (MTFTableType=="MTF CCI") table.cell(dashboard, 0, 0, text="CCI", text_color=LabelColor, text_halign=text.align_left, text_size=size.small, width=2) table.cell(dashboard, 0, 1, text=TF_1_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 0, 2, text=TF_2_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 0, 3, text=TF_3_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 1, 0, text="", width=3, text_color=LabelColor, text_halign=text.align_left, text_size=size.small) table.cell(dashboard, 1, 1, text=str.tostring(math.round(MTF1_2, 0)) , text_color=_CCIlabelColor(MTF1_2, MTF_OBTHRESH_1_2, MTF_OSTHRESH_1_2), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 1, 2, text=str.tostring(math.round(MTF2_2, 0)) , text_color=_CCIlabelColor(MTF2_2, MTF_OBTHRESH_2_2, MTF_OSTHRESH_2_2), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 1, 3, text=str.tostring(math.round(MTF3_2, 0)), text_color=_CCIlabelColor(MTF3_2, MTF_OBTHRESH_3_2, MTF_OSTHRESH_3_2), text_halign=text.align_right, text_size=size.small) if (MTFTableType=="MTF Stoch RSI") table.cell(dashboard, 2, 0, text="SRSI", text_color=LabelColor, text_halign=text.align_left, text_size=size.small, width=2) table.cell(dashboard, 2, 1, text=TF_1_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 2, 2, text=TF_2_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 2, 3, text=TF_3_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 3, 0, text="", width=3, text_color=LabelColor, text_halign=text.align_left, text_size=size.small) table.cell(dashboard, 3, 1, text=str.tostring(math.round(MTF1_1, 0)) , text_color=_SRSIlabelColor(MTF1_1, MTF_OBTHRESH_1_1, MTF_OSTHRESH_1_1), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 3, 2, text=str.tostring(math.round(MTF2_1, 0)) , text_color=_SRSIlabelColor(MTF2_1, MTF_OBTHRESH_2_1, MTF_OSTHRESH_2_1), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 3, 3, text=str.tostring(math.round(MTF3_1, 0)) , text_color=_SRSIlabelColor(MTF3_1, MTF_OBTHRESH_3_1, MTF_OSTHRESH_3_1), text_halign=text.align_right, text_size=size.small) if (MTFTableType=="Both") table.cell(dashboard, 0, 0, text="CCI", text_color=LabelColor, text_halign=text.align_left, text_size=size.small, width=2) table.cell(dashboard, 0, 1, text=TF_1_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 0, 2, text=TF_2_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 0, 3, text=TF_3_2+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 1, 0, text="", width=3, text_color=LabelColor, text_halign=text.align_left, text_size=size.small) table.cell(dashboard, 1, 1, text=str.tostring(math.round(MTF1_2, 0)) , text_color=_CCIlabelColor(MTF1_2, MTF_OBTHRESH_1_2, MTF_OSTHRESH_1_2), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 1, 2, text=str.tostring(math.round(MTF2_2, 0)) , text_color=_CCIlabelColor(MTF2_2, MTF_OBTHRESH_2_2, MTF_OSTHRESH_2_2), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 1, 3, text=str.tostring(math.round(MTF3_2, 0)), text_color=_CCIlabelColor(MTF3_2, MTF_OBTHRESH_3_2, MTF_OSTHRESH_3_2), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 2, 0, text="SRSI", text_color=LabelColor, text_halign=text.align_left, text_size=size.small, width=2) table.cell(dashboard, 2, 1, text=TF_1_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 2, 2, text=TF_2_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 2, 3, text=TF_3_1+"m", text_color=LabelColor, text_halign=text.align_left, text_size=size.tiny) table.cell(dashboard, 3, 0, text="", width=3, text_color=LabelColor, text_halign=text.align_left, text_size=size.small) table.cell(dashboard, 3, 1, text=str.tostring(math.round(MTF1_1, 0)) , text_color=_SRSIlabelColor(MTF1_1, MTF_OBTHRESH_1_1, MTF_OSTHRESH_1_1), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 3, 2, text=str.tostring(math.round(MTF2_1, 0)) , text_color=_SRSIlabelColor(MTF2_1, MTF_OBTHRESH_2_1, MTF_OSTHRESH_2_1), text_halign=text.align_right, text_size=size.small) table.cell(dashboard, 3, 3, text=str.tostring(math.round(MTF3_1, 0)) , text_color=_SRSIlabelColor(MTF3_1, MTF_OBTHRESH_3_1, MTF_OSTHRESH_3_1), text_halign=text.align_right, text_size=size.small)
Physics Candles
https://www.tradingview.com/script/LNQfFgXU-Physics-Candles/
Techotomy
https://www.tradingview.com/u/Techotomy/
223
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/ // © Techotomy //@version=5 indicator(title="Physics Candles", shorttitle = "Physics Beta", overlay=true, max_labels_count=500, max_boxes_count=500) EMPTY_COLOR = color.new(color.black, 100) BUG_PREFIX = "ᄽ(◉෴◉)ᄿ Evil Bug Detected: " ERROR_PREFIX = "(◎_◎) Error Detected: " MIN_COLOR_UP = color.new(color.green, 90) MAX_COLOR_UP = color.new(color.green, 10) MIN_COLOR_DN = color.new(color.red, 90) MAX_COLOR_DN = color.new(color.red, 10) price_source_tooltip = "[Optional] Specify the candle price source by entering the data feed source and ticker symbol bisected by a colon (E.g., NASDAQ:TSLA or CME_MINI:ES!.). The price source defaults to the TV chart symbol." physics_source_tooltip = "[Optional] Specify the candle volume source by entering the data feed source and ticker symbol bisected by a colon (E.g., NASDAQ:TSLA or CME_MINI:ES!). The price source defaults to the TV chart symbol. " cycle_tooltip = "Specify the cycle time frame that restarts window collection when compares current volume intensity against. For example, to compare real-time relative volume in the current 15-minute window for each day, select Daily" sample_tooltip = "Specify the raw sampling granularity. A lower timeframe may give higher accuracy in volume segmentation at the cost of sample count due to TV data limits. Raw volume samples are processed by segmentation and are not equivalent to the processed sample count." window_tooltip = "Specify the window time frame to compare current relative volume against. For example, to compare real-time relative volume in the f current 15-minute window for each day, select 15-minute. Low window timeframes are useful for market open and closes to account for their inherent variability minute-to-minute" sample_date_tooltip = "Specify the start and end date for data collection. These default to the maximum start and end date times enforced by TV data limits." distribution_tooltip = "Describe the distribution of volume in candle segments. A normal distribution assumes samples are distributed as a standard bell-curve while a log-normal distribution takes the logarithm of samples to convert to a standard bell-curve." method_tooltip = "Describe the method of volume data transformation before normalization to the color range. Linear uses raw volume values without transformation, logarithm takes the log of volume, z-score converts volume to the multiples of the standard deviations away from the mean, and power-law takes the exponent of volume to the power of gamma. Logarithm and power-law with a gamma below one tend to increase sensitivity while power-law with a gamma above one decreases sensivity to highlight large volume anomalies." gamma_tooltip = "Specify the value of the exponent when using a power-law indicator transformation" cutoff_tooltip = "Specify the static minimum and maximum values to normalize between the minimum and maximum color range. The scores at or below the minimum cutoff will have the same intensity as the minimum color settings while the scores at or above the maximum cutoff will have the same intensity as the maximum color settings with a linear transition to color for scores in between the two cutoffs" autonorm_tooltip = "Auto-Normalization automatically interpolates color intensity between the minimum and maximum multiples of standard deviations from the mean for each distribution/window of physics values. For example, a minimum multiplier of 0 and a maximum multiplier of 3 interpolates colors between the mean (mean + 0*stdev) and 3 standard deviations from the mean (mean + 3*stdev) for each window. Values below the mean are pinned to the minimum color scheme while values above 3 are pinned to the maximum color scheme. This is different than the static min and max cutoff values above since those values remain constant across every window and are not automatically adjusted according to the aggregrated statistics of each window." plot_dist_tooltip = "Plot the processed sample distribution for a given window, where samples are segmented and scored. To find the window of interest to plot, use the Print Windows feature." resolution_tooltip = "Specify the number of volume segments per candle. The maximum number is 8 when using one indicator, but additional indicators can be applied to the chart to increase the resolution. For example, for 16 segments per candle, set the resolution to 16 with one indicator Stack Number set to 0 and the other indicator Stack Number set to 1." stack_tooltip = "Specify the indicator number when increasing candle resolution in increasing order starting with 0 (e.g., 0 for first indicator, 1 for second, 2 for the third)" overlay_tooltip = "Specify the number of indicator overlays to automaticaly decrease the transparency of the color scheme for each individual indicator such that combined overlay equals the target transparency. The maximum transparency of the color scheme should be less than 100% since only an infinite number of transparent overlays can equal 100%." hide_tooltip = "Specify the intraday time to hide theindicator. This is useful when calibrating multiple indicators to different parts of the trading day." price_source = input.string(defval='', title='Candle Source  ', group='Sources', tooltip=price_source_tooltip) physics_source = input.string(defval='', title='Physics Source  ', group='Sources', tooltip=physics_source_tooltip) mass_selection = input.string(defval='Volume', title='Mass', group='Sources', options=['Volume', 'Time']) physics_selection = input.string(defval='Mass', title='Physics', group='Sources', options= ['Mass', 'Position', 'Velocity', 'Acceleration', 'Momentum', 'Force', 'Kinetic Energy']) input_to_timeframe(str) => string tf = switch str "1 Min" => "1" "2 Mins" => "2" "3 Mins" => "3" "5 Mins" => "5" "10 Mins" => "10" "15 Mins" => "15" "30 Mins" => "30" "45 Mins" => "45" "1 Hour" => "60" "2 Hours" => "120" "3 Hours" => "180" "4 Hours" => "240" "24 Hours" => "1440" "1 day" => "1D" "1 week" => "1W" "1 month" => "1M" "1 quarter" => "3M" "1 year" => "12M" "Daily" => "1D" "Weekly" => "1W" "Monthly" => "1M" "Quarterly" => "3M" "Yearly" => "12M" "Day" => "1D" "Week" => "1W" "Month" => "1M" "Quarter" => "3M" "Year" => "12M" ctf = input.timeframe( defval="Daily", title='Cycle Time Frame', group='Data Collection', options= ["Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], tooltip=cycle_tooltip) cycle_tf = input_to_timeframe(ctf) stf = input.string( defval="1 Min", title='Sample Time Frame', group='Data Collection', options= ["1 Min", "2 Mins", "3 Mins", "5 Mins", "10 Mins", "15 Mins", "30 Mins", "45 Mins", "1 Hour", "2 Hours", "3 Hours", "4 Hours", "24 Hours", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], tooltip=sample_tooltip) sample_tf = input_to_timeframe(stf) wtf = input.string( defval="30 Mins", title='Window Time Frame', group='Data Collection', options= ["1 Min", "2 Mins", "3 Mins", "5 Mins", "10 Mins", "15 Mins", "30 Mins", "45 Mins", "1 Hour", "2 Hours", "3 Hours", "4 Hours", "24 Hours", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"], tooltip=window_tooltip) window_tf = input_to_timeframe(wtf) use_start_date = input.bool(defval=false, title='Start', inline='start', group='Data Collection') start_date = input.time( defval=timestamp("1 Jan 2021 0:00"), title='', inline='start', group='Data Collection', tooltip=sample_date_tooltip) use_end_date = input.bool(defval=false, title='End ', inline='end', group='Data Collection') end_date = input.time( defval=timestamp("1 Jan 2022 0:00"), title='', inline='end', group='Data Collection', tooltip=sample_date_tooltip) dist_type = input.string( defval='Log-Normal', title='Distribution', group='Physics Normalization', options=['Normal', 'Log-Normal'], tooltip=distribution_tooltip) norm_type = input.string( defval="Z-Score", title='Method', group='Physics Normalization', options=["Linear", "Logarithm", "Z-Score", "Power-Law"], tooltip=method_tooltip) min_score = input.float( defval=0, title='Min Score Cutoff', group='Physics Normalization', tooltip=cutoff_tooltip) max_score = input.float( defval=3, title='Max Score Cutoff', group='Physics Normalization', tooltip=cutoff_tooltip) is_auto_norm = input.bool( defval=true, title='Auto-Normalization', group='Auto-Normalization', tooltip=autonorm_tooltip) min_auto = input.float(defval=0, title='Min Stdev Multiplier', group='Auto-Normalization') max_auto = input.float(defval=3, title='Max Stdev Multiplier', group='Auto-Normalization') gamma = input.float(defval=2.0, title='Gamma', group='Power-Law Normalization', tooltip=gamma_tooltip) smooth_method = input.string(defval='WMA', title='Method', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA'], group='Smoothing') smooth_length = input.int(defval=1, title='Length', minval=1, group='Smoothing') is_plot = input.bool( defval=false, title='Plot Window  ', inline='plot0', group='Data Validation') plot_index = input.int( defval=10, title='  ', minval=0, inline='plot0', group='Data Validation') plot_color = input.color( defval=#9598a1, title='', inline='plot0', group='Data Validation', tooltip=plot_dist_tooltip) // plot_width = input.int( // defval=400, title='Width', inline='plot2', group='Data Validation') // plot_height = input.int( // defval=5, title='Height', inline='plot2', group='Data Validation') // plot_y_shift = input.int( // defval=0, title='y-Shift', inline='plot3', group='Data Validation') // plot_x_shift = input.int( // defval=50, title='x-Shift', inline='plot3', group='Data Validation') plot_width=400 plot_height=5 plot_y_shift=0 plot_x_shift=35 is_print_stats = input.bool( defval=false, title='Print Statistics  ', inline='print', group='Data Validation') is_print_windows = input.bool( defval=false, title='Print Windows', inline='print', group='Data Validation') print_color = input.color( defval=color.new(#434651, 0), title='', inline='print', group='Data Validation') res = input.int(defval=8, title='Resolution', minval=1, group='Multiplicity', tooltip=resolution_tooltip) ind_num = input.int( defval=0, title='Stack Number', minval=0, group='Multiplicity', tooltip=stack_tooltip) num_overlays = input.float( defval=1, title='Number of Overlays', minval=0, group='Multiplicity', tooltip=overlay_tooltip) shift_percent = input.float( defval=0, title='Overlay Shift (%)', group='Multiplicity') hide_0 = input.bool( defval=false, title='Hide', inline='h0', group='Multiplicity') session_0 = input.session( defval="0000-0000", title="", inline='h0', group='Multiplicity', tooltip=hide_tooltip) hide_1 = input.bool( defval=false, title='Hide', inline='h1', group='Multiplicity') session_1 = input.session( defval="0000-0000", title="", inline='h1', group='Multiplicity', tooltip=hide_tooltip) hide_2 = input.bool( defval=false, title='Hide', inline='h2', group='Multiplicity') session_2 = input.session( defval="0000-0000", title="", inline='h2', group='Multiplicity', tooltip=hide_tooltip) divide_transp(transp, divisions) => 100 * math.pow(transp / 100, 1 / divisions) filter_color(_color, num_overlays, use_global_coloring, global_color) => color c = _color if use_global_coloring c := global_color transp = color.t(_color) if num_overlays > 1 transp := divide_transp(transp, num_overlays) color.new(c, transp) min_global_color_up = input.color(defval=MIN_COLOR_UP, inline='min', title='Minimum Global Color      Up', group='Global Coloring') min_global_color_dn = input.color(defval=MIN_COLOR_DN, inline='min', title='Down', group='Global Coloring') max_global_color_up = input.color(defval=MAX_COLOR_UP, inline='max', title='Maximum Global Color      Up', group='Global Coloring') max_global_color_dn = input.color(defval=MAX_COLOR_DN, inline='max', title='Down', group='Global Coloring') use_global_coloring = input.bool(defval=false, title='Use Global Coloring', group='Global Coloring') min_body_color_up = filter_color(input.color(defval=MIN_COLOR_UP, inline='min0', title='Minimum Body Color       Up', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_up) min_body_color_dn = filter_color(input.color(defval=MIN_COLOR_DN, inline='min0', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_dn) max_body_color_up = filter_color(input.color(defval=MAX_COLOR_UP, inline='max0', title='Maximum Body Color       Up', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_up) max_body_color_dn = filter_color(input.color(defval=MAX_COLOR_DN, inline='max0', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_dn) min_tail_color_up = filter_color(input.color(defval=MIN_COLOR_UP, inline='min1', title='Minimum Tail Color        Up', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_up) min_tail_color_dn = filter_color(input.color(defval=MIN_COLOR_DN, inline='min1', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_dn) max_tail_color_up = filter_color(input.color(defval=MAX_COLOR_UP, inline='max1', title='Maximum Tail Color        Up', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_up) max_tail_color_dn = filter_color(input.color(defval=MAX_COLOR_DN, inline='max1', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_dn) min_border_color_up = filter_color(input.color(defval=MIN_COLOR_UP, inline='min2', title='Minimum Border Color     Up', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_up) min_border_color_dn = filter_color(input.color(defval=MIN_COLOR_DN, inline='min2', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_dn) max_border_color_up = filter_color(input.color(defval=MAX_COLOR_UP, inline='max2', title='Maximum Border Color     Up', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_up) max_border_color_dn = filter_color(input.color(defval=MAX_COLOR_DN, inline='max2', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_dn) min_wick_color_up = filter_color(input.color(defval=MIN_COLOR_UP, inline='min4', title='Minimum Wick Color       Up', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_up) min_wick_color_dn = filter_color(input.color(defval=MIN_COLOR_DN, inline='min4', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, min_global_color_dn) max_wick_color_up = filter_color(input.color(defval=MAX_COLOR_UP, inline='max4', title='Maximum Wick Color       Up', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_up) max_wick_color_dn = filter_color(input.color(defval=MAX_COLOR_DN, inline='max4', title='Down', group='Segment Coloring'), num_overlays, use_global_coloring, max_global_color_dn) min_outline_body_color_up = filter_color(input.color(defval=MIN_COLOR_UP, inline='min3', title='Minimum Border Color     Up', group='Candle Outline Coloring'), num_overlays, use_global_coloring, min_global_color_up) min_outline_body_color_dn = filter_color(input.color(defval=MIN_COLOR_DN, inline='min3', title='Down', group='Candle Outline Coloring'), num_overlays, use_global_coloring, min_global_color_dn) max_outline_body_color_up = filter_color(input.color(defval=MAX_COLOR_UP, inline='max3', title='Maximum Border Color     Up', group='Candle Outline Coloring'), num_overlays, use_global_coloring, max_global_color_up) max_outline_body_color_dn = filter_color(input.color(defval=MAX_COLOR_DN, inline='max3', title='Down', group='Candle Outline Coloring'), num_overlays, use_global_coloring, max_global_color_dn) min_outline_wick_color_up = filter_color(input.color(defval=MIN_COLOR_UP, inline='min4', title='Minimum Wick Color       Up', group='Candle Outline Coloring'), num_overlays, use_global_coloring, min_global_color_up) min_outline_wick_color_dn = filter_color(input.color(defval=MIN_COLOR_DN, inline='min4', title='Down', group='Candle Outline Coloring'), num_overlays, use_global_coloring, min_global_color_dn) max_outline_wick_color_up = filter_color(input.color(defval=MAX_COLOR_UP, inline='max4', title='Maximum Wick Color       Up', group='Candle Outline Coloring'), num_overlays, use_global_coloring, max_global_color_up) max_outline_wick_color_dn = filter_color(input.color(defval=MAX_COLOR_DN, inline='max4', title='Down', group='Candle Outline Coloring'), num_overlays, use_global_coloring, max_global_color_dn) close_based = input.bool(defval=false, title='Color by previous close', group='Candle Settings') fat_wicks = input.bool(defval=false, title='Thick Wicks', group='Candle Settings') source_to_ticker(source) => pos = str.pos(source, ':') prefix = str.substring(source, 0, pos) suffix = str.substring(source, pos+1) ticker = ticker.new(prefix, suffix, syminfo.session) chart_ticker= ticker.new(syminfo.prefix, syminfo.ticker, syminfo.session) price_ticker = source_to_ticker(price_source) value_ticker = source_to_ticker(physics_source) [open_, high_, low_, close_] = request.security( price_source == '' ? chart_ticker: str.contains(price_source, '-') or str.contains(price_source, '+') or str.contains(price_source, '*') or str.contains(price_source, '/') ? price_source : price_ticker, timeframe.period, [open, high, low, close]) [iopen, ihigh, ilow, iclose] = request.security_lower_tf( price_source == '' ? chart_ticker: str.contains(price_source, '-') or str.contains(price_source, '+') or str.contains(price_source, '*') or str.contains(price_source, '/') ? price_source : price_ticker, sample_tf, [open, high, low, close]) if timeframe.in_seconds(timeframe.period) >= timeframe.in_seconds("D") and array.size(iopen) > 0 open_ := array.get(iopen, 0) high_ := array.max(ihigh) low_ := array.min(ilow) close_ := array.get(iclose, array.size(iclose)-1) print(price, _text, _color=color.gray, _textcolor=color.silver, _size=size.auto, _style=label.style_label_down, _yloc=yloc.price) => label.new(bar_index, price, color=_color, textcolor=_textcolor, size=_size, style=_style, yloc=_yloc, text=str.tostring(_text)) get_price_range(bin_num, res) => float max_price = ((bin_num + 1) / res) * (high_ - low_) + low_ float min_price = (bin_num / res) * (high_ - low_) + low_ [min_price, max_price] get_body_range() => float body_low = math.min(open_, close_) float body_high = math.max(open_, close_) [body_low, body_high] updn_color(zscore, min_value, max_value, min_color_dn, max_color_dn, min_color_up, max_color_up, close_based) => color _color = color.from_gradient( zscore, min_value, max_value, min_color_dn, max_color_dn) if (close_[0] >= close_[1] and close_based) or (close_ >= open_ and not close_based) _color := color.from_gradient( zscore, min_value, max_value, min_color_up, max_color_up) _color get_candle_colors( zscores, bin_num, res, fat_wicks, close_based, min_value, max_value, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn) => color _color = EMPTY_COLOR [min_price, max_price] = get_price_range(bin_num, res) [body_low, body_high] = get_body_range() float z = 0 if bin_num < res z := array.get(zscores, bin_num) // if it doesn't have a thin wick if not (max_price <= body_low or min_price >= body_high) _color := updn_color(z, min_value, max_value, min_body_color_dn, max_body_color_dn, min_body_color_up, max_body_color_up, close_based) // if it does have thin wick, but we want a fat tail if fat_wicks and (max_price <= body_low or min_price >= body_high) _color := updn_color(z, min_value, max_value, min_tail_color_dn, max_tail_color_dn, min_tail_color_up, max_tail_color_up, close_based) _color get_wick_color( zscores, bin_num, res, fat_wicks, close_based, min_value, max_value, min_color_up, min_color_dn, max_color_up, max_color_dn) => color _color = EMPTY_COLOR [min_price, max_price] = get_price_range(bin_num, res) [body_low, body_high] = get_body_range() // if it has a thin wick if (max_price < body_low or min_price > body_high or (max_price >= body_low and min_price < body_low) or (min_price <= body_high and max_price > body_high)) and not fat_wicks float z = 0 if bin_num < res z := array.get(zscores, bin_num) _color := updn_color(z, min_value, max_value, min_color_dn, max_color_dn, min_color_up, max_color_up, close_based) _color // match border segment color with body color get_border_color( zscores, bin_num, res, fat_wicks, close_based, min_value, max_value, min_color_up, min_color_dn, max_color_up, max_color_dn) => color _color = EMPTY_COLOR [body_low, body_high] = get_body_range() [min_price, max_price] = get_price_range(bin_num, res) // if inside body if not (max_price <= body_low or min_price >= body_high) float z = 0 if bin_num < res z := array.get(zscores, bin_num) _color := updn_color(z, min_value, max_value, min_color_dn, max_color_dn, min_color_up, max_color_up, close_based) _color := color.new(_color, divide_transp(color.t(_color), 2)) // if outside body but we want a fat wick if fat_wicks and (max_price <= body_low or min_price >= body_high) _color := EMPTY_COLOR _color get_bin_ohlc(bin_num, res, fat_wicks) => [min_price, max_price] = get_price_range(bin_num, res) float _open = open_ float _high = max_price float _low = min_price float _close = close_ body_low = math.min(open_, close_) body_high = math.max(open_, close_) // create lower wick if max_price < body_low _close := max_price _open := fat_wicks ? min_price : max_price // create lower wick and body else if max_price >= body_low and min_price < body_low and max_price <= body_high _close := max_price _open := fat_wicks ? min_price : body_low // create body else if max_price <= body_high and min_price >= body_low _open := min_price _close := max_price // create upper wick and body else if max_price >= body_high and min_price < body_high and min_price >= body_low _open := min_price _close := fat_wicks ? max_price : body_high // create upper wick else if min_price > body_high _open := min_price _close := fat_wicks ? max_price : min_price [_open, _high, _low, _close] //http://www.burtonsys.com/climate/composite_standard_deviations.html update_group_stats(new_count, old_count, new_mean, old_mean, new_stdev, old_stdev) => count = new_count + old_count mean = ((new_count * new_mean) + (old_count * old_mean)) / count var1 = math.pow(new_stdev, 2) essg1 = (new_count - 1) * var1 var2 = math.pow(old_stdev, 2) essg2 = (old_count - 1) * var2 ess = essg1 + essg2 gss1 = math.pow(new_mean - mean, 2) * new_count gss2 = math.pow(old_mean - mean, 2) * old_count tgss = gss1 + gss2 gv = (ess + tgss) / (count - 1) stdev = math.sqrt(gv) [count, mean, stdev] set_value(value, values, index) => prev_value = array.get(values, index) if na(prev_value) array.set(values, index, value) else array.set(values, index, value + prev_value) interpolate_segment_values(lows, highs, values, resolution) => float[] segment_values = array.new_float(resolution, na) for v=0 to array.size(values)-1 _low = array.get(lows, v) _high = array.get(highs, v) _val = array.get(values, v) lowest = array.min(lows) highest = array.max(highs) seg_low = (_low - low_)/(high_ - low_) * resolution seg_high = (_high - low_)/(high_ - low_) * resolution start = math.floor(seg_low) end = math.ceil(seg_high) sl = seg_low seg_tot = seg_high - seg_low // if na(start) or na(end) for i=0 to resolution-1 set_value(_val / resolution, segment_values, i) if start >=0 and end <= resolution if (start == end or _low == _high) i = int((_low - low_)/(high_ - low_) * resolution) i := math.min(i, resolution-1) set_value(_val, segment_values, i) else for i=start to end-1 sh = seg_high if seg_high >= (i+1) sh := i+1 seg_val = ((sh - sl) / seg_tot) * _val set_value(seg_val, segment_values, i) sl := i+1 segment_values get_tick_values(value, newbar_value, resolution) => varip float[] highs = array.new_float(0) varip float[] lows = array.new_float(0) varip float[] closes = array.new_float(0) varip float[] values = array.new_float(0) varip float prev_value = newbar_value varip reset = false if barstate.isnew array.clear(highs) array.clear(lows) array.clear(closes) array.clear(values) prev_value := newbar_value reset := true last = open_ if array.size(closes) > 0 last := array.get(closes, array.size(closes)-1) if close_ > last array.push(highs, close_) array.push(lows, last) else array.push(highs, last) array.push(lows, close_) array.push(closes, close_) array.push(values, value - prev_value) prev_value := value segment_values = interpolate_segment_values(lows, highs, values, resolution) segment_values filter_nans(a) => float[] filter = array.new_float(0) for i=0 to array.size(a)-1 if not na(array.get(a, i)) array.push(filter, array.get(a, i)) filter update_stats( is_update, samples, index, prev_index, num_indices, index_change, hist_counts, hist_means, hist_stdevs) => var int window_count = na var float window_mean = na var float window_stdev = na _samples = filter_nans(samples) if (index_change or num_indices == 2) and window_count > 0 and is_update hist_count = array.get(hist_counts, prev_index) hist_mean = array.get(hist_means, prev_index) hist_stdev = array.get(hist_stdevs, prev_index) if na(hist_count) hist_count := window_count hist_mean := window_mean hist_stdev := window_stdev else [update_count, update_mean, update_stdev] = update_group_stats( window_count, hist_count, window_mean, hist_mean, window_stdev, hist_stdev) hist_count := update_count hist_mean := update_mean hist_stdev := update_stdev array.set(hist_counts, prev_index, hist_count) array.set(hist_means, prev_index, hist_mean) array.set(hist_stdevs, prev_index, hist_stdev) window_count := na window_mean := na window_stdev := na candle_count = array.size(_samples) candle_mean = array.avg(_samples) candle_stdev = array.stdev(_samples, biased=false) if na(candle_stdev) candle_stdev := 0.0 if candle_count > 0 and is_update if na(window_count) window_count := candle_count window_mean := candle_mean window_stdev := candle_stdev else [update_count, update_mean, update_stdev] = update_group_stats( candle_count, window_count, candle_mean, window_mean, candle_stdev, window_stdev) window_count := update_count window_mean := update_mean window_stdev := update_stdev calc_zscore(x, mean, stdev) => zscore = (x - mean) / stdev linears_to_logs(linears) => float[] logs = array.new_float(array.size(linears), 0) for i=0 to array.size(linears)-1 val = array.get(linears, i) array.set(logs, i, math.log(val)) logs linears_to_powers(linears, gamma) => float[] powers = array.new_float(array.size(linears), 0) for i=0 to array.size(linears)-1 val = array.get(linears, i) array.set(powers, i, math.pow(val, gamma)) powers linears_to_zscores(linears, mean, stdev) => float[] zscores = array.new_float(array.size(linears), 0) for i=0 to array.size(linears)-1 val = array.get(linears, i) float z = calc_zscore(val, mean, stdev) array.set(zscores, i, z) zscores map_linears(map_type, linears, mean, stdev, gamma) => float[] values = linears if map_type == 'Z-Score' values := linears_to_zscores(linears, mean, stdev) else if map_type == 'Logarithm' values := linears_to_logs(linears) else if map_type == 'Power-Law' values := linears_to_powers(linears, gamma) values extract_timeframe(tf) => unit = str.substring(tf, str.length(tf)-1) multiplier = 0 period = '' if unit == 'D' or unit == 'W' or unit == 'M' multiplier := int(str.tonumber(str.substring(tf, 0, str.length(tf)-1))) period := unit [multiplier, period] verticalize_scores(scores) => string verticals = 'Scores : \n' for i=array.size(scores)-1 to 0 verticals += str.tostring( str.format("{0, number, .####}",array.get(scores, i)) + '\n') verticals get_index(_time, cycle_tf, window_tf) => index = -1 cycle_tf_mins = timeframe.in_seconds(cycle_tf) / 60 window_tf_mins = timeframe.in_seconds(window_tf) / 60 if cycle_tf_mins <= timeframe.in_seconds("1D") / 60 index := math.floor( (hour(_time) * 60 + minute(_time)) / window_tf_mins) else if cycle_tf_mins <= (timeframe.in_seconds("1W") / 60) index:= math.floor( ((dayofweek(_time)-1) * 24 * 60 + hour(_time) * 60 + minute(_time)) / window_tf_mins) else if cycle_tf_mins <= timeframe.in_seconds("1M") / 60 index := math.floor( ((dayofmonth(_time)-1) * 24 * 60 + hour(_time) * 60 + minute(_time)) / window_tf_mins) else if cycle_tf_mins == timeframe.in_seconds("3M") / 60 and window_tf_mins % (timeframe.in_seconds("W") / 60) == 0 and window_tf_mins < timeframe.in_seconds("M") / 60 quarter = math.floor((month(_time)-1) / 3) + 1 first_month = quarter * 3 - 2 t0_s = timestamp(year(_time), first_month, 0) / 1000 t1_s = timestamp(year(_time), month(_time), dayofmonth(_time)) / 1000 index := math.floor((t1_s - t0_s - 1) / timeframe.in_seconds("1W")) else if cycle_tf_mins <= timeframe.in_seconds("12M") / 60 and timeframe.in_seconds(window_tf) % timeframe.in_seconds("M") == 0 [cyc_mult, _] = extract_timeframe(cycle_tf) [win_mult, _] = extract_timeframe(window_tf) index := math.floor(((month(_time)-1) % (cyc_mult)) / win_mult) if index == -1 runtime.error( "The chart and window time frame combination is not available") index update_mean(count, mean, value) => _count = count + 1 delta = value - mean _mean = delta / _count + mean [_count, _mean] partition_candles(lows, highs, values) => low_highs = array.concat(array.copy(lows), highs) array.sort(low_highs) parts = array.from(array.get(low_highs, 0)) // remove duplicates for i=1 to array.size(low_highs)-1 v1 = array.get(low_highs, i) v0 = array.get(parts, array.size(parts)-1) if v1 != v0 array.push(parts, v1) parts average_partitions(parts, lows, highs, values) => counts = array.new_float(array.size(parts)-1, 0) part_avgs = array.new_float(array.size(parts)-1, 0) indices = array.new_int(0) for i=0 to array.size(values)-1 array.push(indices, i) part_lows = array.new_float(0) part_highs = array.new_float(0) for i=0 to array.size(parts)-2 part_low = array.get(parts, i) array.push(part_lows, part_low) part_high = array.get(parts, i+1) array.push(part_highs, part_high) new_indices = array.new_int(0) for j=0 to array.size(indices)-1 k = array.get(indices, j) value_low = array.get(lows, k) value_high = array.get(highs, k) value = array.get(values, k) if value_low <= part_low and value_high >= part_high [c, m] = update_mean(array.get(counts, i), array.get(part_avgs, i), value) array.set(counts, i, c) array.set(part_avgs, i, m) if value_high > part_high array.push(new_indices, k) indices := new_indices [part_lows, part_highs, part_avgs] scale_partition_values(part_lows, part_highs, part_values, res) => float segment_size = (high_ - low_) / res float[] scaled_parts = array.new_float(0) for i=0 to array.size(part_values)-1 v = array.get(part_values, i) h = array.get(part_highs, i) l = array.get(part_lows, i) array.push(scaled_parts, v * (h-l)/segment_size) scaled_parts percent_change(v0, v1) => percent = 100 * (v1 - v0) / v0 get_velocity(v0, v1) => percent_change(v0, v1) get_acceleration(v0, v1) => percent_change(v0, v1) - percent_change(v0[1], v1[1]) get_physics(mass_option, physics_option) => float mass = na if mass_option == "Volume" mass := volume else if mass_option == "Time" mass := time_close - time float motion = na motion := switch physics_option 'Position' => close 'Velocity' => get_velocity(open, close) 'Momentum' => get_velocity(open, close) 'Kinetic Energy' => get_velocity(open, close) 'Acceleration' => get_acceleration(open, close) 'Force' => get_acceleration(open, close) 'Potential Energy' => 1 / get_velocity(open, close) [mass, motion, time] should_have_motion(option) => bool is_sum = switch option 'Position' => true 'Velocity' => true 'Momentum' => true 'Kinetic Energy' => true 'Acceleration' => true 'Force' => true 'Potential Energy' => true => false should_have_mass(option) => bool is_avg = switch option 'Mass' => true // if mass is said to "have" energy, then time also // has mass via E=mc^2 where time ≈ distance * sqrt(mass/E). 'Time' => true 'Volume' => true 'Momentum' => true 'Kinetic Energy' => true 'Force' => true 'Potential Energy' => true => false multiply_arrays(a0, a1) => float[] product = array.new_float(0) for i=0 to array.size(a0)-1 array.push(product, array.get(a0, i) * array.get(a1, i)) product calc_segment_physics(mass_segments, motion_segments, physics_selection, resolution) => float[] segment_values = switch physics_selection 'Mass' => mass_segments 'Time' => mass_segments 'Volume' => mass_segments 'Position' => motion_segments 'Velocity' => motion_segments 'Momentum' => multiply_arrays(mass_segments, motion_segments) 'Kinetic Energy' => multiply_arrays(mass_segments, multiply_arrays(motion_segments, motion_segments)) 'Acceleration' => motion_segments 'Force' => multiply_arrays(mass_segments, motion_segments) 'Potential Energy' => multiply_arrays(mass_segments, motion_segments) => array.new_float(resolution, na) absolute_array(a) => for i=0 to array.size(a)-1 array.set(a, i, math.abs(array.get(a, i))) a get_segment_values(is_get, mass, masses, motions, lows, highs, sample_tf, resolution, mass_selection, physics_selection) => float[] mass_segments = array.new_float(resolution, na) float[] motion_segments = array.new_float(resolution, na) if is_get has_mass = should_have_mass(physics_selection) has_motion = should_have_motion(physics_selection) if has_motion and array.size(motions) == array.size(lows) and array.size(motions) == array.size(highs) partitions = partition_candles(lows, highs, motions) if array.size(partitions) > 1 [part_lows, part_highs, part_avgs] = average_partitions( partitions, lows, highs, motions) scaled_values = scale_partition_values( part_lows, part_highs, part_avgs, resolution) motion_segments := interpolate_segment_values( part_lows, part_highs, scaled_values, resolution) else motion_segments := interpolate_segment_values(lows, highs, motions, resolution) if has_mass and array.size(masses) == array.size(lows) and array.size(masses) == array.size(highs) values = masses if barstate.isrealtime if mass_selection == "Time" mass_segments := get_tick_values(timenow, time, resolution) else if mass_selection == "Volume" mass_segments := get_tick_values(mass, 0, resolution) else mass_segments := interpolate_segment_values(lows, highs, masses, resolution) motion_segments := absolute_array(motion_segments) segment_values = calc_segment_physics( mass_segments, motion_segments, physics_selection, resolution) get_scores( is_get, segment_values, lows, highs, resolution, mean, stdev, norm_type, gamma) => float[] scores = array.new_float(resolution, na) if is_get scores := map_linears(norm_type, segment_values, mean, stdev, gamma) scores auto_norm(mean, stdev, min_mult, max_mult) => min_cutoff = mean + min_mult*stdev max_cutoff = mean + max_mult*stdev [min_cutoff, max_cutoff] print_statistics( is_print, scores, index, num_indices, cycle_tf, mean, stdev, raw_sample_count, score_sample_count, print_color) => if (ta.change(index) or (timeframe.change(cycle_tf) and num_indices == 2)) and is_print print(low_, verticalize_scores(scores), _color=print_color, _style=label.style_label_up) stats = 'Window [' + str.tostring(index) + ']\n' + 'Mean:' + '\n' + str.tostring( str.format("{0, number, .####}", mean)) + '\n' + 'Std Dev:' + '\n' + str.tostring( str.format("{0, number, .####}", stdev)) + '\n' + 'Raw Samples:' + '\n' + str.tostring( raw_sample_count) + '\n' + 'Score Samples:' + '\n' + str.tostring( score_sample_count) print(high_, stats, _color=print_color) print_windows(is_print, index, num_indices, cycle_tf, print_color) => if (ta.change(index) or (timeframe.change(cycle_tf) and num_indices == 2)) and is_print print(high_, index, _color=print_color, _yloc=yloc.price) label_sampling_start_date(is_label, print_color) => var bool show = false if not show and is_label show := true print(low_, "Start Data Collection", _color=print_color, _size=size.small) plot_stat_line(stat_x0, x0, y0, y1, txt, plot_color, label_style) => line li = line.new(stat_x0 + x0, y0, stat_x0 + x0, y1, color=plot_color, style=line.style_dotted, xloc=xloc.bar_index) y = y1 if label_style == label.style_label_down y := y0 label la = label.new(stat_x0 + x0, y, text=txt, size=size.small, color=EMPTY_COLOR, textcolor=plot_color, style=label_style, xloc=xloc.bar_index) [li, la] bin_distribution(samples, min_value, max_value, num_bins) => float[] bins = array.new_float(num_bins, 0) bin_size = (max_value - min_value) / num_bins for i=0 to array.size(samples)-1 sample = array.get(samples, i) if sample >= min_value and sample <= max_value bin_index = math.floor( ((sample - min_value) / (max_value - min_value)) * (num_bins-1)) prev_count = array.get(bins, bin_index) array.set(bins, bin_index, prev_count + 1) bins construct_plot( x0, y0, x1, y1, stat_x0, stat_x1, samples, plot_index, plot_color, plot_width, text_width, mean, stdev, is_auto_norm, min_auto, max_auto, norm_type, dist_type, min_score, max_score) => var box histogram_frame = na var box[] histograms = array.new_box(0) var box stat_box = na var line[] plot_lines = array.new_line(0) var label[] plot_labels = array.new_label(0) sample_count = array.size(samples) sample_min = array.min(samples) sample_max = array.max(samples) sample_mean = array.avg(samples) sample_stdev = array.stdev(samples, biased=false) sample_min := sample_min < sample_mean - 4*sample_stdev ? sample_mean - 4*sample_stdev : sample_min sample_max := sample_max > sample_mean + 4*sample_stdev ? sample_mean + 4*sample_stdev : sample_max score_min = min_score score_max = max_score if is_auto_norm [mi, mx] = auto_norm(mean, stdev, min_auto, max_auto) score_min := mi score_max := mx bin_width = plot_width - text_width binned_distribution = bin_distribution( samples, sample_min, sample_max, bin_width) binned_min = bin_distribution( array.from(score_min), sample_min, sample_max, bin_width) binned_max = bin_distribution( array.from(score_max), sample_min, sample_max, bin_width) binned_mean = bin_distribution( array.from(sample_mean), sample_min, sample_max, bin_width) binned_stdev_pos = bin_distribution( array.from(sample_mean+sample_stdev), sample_min, sample_max, bin_width) binned_stdev_neg = bin_distribution( array.from(sample_mean-sample_stdev), sample_min, sample_max, bin_width) max_count = array.max(binned_distribution) max_height = (y0-y1) for i=0 to array.size(binned_distribution)-1 count = array.get(binned_distribution, i) height = (count / max_count) * max_height array.push(histograms, box.new( x0+(i), height + y1, x0+(i+1), y1, xloc=xloc.bar_index, border_color=plot_color, bgcolor=plot_color)) histogram_frame := box.new(x0-1, y0, x1+1, y1, bgcolor=color.new(color.black, 100), text='\n' + norm_type + ' on ' + dist_type + ' Distribution', xloc=xloc.bar_index, text_size=size.normal, text_valign=text.align_top, text_halign=text.align_right, border_color=plot_color, text_color=plot_color) bin_min = array.indexof(binned_min, 1) bin_max = array.lastindexof(binned_max, 1) bin_mean = array.indexof(binned_mean, 1) bin_stdev_pos = array.indexof(binned_stdev_pos, 1) bin_stdev_neg = array.indexof(binned_stdev_neg, 1) int[] bin_stats = array.from( bin_min, bin_max, bin_mean, bin_stdev_pos, bin_stdev_neg) string[] bin_txts = array.from( 'Min\nCutoff', 'Max\nCutoff', 'Mean', '[+]\nStdev', '[-]\nStdev') for i=0 to array.size(bin_stats)-1 bs = array.get(bin_stats, i) bt = array.get(bin_txts, i) style = label.style_label_down if i > 1 style := label.style_label_up line plot_line = na label plot_label = na if bs != -1 [li, la] = plot_stat_line(bs, x0, y0, y1, bt, plot_color, style) plot_line := li plot_label := la array.push(plot_lines, plot_line) array.push(plot_labels, plot_label) stat_txt = 'Window [' + str.tostring(plot_index) + ']' + '\n' + 'Mean: ' + str.format("{0, Number, .###}", sample_mean) + '\n' + 'Std Dev: ' + str.format("{0, Number, .###}", sample_stdev) + '\n' + 'Min Value: ' + str.format("{0, Number, .###}", sample_min) + '\n' + 'Max Value: ' + str.format("{0, Number, .###}", sample_max) + '\n' + 'Min Cutoff: ' + str.format("{0, Number, .###}", score_min) + '\n' + 'Max Cutoff: ' + str.format("{0, Number, .###}", score_max) + '\n' + 'Samples: ' + str.tostring(sample_count) stat_box := box.new(stat_x0, y0, stat_x1, y1, text=stat_txt, bgcolor=EMPTY_COLOR, text_color=plot_color, text_size=size.auto, text_halign=text.align_right, border_color=EMPTY_COLOR) [histogram_frame, histograms, stat_box, bin_stats, plot_lines, plot_labels] update_plot( x0, x1, stat_x0, stat_x1, histogram_frame, histograms, stat_box, bin_stats, plot_lines, plot_labels) => for i=0 to array.size(histograms)-1 h = array.get(histograms, i) box.set_left(h, x0+i) box.set_right(h, x0+(i+1)) box.set_left(histogram_frame, x0) box.set_right(histogram_frame, x1) box.set_left(stat_box, stat_x0) box.set_right(stat_box, stat_x1) for i=0 to array.size(bin_stats)-1 bs = array.get(bin_stats, i) line.set_xloc(array.get(plot_lines, i), x0+bs, x0+bs, xloc=xloc.bar_index) label.set_xloc(array.get(plot_labels, i), x0+bs, xloc=xloc.bar_index) plot_distribution( is_plot, samples, plot_index, plot_color, plot_width, plot_height, plot_x_shift, plot_y_shift, means, stdevs, is_auto_norm, min_auto, max_auto, norm_type, dist_type, min_score, max_score) => var box histogram_frame = na var box[] histograms = na var box stat_box = na var line[] plot_lines = na var label[] plot_labels = na var int[] bin_stats = na if is_plot int text_width = 60 float y0 = close_*(plot_y_shift/100 + 1) float y1 = y0 - (plot_height/100)*close_ int x0 = bar_index + plot_x_shift int x1 = x0 + plot_width int stat_x0 = x0 + plot_width - text_width int stat_x1 = stat_x0+text_width-10 if barstate.isconfirmed and not na(histograms) update_plot( x0, x1, stat_x0, stat_x1, histogram_frame, histograms, stat_box, bin_stats, plot_lines, plot_labels) if barstate.islast and na(histograms) if array.size(samples) == 0 runtime.error(ERROR_PREFIX + "No data was collected in this window to plot. Turn distribution plotting off or change window number to one that exists in this plane of existence.") mean = array.get(means, plot_index) stdev = array.get(stdevs, plot_index) [hf, hs, sb, bs, lis, las] = construct_plot( x0, y0, x1, y1, stat_x0, stat_x1, samples, plot_index, plot_color, plot_width, text_width, mean, stdev, is_auto_norm, min_auto, max_auto, norm_type, dist_type, min_score, max_score) histogram_frame := hf histograms := hs stat_box := sb plot_lines := lis plot_labels := las bin_stats := bs collect_distribution(is_collect, scores) => var float[] distribution = array.new_float(0) if is_collect for i=0 to array.size(scores)-1 if not na(array.get(scores, i)) array.push(distribution, array.get(scores, i)) distribution should_hide_candles(hide_0, session_0, hide_1, session_1, hide_2, session_2) => bool is_hide = false if (hide_0 and not na(time(timeframe.period, session_0))) or (hide_1 and not na(time(timeframe.period, session_1))) or (hide_2 and not na(time(timeframe.period, session_2))) is_hide := true is_hide should_collect_samples(use_start_date, start_date, use_end_date, end_date) => var bool is_collect = false if (time >= start_date and use_start_date) or not use_start_date is_collect := true if is_collect and (time >= end_date and use_end_date) is_collect := false is_collect zero_array_nans(a) => if array.size(a) > 0 for i=0 to array.size(a)-1 array.set(a, i, nz(array.get(a, i))) a calc_sma(v0, v1, length) => delta = v0 - v1 float sma = delta / length + v1 calc_ema(v0, v1, length) => var alpha = 2 / (length + 1) float ema = alpha * v0 + (1 - alpha) * v1 calc_rma(v0, v1, length) => var alpha = 1 / length float rma = alpha * v0 + (1 - alpha) * v1 calc_wma(v0, v1, length) => float wma = ((length-1) * v1 + length * v0) / length smooth_operator(is_smooth, values, value_mean, smooth_method, smooth_length) => smoothed_values = values if is_smooth rolling_mean = switch smooth_method "SMA" => ta.sma(value_mean, smooth_length-1) "EMA" => ta.ema(value_mean, smooth_length-1) "SMMA (RMA)" => ta.rma(value_mean, smooth_length-1) "WMA" => ta.wma(value_mean, smooth_length-1) smoothed_values := array.new_float(0) for i=0 to array.size(values)-1 switch smooth_method "SMA" => array.push(smoothed_values, calc_sma(array.get(values, i), rolling_mean, smooth_length)) "EMA" => array.push(smoothed_values, calc_ema(array.get(values, i), rolling_mean, smooth_length)) "SMMA (RMA)" => array.push(smoothed_values, calc_rma(array.get(values, i), rolling_mean, smooth_length)) "WMA" => array.push(smoothed_values, calc_wma(array.get(values, i), rolling_mean, smooth_length)) smoothed_values input_validation(sample_tf, window_tf, chart_tf, cycle_tf, use_start_date, start_date, use_end_date, end_date, masses, physics_selection, physics_source) => sample_tf_mins = timeframe.in_seconds(sample_tf) / 60 window_tf_mins = timeframe.in_seconds(window_tf) / 60 chart_tf_mins = timeframe.in_seconds(timeframe.period) / 60 cycle_tf_mins = timeframe.in_seconds(cycle_tf) / 60 if window_tf_mins > cycle_tf_mins runtime.error(ERROR_PREFIX + "Sample time frame must be lower or equal to the cycle timeframe") else if cycle_tf_mins == timeframe.in_seconds("M") / 60 and window_tf_mins < timeframe.in_seconds("D") / 60 runtime.error(ERROR_PREFIX + "Sample time frame is too low for the cycle timeframe") else if cycle_tf_mins == timeframe.in_seconds("3M") / 60 and window_tf_mins < timeframe.in_seconds("W") / 60 runtime.error(ERROR_PREFIX + "Sample time frame is too low for the cycle timeframe") else if cycle_tf_mins == timeframe.in_seconds("12M") / 60 and window_tf_mins < timeframe.in_seconds("M") / 60 runtime.error(ERROR_PREFIX + "Sample time frame is too low for the cycle timeframe") if chart_tf_mins < sample_tf_mins runtime.error(ERROR_PREFIX + "Chart time frame is too low for sample time frame") if chart_tf_mins % sample_tf_mins != 0 runtime.error(ERROR_PREFIX + "Chart time frame should be evenly divisible by sample time frame") if use_start_date and start_date > timenow runtime.error(ERROR_PREFIX + "The Data Collection Start Date is in the future. Please taxi a time machine to start collecting that data") if use_start_date and use_end_date and end_date <= start_date runtime.error(ERROR_PREFIX + "The Data Collection Start Date is at or after the End Date. Did Bill and Ted take you for a ride again?") var float total_mass = 0 var bool has_mass = should_have_mass(physics_selection) if has_mass if array.size(masses) > 0 total_mass += array.sum(zero_array_nans(masses)) if barstate.islast and (total_mass == 0 or na(total_mass)) source = physics_source == '' ? syminfo.ticker : physics_source runtime.error("No volume is available from " + + source + " to calculate " + physics_selection) update_minmax(values, mins, maxs, index) => min = array.get(mins, index) max = array.get(maxs, index) if na(min) min := array.get(values, 0) if na(max) max := array.get(values, 0) for i=0 to array.size(values)-1 v = array.get(values, i) if v < min min := v if v > max max := v array.set(mins, index, min) array.set(maxs, index, max) sample_tf_mins = timeframe.in_seconds(sample_tf) / 60 window_tf_mins = timeframe.in_seconds(window_tf) / 60 chart_tf_mins = timeframe.in_seconds(timeframe.period) / 60 cycle_tf_mins = timeframe.in_seconds(cycle_tf) / 60 scale_factor = (chart_tf_mins / sample_tf_mins) num_indices = math.ceil((cycle_tf_mins / window_tf_mins)) + 1 var int[] sample_counts = array.new_int(num_indices, 0) var float[] seg_counts = array.new_float(num_indices, na) var float[] seg_means = array.new_float(num_indices, na) var float[] seg_stdevs = array.new_float(num_indices, na) var float[] score_counts = array.new_float(num_indices, na) var float[] score_means = array.new_float(num_indices, na) var float[] score_stdevs = array.new_float(num_indices, na) var float[] score_min = array.new_float(num_indices, na) var float[] score_max = array.new_float(num_indices, na) [masses, motions, mtimes] = request.security_lower_tf( physics_source == '' ? chart_ticker: str.contains(physics_source, '-') or str.contains(physics_source, '+') or str.contains(physics_source, '*') or str.contains(physics_source, '/') ? physics_source : value_ticker , sample_tf, get_physics(mass_selection, physics_selection)) // Ironically, the sum of lower timeframe volumes from security_lower_tf // is not equal ot the real-time volume so a separate request is needed [mass, motion, _] = request.security( physics_source == '' ? chart_ticker: str.contains(physics_source, '-') or str.contains(physics_source, '+') or str.contains(physics_source, '*') or str.contains(physics_source, '/') ? physics_source : value_ticker , timeframe.period, get_physics(mass_selection, physics_selection)) input_validation(sample_tf, window_tf, timeframe.period, cycle_tf, use_start_date, start_date, use_end_date, end_date, masses, physics_selection, physics_source) [highs, lows, hltimes] = request.security_lower_tf( price_source == '' ? chart_ticker: str.contains(price_source, '-') or str.contains(price_source, '+') or str.contains(price_source, '*') or str.contains(price_source, '/') ? price_source : price_ticker, sample_tf, [high, low, time]) is_hide = should_hide_candles( hide_0, session_0, hide_1, session_1, hide_2, session_2) is_collect = should_collect_samples( use_start_date, start_date, use_end_date, end_date) first_index = get_index(time, cycle_tf, window_tf) last_index = get_index(time_close-1, cycle_tf, window_tf) normalize(value, min, max) => v = value < min ? min : value v := value > max ? max : v float norm = (v - min) / (max - min) norm var prev_index = 0 float[] scores = array.new_float(res, na) int[] counts = array.new_int(res, 0) var float plot_min_score = 0 var float plot_max_score = 0 var float[] distribution = na for index=first_index to last_index float[] index_masses = array.new_float(0) float[] index_motions = array.new_float(0) float[] index_highs = array.new_float(0) float[] index_lows = array.new_float(0) if array.size(masses) > 0 and array.size(masses) == array.size(lows) for i=0 to array.size(masses)-1 if index == get_index(array.get(mtimes, i), cycle_tf, window_tf) and index == get_index(array.get(hltimes, i), cycle_tf, window_tf) array.push(index_masses, array.get(masses, i)) array.push(index_motions, array.get(motions, i)) array.push(index_highs, array.get(highs, i)) array.push(index_lows, array.get(lows, i)) array.set(sample_counts, index, array.get(sample_counts, index) + array.size(index_masses)) segment_values = get_segment_values( array.size(index_masses) > 0, mass, index_masses, index_motions, index_lows, index_highs, sample_tf, res, mass_selection, physics_selection) if dist_type == 'Log-Normal' segment_values := linears_to_logs(segment_values) index_change = false if index != prev_index index_change := true update_stats( is_collect, segment_values, index, prev_index, num_indices, index_change, seg_counts, seg_means, seg_stdevs) index_scores = get_scores( not is_hide and array.size(index_masses) > 0, segment_values, index_lows, index_highs, res, array.get(seg_means, index), array.get(seg_stdevs, index), norm_type, gamma) distribution := collect_distribution( is_plot and is_collect and array.size(masses) > 0 and index == plot_index, index_scores) update_stats( not is_hide, index_scores, index, prev_index, num_indices, index_change, score_counts, score_means, score_stdevs) if is_auto_norm [mi, mx] = auto_norm( array.get(score_means, index), array.get(score_stdevs, index), min_auto, max_auto) min_score := mi max_score := mx if index == plot_index plot_min_score := min_score plot_max_score := max_score for i=0 to array.size(scores)-1 index_score = array.get(index_scores, i) score = array.get(scores, i) if not na(index_score) and na(score) norm = normalize(index_score, min_score, max_score) array.set(counts, i, 1) array.set(scores, i, norm) else if not na(index_score) and not na(score) norm = normalize(index_score, min_score, max_score) [c, m] = update_mean(array.get(counts, i), score, norm) array.set(counts, i, c) array.set(scores, i, m) prev_index := index score_mean = array.avg(scores) for i=0 to array.size(scores)-1 if na(array.get(scores, i)) array.set(scores, i, 0) print_statistics( is_print_stats and not is_hide, scores, first_index, num_indices, cycle_tf, array.get(score_means, first_index), array.get(score_stdevs, first_index), array.get(sample_counts, first_index), array.get(score_counts, first_index), print_color) print_windows( is_print_windows and not is_hide, first_index, num_indices, cycle_tf, print_color) label_sampling_start_date( array.sum(masses) and is_collect, print_color) plot_distribution( is_plot, distribution, plot_index, plot_color, plot_width, plot_height, plot_x_shift, plot_y_shift, score_means, score_stdevs, is_auto_norm, min_auto, max_auto, norm_type, dist_type, plot_min_score, plot_max_score) scores := smooth_operator( smooth_length > 1 and not is_hide and array.size(masses) > 0 and not na(score_mean[1]), scores, score_mean[1], smooth_method, smooth_length) if smooth_length > 1 and not is_hide and array.size(masses) > 0 score_mean := array.avg(scores) offset = ind_num * 8 shift = (shift_percent/100)*close [o0, h0, l0, c0] = get_bin_ohlc(0+offset, res, fat_wicks) plotcandle(is_hide or res < 1 ? na : o0+shift, h0+shift, l0+shift, c0+shift, color=get_candle_colors(scores, 0+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 0+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 0+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o1, h1, l1, c1] = get_bin_ohlc(1+offset, res, fat_wicks) plotcandle(is_hide or res < 2 ? na : o1+shift, h1+shift, l1+shift, c1+shift, color=get_candle_colors(scores, 1+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 1+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 1+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o2, h2, l2, c2] = get_bin_ohlc(2+offset, res, fat_wicks) plotcandle(is_hide or res < 3 ? na : o2+shift, h2+shift, l2+shift, c2+shift, color=get_candle_colors(scores, 2+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 2+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 2+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o3, h3, l3, c3] = get_bin_ohlc(3+offset, res, fat_wicks) plotcandle(is_hide or res < 4 ? na : o3+shift, h3+shift, l3+shift, c3+shift, color=get_candle_colors(scores, 3+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 3+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 3+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o4, h4, l4, c4] = get_bin_ohlc(4+offset, res, fat_wicks) plotcandle(is_hide or res < 5 ? na : o4+shift, h4+shift, l4+shift, c4+shift, color=get_candle_colors(scores, 4+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 4+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 4+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o5, h5, l5, c5] = get_bin_ohlc(5+offset, res, fat_wicks) plotcandle(is_hide or res < 6 ? na : o5+shift, h5+shift, l5+shift, c5+shift, color=get_candle_colors(scores, 5+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 5+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 5+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o6, h6, l6, c6] = get_bin_ohlc(6+offset, res, fat_wicks) plotcandle(is_hide or res < 7 ? na : o6+shift, h6+shift, l6+shift, c6+shift, color=get_candle_colors(scores, 6+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 6+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 6+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) [o7, h7, l7, c7] = get_bin_ohlc(7+offset, res, fat_wicks) plotcandle(is_hide or res < 8 ? na : o7+shift, h7+shift, l7+shift, c7+shift, color=get_candle_colors(scores, 7+offset, res, fat_wicks, close_based, 0, 1, min_body_color_up, min_body_color_dn, max_body_color_up, max_body_color_dn, min_tail_color_up, min_tail_color_dn, max_tail_color_up, max_tail_color_dn), wickcolor=get_wick_color(scores, 7+offset, res, fat_wicks, close_based, 0, 1, min_wick_color_up, min_wick_color_dn, max_wick_color_up, max_wick_color_dn), bordercolor=get_border_color(scores, 7+offset, res, fat_wicks, close_based, 0, 1, min_border_color_up, min_border_color_dn, max_border_color_up, max_border_color_dn), display=display.all - display.price_scale, editable=false) // skeletor candle plotcandle(is_hide ? na : open_+shift, high_+shift, low_+shift, close_+shift, color=EMPTY_COLOR, wickcolor=ind_num == 0 ? updn_color(score_mean, 0, 1, min_outline_wick_color_dn, max_outline_wick_color_dn, min_outline_wick_color_up, max_outline_wick_color_up, close_based): EMPTY_COLOR, bordercolor=ind_num == 0 ? updn_color(score_mean, 0, 1, min_outline_body_color_dn, max_outline_body_color_dn, min_outline_body_color_up, max_outline_body_color_up, close_based) : EMPTY_COLOR, display=display.all - display.price_scale, editable=false)
[MAD] almost RSI
https://www.tradingview.com/script/Tqze749W-MAD-almost-RSI/
djmad
https://www.tradingview.com/u/djmad/
200
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/ // © djmad //@version=5 indicator('[MAD MBS] almost RSI', shorttitle='[MAD MBS] almost RSI', format=format.price, precision=2) // Inputs { int n1 = input.int(10, 'RSI Length') string TF = input.timeframe('', 'Timeframe 1') float POWFACTOR = input.float(1.0, "POW - Faktor",group="Wave compression", tooltip='0 < compress < 1 < expand < 10',step=0.1) bool triggersignal_use_avg = input(false, 'Activate Smoothing',group="final averaging") int sma = input.int(20, 'sma',group="final averaging",inline='1a') int ema = input.int(5, 'ema',group="final averaging",inline='1a', tooltip='disabled with "1"') float obLevel1 = input.float(30, 'Over Bought Level',group='Triggerlines') float osLevel1 = input.float(-30, 'Over Sold Level',group='Triggerlines') string Alertmode = input.string('ChangeDir-Outside', title='Alert mode', options=['Outside', 'CrossIn', 'CrossOut', 'ChangeDir-All','ChangeDir-Outside'],group='Triggerlines',inline='00a') bool showalerts_L1 = input.bool(true,'Show Alerts') //} ////////// GET AND MAP ALL DATA //////////////// //The code calculates the relative strength index (RSI) of a security in //TradingView and processes the data to obtain a modified version of the RSI for //further analysis. The modified RSI is either the average of the RSI over a //specified period of time, or the RSI itself, depending on the value of the "triggersignal_use_avg" input. // Get RSI { f_rsi(_src, _n1) => rsi = ta.rsi(_src, _n1) rsi rsi_TF1 = request.security(syminfo.tickerid, TF,f_rsi(close, n1), barmerge.gaps_on, barmerge.lookahead_off) // } // compression and sloothing { rsi_mtf = (rsi_TF1 -50) > 0 ? math.pow(rsi_TF1 -50,POWFACTOR) : - math.pow(math.abs(rsi_TF1 -50),POWFACTOR) rsi_mtf_average = ta.ema(ta.sma(rsi_mtf, sma), ema) rsi_work = triggersignal_use_avg ? rsi_mtf_average : rsi_mtf // } // Alarms { var signalout = 0 bool signal_buy = na, bool signal_sell = na if Alertmode == 'CrossIn' signal_buy := ta.crossover(rsi_work, osLevel1) signal_sell := ta.crossunder(rsi_work, obLevel1) if Alertmode == 'CrossOut' signal_buy := ta.crossunder(rsi_work, osLevel1) signal_sell := ta.crossover(rsi_work, obLevel1) if Alertmode == 'ChangeDir-Outside' signal_buy := rsi_work[5] > rsi_work[4] and rsi_work[4] > rsi_work[3] and rsi_work[3] > rsi_work[2] and rsi_work[2] > rsi_work[1] and rsi_work[1] < rsi_work[0] and rsi_work < osLevel1 signal_sell := rsi_work[5] < rsi_work[4] and rsi_work[4] < rsi_work[3] and rsi_work[3] < rsi_work[2] and rsi_work[2] < rsi_work[1] and rsi_work[1] > rsi_work[0] and rsi_work > obLevel1 if Alertmode == 'ChangeDir-All' signal_buy := rsi_work[5] > rsi_work[4] and rsi_work[4] > rsi_work[3] and rsi_work[3] > rsi_work[2] and rsi_work[2] > rsi_work[1] and rsi_work[1] < rsi_work[0] signal_sell := rsi_work[5] < rsi_work[4] and rsi_work[4] < rsi_work[3] and rsi_work[3] < rsi_work[2] and rsi_work[2] < rsi_work[1] and rsi_work[1] > rsi_work[0] filter_sell = (rsi_work) > obLevel1 filter_buy = (rsi_work) < osLevel1 // } // plotting all the data { trl = plot(rsi_work, 'Triggerline', color=color.new(color.yellow, 0)) hline(0, title='Middle Level', linestyle=hline.style_dotted, color=#606060) osl = plot(osLevel1, 'Oversell-Line', color=color.gray) obl = plot(obLevel1, 'Overbuy-Line', color=color.gray) fill(osl, trl, color=(rsi_work) < osLevel1 ? color.new(color.green, 40) : na) fill(obl, trl, color=(rsi_work) > obLevel1 ? color.new(color.red, 40) : na) plotshape(showalerts_L1? signal_buy? rsi_work+rsi_work*0.6: na :na, style=shape.triangleup, location=location.absolute, color=color.new(#44ff44, 0), size=size.small) plotshape(showalerts_L1? signal_sell? rsi_work+rsi_work*0.6: na :na, style=shape.triangledown, location=location.absolute, color=color.new(#ff4444, 0), size=size.small) //} //*** MULTIBIT Inputs ***{ string inputtype = input.string("NoInput" , title="Signal Type", group='Signal transmission config', options=["MultiBit", "MultiBit_pass", "NoInput"], tooltip='Multibit Daisychain with and without infusing\nMutlibit is the Signal-Type used in my Backtestsystem',inline='3a') float inputModule = input(title='Select L1 Indicator Signal', group='Signal transmission config', defval=close, inline='3a') int Signal_Channel_1 = input.int(2, "Channel long trend", minval=-1, maxval=15,group='Signal transmission config',inline='1a') int Signal_Channel_2 = input.int(3, "Channel short trend", minval=-1, maxval=15,group='Signal transmission config',inline='1a') int Signal_Channel_3 = input.int(4, "Channel long signal", minval=-1, maxval=15,group='Signal transmission config',inline='2a') int Signal_Channel_4 = input.int(5, "Channel short signal", minval=-1, maxval=15,group='Signal transmission config',inline='2a') // } //*** MULTIBIT LIBARY AND INFUSE *** { import djmad/Signal_transcoder_library/7 as transcode bool [] Multibit = array.new<bool>(16,false) if inputtype == "MultiBit" or inputtype == "MultiBit_pass" Multibit := transcode._16bit_decode(inputModule) if inputtype != "MultiBit_pass" transcode.f_infuse_signal(Signal_Channel_1, filter_buy, Signal_Channel_2, filter_sell, Signal_Channel_3, signal_buy, Signal_Channel_4, signal_sell, Multibit) float plot_output = transcode._16bit_encode(Multibit) plot(plot_output,title='MultiBit Signal',display=display.none) // }
Candlestick OB Finder
https://www.tradingview.com/script/sFIN2FEz-Candlestick-OB-Finder/
simwai
https://www.tradingview.com/u/simwai/
114
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © simwai //@version=5 indicator(title='Candlestick OB Finder', overlay=true) bool isReverted = input.bool(false, 'Is logic reverted?') bool isCurrentBarGreen = open[1] < close[1] bool isCurrentBarRed = open[1] > close[1] bool isLastBarGreen = open[2] < close[2] bool isLastBarRed = open[2] > close[2] float currentGreenBarBody = close[1] - open[1] float currentRedBarBody = open[1] - close[1] float lastGreenBarBody = close[2] - open[2] float lastRedBarBody = open[2] - close[2] bool shortPlotCondition = isReverted ? (isLastBarRed and isCurrentBarGreen) and (currentGreenBarBody > (4 * lastRedBarBody)) : (isLastBarGreen and isCurrentBarRed) and (currentGreenBarBody < (4 * lastRedBarBody)) plotshape(shortPlotCondition, color=color.orange, location=location.abovebar, style=shape.circle) bool longPlotCondition = isReverted ? (isLastBarGreen and isCurrentBarRed) and (currentGreenBarBody < (4 * lastRedBarBody)) : (isLastBarRed and isCurrentBarGreen) and (currentGreenBarBody > (4 * lastRedBarBody)) plotshape(longPlotCondition, color=color.lime, location=location.belowbar, style=shape.circle)
ICT - GAPs and Volume Imbalance
https://www.tradingview.com/script/MDxlrsRo-ICT-GAPs-and-Volume-Imbalance/
Vulnerable_human_x
https://www.tradingview.com/u/Vulnerable_human_x/
1,052
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/ // © Vulnerable_human_x //@version=5 indicator("ICT - GAPS, BPR, Volume & Price Imbalance", shorttitle = "ICT - Imbalances [VHX]", overlay=true) //Volume Imbalance showbullvi = input.bool(true, "Show Bullish Volume Imbalance", group="Volume Imbalance") showbearvi = input.bool(true, "Show Bearish Volume Imbalance", group="Volume Imbalance") bullimbalance = input.color(color.new(#00e640,90), "Bullish VI Color", group="Volume Imbalance", inline="1") bearimbalance = input.color(color.new(#e30000,90), "Bearish VI Color", group="Volume Imbalance", inline="1") viMaxBoxSet = input.int(defval=5, title='Maximum Box Displayed', minval=1, maxval=100, group="Volume Imbalance", tooltip='Minimum = 1, Maximum = 100') vimitigationtype = input.string(defval="Engulf", title="VI Mitigation Type", options = ["Engulf","Mitigate"], group="Volume Imbalance", tooltip = "Body close below Bullish VI and above Bearish VI required for Engulf Mitigation Type") extendvibox = input.bool(true, title="Extend Unmitigated VI Boxes", group="Volume Imbalance") extendallvis = input.bool(false,title="Extend all VI Boxes", group="Volume Imbalance") //Gaps showgaps = input.bool(true, "Show Gaps in Price", group="GAP") gapcolor = input.color(color.new(#4ec1f7, 90), "GAP Color", group="GAP") gapsMaxBoxSet = input.int(defval=7, title='Maximum Box Displayed', minval=1, maxval=100, group="GAP", tooltip='Minimum = 1, Maximum = 100') gapmitigationtype = input.string(defval="C.E.", title="GAP Mitigation Type", options = ["Engulf","C.E."], group="GAP", tooltip = "Body close abov/below a GAP is required for Engulf Mitigation Type. 50% mitigation required Consequent Encroachment Type.") extendgapbox = input.bool(true, title="Extend Unmitigated GAP Boxes", group="GAP") //FVG and BPR plotFVG = input.bool(true, "FVG BOX", inline="18", group="FVG/BPR") plotBPR = input.bool(false, "BPR BOX", inline="18", group="FVG/BPR") showifvg = input.bool(true,"I.FVG", inline="18", group="FVG/BPR") fvgBullColor = input.color(defval=color.new(color.green, 90), title='Bullish FVG',inline="1", group="FVG/BPR") fvgBearColor = input.color(defval=color.new(color.red, 90), title='Bearish FVG',inline="1", group="FVG/BPR") bprBullColor = input.color(defval=color.new(color.green, 90), title='Bullish BPR',inline="2", group="FVG/BPR") bprBearColor = input.color(defval=color.new(color.red, 90), title='Bearish BPR',inline="2", group="FVG/BPR") ifvgBullColor = input.color(defval=color.new(color.green, 90), title='Bullish I.FVG',inline="3", group="FVG/BPR") ifvgBearColor = input.color(defval=color.new(color.red, 90), title='Bearish I.FVG',inline="3", group="FVG/BPR") var float bprprecision = input.float(0.00005,"BPR Precision",step=0.00001, group="FVG/BPR") fvgMaxBoxSet = input.int(defval=10, title='Maximum Box Displayed', minval=1, maxval=100, group="FVG/BPR", tooltip='Minimum = 1, Maximum = 100') fvgmitigationtype = input.string(defval="Engulf", title="FVG Mitigation", options = ["Engulf","Mitigate"], group="FVG/BPR", tooltip = "Body close below Bullish FVG and above Bearish FVG required for Engulf Mitigation Type") cefvg = input.bool(false,title="C.E. FVG", group="FVG/BPR") cetransparency = input.int(50,title="C.E. Transparency", group="FVG/BPR") extendfvgbox = input.bool(true, title="Extend Unmitigated FVG/BPR Boxes", group="FVG/BPR") //Box Styling BoxBorder = input.string(defval=line.style_solid, title='Box Border Style', options=[line.style_dashed, line.style_dotted, line.style_solid], group="Box Style", tooltip='To disable border, set Border Width below to 0') BorderTransparency = input.int(defval=85, title='Border Box Transparency', minval=0, maxval=100, group="Box Style") Highlightboxtransparancy = input.int(75, "Highlight Box BG", group="Box Style", tooltip = "Highlight box background color when price is inside the box") Highlightboxbordertransparancy = input.int(50, "Highlight Box Border", group="Box Style", tooltip = "Highlight box Border color when price is inside the box") plotBoxLabel = input.bool(defval=true, title='Plot Label', group="Box Style") BoxLabelSize = input.string(defval=size.tiny, title="Label Size", options=[size.huge, size.large, size.small, size.tiny, size.auto, size.normal], group="Box Style") BoxLabelColor = input.color(defval=color.rgb(161, 163, 171), title='Label Color', group="Box Style") filterMitBOX = input.bool(defval=true, title='Mitigated Box Color', group="Mitigated Box Style") mitBOXColor = input.color(defval=color.new(color.gray, 85), title='Mitigated Box Color', group="Mitigated Box Style", tooltip='Set Transparency to 0 to make mitigated Boxes disappear') MitBoxLabelColor = input.color(defval=color.rgb(161, 163, 171, 70), title='Mitigated Box Label Color', group="Mitigated Box Style") var bool buifvgtouch = false var bool beifvgtouch = false var bool bufvgtouch = false var bool befvgtouch = false var bool buvitouch = false var bool bevitouch = false var bool bugaptouch = false var bool begaptouch = false var int _fvg = 2 var int _vi = 3 //Box Labels var string _fvgLabel = "FVG" var string _plus = "+" var string _minus = "-" var string _empty = "" var string _bprLabel = "BPR" var box[] _bearBoxesFVG = array.new_box() var box[] _bullBoxesFVG = array.new_box() var box[] _gapsboxesbu = array.new_box() var box[] _gapsboxesbe = array.new_box() var box[] _bullishvi = array.new_box() var box[] _bearishvi = array.new_box() var box[] _bullishifvg = array.new_box() var box[] _bearishifvg = array.new_box() var line[] _bufvgce = array.new_line() var line[] _befvgce = array.new_line() _controlBox(_boxes, _high, _low, _type) => if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if (filterMitBOX and _type == _fvg) if na or (bar_index == _boxRight and not((_high > _boxLow and _low < _boxLow) or (_high > _boxHigh and _low < _boxHigh))) box.set_right(_box, bar_index + 1) else if _type == _fvg box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) else if na or (bar_index == _boxRight and not((_high > _boxLow and _low < _boxLow) or (_high > _boxHigh and _low < _boxHigh))) box.set_right(_box, bar_index + 1) _controlBox2(_boxes, _high, _low, _type) => if array.size(_boxes) > 0 for i = array.size(_boxes) - 1 to 0 by 1 _box = array.get(_boxes, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if extendallvis box.set_right(_box, bar_index + 1) //Volume Imbalance isBuVI(index) => (open[index] > close[index+1] and low[index] <= high[index+1] and close[index] > close[index+1] and open[index] > open[index+1]) isBeVI(index) => (open[index] < close[index+1] and open[index] < open[index+1] and high[index] >= low[index+1] and close[index] < close[index+1] and close[index] < open[index+1]) //Bullish Volume Imbalance if showbullvi and isBuVI(0) box _bullboxVI = na _bullboxVI := box.new(left=bar_index-1, top=math.min(open,close), right=bar_index+1, bottom=math.max(close[1],open[1]), bgcolor=bullimbalance,border_style=BoxBorder, border_color=color.new(bullimbalance,BorderTransparency), text=plotBoxLabel?"VI+":na, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) if array.size(_bullishvi) > viMaxBoxSet box.delete(array.shift(_bullishvi)) array.push(_bullishvi, _bullboxVI) //Bearish Volume Imbalance if showbearvi and isBeVI(0) box _bearboxVI = na _bearboxVI := box.new(left=bar_index-1, top=math.min(close[1],open[1]), right=bar_index+1, bottom=math.max(open,close), bgcolor=bearimbalance,border_style=BoxBorder, border_color=color.new(bearimbalance,BorderTransparency),text=plotBoxLabel?"VI-":na, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) if array.size(_bearishvi) > viMaxBoxSet box.delete(array.shift(_bearishvi)) array.push(_bearishvi, _bearboxVI) _controlBox2(_bullishvi,high,low,_fvg) _controlBox2(_bearishvi,high,low,_fvg) //Gap if (showgaps and high[1] < low) or (showgaps and low[1] > high) box _gapsbu = na box _gapsbe = na if high[1] < low _gapsbu := box.new(left=bar_index-1, top=math.min(open,close), right=bar_index+1, bottom=math.max(open[1],close[1]), bgcolor=gapcolor, border_color=color.new(gapcolor,BorderTransparency), text=plotBoxLabel?"GAP+":na,border_style=BoxBorder, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) else if low[1] > high _gapsbe := box.new(left=bar_index-1, top=math.min(open[1],close[1]), right=bar_index+1, bottom=math.max(open,close), bgcolor=gapcolor, border_color=color.new(gapcolor,BorderTransparency), text=plotBoxLabel?"GAP-":na,border_style=BoxBorder, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) if array.size(_gapsboxesbu) > gapsMaxBoxSet box.delete(array.shift(_gapsboxesbu)) array.push(_gapsboxesbu, _gapsbu) if array.size(_gapsboxesbe) > gapsMaxBoxSet box.delete(array.shift(_gapsboxesbe)) array.push(_gapsboxesbe, _gapsbe) //fvg isFvgUp(index) => (low[index] > high[index + 2] and low[index + 1] <= high[index + 2] and high[index + 1] >= low[index]) isFvgDown(index) => (high[index] < low[index + 2] and high[index] >= low[index + 1] and high[index +1] >= low[index +2]) //Balanced Price Range isbprdown (index) => low[index + 3] > high[index] and low[index + 3] < low[index + 2] and low[index + 3] < close[index + 3] and high[index + 2] >= close[index + 2] and high[index + 1] <= ((open[index + 1]) + (open[index + 1] * bprprecision)) and (low[index + 2] >= ((open[index + 2]) - (open[index + 2] * bprprecision)) or low[index + 2] >= ((close[index + 2]) - (close[index + 2] * bprprecision))) isbprup (index) => high[index + 3] < low[index] and high[index + 3] > high[index + 2] and high[index + 3] > close[index + 3] and low[index + 2] <= close[index + 2] and low[index + 1] >= ((open[index + 1]) - (open[index + 1] * bprprecision)) and (high[index + 2] <= ((open[index + 2]) + (open[index + 2] * bprprecision)) or high[index + 2] <= ((close[index + 2]) + (close[index + 2] * bprprecision))) //Bullish FVG Box Plotting if isbprup(0) and isFvgUp(0) box _bullboxFVG = na line _buline = na if plotBPR _bullboxFVG := box.new(left=bar_index-3, top=low[0], right=bar_index, bottom=high[3], bgcolor=bprBullColor, border_color=color.new(bprBullColor,BorderTransparency), border_style=BoxBorder, border_width=1, text=plotBoxLabel ? _bprLabel + _plus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) else if plotFVG _bullboxFVG := box.new(left=bar_index-2, top=low[0], right=bar_index, bottom=high[2], bgcolor=fvgBullColor, border_color=color.new(fvgBullColor,BorderTransparency), border_style=BoxBorder, border_width=1, text=plotBoxLabel ? _fvgLabel + _plus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) _buline := cefvg?line.new(bar_index-2,math.avg(low,high[2]),bar_index,math.avg(low,high[2]),color=color.new(fvgBullColor,cetransparency)):na if array.size(_bullBoxesFVG) > fvgMaxBoxSet and array.size(_bufvgce) > fvgMaxBoxSet box.delete(array.shift(_bullBoxesFVG)) line.delete(array.shift(_bufvgce)) array.push(_bullBoxesFVG, _bullboxFVG) array.push(_bufvgce,_buline) else if isFvgUp(0) box _bullboxFVG = na line _buline = na if plotFVG _bullboxFVG := box.new(left=bar_index-2, top=low[0], right=bar_index, bottom=high[2], bgcolor=fvgBullColor, border_color=color.new(fvgBullColor,BorderTransparency), border_style=BoxBorder, border_width=1, text=plotBoxLabel ? _fvgLabel + _plus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) _buline := cefvg?line.new(bar_index-2,math.avg(low,high[2]),bar_index,math.avg(low,high[2]), color=color.new(fvgBullColor,cetransparency)):na if array.size(_bullBoxesFVG) > fvgMaxBoxSet and array.size(_bufvgce) > fvgMaxBoxSet box.delete(array.shift(_bullBoxesFVG)) line.delete(array.shift(_bufvgce)) array.push(_bullBoxesFVG, _bullboxFVG) array.push(_bufvgce,_buline) //Bearish FVG Box Plotting if isbprdown(0) and isFvgDown(0) box _bearboxFVG = na line _beline = na if plotBPR _bearboxFVG := box.new(left=bar_index-3, top=low[3], right=bar_index, bottom=high[0], bgcolor=bprBearColor, border_color=color.new(bprBearColor,BorderTransparency), border_style=BoxBorder, border_width=1, text=plotBoxLabel ? _bprLabel + _minus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) else if plotFVG _bearboxFVG := box.new(left=bar_index-2, top=low[2], right=bar_index, bottom=high[0], bgcolor=fvgBearColor, border_color=color.new(fvgBearColor,BorderTransparency), border_style=BoxBorder, border_width=1, text=plotBoxLabel ? _fvgLabel + _minus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) _beline := cefvg?line.new(bar_index-2,math.avg(low[2],high),bar_index,math.avg(low[2],high),color=color.new(fvgBearColor,cetransparency)):na if array.size(_bearBoxesFVG) > fvgMaxBoxSet and array.size(_befvgce) > fvgMaxBoxSet box.delete(array.shift(_bearBoxesFVG)) line.delete(array.shift(_befvgce)) array.push(_bearBoxesFVG, _bearboxFVG) array.push(_befvgce,_beline) else if isFvgDown(0) box _bearboxFVG = na line _beline = na if plotFVG _bearboxFVG := box.new(left=bar_index-2, top=low[2], right=bar_index, bottom=high[0], bgcolor=fvgBearColor, border_color=color.new(fvgBearColor,BorderTransparency), border_style=BoxBorder, border_width=1, text=plotBoxLabel ? _fvgLabel + _minus : _empty, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) _beline := cefvg?line.new(bar_index-2,math.avg(low[2],high),bar_index,math.avg(low[2],high),color=color.new(fvgBearColor,cetransparency)):na if array.size(_bearBoxesFVG) > fvgMaxBoxSet and array.size(_befvgce) > fvgMaxBoxSet box.delete(array.shift(_bearBoxesFVG)) line.delete(array.shift(_befvgce)) array.push(_bearBoxesFVG, _bearboxFVG) array.push(_befvgce,_beline) //-----BEARISH IMPLIED FAIR VALUE GAP---------------// isBeIFvg(index) => (low[index] < low[index+2] and high[index+2] > high[index] and high[index] >= low[index+2] and math.min(open[index+2],close[index+2]) - low[index+2] > (math.max(open[index+2],close[index+2]) - math.min(open[index+2],close[index+2]))/2 and high[index] - math.max(open[index],close[index]) > (math.max(open[index],close[index]) - math.min(open[index],close[index]))/2 and high[index] < high[index+1] and (math.min(open[index+2],close[index+2]) + low[index+2])/2 > (high[index] + math.max(open[index],close[index]))/2) //-----BULLISH IMPLIED FAIR VALUE GAP---------------// isBuIFvg(index) => (high[index] > high[index+2] and low[index+2] < low[index] and low[index] <= high[index+2] and high[index+2] - math.max(open[index+2],close[index+2]) > (math.max(open[index+2],close[index+2]) - math.min(open[index+2],close[index+2]))/2 and math.min(open[index],close[index]) - low[index] > (math.max(open[index],close[index]) - math.min(open[index],close[index]))/2 and low[index] > low[index+1] and (high[2] + math.max(open[2],close[2]))/2 < (math.min(open,close) + low)/2) if isBeIFvg(0) and showifvg box _bearboxifvg = na _bearboxifvg := box.new(left=bar_index-2, top=(math.min(open[2],close[2]) + low[2])/2, right=bar_index+1, bottom=(math.max(open,close) + high)/2, bgcolor=ifvgBearColor,border_style=BoxBorder, border_color=color.new(ifvgBearColor,BorderTransparency),text=plotBoxLabel?"I.FVG-":na, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) if array.size(_bearishifvg) > fvgMaxBoxSet box.delete(array.shift(_bearishifvg)) array.push(_bearishifvg, _bearboxifvg) if isBuIFvg(0) and showifvg box _bullboxifvg = na _bullboxifvg := box.new(left=bar_index-2, top=(high[2] + math.max(open[2],close[2]))/2, right=bar_index+1, bottom=(math.min(open,close) + low)/2, bgcolor=ifvgBullColor,border_style=BoxBorder, border_color=color.new(ifvgBullColor,BorderTransparency),text=plotBoxLabel?"I.FVG+":na, text_halign=text.align_right, text_valign=text.align_bottom, text_size=BoxLabelSize, text_color=BoxLabelColor) if array.size(_bullishifvg) > fvgMaxBoxSet box.delete(array.shift(_bullishifvg)) array.push(_bullishifvg, _bullboxifvg) //-------IMPLIED FVG EXTEND - MITIGATION TYPE = ENGULF ----------- //ifvg boxes extend (bullish) if array.size(_bullishifvg) > 0 and array.size(_bufvgce) > 0 and extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Engulf" for i = array.size(_bullishifvg) - 1 to 0 by 1 _box = array.get(_bullishifvg, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if close < _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //ifvg boxes extend (bearish) if array.size(_bearishifvg) > 0 and extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Engulf" for i = array.size(_bearishifvg) - 1 to 0 by 1 _box = array.get(_bearishifvg, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if close > _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) // ifvg box border animation (bullish) if array.size(_bullishifvg) > 0 and extendfvgbox and fvgmitigationtype=="Engulf" for i = array.size(_bullishifvg) - 1 to 0 by 1 _box = array.get(_bullishifvg, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight and low < _boxHigh box.set_bgcolor(_box,color.new(ifvgBullColor,Highlightboxtransparancy)) box.set_border_color(_box,color.new(ifvgBullColor,Highlightboxbordertransparancy)) buifvgtouch := true // ifvg box border animation (bearish) if array.size(_bearishifvg) > 0 and extendfvgbox and fvgmitigationtype=="Engulf" for i = array.size(_bearishifvg) - 1 to 0 by 1 _box = array.get(_bearishifvg, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight and high > _boxLow box.set_bgcolor(_box,color.new(ifvgBearColor,Highlightboxtransparancy)) box.set_border_color(_box,color.new(ifvgBearColor,Highlightboxbordertransparancy)) beifvgtouch := true //-------IMPLIED FVG EXTEND - MITIGATION TYPE = MITIGATE ----------- if extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Mitigate" _controlBox(_bearishifvg, high, low, _fvg) _controlBox(_bullishifvg, high, low, _fvg) //-------FVG EXTEND - MITIGATION TYPE = ENGULF ----------- //Bullish FVG Extend if array.size(_bullBoxesFVG) > 0 and array.size(_bufvgce) > 0 and extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Engulf" for i = array.size(_bullBoxesFVG) - 1 to 0 by 1 _line = array.get(_bufvgce, i) _box = array.get(_bullBoxesFVG, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight box.set_right(_box, bar_index + 1) line.set_x2(_line, bar_index + 1) else if close < _boxLow and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) line.set_color(_line,mitBOXColor) //Bearish FVG Extend if array.size(_bearBoxesFVG) > 0 and array.size(_bufvgce) > 0 and extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Engulf" for i = array.size(_bearBoxesFVG) - 1 to 0 by 1 _line = array.get(_befvgce, i) _box = array.get(_bearBoxesFVG, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) line.set_x2(_line, bar_index + 1) else if close > _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) line.set_color(_line,mitBOXColor) //box border animation - FVG+ if array.size(_bullBoxesFVG) > 0 and extendfvgbox and fvgmitigationtype=="Engulf" for i = array.size(_bullBoxesFVG) - 1 to 0 by 1 _box = array.get(_bullBoxesFVG, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight and low < _boxHigh box.set_bgcolor(_box,color.new(fvgBullColor,Highlightboxtransparancy)) box.set_border_color(_box,color.new(fvgBullColor,Highlightboxbordertransparancy)) bufvgtouch := true //box border animation - FVG- if array.size(_bearBoxesFVG) > 0 and extendfvgbox and fvgmitigationtype=="Engulf" for i = array.size(_bearBoxesFVG) - 1 to 0 by 1 _box = array.get(_bearBoxesFVG, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight and high > _boxLow box.set_bgcolor(_box,color.new(fvgBearColor,Highlightboxtransparancy)) box.set_border_color(_box,color.new(fvgBearColor,Highlightboxbordertransparancy)) befvgtouch := true //-------FVG EXTEND - MITIGATION TYPE = MITIGATE ----------- //bullish FVG if array.size(_bullBoxesFVG) > 0 and array.size(_bufvgce) > 0 and extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Mitigate" for i = array.size(_bullBoxesFVG) - 1 to 0 by 1 _line = array.get(_bufvgce, i) _box = array.get(_bullBoxesFVG, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low >= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) line.set_x2(_line, bar_index + 1) else if low < _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) line.set_color(_line,mitBOXColor) //Bearish FVG if array.size(_bearBoxesFVG) > 0 and array.size(_befvgce) > 0 and extendfvgbox and barstate.isconfirmed and fvgmitigationtype=="Mitigate" for i = array.size(_bearBoxesFVG) - 1 to 0 by 1 _line = array.get(_befvgce, i) _box = array.get(_bearBoxesFVG, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if high <= _boxLow and bar_index == _boxRight box.set_right(_box, bar_index + 1) line.set_x2(_line, bar_index + 1) else if high > _boxLow and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) line.set_color(_line,mitBOXColor) //-------VI EXTEND - MITIGATION TYPE = ENGULF ----------- //bullish VI extend if array.size(_bullishvi) > 0 and extendvibox and barstate.isconfirmed and vimitigationtype=="Engulf" for i = array.size(_bullishvi) - 1 to 0 by 1 _box = array.get(_bullishvi, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if close < _boxLow and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //Bearish VI Extend if array.size(_bearishvi) > 0 and extendvibox and barstate.isconfirmed and vimitigationtype=="Engulf" for i = array.size(_bearishvi) - 1 to 0 by 1 _box = array.get(_bearishvi, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if close > _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //Vi Box Border Animation (bullish) if array.size(_bullishvi) > 0 and extendvibox and vimitigationtype=="Engulf" for i = array.size(_bullishvi) - 1 to 0 by 1 _box = array.get(_bullishvi, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight and low < _boxHigh box.set_bgcolor(_box,color.new(bullimbalance,Highlightboxtransparancy)) box.set_border_color(_box,color.new(bullimbalance,Highlightboxbordertransparancy)) buvitouch := true //Vi Box Border Animation (bearish) if array.size(_bearishvi) > 0 and extendvibox and vimitigationtype=="Engulf" for i = array.size(_bearishvi) - 1 to 0 by 1 _box = array.get(_bearishvi, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight and high > _boxLow box.set_bgcolor(_box,color.new(bearimbalance,Highlightboxtransparancy)) box.set_border_color(_box,color.new(bearimbalance,Highlightboxbordertransparancy)) bevitouch := true //-------VI EXTEND - MITIGATION TYPE = MITIGATE ----------- //bullish VI extend MITIGATION TYPE - MITIGATE if array.size(_bullishvi) > 0 and extendvibox and barstate.isconfirmed and vimitigationtype=="Mitigate" for i = array.size(_bullishvi) - 1 to 0 by 1 _box = array.get(_bullishvi, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low > _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if low <= _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //Bearish VI Extend MITIGATION TYPE MITIGATE if array.size(_bearishvi) > 0 and extendvibox and barstate.isconfirmed and vimitigationtype=="Mitigate" for i = array.size(_bearishvi) - 1 to 0 by 1 _box = array.get(_bearishvi, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if high < _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if high >= _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //-------GAP EXTEND - MITIGATION TYPE = C.E. ----------- //gap boxes extend (bullish) if array.size(_gapsboxesbu) > 0 and extendgapbox and barstate.isconfirmed and gapmitigationtype=="C.E." for i = array.size(_gapsboxesbu) - 1 to 0 by 1 _box = array.get(_gapsboxesbu, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if low > (_boxHigh+_boxLow)/2 and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if low <= (_boxHigh+_boxLow)/2 and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //gap boxes extend (bearish) if array.size(_gapsboxesbe) > 0 and extendgapbox and barstate.isconfirmed and gapmitigationtype=="C.E." for i = array.size(_gapsboxesbe) - 1 to 0 by 1 _box = array.get(_gapsboxesbe, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if high < (_boxHigh+_boxLow)/2 and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if high >= (_boxHigh+_boxLow)/2 and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //-------GAP EXTEND - MITIGATION TYPE = ENGULF ----------- //gap boxes extend (bullish) if array.size(_gapsboxesbu) > 0 and extendgapbox and barstate.isconfirmed and gapmitigationtype=="Engulf" for i = array.size(_gapsboxesbu) - 1 to 0 by 1 _box = array.get(_gapsboxesbu, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if close < _boxLow and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) //gap boxes extend (bearish) if array.size(_gapsboxesbe) > 0 and extendgapbox and barstate.isconfirmed and gapmitigationtype=="Engulf" for i = array.size(_gapsboxesbe) - 1 to 0 by 1 _box = array.get(_gapsboxesbe, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight box.set_right(_box, bar_index + 1) else if close > _boxHigh and bar_index == _boxRight and filterMitBOX box.set_bgcolor(_box, mitBOXColor) box.set_border_color(_box, mitBOXColor) box.set_text_color(_box,MitBoxLabelColor) // gap box border animation(bullish) if array.size(_gapsboxesbu) > 0 and extendgapbox and gapmitigationtype=="Engulf" for i = array.size(_gapsboxesbu) - 1 to 0 by 1 _box = array.get(_gapsboxesbu, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close >= _boxLow and bar_index == _boxRight and low < _boxHigh box.set_bgcolor(_box,color.new(gapcolor,Highlightboxtransparancy)) box.set_border_color(_box,color.new(gapcolor,Highlightboxbordertransparancy)) bugaptouch := true // gap box border animation (bearish) if array.size(_gapsboxesbe) > 0 and extendgapbox and gapmitigationtype=="Engulf" for i = array.size(_gapsboxesbe) - 1 to 0 by 1 _box = array.get(_gapsboxesbe, i) _boxLow = box.get_bottom(_box) _boxHigh = box.get_top(_box) _boxRight = box.get_right(_box) if close <= _boxHigh and bar_index == _boxRight and high > _boxLow box.set_bgcolor(_box,color.new(gapcolor,Highlightboxtransparancy)) box.set_border_color(_box,color.new(gapcolor,Highlightboxbordertransparancy)) begaptouch := true //---------ALERTS---------------- alertcondition(barstate.isconfirmed and isFvgUp(0) , title="FVG+", message="FVG+ : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and isFvgDown(0) , title="FVG-", message="FVG- : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and isBuIFvg(0) , title="I.FVG+", message="I.FVG+ : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and isBeIFvg(0) , title="I.FVG-", message="I.FVG- : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and open > close[1] and low <= high[1] and close > close[1] and open > open[1],title="VI+",message="VI+ : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and open < close[1] and open < open[1] and high >= low[1] and close < close[1] and close < open[1],title="VI-",message="VI- : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and high[1] < low,title="GAP+", message="GAP+ : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(barstate.isconfirmed and low[1] > high,title="GAP-", message="GAP- : {{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(bugaptouch, title="GAP(+) Mitigation", message="GAP(+) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(begaptouch, title="GAP(-) Mitigation", message="GAP(-) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(buifvgtouch, title="I.FVG(+) Mitigation", message="I.FVG(+) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(beifvgtouch, title="I.FVG(-) Mitigation", message="I.FVG(-) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(bufvgtouch, title="FVG(+) Mitigation", message="FVG(+) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(befvgtouch, title="FVG(-) Mitigation", message="FVG(-) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(buvitouch, title="VI(+) Mitigation", message="VI(+) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") alertcondition(bevitouch, title="VI(-) Mitigation", message="VI(-) Mitigated :{{exchange}}:{{ticker}} TIMEFRAME:{{interval}}") //end of script
RF+ Replay for Heikin Ashi
https://www.tradingview.com/script/uWitps3o-RF-Replay-for-Heikin-Ashi/
tvenn
https://www.tradingview.com/u/tvenn/
310
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/ // © tvenn //@version=5 indicator(title="RF+ Replay for Heikin Ashi", shorttitle="RF+ Replay", overlay = true, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400) //=Constants green = #95BD5F red = #EA1889 mocha = #C0A392 transp = color.new(#000000, 100) haTicker = ticker.heikinashi(syminfo.tickerid) initO = request.security(haTicker, timeframe.period, open) initC = request.security(haTicker, timeframe.period, close) initH = request.security(haTicker, timeframe.period, high) initL = request.security(haTicker, timeframe.period, low) haC = (open + high + low + close) / 4 haO = float(na) haO := na(haO[1]) ? (initO + initC) / 2 : (nz(initO[1]) + nz(initC[1])) / 2 haH = high haL = low useHAMode = input(true, title="Enable Heikin Ashi Mode", tooltip="Range filters and moving averages will be calculated using Heikin Ashi OHLC values when this is enabled.") showHACandles = input(true, title="Show Heikin Ashi Candles", tooltip="This will print HA candles onto your standard chart, to help backtest using the Tradingview replay mode using Heikin Ashi type candles while using realprice data.\n\nYou will need to hide your existing chart candles, so you don't see two sets of candles.\n\nThese settings can be found by clicking the settings Cog icon, or right-clicking on your chart and selecting 'Chart Settings' from the menu, then selecting the tab named 'Symbol' and unchecking 'Body', 'Borders' and 'Wick'. This can also then be saved as a template and applied to a layout.") showRangeFilters = input(true, title="Show Range Filters") enableMA = input(true, title="Show Moving Averages") enableMTFMA = input(false, title="Show MTF Moving Average levels") showRealPriceLine = input(false, title="Show Real Price Line", tooltip="This will show a real price line for use with Heikin Ashi candles.\n\nNOTE: this feature may lag slightly due to the large number of features. Consider using a standalone indicator such as 'Real Price Line + Dots (for Heikin Ashi), linked in my Tradingview profile.") plotrealclosedots = input(false, title="Show Real Price Close Dots") enableSessions = input(true, title="Show Sessions", tooltip="This simply toggles your sessions so you don't have to reselect all the options to turn your prefered sessions settings on and off.") showWatermark = input(true, title="Show Watermark") grp_HA = "Heikin Ashi candles" candleUpColor = input.color(#ffffff, title="", group=grp_HA, inline="2") candleDownColor = input.color(color.rgb(131, 131, 131), title="", group=grp_HA, inline="2") candleBodyEnabled = input(true, title="Body", group=grp_HA, inline="2") candleUpBorderColor = input.color(color.black, title="", group=grp_HA, inline="3") candleDownBorderColor = input.color(color.black, title="", group=grp_HA, inline="3") candleBorderEnabled = input(true, title="Border", group=grp_HA, inline="3") wickUpColor = input.color(color.rgb(110, 110, 110), title="", group=grp_HA, inline="4") wickDownColor = input.color(color.rgb(110, 110, 110), title="", group=grp_HA, inline="4") candleWickEnabled = input(true, title="Wick", group=grp_HA, inline="4") candleColor = haC >= haO and showHACandles and candleBodyEnabled ? candleUpColor : showHACandles and candleBodyEnabled ? candleDownColor : na candleBorderColor = haC >= haO and showHACandles and candleBorderEnabled ? candleUpBorderColor : showHACandles and candleBorderEnabled ? candleDownBorderColor : na candleWickColor = haC >= haO and showHACandles and candleWickEnabled ? wickUpColor : showHACandles and candleWickEnabled ? wickDownColor : na //=Moving averages //================================================================================================================================== ma(length, type) => if(useHAMode) switch type "SMA" => ta.sma(haC, length) "EMA" => ta.ema(haC, length) "SMMA (RMA)" => ta.rma(haC, length) "WMA" => ta.wma(haC, length) "VWMA" => ta.vwma(haC, length) else switch type "SMA" => ta.sma(close, length) "EMA" => ta.ema(close, length) "SMMA (RMA)" => ta.rma(close, length) "WMA" => ta.wma(close, length) "VWMA" => ta.vwma(close, length) grp_MA = "Moving averages" ma1color = input(color.new(color.orange, 40), title="", group=grp_MA, inline="1") lenMA1 = input(144, title="", group=grp_MA, inline="1") typeMA1 = input.string(title = "", defval = "EMA", options=["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"], group=grp_MA, inline="1") showma1 = input(true, title="Show", group=grp_MA, inline="1") ma2color = input(color.new(green, 40), title="", group=grp_MA, inline="2") lenMA2 = input(50, title="", group=grp_MA, inline="2") typeMA2 = input.string(title = "", defval = "EMA", options=["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"], group=grp_MA, inline="2") showma2 = input(false, title="Show", group=grp_MA, inline="2") ma3color = input(color.new(red, 40), title="", group=grp_MA, inline="3") lenMA3 = input(21, title="", group=grp_MA, inline="3") typeMA3 = input.string(title = "", defval = "EMA", options=["EMA", "SMA", "SMMA (RMA)", "WMA", "VWMA"], group=grp_MA, inline="3") showma3 = input(false, title="Show", group=grp_MA, inline="3") plot(enableMA and showma1 ? ma(lenMA1, typeMA1) : na, title="MA 1", color = ma1color, linewidth=2) plot(enableMA and showma2 ? ma(lenMA2, typeMA2) : na, title="MA 2", color = ma2color, linewidth=2) plot(enableMA and showma3 ? ma(lenMA3, typeMA3) : na, title="MA 3", color = ma3color, linewidth=2) priceCrossingMA1 = ta.crossover(ma(lenMA1, typeMA1), close) //=MTF MA settings //================================================================================================================================== grp_MTFMA = "MTF MA Settings" MTFMALen = input.int(144, title="", minval=2, maxval=200, step=1, group=grp_MTFMA, inline="0") MTFMAType = input.string("EMA", title="", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group=grp_MTFMA, inline="0") realPriceTicker = ticker.new(prefix=syminfo.prefix, ticker=syminfo.ticker) getTimeframe(timeframe) => switch timeframe "1 min" => "1" "2 min" => "2" "3 min" => "3" "5 min" => "5" "10 min" => "10" "15 min" => "15" // MTF MA #1 tf1LineColor = input.color(color.new(color.orange, 40), title="", group=grp_MTFMA, inline='1') tf1 = input.string("3 min", title="", options=["1 min", "2 min", "3 min", "5 min", "10 min", "15 min"], group=grp_MTFMA, inline='1') enableTF1 = input.bool(true, title='Show Level', group=grp_MTFMA, inline='1', tooltip="") // MTF MA #2 tf2LineColor = input.color(color.new(color.orange, 40), title="", group=grp_MTFMA, inline='2') tf2 = input.string("5 min", title="", options=["1 min", "2 min", "3 min", "5 min", "10 min", "15 min"], group=grp_MTFMA, inline='2') enableTF2 = input.bool(true, title='Show Level', group=grp_MTFMA, inline='2') // MTF MA #3 tf3LineColor = input.color(color.new(color.orange, 40), title='', group=grp_MTFMA, inline='3') tf3 = input.string("15 min", title='', options=["1 min", "2 min", "3 min", "5 min", "10 min", "15 min"], group=grp_MTFMA, inline='3') enableTF3 = input.bool(true, title='Show Level', group=grp_MTFMA, inline='3') mtf1MA = request.security(symbol=realPriceTicker, timeframe=getTimeframe(tf1), expression=ma(MTFMALen, MTFMAType), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off) mtf2MA = request.security(symbol=realPriceTicker, timeframe=getTimeframe(tf2), expression=ma(MTFMALen, MTFMAType), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off) mtf3MA = request.security(symbol=realPriceTicker, timeframe=getTimeframe(tf3), expression=ma(MTFMALen, MTFMAType), lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off) mtfMATextColor = input.color(color.new(color.orange, 70), title="", group=grp_MTFMA, inline="4") showTFLabel = input.bool(true, title='Show Timeframe Labels', group=grp_MTFMA, inline="4") if (enableMTFMA and enableTF1) mtf1MALine = line.new(x1=bar_index, x2=bar_index + 10, y1=mtf1MA, y2=mtf1MA, extend=extend.right, style=line.style_dotted, color=tf1LineColor) line.delete(mtf1MALine[1]) if(showTFLabel) mtf1MALabel = label.new(x=(bar_index + 20), y=mtf1MA, style=label.style_label_down, text=tf1, color=na, textcolor=mtfMATextColor) label.delete(mtf1MALabel[1]) if(enableMTFMA and enableTF2) mtf2MALine = line.new(x1=bar_index, x2=bar_index + 10, y1=mtf2MA, y2=mtf2MA, extend=extend.right, style=line.style_dotted, color=tf2LineColor) line.delete(mtf2MALine[1]) if(showTFLabel) mtf2MALabel = label.new(x=(bar_index + 20), y=mtf2MA, style=label.style_label_down, text=tf2, color=na, textcolor=mtfMATextColor) label.delete(mtf2MALabel[1]) if(enableMTFMA and enableTF3) mtf3MALine = line.new(x1=bar_index, x2=bar_index + 10, y1=mtf3MA, y2=mtf3MA, extend=extend.right, style=line.style_dotted, color=tf3LineColor) line.delete(mtf3MALine[1]) if(showTFLabel) mtf3MALabel = label.new(x=(bar_index + 20), y=mtf3MA, style=label.style_label_down, text=tf3, color=na, textcolor=mtfMATextColor) label.delete(mtf3MALabel[1]) //=Real price line & real price close dots //================================================================================================================================== //Real price line and dot settings grp_RPHA = "Real price for Heikin Ashi candles" showRealPriceLinelinecolor = input(color.new(#41ffb0, 0), title="Real Price Line Color", group=grp_RPHA) realpricelinewidth = input.string("Thin", options=["Thin", "Thicc"], title="Real Price Line Width", group=grp_RPHA) realclosedotscolor = input(color.new(#41ffb0, 40), title="Real Price Close Dot Color", group=grp_RPHA) size = input.string("Auto", options=["Auto", "Tiny", "Small"], title="Real Price Close Dot Size", group=grp_RPHA) _realPriceLineWidth = switch realpricelinewidth "Thin" => 1 "Thicc" => 2 real_price = ticker.new(prefix=syminfo.prefix, ticker=syminfo.ticker) real_close = request.security(symbol=real_price, timeframe='', expression=close, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) if(showRealPriceLine) real_price_line = line.new(bar_index[1], real_close, bar_index, real_close, xloc.bar_index, extend.both, showRealPriceLinelinecolor, line.style_dotted, _realPriceLineWidth) line.delete(real_price_line[1]) //=Plot candles above MA and Below Range Filters //================================================================================================================================== plotcandle(haO, haH, haL, haC, color=candleColor, bordercolor=candleBorderColor, wickcolor=candleWickColor) //Show real price close dots above candles showrealpricemicrodotstiny = (plotrealclosedots and size=="Tiny" ? display.all : display.none) showrealpricemicrodotsauto = (plotrealclosedots and size=="Auto" ? display.all : display.none) showrealpricedotslarge = (plotrealclosedots and size=="Small" ? display.all : display.none) plotchar(series=real_close, title="Real close dots", location=location.absolute, color=realclosedotscolor, editable=false, char="•", size=size.tiny, display=showrealpricemicrodotstiny) plotchar(series=real_close, title="Real close dots", location=location.absolute, color=realclosedotscolor, editable=false, char="•", size=size.auto, display=showrealpricemicrodotsauto) plotshape(series=real_close, title="Real close dots", location=location.absolute, color=realclosedotscolor, editable=false, style=shape.circle, size=size.auto, display=showrealpricedotslarge) //=Range Filter settings //================================================================================================================================== //Range Filter #1 Settings grp_RF1 = "Range Filter #1 settings" rf1UpColor = input.color(color.new(#ffffff, 40), title="Range Filter 1 bullish color", group=grp_RF1) rf1DownColor = input.color(color.new(color.blue, 40), title="Range Filter 1 bearish color", group=grp_RF1) rf1LineWidth = input.int(1, minval=1, maxval=3, title="Range Filter 1 line width", group=grp_RF1) src1 = input(defval=hl2, title="Source", group=grp_RF1) per1 = input(defval=30, title="Sampling Period", group=grp_RF1) mult1 = input(defval=2.6, title="Range Multiplier", group=grp_RF1) //Range Filter #2 Settings grp_RF2 = "Range Filter #2 settings" rf2UpColor = input.color(color.new(#ffffff, 10), title="Range Filter 2 bullish color", group=grp_RF2) rf2DownColor = input.color(color.new(color.blue, 10), title="Range Filter 2 bearish color", group=grp_RF2) rf2LineWidth = input.int(2, minval=1, maxval=3, title="Range Filter 2 line width", group=grp_RF2) src2 = input(defval=ohlc4, title="Source", group=grp_RF2) per2 = input(defval=48, title="Sampling Period", group=grp_RF2) mult2 = input(defval=3.4, title="Range Multiplier", group=grp_RF2) sourceType(type, showHA) => if(useHAMode) switch type open => initO high => initH low => initL close => initC hl2 => ((initH + initL) / 2) hlc3 => (initH + initL + initC / 3) ohlc4 => ((initO + initH + initL + initC) / 4) hlcc4 => ((initH + initL + initC + initC) / 4) else if(useHAMode==false) switch type open => open high => high low => low close => close hl2 => hl2 hlc3 => hlc3 ohlc4 => ohlc4 hlcc4 => hlcc4 filterSrc1 = sourceType(src1, useHAMode) filterSrc2 = sourceType(src2, useHAMode) // Smooth average smoothrng(x, t, m) => wper = t * 2 - 1 avrng = ta.ema(math.abs(x - x[1]), t) smoothrng = ta.ema(avrng, wper) * m smoothrng smrng1 = smoothrng(filterSrc1, per1, mult1) smrng2 = smoothrng(filterSrc2, per2, mult2) // Range Filter calculation 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 filt1 = rngfilt(filterSrc1, smrng1) filt2 = rngfilt(filterSrc2, smrng2) //RF Filter direction upward1 = 0.0 downward1 = 0.0 upward2 = 0.0 downward2 = 0.0 upward1 := filt1 > filt1[1] ? nz(upward1[1]) + 1 : filt1 < filt1[1] ? 0 : nz(upward1[1]) downward1 := filt1 < filt1[1] ? nz(downward1[1]) + 1 : filt1 > filt1[1] ? 0 : nz(downward1[1]) upward2 := filt2 > filt2[1] ? nz(upward2[1]) + 1 : filt2 < filt2[1] ? 0 : nz(upward2[1]) downward2 := filt2 < filt2[1] ? nz(downward2[1]) + 1 : filt2 > filt2[1] ? 0 : nz(downward2[1]) //RF Target bands hband1 = filt1 + smrng1 lband1 = filt1 - smrng1 hband2 = filt2 + smrng2 lband2 = filt2 - smrng2 //RF Colors filtcolor1 = upward1 > 0 ? rf1UpColor : rf1DownColor filtcolor2 = upward2 > 0 ? rf2UpColor : rf2DownColor filtplot1 = plot((showRangeFilters ? filt1 : na), color=filtcolor1, linewidth=rf1LineWidth, title="Range Filter #1") filtplot2 = plot((showRangeFilters ? filt2 : na), color=filtcolor2, linewidth=rf2LineWidth, title="Range Filter #2") //RF range bands upper / lower hbandplot1 = plot(hband1, color=transp, title="RF #1 high", linewidth=1, display=display.none) lbandplot1 = plot(lband1, color=transp, title="RF #1 low", linewidth=1, display=display.none) hbandplot2 = plot(hband2, color=color.new(#CCCCCC, 70), title="RF #2 high", linewidth=1, display=display.none) lbandplot2 = plot(lband2, color=color.new(#CCCCCC, 70), title="RF #2 low", linewidth=1, display=display.none) //RF Fills fill(hbandplot1, filtplot1, color=color.new(#5B9CF6, 100), title="RF #1 area high") fill(lbandplot1, filtplot1, color=color.new(#5B9CF6, 100), title="RF #1 area low") fill(hbandplot2, filtplot2, color=color.new(#cccccc, 100), title="RF #2 area high") fill(lbandplot2, filtplot2, color=color.new(#cccccc, 100), title="RF #2 area low") //=Sessions //================================================================================================================================== london_color = color.new(color.green, 90) newyork_color = color.new(color.blue, 90) tokyo_color = color.new(color.red, 90) sydney_color = color.new(color.orange, 90) grp_SESS = "Sessions" utcsetting = input.string(title="Select UTC timezone", defval="UTC+1", options=["UTC-11","UTC-10","UTC-9","UTC-8","UTC-7","UTC-6","UTC-5","UTC-4","UTC-3","UTC-2:30","UTC-2","UTC-1","UTC","UTC+1","UTC+2","UTC+3","UTC+4","UTC+4:30","UTC+5","UTC+6","UTC+7","UTC+8","UTC+9","UTC+10","UTC+11","UTC+12","UTC+13"], group=grp_SESS) daylightsavings = input(false, title="Add 1hr for daylight savings time (DST)", group=grp_SESS) // Show sessions timelondon = time(timeframe.period, daylightsavings ? "0800-1700:23456" : "0700-1600:23456", utcsetting) timenewyork = time(timeframe.period, daylightsavings ? "1300-2200:23456" : "1200-2100:23456", utcsetting) timetokyo = time(timeframe.period, daylightsavings ? "0000-0900:23456" : "2300-0800:23456", utcsetting) timesydney = time(timeframe.period, daylightsavings ? "2200-0700:23456" : "2100-0600:23456", utcsetting) // Show Trading Sessions // Inverted Sessions Logic invertedsessioncolor= input.color(color.new(color.blue, 90), title="", group=grp_SESS, inline="0") invertsessioncolour = input(false, title="Enable inverted session(s) color", tooltip="This will color the background of the entire chart - except the trading session(s) you select, to give you a clear chart, free of a distracting background colors. 👌", group=grp_SESS, inline="0") // London Session londonsessioncolor = input.color(london_color, title="", group=grp_SESS, inline="1") showlondonsession = input(false, title="Show London session", group=grp_SESS, inline="1") bgcolor((enableSessions and timelondon and showlondonsession and not invertsessioncolour) ? londonsessioncolor : na) // New York Session newyorksessioncolor = input.color(newyork_color, title="", group=grp_SESS, inline="2") shownewyorksession = input(false, title="Show New York session", group=grp_SESS, inline="2") bgcolor((enableSessions and timenewyork and shownewyorksession and not invertsessioncolour) ? newyorksessioncolor : na) // Tokyo Session tokyosessioncolor = input.color(tokyo_color, title="", group=grp_SESS, inline="3") showtokyosession = input(false, title="Show Tokyo session", group=grp_SESS, inline="3") bgcolor((enableSessions and timetokyo and showtokyosession and not invertsessioncolour) ? tokyosessioncolor : na) // Sydney Session sydneysessioncolor = input.color(sydney_color, title="", group=grp_SESS, inline="4") showsydneysession = input(false, title="Show Sydney session", group=grp_SESS, inline="4") bgcolor((enableSessions and timesydney and showsydneysession and not invertsessioncolour) ? sydneysessioncolor : na) bgcolor((enableSessions and invertsessioncolour and not (showlondonsession ? timelondon : na) and not (shownewyorksession ? timenewyork : na) and not (showtokyosession ? timetokyo : na) and not (showsydneysession ? timesydney : na)) ? invertedsessioncolor : na) //=Watermark //================================================================================================================================== textVPosition = input.string("top", "", options = ["top", "middle", "bottom"], group = "Watermark text", inline="w0") showText = input(true, title="Show text", group = "Watermark text", inline="w0") s_title = input.string("normal", "", options = ["small", "normal", "large", "huge", "auto"], group = "Watermark text", inline="w1") c_title = input.color(color.new(color.gray, 0), "", group = "Watermark text", inline="w1") title = input("RF+", "", group = "Watermark text", inline="w1") s_subtitle = input.string("normal", "", options = ["small", "normal", "large", "huge", "auto"], group = "Watermark text", inline="w2") c_subtitle = input(color.new(color.gray, 0), "", group = "Watermark text", inline="w2") subtitle = input("Replay for Heikin Ashi", "", group = "Watermark text", inline="w2") symVPosition = input.string("bottom", "", options = ["top", "middle", "bottom"], group = "Watermark symbol", inline="w3") showSymText = input(true, title="Show symbol", group = "Watermark symbol", inline="w3") symInfo = syminfo.ticker + " | " + timeframe.period + (timeframe.isminutes ? "M" : na) date = str.tostring(dayofmonth(time_close)) + "/" + str.tostring(month(time_close)) + "/" + str.tostring(year(time_close)) s_symInfo = input.string("normal", "", options = ["small", "normal", "large", "huge", "auto"], group = "Watermark symbol", inline="w4") c_symInfo = input(color.new(color.gray, 30), "", group = "Watermark symbol", inline="w4") c_bg = color.new(color.blue, 100) //text watermark creation textWatermark = table.new(textVPosition + "_" + "center", 1, 3) if showText == true and showWatermark table.cell(textWatermark, 0, 0, title, 0, 0, c_title, "center", text_size = s_title, bgcolor = c_bg) table.cell(textWatermark, 0, 1, subtitle, 0, 0, c_subtitle, "center", text_size = s_subtitle, bgcolor = c_bg) //symbol info watermark creation symWatermark = table.new(symVPosition + "_" + "center", 5, 5) if showSymText == true and showWatermark table.cell(symWatermark, 0, 1, symInfo, 0, 0, c_symInfo, "center", text_size = s_symInfo, bgcolor = c_bg)
FieryTrading: Buy The Dip - Sell The Rip
https://www.tradingview.com/script/jA5Bzt2Q-FieryTrading-Buy-The-Dip-Sell-The-Rip/
FieryTrading
https://www.tradingview.com/u/FieryTrading/
371
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/ // © FieryTrading //@version=5 indicator("FieryTrading BTD - STR", overlay=true) /// RSI rsi = ta.rsi(close, 14) smooth_len = input.int(3, "RSI Smoothing") smooth_rsi = ta.sma(rsi,smooth_len) /// MTF SMA sma_res = input.timeframe('W', "MTF Resolution") mtf_len = input.int(20, "MTF Length") rp_security(_symbol, _mtflen, _src) => request.security(_symbol, _mtflen, _src[barstate.isrealtime ? 1 : 0]) mtf_sma = rp_security(syminfo.tickerid, sma_res, ta.sma(close, 20)) /// Entry conditions long = smooth_rsi<30 and smooth_rsi>smooth_rsi[1] and close>mtf_sma short = smooth_rsi>70 and smooth_rsi<smooth_rsi[1] and close<mtf_sma /// Plots & Alerts plotshape(long and not long[1], style = shape.triangleup, color=color.green, size=size.small, location = location.belowbar) plotshape(short and not short[1], style = shape.triangledown, color=color.red, size=size.small, location = location.abovebar) alertcondition(long and not long[1], "Long Entry") alertcondition(short and not short[1], "Short Entry")
Hammer & Shooting Star [C] - Kaspricci
https://www.tradingview.com/script/6Mj7sHoE/
Kaspricci
https://www.tradingview.com/u/Kaspricci/
180
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/ // © Kaspricci //@version=5 indicator("Hammer & Shooting Star [C] - Kaspricci", shorttitle = "Hammer & Shooting Star [C]", overlay = true) FIB_LEVEL = input.float( defval = 0.382, title = "Fibonacci Level", options = [0.236, 0.382, 0.5]) confirm = input.bool( defval = false, title = "Confirm by next candle", tooltip = "A green candle confirms a hammer and a red candle confirms a shooting star") showLabels = input.bool( defval = true, title = "Show labels on chart") isGreen = open < close isRed = open > close candleSize = math.abs(high - low) // hammer candle = the whole body of the candle is within 38.2% of the upper part of the candle isHammer = high - FIB_LEVEL * candleSize < math.min(open, close) // shooting star candle = the whole body of the candle is within 38.2% of the lower part of the candle isShoot = low + FIB_LEVEL * candleSize > math.max(open, close) isConfirmedHammer = confirm ? isHammer[1] and isGreen : isHammer isConfirmedShoot = confirm ? isShoot[1] and isRed : isShoot plotshape( series = isConfirmedHammer ? low : na, title = "Hammer Candle", text = "Hammer", style = shape.arrowup, location = location.belowbar, color = color.green, textcolor = color.green, offset = confirm ? -1 : 0, display = showLabels ? display.pane : display.none) plotshape( series= isConfirmedShoot ? high : na, title = "Shooting Star Candle", text = "Shooting", style = shape.arrowdown, location = location.abovebar, color = color.red, textcolor = color.red, offset = confirm ? -1 : 0, display = showLabels ? display.pane : display.none) // ---------------------------------------------------------------------------------------------------------------------- // handle entry & exit signals longEntry = isConfirmedHammer shortEntry = isConfirmedShoot // support alerts for entry $ exit signals alertcondition( condition = longEntry, title = "Hammer Candle Alert", message = "Hammer candle occured for {{ticker\}} at {{close}}") alertcondition( condition = shortEntry, title = "Shooting Start Alert", message = "Shooting Start candle occured for {{ticker}} at {{close}}") // connector to backtester strategy connector = 0 connector := longEntry ? 2 : 0 connector := shortEntry ? -2 : connector plot(connector, title = "Connector", display = display.status_line, color = color.gray)
KH MA Cross,
https://www.tradingview.com/script/gnNDDpfZ-KH-MA-Cross/
kurthennig18
https://www.tradingview.com/u/kurthennig18/
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/ // © kurthennig18 import ZenAndTheArtOfTrading/ZenLibrary/5 //@version=5 indicator("MA Cross", overlay = true) ///GET MAs/// sma1 = ta.sma (close, 8) sma2 = ta.sma (close, 21) sma3 = ta.sma(close, 50) //Draw MAs plot(sma1, color = color.lime)//8// plot(sma2, color = color.red)//21// plot(sma3, color = color.black)//50// //MA input// short = input.int(8, minval = 1, title = "Short-Period") medium = input.int(21, minval = 1, title = "Medium-Period") long = input.int(50, minval = 1, title = "Long-Period") //Get crosses// maCrossOver1 = ta.crossover(sma1, sma2) maCrossUnder2 = ta.crossunder(sma1, sma2) ///////////////////////////////////////// maCrossOver3 = ta.crossover(sma2, sma3) maCrossOver4 = ta.crossunder(sma2, sma3) //Draw BG cross bgcolor (maCrossOver1 ? color.new(color.lime, 90) : na, show_last = 100, title = "8/21 Bull") bgcolor (maCrossUnder2 ? color.new(color.black, 90) : na, show_last = 100, title = "21/50 Bear") bgcolor(maCrossOver3 ? color.new(color.red, 90) : na, show_last = 100, title = "21/50 Bull ") bgcolor(maCrossOver4 ? color.new(color.blue, 90) : na, show_last = 100, title = "21/50 Bull ")
MA Crosses
https://www.tradingview.com/script/R6BvhlQd-MA-Crosses/
kurthennig18
https://www.tradingview.com/u/kurthennig18/
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/ // © kurthennig18 import ZenAndTheArtOfTrading/ZenLibrary/5 //@version=5 indicator("MA Cross", overlay = true) ///GET MAs/// sma1 = ta.sma (close, 8) sma2 = ta.sma (close, 21) sma3 = ta.sma(close, 50) //Draw MAs plot(sma1, color = color.lime)//8// plot(sma2, color = color.red)//21// plot(sma3, color = color.black)//50// //MA input// short = input.int(8, minval = 1, title = "Short-Period") medium = input.int(21, minval = 1, title = "Medium-Period") long = input.int(50, minval = 1, title = "Long-Period") //Get crosses// maCrossOver1 = ta.crossover(sma1, sma2) maCrossUnder2 = ta.crossunder(sma1, sma2) ///////////////////////////////////////// maCrossOver3 = ta.crossover(sma2, sma3) maCrossOver4 = ta.crossunder(sma2, sma3) //Draw BG cross bgcolor (maCrossOver1 ? color.new(color.lime, 90) : na, show_last = 100, title = "8/21 Bull") bgcolor (maCrossUnder2 ? color.new(color.black, 90) : na, show_last = 100, title = "21/50 Bear") bgcolor(maCrossOver3 ? color.new(color.red, 90) : na, show_last = 100, title = "21/50 Bull ") bgcolor(maCrossOver4 ? color.new(color.blue, 90) : na, show_last = 100, title = "21/50 Bull ")
Traders Reality Main
https://www.tradingview.com/script/Etj1ixAs-Traders-Reality-Main/
TradersReality
https://www.tradingview.com/u/TradersReality/
3,239
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/ // Original pattern formation by plasmapug, rise retrace continuation to the upside by infernix, peshocore and xtech5192 // dst auto f-n and psy refactor for dst by xtech5192 // Range daily/weekly Hi/Lo added with research contributions from xtech5192 // Please note while the code is open source and you are free to use it however you like - the 'Traders Reality' name is not - ie if you produce derivatives of this // source code you to name those scripts using "Traders Reality", "Pattern Watchers" or any other name that relates to Traders Reality in any way. //Session Local Time DST OFF (UCT+0) DST ON (UTC+0) DST ON 2022 DST OFF 2022 DST ON 2023 DST OFF 2023 DST ON 2024 DST OFF 2024 //London 8am-430pm 0800-1630 0700-1530 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27 //NewYork 930am-4pm 1430-2100 1330-2000 March, 13 November, 6 March, 12 November, 5 March, 10 November, 3 //Tokyo 9am-3pm 0000-0600 0000-0600 N/A N/A N/A N/A N/A N/A //HongKong 930am-4pm 0130-0800 0130-0800 N/A N/A N/A N/A N/A N/A //Sydney (NZX+ASX) NZX start 10am, ASX end 4pm 2200-0600 2100-0500 October, 2 April, 3 October, 1 April, 2 October, 6 April, 7 //EU Brinx 800am-900am 0800-0900 0700-0800 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27 //US Brinx 900am-10am 1400-1500 1300-1400 March, 13 November, 6 March, 12 November, 5 March, 10 November, 3 //Frankfurt 800am-530pm 0700-1630 0600-1530 March, 27 October, 30 March, 26 October, 29 March, 31 October, 27 //@version=5 indicator(title = 'Traders Reality Main', shorttitle='TR_MAIN', overlay=true, max_bars_back=300,max_boxes_count=500, max_lines_count=500, max_labels_count=500) import TradersReality/Traders_Reality_Lib/2 as trLib // Config labelOffsetInput = input.int(group='Label offsets', title='General', defval=12, inline='labeloffset1') pivotOffsetInput = input.int(group='Label offsets', title='Pivots', defval=6, inline='labeloffset1') adrOffsetInput = input.int(group='Label offsets', title='ADR', defval=12, inline='labeloffset1') adrOffsetInput50 = input.int(group='Label offsets', title='50% ADR', defval=12, inline='labeloffset1') rdOffsetInput = input.int(group='Label offsets', title='RD/W', defval=24, inline='labeloffset1') rdOffsetInput50 = input.int(group='Label offsets', title='50% RD/W', defval=24, inline='labeloffset1') color redVectorColor = input.color(title='Vector: Red', group='PVSRA Colors', defval=color.red, inline='vectors') color greenVectorColor = input.color(title='Green', group='PVSRA Colors', defval=color.lime, inline='vectors') color violetVectorColor = input.color(title='Violet', group='PVSRA Colors', defval=color.fuchsia, inline='vectors') color blueVectorColor = input.color(title='Blue', group='PVSRA Colors', defval=color.blue, inline='vectors', tooltip='Bull bars are green and bear bars are red when the bar is with volume >= 200% of the average volume of the 10 previous bars, or bars where the product of candle spread x candle volume is >= the highest for the 10 previous bars.\n Bull bars are blue and bear are violet when the bar is with with volume >= 150% of the average volume of the 10 previous bars.') color regularCandleUpColor = input.color(title='Regular: Up Candle', group='PVSRA Colors', defval=#999999, inline='nonVectors') color regularCandleDownColor = input.color(title='Down Candle', group='PVSRA Colors', defval=#4d4d4d, inline='nonVectors', tooltip='Bull bars are light gray and bear are dark gray when none of the red/green/blue/violet vector conditions are met.') showEmas = input.bool(group='EMAs', title='Show EMAs?', defval=true, inline='showemas') labelEmas = input.bool(group='EMAs', title='EMA Labels?', defval=false, inline='showemas') oneEmaColor = input.color(group='EMAs', title='EMA Color: 5', defval=color.rgb(254, 234, 74, 0), inline='emacolors') twoEmaColor = input.color(group='EMAs', title='13', defval=color.rgb(253, 84, 87, 0), inline='emacolors') threeEmaColor = input.color(group='EMAs', title='50', defval=color.rgb(31, 188, 211, 0), inline='emacolors') fourEmaColor = input.color(group='EMAs', title='200', defval=color.rgb(255, 255, 255, 0), inline='emacolors') fiveEmaColor = input.color(group='EMAs', title='800', defval=color.rgb(50, 34, 144, 0), inline='emacolors') emaCloudColor = input.color(group='EMAs', title='EMA Cloud', defval=color.rgb(155, 47, 174, 60), inline='emacloud') emaCloudBorderColor = input.color(group='EMAs', title='Border', defval=color.rgb(18, 137, 123, 100), inline='emacloud') //Daily Pivot Points showLevelOnePivotPoints = input.bool(group='Pivot Points', title='Show Level: 1 R/S?', defval=false, inline='pivotlevels') showLevelTwoPivotPoints = input.bool(group='Pivot Points', title='2 R/S?', defval=false, inline='pivotlevels') showLevelThreePivotPoints = input.bool(group='Pivot Points', title=' 3 R/S?', defval=false, inline='pivotlevels') showPivotLabels = input.bool(group='Pivot Points', title='Show labels?', defval=true, inline='pivotlevels') string rsStyleX = input.string(group='Pivot Points', defval='Dashed', title='R/S Levels Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='pivotcolorsRS') rsStyle = rsStyleX == 'Dotted' ? line.style_dotted : (rsStyleX == 'Dashed' ? line.style_dashed : (rsStyleX == 'Solid' ? line.style_solid : line.style_dashed)) activeM = input.bool(group='Pivot Points', title='Show M levels?', defval=true, inline='mlevels') showMLabels = input.bool(group='Pivot Points', title='Labels?', defval=true, inline='mlevels') extendPivots = input.bool(group='Pivot Points', title='Extend lines in both directions?', defval=false) pivotColor = input.color(group='Pivot Points', title='Colors: Pivot Point', defval=color.rgb(254, 234, 78, 50), inline='pivotcolors') pivotLabelColor = input.color(group='Pivot Points', title='Pivot Point Label', defval=color.rgb(254, 234, 78, 50), inline='pivotcolors') mColor = input.color(group='Pivot Points', title='Colors: M Levels', defval=color.rgb(255, 255, 255, 50), inline='pivotcolors1') mLabelColor = input.color(group='Pivot Points', title='M Levels Label', defval=color.rgb(255, 255, 255, 50), inline='pivotcolors1') string mStyleX = input.string(group='Pivot Points', defval='Dashed', title='M Levels Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='pivotcolors2') mStyle = mStyleX == 'Dotted' ? line.style_dotted : (mStyleX == 'Dashed' ? line.style_dashed : (mStyleX == 'Solid' ? line.style_solid : line.style_dashed)) showDayHighLow = input.bool(group="Yesterday's and Last Week's High/low", title='Show Hi/Lo: Daily?', defval=true, inline='highlow') dailyHiLoColor = color.new(color.blue, 50) //input.color(group="Yesterday's and Last Week's High/low", title='Color', defval=color.new(color.blue, 50), inline='dhighlow') showWeekHighLow = input.bool(group="Yesterday's and Last Week's High/low", title='Weekly?', defval=true, inline='highlow') weeklyHiLoColor = color.new(color.green, 60) //input.color(group="Yesterday's and Last Week's High/low", title='Color', defval=color.new(color.green, 60), inline='whighlow') showDayHighLowLabels = input.bool(group="Yesterday's and Last Week's High/low", title='Show labels?', defval=true, inline='highlow') showADR = input.bool(group='Average Daily Range - ADR', title='Show ADR?', defval=true, inline='adr') showADRDO = input.bool(group='Average Daily Range - ADR', title='Use Daily Open (DO) calc?', defval=false, inline='adr', tooltip='Measure the ADR from the daily open. This will make the ADR static throughout the day. ADR is usually measured taking today high and low. Since todays high and low will change throughout the day, some might prefer to have a static range instead.') showADRLabels = input.bool(group='Average Daily Range - ADR', title='Labels?', defval=true, inline='adr1') showADRRange = input.bool(group='Average Daily Range - ADR', title='Range label?', defval=false, inline='adr1') showADR50 = input.bool(group='Average Daily Range - ADR', title='Show 50% ADR?', defval=false, inline='adr1') aDRRange = input.int(group='Average Daily Range - ADR', title='ADR length (days)?', defval=14, minval=1, maxval=31, step=1, inline='adr2', tooltip="Defaults taken from mt4. This defines how many days back to take into consideration when calculating the ADR") adrColor = input.color(group='Average Daily Range - ADR', title='ADR Color', defval=color.new(color.silver, 50), inline='adr3') string adrStyleX = input.string(group='Average Daily Range - ADR', defval='Dotted', title='ADR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='adr3') adrStyle = adrStyleX == 'Dotted' ? line.style_dotted : (adrStyleX == 'Dashed' ? line.style_dashed : (adrStyleX == 'Solid' ? line.style_solid : line.style_dotted)) showAWR = input.bool(group='Average Weekly Range - AWR', title='Show AWR?', defval=false, inline='awr') showAWRWO = input.bool(group='Average Weekly Range - AWR', title='Use Weekly Open (WO) calc?', defval=false, inline='awr', tooltip='Measure the AWR from the weekly open. This will make the AWR static throughout the week. AWR is usually measured taking this weeks high and low. Since this weeks high and low will change throughout the week, some might prefer to have a static range instead.') showAWRLabels = input.bool(group='Average Weekly Range - AWR', title='Labels?', defval=true, inline='awr1') showAWRRange = input.bool(group='Average Weekly Range - AWR', title='Range label?', defval=false, inline='awr1') showAWR50 = input.bool(group='Average Weekly Range - AWR', title='Show 50% AWR?', defval=false, inline='awr1') aWRRange = input.int(group='Average Weekly Range - AWR', title='AWR length (weeks)?', defval=4, minval=1, maxval=52, step=1, inline='awr2', tooltip="Defaults taken from mt4. This defines how many weeks back to take into consideration when calculating the AWR") awrColor = input.color(group='Average Weekly Range - AWR', title='AWR Color', defval=color.new(color.orange, 50), inline='awr3') string awrStyleX = input.string(group='Average Weekly Range - AWR', defval='Dotted', title='AWR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='awr3') awrStyle = awrStyleX == 'Dotted' ? line.style_dotted : (awrStyleX == 'Dashed' ? line.style_dashed : (awrStyleX == 'Solid' ? line.style_solid : line.style_dotted)) showAMR = input.bool(group='Average Monthly Range - AMR', title='Show AMR?', defval=false, inline='amr') showAMRMO = input.bool(group='Average Monthly Range - AMR', title='Use Monthly Open (MO) calc?', defval=false, inline='amr',tooltip='Measure the AMR from the monthly open. This will make the AMR static throughout the month. AMR is usually measured taking this months high and low. Since this months high and low will change throughout the month, some might prefer to have a static range instead.') showAMRLabels = input.bool(group='Average Monthly Range - AMR', title='Labels?', defval=true, inline='amr1') showAMRRange = input.bool(group='Average Monthly Range - AMR', title='Range label?', defval=false, inline='amr1') showAMR50 = input.bool(group='Average Monthly Range - AMR', title='Show 50% AMR?', defval=false, inline='amr1') aMRRange = input.int(group='Average Monthly Range - AMR', title='AMR length (months)?', defval=6, minval=1, maxval=12, step=1, inline='amr2', tooltip="Defaults taken from mt4. This defines how many months back to take into consideration when calculating the AMR") amrColor = input.color(group='Average Monthly Range - AMR', title='AMR Color', defval=color.new(color.red, 50), inline='amr3') string amrStyleX = input.string(group='Average Monthly Range - AMR', defval='Dotted', title='AMR Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='amr3') amrStyle = amrStyleX == 'Dotted' ? line.style_dotted : (amrStyleX == 'Dashed' ? line.style_dashed : (amrStyleX == 'Solid' ? line.style_solid : line.style_dotted)) showRD = input.bool(group='Range Daily Hi/Lo - RD Hi/Lo', title='Show RD?', defval=false, inline='rd') showRDDO = input.bool(group='Range Daily Hi/Lo - RD Hi/Lo', title='Use Daily Open (DO) calc?', defval=false, inline='rd',tooltip='Measure the RD from the daily open. This will make the RD static throughout the day. RD is usually measured taking todays high and low. Since today high and low will change throughout the day, some might prefer to have a static range instead.') showRDLabels = input.bool(group='Range Daily Hi/Lo - RD Hi/Lo', title='Labels?', defval=true, inline='rd1') showRDRange = input.bool(group='Range Daily Hi/Lo - RD Hi/Lo', title='Range label?', defval=false, inline='rd1') showRD50 = input.bool(group='Range Daily Hi/Lo - RD Hi/Lo', title='Show 50% RD?', defval=false, inline='rd1') rdRange = input.int(group='Range Daily Hi/Lo - RD Hi/Lo', title='RD length (days)?', defval=15, minval=1, maxval=31, step=1, inline='rd2', tooltip="Defaults taken from Trader At Home PVSRA documentation. This defines how many days back to take into consideration when calculating the RD") rdColor = input.color(group='Range Daily Hi/Lo - RD Hi/Lo', title='RD Color', defval=color.new(color.red, 30), inline='rd3') string rdStyleX = input.string(group='Range Daily Hi/Lo - RD Hi/Lo', defval='Solid', title='RD Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='rd3') rdStyle = rdStyleX == 'Dotted' ? line.style_dotted : (rdStyleX == 'Dashed' ? line.style_dashed : (rdStyleX == 'Solid' ? line.style_solid : line.style_dotted)) showRW = input.bool(group='Range Weekly Hi/Lo - RW Hi/Lo', title='Show RW?', defval=false, inline='rw') showRWWO = input.bool(group='Range Weekly Hi/Lo - RW Hi/Lo', title='Use Weekly Open (WO) calc?', defval=false, inline='rw', tooltip='Measure the RW from the weekly open. This will make the RW static throughout the week. RW is usually measured taking this weeks high and low. Since this weeks high and low will change throughout the week, some might prefer to have a static range instead.') showRWLabels = input.bool(group='Range Weekly Hi/Lo - RW Hi/Lo', title='Labels?', defval=true, inline='rw1') showRWRange = input.bool(group='Range Weekly Hi/Lo - RW Hi/Lo', title='Range label?', defval=false, inline='rw1') showRW50 = input.bool(group='Range Weekly Hi/Lo - RW Hi/Lo', title='Show 50% RW?', defval=false, inline='rw1') rwRange = input.int(group='Range Weekly Hi/Lo - RW Hi/Lo', title='RW length (weeks)?', defval=13, minval=1, maxval=52, step=1, inline='rw2', tooltip="Defaults taken from Trader At Home PVSRA documentation. This defines how many weeks back to take into consideration when calculating the RW") rwColor = input.color(group='Range Weekly Hi/Lo - RW Hi/Lo', title='RW Color', defval=color.new(color.blue, 30), inline='rw3') string rwStyleX = input.string(group='Range Weekly Hi/Lo - RW Hi/Lo', defval='Solid', title='RW Line Style', options=['Dotted', 'Dashed', 'Solid'], inline='rw3') rwStyle = rwStyleX == 'Dotted' ? line.style_dotted : (rwStyleX == 'Dashed' ? line.style_dashed : (rwStyleX == 'Solid' ? line.style_solid : line.style_dotted)) showAdrTable = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show ADR Table', inline='adrt', defval=true) showAdrPips = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show ADR PIPS', inline='adrt', defval=true) and showAdrTable showAdrCurrency = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show ADR Currency', inline='adrt', defval=false) and showAdrTable showRDPips = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show RD PIPS', inline='adrt', defval=false) and showAdrTable showRDCurrency = input.bool(group='ADR/ADRx3/AWR/AMR Table', title='Show RD Currency', inline='adrt', defval=false) and showAdrTable choiceAdrTable = input.string(group='ADR/ADRx3/AWR/AMR Table', title='ADR Table postion', inline='adrt', defval='top_right', options=['top_right', 'top_left', 'top_center', 'bottom_right', 'bottom_left', 'bottom_center']) adrTableBgColor = input.color(group='ADR/ADRx3/AWR/AMR Table', title='ADR Table: Background Color', inline='adrtc', defval=color.rgb(93, 96, 107, 70)) adrTableTxtColor = input.color(group='ADR/ADRx3/AWR/AMR Table', title='Text Color', inline='adrtc', defval=color.rgb(31, 188, 211, 0)) /// market boxes and daily open only on intraday bool show = timeframe.isminutes and timeframe.multiplier <= 240 and timeframe.multiplier >= 1 bool showDly = timeframe.isminutes //and timeframe.multiplier < 240 bool showRectangle9 = input.bool(group='Daily Open', defval=true, title='Show: line ?', inline='dopenconf') and showDly bool showLabel9 = input.bool(group='Daily Open', defval=true, title='Label?', inline='dopenconf') and showRectangle9 and showDly bool showallDly = input.bool(group='Daily Open', defval=false, title='Show historical daily opens?', inline='dopenconf') color sess9col = input.color(group='Daily Open', title='Daily Open Color', defval=color.rgb(254, 234, 78, 0), inline='dopenconf1') bool overrideSym = input.bool(group='PVSRA Override', title='Override chart symbol?', defval=false, inline='pvsra') string pvsraSym = input.string(group='PVSRA Override', title='', defval='INDEX:BTCUSD', tooltip='You can use INDEX:BTCUSD or you can combine multiple feeds, for example BINANCE:BTCUSDT+COINBASE:BTCUSD. Note that adding too many will slow things down.', inline='pvsra') bool showVCZ = input.bool(true, 'Show VCZ?' , group='Vector Candle Zones', inline="vczOn") int zonesMax = input.int(500, 'Maximum zones to draw', group='Vector Candle Zones', inline="vczOn") string zoneType = input.string(group='Vector Candle Zones', defval='Body only', title='Zone top/bottom is defined with: ', options=['Body only', 'Body with wicks']) string zoneUpdateType = input.string(group='Vector Candle Zones', defval='Body with wicks', title='Zones are cleared using candle: ', options=['Body only', 'Body with wicks']) int borderWidth = input.int(0, 'Zone border width', group='Vector Candle Zones') bool colorOverride = input.bool(true, 'Override color?' , group='Vector Candle Zones', inline="vcz1") color zoneColor = input.color(title='Color', group='Vector Candle Zones', defval=color.rgb(255, 230, 75, 90), inline="vcz1", tooltip='the vector candle zones color to use if you dont not want to use the PVSRA Candle Colors.') int transperancy = input.int(90, 'Zone Transperancy', minval = 0, maxval = 100, group='Vector Candle Zones', tooltip='If the vector candle zones color is not overriden, then we want to set the transparancy of the vector candle colors as defined by the PBSRA candle colors. This setting only affects the candle zone colors not the candle colors themselves.') string rectStyle = input.string(group='Market sessions', defval='Dashed', title='Line style of Market Session hi/lo line', options=['Dashed', 'Solid']) bool showMarkets = input.bool(true, group='Market sessions', title='Show Market Sessions?', tooltip='Turn on or off all market sessions') and show bool showMarketsWeekends = input.bool(false, group='Market sessions', title='Show Market Session on Weekends?', tooltip='Turn on or off market sessions in the weekends. Note do not turn this on for exchanges that dont have weekend data like OANDA') and show string weekendSessions = ':1234567' string noWeekendSessions = ':23456' bool showRectangle1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session1conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval=true, title='Label?', inline='session1conf') and showRectangle1 and showMarkets bool showOr1 = input.bool(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session1conf', tooltip='This controls the shaded area for the session') and showRectangle1 and showMarkets string sess1Label = input.string(group='Market session: London (0800-1630 UTC+0) - DST Aware', defval='London', title='Name:', inline='session1style') color sess1col = input.color(group='Market session: London (0800-1630 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(120, 123, 134, 75), inline='session1style') color sess1colLabel = input.color(group='Market session: London (0800-1630 UTC+0) - DST Aware', title='Label', defval=color.rgb(120, 123, 134, 0), inline='session1style') string sess1TimeX = '0800-1630'//input.session(group='Market session: London (0800-1630 UTC+0)', defval='0800-1630', title='Time (UTC+0):', inline='session1style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST and times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess1Time = showMarketsWeekends ? sess1TimeX + weekendSessions : sess1TimeX + noWeekendSessions bool showRectangle2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session2conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval=true, title='Label?', inline='session2conf') and showRectangle2 and showMarkets bool showOr2 = input.bool(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session2conf', tooltip='This controls the shaded area for the session') and showRectangle2 and showMarkets string sess2Label = input.string(group='Market session: New York (1430-2100 UTC+0) - DST Aware', defval='NewYork', title='Name:', inline='session2style') color sess2col = input.color(group='Market session: New York (1430-2100 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(251, 86, 91, 75), inline='session2style') color sess2colLabel = input.color(group='Market session: New York (1430-2100 UTC+0) - DST Aware', title='Label', defval=color.rgb(253, 84, 87, 25), inline='session2style') string sess2TimeX = '1430-2100'//input.session(group='Market session: New York (1430-2100 UTC+0)', defval='1430-2100', title='Time (UTC+0):', inline='session2style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess2Time = showMarketsWeekends ? sess2TimeX + weekendSessions : sess2TimeX + noWeekendSessions bool showRectangle3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session3conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Label?', inline='session3conf') and showRectangle3 and showMarkets bool showOr3 = input.bool(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session3conf', tooltip='This controls the shaded area for the session') and showRectangle3 and showMarkets string sess3Label = input.string(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', defval='Tokyo', title='Name:', inline='session3style') color sess3col = input.color(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(80, 174, 85, 75), inline='session3style') color sess3colLabel = input.color(group='Market session: Tokyo (0000-0600 UTC+0) - DST Aware', title='Label', defval=color.rgb(80, 174, 85, 25), inline='session3style') string sess3TimeX = '0000-0600'//input.session(group='Market session: Tokyo (0000-0600 UTC+0)', defval='0000-0600', title='Time (UTC+0):', inline='session3style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess3Time = showMarketsWeekends ? sess3TimeX + weekendSessions : sess3TimeX + noWeekendSessions bool showRectangle4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session4conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval=true, title='Label?', inline='session4conf') and showRectangle4 and showMarkets bool showOr4 = input.bool(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session4conf', tooltip='This controls the shaded area for the session') and showRectangle4 and showMarkets string sess4Label = input.string(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', defval='HongKong', title='Name:', inline='session4style') color sess4col = input.color(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(128, 127, 23, 75), inline='session4style') color sess4colLabel = input.color(group='Market session: Hong Kong (0130-0800 UTC+0) - DST Aware', title='Label', defval=color.rgb(128, 127, 23, 25), inline='session4style') string sess4TimeX = '0130-0800'//input.session(group='Market session: Hong Kong (0130-0800 UTC+0)', defval='0130-0800', title='Time (UTC+0):', inline='session4style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess4Time = showMarketsWeekends ? sess4TimeX + weekendSessions : sess4TimeX + noWeekendSessions bool showRectangle5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session5conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval=true, title='Label?', inline='session5conf') and showRectangle5 and showMarkets bool showOr5 = input.bool(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session5conf', tooltip='This controls the shaded area for the session') and showRectangle5 and showMarkets string sess5Label = input.string(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', defval='Sydney', title='Name:', inline='session5style') color sess5col = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(37, 228, 123, 75), inline='session5style') color sess5colLabel = input.color(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0) - DST Aware', title='Label', defval=color.rgb(37, 228, 123, 25), inline='session5style') string sess5TimeX = '2200-0600'//input.session(group='Market session: Sydney (NZX+ASX 2200-0600 UTC+0)', defval='2200-0600', title='Time (UTC+0):', inline='session5style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess5Time = showMarketsWeekends ? sess5TimeX + weekendSessions : sess5TimeX + noWeekendSessions bool showRectangle6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session6conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval=true, title='Label?', inline='session6conf') and showRectangle6 and showMarkets bool showOr6 = input.bool(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session6conf', tooltip='This controls the shaded area for the session') and showRectangle6 and showMarkets string sess6Label = input.string(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', defval='EU Brinks', title='Name:', inline='session6style') color sess6col = input.color(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session6style') color sess6colLabel = input.color(group='Market session: EU Brinks (0800-0900 UTC+0) - DST Aware', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session6style') string sess6TimeX = '0800-0900'//input.session(group='Market session: EU Brinks (0800-0900 UTC+0)', defval='0800-0900', title='Time (UTC+0):', inline='session6style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess6Time = showMarketsWeekends ? sess6TimeX + weekendSessions : sess6TimeX + noWeekendSessions bool showRectangle7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval=true, title='Show: session?', inline='session7conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval=true, title='Label?', inline='session7conf') and showRectangle7 and showMarkets bool showOr7 = input.bool(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session7conf', tooltip='This controls the shaded area for the session') and showRectangle7 and showMarkets string sess7Label = input.string(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', defval='US Brinks', title='Name:', inline='session7style') color sess7col = input.color(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(255, 255, 255, 65), inline='session7style') color sess7colLabel = input.color(group='Market session: US Brinks (1400-1500 UTC+0) - DST Aware', title='Label', defval=color.rgb(255, 255, 255, 25), inline='session7style') string sess7TimeX = '1400-1500'//input.session(group='Market session: US Brinks (1400-1500 UTC+0)', defval='1400-1500', title='Time (UTC+0):', inline='session7style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess7Time = showMarketsWeekends ? sess7TimeX + weekendSessions : sess7TimeX + noWeekendSessions bool showRectangle8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval=false, title='Show: session?', inline='session8conf', tooltip='If this checkbox is off, Label and Open Range have no effect') and showMarkets bool showLabel8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval=true, title='Label?', inline='session8conf') and showRectangle8 and showMarkets bool showOr8 = input.bool(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval=true, title='Opening Range?', inline='session8conf', tooltip='This controls the shaded area for the session') and showRectangle8 and showMarkets string sess8Label = input.string(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', defval='Frankfurt', title='Name:', inline='session8style') color sess8col = input.color(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', title='Color: Box', defval=color.rgb(253, 152, 39, 75), inline='session8style') color sess8colLabel = input.color(group='Market session: Frankfurt (0700-1630 UTC+0) - DST Aware', title='Label', defval=color.rgb(253, 152, 39, 25), inline='session8style') string sess8TimeX = '0700-1630'//input.session(group='Market session: Frankfurt (0700-1630 UTC+0)', defval='0700-1630', title='Time (UTC+0):', inline='session8style', tooltip='Normally you will not want to adjust these times. Defaults are taken as if the session is NOT in DST times must be in UTC+0. Note due to limitations of pinescript some values sellected here other than the default might not work correctly on all exchanges.') sess8Time = showMarketsWeekends ? sess8TimeX + weekendSessions : sess8TimeX + noWeekendSessions bool showPsy = timeframe.isminutes and (timeframe.multiplier == 60 or timeframe.multiplier == 30 or timeframe.multiplier == 15 or timeframe.multiplier == 5 or timeframe.multiplier == 3 or timeframe.multiplier == 1) bool showPsylevels = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Show: Levels?', inline='psyconf') and showPsy bool showPsylabel = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=true, title='Labels?', inline='psyconf', tooltip="The Psy High/Low will only show on these timeframes: 1h/30min/15min/5min/3min/1min. It is disabled on all others. This is because the calculation requires a candle to start at the correct time for Sydney/Tokyo but in other timeframes the data does not have values at the designated time for the Sydney/Tokyo sessions.") and showPsylevels bool showAllPsy = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=false, title='Show historical psy levels?', inline='psyconf') and showPsylevels color psyColH = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Hi Color', defval=color.new(color.orange, 30), inline='psyconf1') color psyColL = input.color(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', title='Psy Low Color', defval=color.new(color.orange, 30), inline='psyconf1') bool overridePsyType = input.bool(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval=false, title='Override PsyType', inline='psyconf12') string psyTypeX = input.string(group='Weekly Psy Levels (valid tf 1h/30min/15min/5min/3min/1min)', defval='crypto', title='Psy calc type', options=['crypto', 'forex'], inline='psyconf12', tooltip="Selecting the override psy type lets you manually adjust the psy type otherwise it will be automatic. If the override psy type checkbox is of then this setting has no effect. usAre you looking at Crypto or Forex? Crypto calculations start with the Sydney session on Saturday night. Forex calculations start with the Tokyo session on Monday morning. Note some exchanges like Oanda do not have sessions on the weekends so you might be forced to select Forex for exchanges like Oanda even when looking at symbols like BITCOIN on Oanda.") string psyType = overridePsyType ? psyTypeX : (syminfo.type == 'forex' ? 'forex' : 'crypto') showDstTable = input.bool(group='Daylight Saving Time Info (DST)', title='Show DST Table : ', inline='dstt', defval=false) choiceDstTable = input.string(group='Daylight Saving Time Info (DST)', title='DST Table postion', inline='dstt', defval='bottom_center', options=['top_right', 'top_left', 'top_center', 'bottom_right', 'bottom_left', 'bottom_center']) dstTableBgColor = input.color(group='Daylight Saving Time Info (DST)', title='DST Table: Background Color', inline='dsttc', defval=color.rgb(93, 96, 107, 70)) dstTableTxtColor = input.color(group='Daylight Saving Time Info (DST)', title='Text Color', inline='dsttc', defval=color.rgb(31, 188, 211, 0)) //Non repainting security f_security(_symbol, _res, _src, _repaint) => request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1] // Basic vars (needed in functions) // Only render intraday validTimeFrame = timeframe.isintraday == true // If above the 5 minute, we start drawing yesterday. below, we start today levelStart = timeframe.isseconds == true or timeframe.isminutes == true and timeframe.multiplier < 5 ? time('D') : time('D') - 86400 * 1000 //levelsstartbar = ta.barssince(levelsstart) pivotLabelXOffset = time_close + pivotOffsetInput * timeframe.multiplier * 60 * 1000 labelXOffset = time_close + labelOffsetInput * timeframe.multiplier * 60 * 1000 adrLabelXOffset = time_close + adrOffsetInput * timeframe.multiplier * 60 * 1000 adrLabelXOffset50 = time_close + adrOffsetInput50 * timeframe.multiplier * 60 * 1000 rdLabelXOffset = time_close + rdOffsetInput * timeframe.multiplier * 60 * 1000 rdLabelXOffset50 = time_close + rdOffsetInput50 * timeframe.multiplier * 60 * 1000 //Emas oneEmaLength = 5 twoEmaLength = 13 threeEmaLength = 50 fourEmaLength = 200 fiveEmaLength = 800 oneEma = ta.ema(close, oneEmaLength) plot(showEmas ? oneEma : na, color=oneEmaColor, title='5 Ema') twoEma = ta.ema(close, twoEmaLength) plot(showEmas ? twoEma : na, color=twoEmaColor, title='13 Ema') threeEma = ta.ema(close, threeEmaLength) plot(showEmas ? threeEma : na, color=threeEmaColor, title='50 Ema') fourEma = ta.ema(close, fourEmaLength) plot(showEmas ? fourEma : na, color=fourEmaColor, title='200 Ema') fiveEma = ta.ema(close, fiveEmaLength) plot(showEmas ? fiveEma : na, color=fiveEmaColor, linewidth=2, title='800 Ema') // Ema 50 cloud placed here for readability on data window cloudSize = ta.stdev(close, threeEmaLength * 2) / 4 p1 = plot(showEmas ? threeEma + cloudSize : na, 'Upper 50 Ema Cloud', color=emaCloudBorderColor, offset=0) p2 = plot(showEmas ? threeEma - cloudSize : na, 'Lower 50 Ema Cloud', color=emaCloudBorderColor, offset=0) fill(p1, p2, title='EMA 50 Cloud', color=emaCloudColor) //Label emas trLib.rLabel(oneEma, '5 Ema', label.style_none, oneEmaColor, labelEmas, labelXOffset) //ry, rtext, rstyle, rcolor,valid trLib.rLabel(twoEma, '13 Ema', label.style_none, twoEmaColor, labelEmas, labelXOffset) trLib.rLabel(threeEma, '50 Ema', label.style_none, threeEmaColor, labelEmas, labelXOffset) trLib.rLabel(fourEma, '200 Ema', label.style_none, fourEmaColor, labelEmas, labelXOffset) trLib.rLabel(fiveEma, '800 Ema', label.style_none, fiveEmaColor, labelEmas, labelXOffset) // Get Daily price data dayHigh = f_security(syminfo.tickerid, 'D', high, false) dayLow = f_security(syminfo.tickerid, 'D', low, false) dayOpen = f_security(syminfo.tickerid, 'D', open, false) dayClose = f_security(syminfo.tickerid, 'D', close, false) //Compute Values pivotPoint = (dayHigh + dayLow + dayClose) / 3 // Updated 2021-03-25 by infernix pivR1 = 2 * pivotPoint - dayLow pivS1 = 2 * pivotPoint - dayHigh pivR2 = pivotPoint - pivS1 + pivR1 pivS2 = pivotPoint - pivR1 + pivS1 pivR3 = 2 * pivotPoint + dayHigh - 2 * dayLow pivS3 = 2 * pivotPoint - (2 * dayHigh - dayLow) //Plot Values pivline = trLib.drawPivot(validTimeFrame and (showLevelOnePivotPoints or showLevelTwoPivotPoints or showLevelThreePivotPoints or activeM) ? pivotPoint : na, 'D', 'PP', pivotColor, pivotLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) pivr1line = trLib.drawPivot(validTimeFrame and showLevelOnePivotPoints ? pivR1 : na, 'D', 'R1', color.new(color.green, 50), color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) pivs1line = trLib.drawPivot(validTimeFrame and showLevelOnePivotPoints ? pivS1 : na, 'D', 'S1', color.new(color.red, 50), color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelOnePivotPoints and showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) pivr2line = trLib.drawPivot(validTimeFrame and showLevelTwoPivotPoints ? pivR2 : na, 'D', 'R2', color.new(color.green, 50), color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) pivs2line = trLib.drawPivot(validTimeFrame and showLevelTwoPivotPoints ? pivS2 : na, 'D', 'S2', color.new(color.red, 50), color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelTwoPivotPoints and showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) pivr3line = trLib.drawPivot(validTimeFrame and showLevelThreePivotPoints ? pivR3 : na, 'D', 'R3', color.new(color.green, 50), color.new(color.green, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) pivs3line = trLib.drawPivot(validTimeFrame and showLevelThreePivotPoints ? pivS3 : na, 'D', 'S3', color.new(color.red, 50), color.new(color.red, 50), rsStyle, 1, extendPivots ? extend.both : extend.right, showLevelThreePivotPoints and showPivotLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) // Daily H/L weekHigh = f_security(syminfo.tickerid, 'W', high, false) weekLow = f_security(syminfo.tickerid, 'W', low, false) validDHLTimeFrame = timeframe.isintraday == true validWHLTimeFrame = timeframe.isintraday == true or timeframe.isdaily == true isToday = year(timenow) == year(time) and month(timenow) == month(time) and dayofmonth(timenow) == dayofmonth(time) isThisWeek = year(timenow) == year(time) and weekofyear(timenow) == weekofyear(time) plot(validDHLTimeFrame and showDayHighLow and (showDayHighLow ? true : isToday) ? dayHigh : na, linewidth=2, color=dailyHiLoColor, style=plot.style_stepline, title="YDay Hi", editable=true) plot(validDHLTimeFrame and showDayHighLow and (showDayHighLow ? true : isToday) ? dayLow : na, linewidth=2, color=dailyHiLoColor, style=plot.style_stepline, title="YDay Lo" , editable=true) trLib.rLabel(dayHigh, 'YDay Hi', label.style_none, color.new(dailyHiLoColor, 0), validDHLTimeFrame and showDayHighLow and showDayHighLowLabels, labelXOffset) //ry, rtext, rstyle, rcolor, valid trLib.rLabel(dayLow, 'YDay Lo', label.style_none, color.new(dailyHiLoColor, 0), validDHLTimeFrame and showDayHighLow and showDayHighLowLabels, labelXOffset) plot(validWHLTimeFrame and showWeekHighLow and (showWeekHighLow ? true : isThisWeek) ? weekHigh : na, linewidth=2, color=weeklyHiLoColor, style=plot.style_stepline, title="LWeek Hi", editable=true) plot(validWHLTimeFrame and showWeekHighLow and (showWeekHighLow ? true : isThisWeek) ? weekLow : na, linewidth=2, color=weeklyHiLoColor, style=plot.style_stepline, title="LWeek Lo", editable=true) trLib.rLabel(weekHigh, 'LWeek Hi', label.style_none, color.new(weeklyHiLoColor, 0), validWHLTimeFrame and showWeekHighLow and showDayHighLowLabels, labelXOffset) //ry, rtext, rstyle, rcolor, valid trLib.rLabel(weekLow, 'LWeek Lo', label.style_none, color.new(weeklyHiLoColor, 0), validWHLTimeFrame and showWeekHighLow and showDayHighLowLabels, labelXOffset) trLib.rLabel(high - (high - low) / 2, 'PVSRA Override Active!', label.style_none, color.orange, overrideSym, labelXOffset) //ry, rtext, rstyle, rcolor, valid pvsraVolume(overrideSymbolX, pvsraSymbolX, tickerIdX) => request.security(overrideSymbolX ? pvsraSymbolX : tickerIdX, '', [volume,high,low,close,open], barmerge.gaps_off, barmerge.lookahead_off) [pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen] = pvsraVolume(overrideSym, pvsraSym, syminfo.tickerid) [pvsraColor, alertFlag, averageVolume, volumeSpread, highestVolumeSpread] = trLib.calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleDownColor, regularCandleUpColor) barcolor(pvsraColor) alertcondition(alertFlag, title='Alert on Any Vector Candle', message='{{ticker}} Vector Candle on the {{interval}}') alertcondition(pvsraColor == greenVectorColor, title='Green Vector Candle', message='{{ticker}} Green Vector Candle on the {{interval}} Note: alert triggers in real time before the candle is closed unless you choose "once per bar close" option - ie the alert might trigger at some point and the pa after that could change the vector color completely. Use with caution.') alertcondition(pvsraColor == redVectorColor, title='Red Vector Candle', message='{{ticker}} Red Vector Candle on the {{interval}} Note: alert triggers in real time before the candle is closed unless you choose "once per bar close" option- ie the alert might trigger at some point and the pa after that could change the vector color completely. Use with caution.') alertcondition(pvsraColor == blueVectorColor, title='Blue Vector Candle', message='{{ticker}} Blue Vector Candle on the {{interval}} Note: alert triggers in real time before the candle is closed unless you choose "once per bar close" option- ie the alert might trigger at some point and the pa after that could change the vector color completely. Use with caution.') alertcondition(pvsraColor == violetVectorColor, title='Purple Vector Candle', message='{{ticker}} Purple Vector Candle on the {{interval}} Note: alert triggers in real time before the candle is closed unless you choose "once per bar close" option- ie the alert might trigger at some point and the pa after that could change the vector color completely. Use with caution.') redGreen = pvsraColor == greenVectorColor and pvsraColor[1] == redVectorColor greenRed = pvsraColor == redVectorColor and pvsraColor[1] == greenVectorColor redBlue = pvsraColor == blueVectorColor and pvsraColor[1] == redVectorColor blueRed = pvsraColor == redVectorColor and pvsraColor[1] == blueVectorColor greenPurpule = pvsraColor == violetVectorColor and pvsraColor[1] == greenVectorColor purpleGreen = pvsraColor == greenVectorColor and pvsraColor[1] == violetVectorColor bluePurpule = pvsraColor == violetVectorColor and pvsraColor[1] == blueVectorColor purpleBlue = pvsraColor == blueVectorColor and pvsraColor[1] == violetVectorColor alertcondition(redGreen, title='Red/Green Vector Candle Pattern', message='{{ticker}} Red/Green Vector Candle Pattern on the {{interval}}') alertcondition(greenRed, title='Green/Red Vector Candle Pattern', message='{{ticker}} Green/Red Vector Candle Pattern on the {{interval}}') alertcondition(redBlue, title='Red/Blue Vector Candle Pattern', message='{{ticker}} Red/Blue Vector Candle Pattern on the {{interval}}') alertcondition(blueRed, title='Blue/Red Vector Candle Pattern', message='{{ticker}} Blue/Red Vector Candle Pattern on the {{interval}}') alertcondition(greenPurpule, title='Green/Purple Vector Candle Pattern', message='{{ticker}} Green/Purple Vector Candle Pattern on the {{interval}}') alertcondition(purpleGreen, title='Purple/Green Vector Candle Pattern', message='{{ticker}} Purple/Green Vector Candle Pattern on the {{interval}}') alertcondition(bluePurpule, title='Blue/Purple Vector Candle Pattern', message='{{ticker}} Blue/Purple Vector Candle Pattern on the {{interval}}') alertcondition(purpleBlue, title='Purple/Blue Vector Candle Pattern', message='{{ticker}} Purple/Blue Vector Candle Pattern on the {{interval}}') //ADR // Daily ADR [dayAdr, dayAdrHigh, dayAdrLow] = request.security(syminfo.tickerid, 'D', trLib.adrHiLo(aDRRange,1, showADRDO), lookahead=barmerge.lookahead_on) dayAdrHigh50 = dayAdrHigh - (dayAdr/2) dayAdrLow50 = dayAdrLow + (dayAdr/2) if showADR string hl = 'Hi-ADR'+ (showADRDO?'(DO)':'') string ll = 'Lo-ADR'+ (showADRDO?'(DO)':'') trLib.drawLine(dayAdrHigh, 'D', hl, adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adrLabelXOffset, validTimeFrame) trLib.drawLine(dayAdrLow, 'D', ll, adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adrLabelXOffset, validTimeFrame) trLib.rLabelOffset((dayAdrHigh + dayAdrLow) / 2, 'ADR ' + str.format('{0,number,#.##}', trLib.toPips(dayAdr)) + 'PIPS|' + str.tostring(dayAdr, format.mintick) + syminfo.currency, label.style_none, adrColor, showADRLabels and validTimeFrame and showADRRange, adrLabelXOffset) //ry, rtext, rstyle, rcolor, valid if showADR and showADR50 string hl = '50% Hi-ADR'+ (showADRDO?'(DO)':'') string ll = '50% Lo-ADR'+ (showADRDO?'(DO)':'') trLib.drawLine(dayAdrHigh50, 'D', hl, adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adrLabelXOffset50, validTimeFrame) trLib.drawLine(dayAdrLow50, 'D', ll, adrColor, adrStyle, 2, extend.right, showADRLabels and validTimeFrame, adrLabelXOffset50, validTimeFrame) trLib.rLabelOffset((dayAdrHigh50 + dayAdrLow50) / 2, '50% ADR ' + str.format('{0,number,#.##}', trLib.toPips(dayAdr/2)) + 'PIPS|' + str.tostring(dayAdr/2, format.mintick) + syminfo.currency, label.style_none, adrColor, showADRLabels and validTimeFrame and showADRRange, adrLabelXOffset50) //ry, rtext, rstyle, rcolor, valid alertcondition(ta.crossover(close,dayAdrHigh) and dayAdrHigh != 0.0 , "ADR High reached", "PA has reached the calculated ADR High") alertcondition(ta.crossunder(close,dayAdrLow) and dayAdrLow != 0.0 , "ADR Low reached", "PA has reached the calculated ADR Low") alertcondition(ta.crossover(close,dayAdrHigh50) and dayAdrHigh50 != 0.0 , "50% of ADR High reached", "PA has reached 50% of the calculated ADR High") alertcondition(ta.crossunder(close,dayAdrLow50) and dayAdrLow50 != 0.0 , "50% ADR Low reached", "PA has reached 50% the calculated ADR Low") //Weekly ADR [weekAdr, weekAdrHigh,weekAdrLow] = request.security(syminfo.tickerid, 'W', trLib.adrHiLo(aWRRange, 1, showAWRWO), lookahead=barmerge.lookahead_on) weekAdrHigh50 = weekAdrHigh - (weekAdr/2) weekAdrLow50 = weekAdrLow + (weekAdr/2) if showAWR string hl = 'Hi-AWR'+ (showAWRWO?'(WO)':'') string ll = 'Lo-AWR'+ (showAWRWO?'(WO)':'') trLib.drawLine(weekAdrHigh, 'W', hl, awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adrLabelXOffset, validTimeFrame) trLib.drawLine(weekAdrLow, 'W', ll, awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adrLabelXOffset, validTimeFrame) trLib.rLabelOffset((weekAdrHigh + weekAdrLow) / 2, 'AWR ' + str.format('{0,number,#.##}', trLib.toPips(weekAdr)) + 'PIPS|' + str.tostring(weekAdr, format.mintick) + syminfo.currency, label.style_none, awrColor, showAWRLabels and validTimeFrame and showAWRRange, adrLabelXOffset) //ry, rtext, rstyle, rcolor, valid if showAWR and showAWR50 string hl = '50% Hi-AWR'+ (showAWRWO?'(WO)':'') string ll = '50% Lo-AWR'+ (showAWRWO?'(WO)':'') trLib.drawLine(weekAdrHigh50, 'W', hl, awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adrLabelXOffset50, validTimeFrame) trLib.drawLine(weekAdrLow50, 'W', ll, awrColor, awrStyle, 1, extend.right, showAWRLabels and validTimeFrame, adrLabelXOffset50, validTimeFrame) trLib.rLabelOffset((weekAdrHigh50 + weekAdrLow50) / 2, '50% AWR ' + str.format('{0,number,#.##}', trLib.toPips(weekAdr/2)) + 'PIPS|' + str.tostring(weekAdr/2, format.mintick) + syminfo.currency, label.style_none, awrColor, showAWRLabels and validTimeFrame and showAWRRange, adrLabelXOffset50) //ry, rtext, rstyle, rcolor, valid alertcondition(ta.crossover(close,weekAdrHigh) and weekAdrHigh != 0 , "AWR High reached", "PA has reached the calculated AWR High") alertcondition(ta.crossunder(close,weekAdrLow) and weekAdrLow != 0 , "AWR Low reached", "PA has reached the calculated AWR Low") alertcondition(ta.crossover(close,weekAdrHigh50) and weekAdrHigh50 != 0 , "50% of AWR High reached", "PA has reached 50% of the calculated AWR High") alertcondition(ta.crossunder(close,weekAdrLow50) and weekAdrLow50 != 0 , "50% AWR Low reached", "PA has reached 50% of the calculated AWR Low") //Monthly ADR [monthAdr, monthAdrHigh,monthAdrLow] = request.security(syminfo.tickerid, 'M', trLib.adrHiLo(aMRRange, 1, showAMRMO), lookahead=barmerge.lookahead_on) monthAdrHigh50 = monthAdrHigh - (monthAdr/2) monthAdrLow50 = monthAdrLow + (monthAdr/2) if showAMR and timeframe.isminutes and timeframe.multiplier >= 3 string hl = 'Hi-AMR'+ (showAMRMO?'(MO)':'') string ll = 'Lo-AMR'+ (showAMRMO?'(MO)':'') trLib.drawLine(monthAdrHigh, 'M', hl, amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adrLabelXOffset, validTimeFrame) trLib.drawLine(monthAdrLow, 'M', ll, amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adrLabelXOffset, validTimeFrame) trLib.rLabelOffset((monthAdrHigh + monthAdrLow) / 2, 'AMR ' + str.format('{0,number,#.##}', trLib.toPips(monthAdr)) + 'PIPS|' + str.tostring(monthAdr, format.mintick) + syminfo.currency, label.style_none, amrColor, showAMRLabels and validTimeFrame and showAMRRange,adrLabelXOffset) //ry, rtext, rstyle, rcolor, valid if showAMR and showAMR50 and timeframe.isminutes and timeframe.multiplier >= 3 string hl = '50% Hi-AMR'+ (showAMRMO?'(MO)':'') string ll = '50% Lo-AMR'+ (showAMRMO?'(MO)':'') trLib.drawLine(monthAdrHigh50, 'M', hl, amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adrLabelXOffset50, validTimeFrame) trLib.drawLine(monthAdrLow50, 'M', ll, amrColor, amrStyle, 1, extend.right, showAMRLabels and validTimeFrame, adrLabelXOffset50, validTimeFrame) trLib.rLabelOffset((monthAdrHigh50 + monthAdrLow50) / 2, '50% AMR ' + str.format('{0,number,#.##}', trLib.toPips(monthAdr/2)) + 'PIPS|' + str.tostring(monthAdr/2, format.mintick) + syminfo.currency, label.style_none, amrColor, showAMRLabels and validTimeFrame and showAMRRange,adrLabelXOffset50) //ry, rtext, rstyle, rcolor, valid alertcondition(ta.crossover(close,monthAdrHigh) and monthAdrHigh != 0 , "AMR High reached", "PA has reached the calculated AMR High") alertcondition(ta.crossunder(close,monthAdrLow) and monthAdrLow != 0 , "AMR Low reached", "PA has reached the calculated AMR Low") alertcondition(ta.crossover(close,monthAdrHigh50) and monthAdrHigh50 != 0 , "50% of AMR High reached", "PA has reached 50% of the calculated AMR High") alertcondition(ta.crossunder(close,monthAdrLow50) and monthAdrLow50 != 0 , "50% of AMR Low reached", "PA has reached 50% of the calculated AMR Low") //Range Daily Hi/Lo [dayRd, dayRangeHigh, dayRangeLow] = request.security(syminfo.tickerid, 'D', trLib.adrHiLo(rdRange, 1, showRDDO), lookahead=barmerge.lookahead_on) dayRangeHigh50 = dayRangeHigh - (dayRd/2) dayRangeLow50 = dayRangeLow + (dayRd/2) if showRD string hl = 'RD-Hi'+ (showRDDO?'(DO)':'') string ll = 'RD-Lo'+ (showRDDO?'(DO)':'') trLib.drawLine(dayRangeHigh, 'D', hl, rdColor, rdStyle, 2, extend.right, showRDLabels and validTimeFrame, rdLabelXOffset, validTimeFrame) trLib.drawLine(dayRangeLow, 'D', ll, rdColor, rdStyle, 2, extend.right, showRDLabels and validTimeFrame, rdLabelXOffset, validTimeFrame) trLib.rLabelOffset((dayRangeHigh + dayRangeLow) / 2, 'RD ' + str.format('{0,number,#.##}', trLib.toPips(dayRd)) + 'PIPS|' + str.tostring(dayRd/2, format.mintick) + syminfo.currency, label.style_none, rdColor, showRDLabels and validTimeFrame and showRDRange, rdLabelXOffset) //ry, rtext, rstyle, rcolor, valid if showRD and showRD50 string hl = '50% RD-Hi'+ (showRDDO?'(DO)':'') string ll = '50% RD-Lo'+ (showRDDO?'(DO)':'') trLib.drawLine(dayRangeHigh50, 'D', hl, rdColor, rdStyle, 2, extend.right, showRDLabels and validTimeFrame, rdLabelXOffset50, validTimeFrame) trLib.drawLine(dayRangeLow50, 'D', ll, rdColor, rdStyle, 2, extend.right, showRDLabels and validTimeFrame, rdLabelXOffset50, validTimeFrame) trLib.rLabelOffset((dayRangeHigh50 + dayRangeHigh50) / 2, '50% RD ' + str.format('{0,number,#.##}', trLib.toPips(dayRd/2)) + 'PIPS|' + str.tostring(dayRd/2, format.mintick) + syminfo.currency, label.style_none, rdColor, showRDLabels and validTimeFrame and showRDRange, rdLabelXOffset50) //ry, rtext, rstyle, rcolor, valid alertcondition(ta.crossover(close, dayRangeHigh) and dayRangeHigh != 0 , "Range Daily High reached", "PA has reached the calculated Range Daily High") alertcondition(ta.crossunder(close,dayRangeLow) and dayRangeLow != 0 , "Range Daily Low reached", "PA has reached the calculated Range Daily Low") alertcondition(ta.crossover(close,dayRangeHigh50) and dayRangeHigh50 != 0 , "50% of Range Daily High reached", "PA has reached 50% of the calculated Range Daily High") alertcondition(ta.crossunder(close,dayRangeLow50) and dayRangeLow50 != 0 , "50% of Range Daily Low reached", "PA has reached 50% of the calculated Range Daily Low") //Range Weekly Hi/Lo [weekRd, weekRangeHigh, weekRangeLow] = request.security(syminfo.tickerid, 'W', trLib.adrHiLo(rwRange, 1, showRWWO), lookahead=barmerge.lookahead_on) weekRangeHigh50 = weekRangeHigh - (weekRd/2) weekRangeLow50 = weekRangeLow + (weekRd/2) if showRW string hl = 'RW-Hi'+ (showRWWO?'(WO)':'') string ll = 'RW-Lo'+ (showRWWO?'(WO)':'') trLib.drawLine(weekRangeHigh, 'D', hl, rwColor, rwStyle, 2, extend.right, showRWLabels and validTimeFrame, rdLabelXOffset, validTimeFrame) trLib.drawLine(weekRangeLow, 'D', ll, rwColor, rwStyle, 2, extend.right, showRWLabels and validTimeFrame, rdLabelXOffset, validTimeFrame) trLib.rLabelOffset((weekRangeHigh + weekRangeLow) / 2, 'RW ' + str.format('{0,number,#.##}', trLib.toPips(weekRd)) + 'PIPS|' + str.tostring(weekRd/2, format.mintick) + syminfo.currency, label.style_none, rwColor, showRWLabels and validTimeFrame and showRWRange,rdLabelXOffset) //ry, rtext, rstyle, rcolor, valid if showRW and showRW50 string hl = '50% RW-Hi'+ (showRWWO?'(WO)':'') string ll = '50% RW-Lo'+ (showRWWO?'(WO)':'') trLib.drawLine(weekRangeHigh50, 'D', hl, rwColor, rwStyle, 2, extend.right, showRWLabels and validTimeFrame, rdLabelXOffset50, validTimeFrame) trLib.drawLine(weekRangeLow50, 'D', ll, rwColor, rwStyle, 2, extend.right, showRWLabels and validTimeFrame, rdLabelXOffset50, validTimeFrame) trLib.rLabelOffset((weekRangeHigh50 + weekRangeLow50) / 2, '50% RW ' + str.format('{0,number,#.##}', trLib.toPips(weekRd/2)) + 'PIPS|' + str.tostring(weekRd/2, format.mintick) + syminfo.currency, label.style_none, rwColor, showRWLabels and validTimeFrame and showRWRange, rdLabelXOffset50) //ry, rtext, rstyle, rcolor, valid alertcondition(ta.crossover(close,weekRangeHigh) and weekRangeHigh != 0 , "Range Weekly High reached", "PA has reached the calculated Range Weekly High") alertcondition(ta.crossunder(close,weekRangeLow) and weekRangeLow != 0 , "Range Weekly Low reached", "PA has reached the calculated Range Weekly Low") alertcondition(ta.crossover(close,weekRangeHigh50) and weekRangeHigh50 != 0 , "50% of Range Weekly High reached", "PA has reached 50% of the calculated Range Weekly High") alertcondition(ta.crossunder(close,weekRangeLow50) and weekRangeLow50 != 0 , "50% of Range Weekly Low reached", "PA has reached 50% of the calculated Range Weekly Low") if barstate.islast and showAdrTable and validTimeFrame if showAdrPips or showAdrCurrency var table panel = table.new(choiceAdrTable, 2, 16, bgcolor=adrTableBgColor) // Table header. table.cell(panel, 0, 0, '') table.cell(panel, 1, 0, '') if showAdrPips table.cell(panel, 0, 2, 'ADR', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 2, str.format('{0,number,#.##}', trLib.toPips(dayAdr)) + "PIPS" , text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 3, 'ADRx3', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 3, str.format('{0,number,#.##}', trLib.toPips(dayAdr) * 3)+ "PIPS", text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 4, 'AWR', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 4, str.format('{0,number,#.##}', trLib.toPips(weekAdr)) + "PIPS", text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 5, 'AMR', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 5, str.format('{0,number,#.##}', trLib.toPips(monthAdr)) + "PIPS", text_color=adrTableTxtColor, text_halign=text.align_left) if showAdrCurrency table.cell(panel, 0, 6, 'ADR', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 6, str.tostring(dayAdr, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 7, 'ADRx3', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 7, str.tostring(dayAdr * 3, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 8, 'AWR', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 8, str.tostring(weekAdr, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 9, 'AMR', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 9, str.tostring(monthAdr, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) if showRDPips table.cell(panel, 0, 10, 'RD', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 10, str.format('{0,number,#.##}', trLib.toPips(dayRd)) + "PIPS" , text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 11, 'RDx3', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 11, str.format('{0,number,#.##}', trLib.toPips(dayRd) * 3)+ "PIPS", text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 12, 'RW', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 12, str.format('{0,number,#.##}', trLib.toPips(weekRd)) + "PIPS", text_color=adrTableTxtColor, text_halign=text.align_left) if showRDCurrency table.cell(panel, 0, 13, 'RD', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 13, str.tostring(dayRd, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 14, 'RDx3', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 14, str.tostring(dayRd * 3, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 0, 15, 'RW', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(panel, 1, 15, str.tostring(weekRd, format.mintick) + syminfo.currency, text_color=adrTableTxtColor, text_halign=text.align_left) // M - Levels //Calculate Pivot Point // 2021-03025 updated by infernix //M calculations m0C = (pivS2 + pivS3) / 2 m1C = (pivS1 + pivS2) / 2 m2C = (pivotPoint + pivS1) / 2 m3C = (pivotPoint + pivR1) / 2 m4C = (pivR1 + pivR2) / 2 m5C = (pivR2 + pivR3) / 2 trLib.drawPivot(validTimeFrame and activeM and m0C ? m0C : na, 'D', 'M0', mColor, mLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) trLib.drawPivot(validTimeFrame and activeM and m1C ? m1C : na, 'D', 'M1', mColor, mLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) trLib.drawPivot(validTimeFrame and activeM and m2C ? m2C : na, 'D', 'M2', mColor, mLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) trLib.drawPivot(validTimeFrame and activeM and m3C ? m3C : na, 'D', 'M3', mColor, mLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) trLib.drawPivot(validTimeFrame and activeM and m4C ? m4C : na, 'D', 'M4', mColor, mLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) trLib.drawPivot(validTimeFrame and activeM and m5C ? m5C : na, 'D', 'M5', mColor, mLabelColor, mStyle, 1, extendPivots ? extend.both : extend.right, showMLabels and validTimeFrame, validTimeFrame, levelStart, pivotLabelXOffset) //***************** // Market sessions //***************** [nyDST, ukDST, sydDST] = trLib.calcDst() if ukDST trLib.drawOpenRange(sess1Time,sess1col,showOr1,'GMT+1') trLib.drawSessionHiLo(sess1Time, showRectangle1, showLabel1, sess1colLabel, sess1Label, 'GMT+1', rectStyle) else trLib.drawOpenRange(sess1Time,sess1col,showOr1,'GMT+0') trLib.drawSessionHiLo(sess1Time, showRectangle1, showLabel1, sess1colLabel, sess1Label, 'GMT+0', rectStyle) if nyDST trLib.drawOpenRange(sess2Time,sess2col,showOr2,'GMT+1') trLib.drawSessionHiLo(sess2Time, showRectangle2, showLabel2, sess2colLabel, sess2Label, 'GMT+1', rectStyle) else trLib.drawOpenRange(sess2Time,sess2col,showOr2,'GMT+0') trLib.drawSessionHiLo(sess2Time, showRectangle2, showLabel2, sess2colLabel, sess2Label, 'GMT+0', rectStyle) // Tokyo trLib.drawOpenRange(sess3Time,sess3col,showOr3,'GMT+0') trLib.drawSessionHiLo(sess3Time, showRectangle3, showLabel3, sess3colLabel, sess3Label, 'GMT+0', rectStyle) // Hong Kong trLib.drawOpenRange(sess4Time,sess4col,showOr4,'GMT+0') trLib.drawSessionHiLo(sess4Time, showRectangle4, showLabel4, sess4colLabel, sess4Label, 'GMT+0', rectStyle) if sydDST trLib.drawOpenRange(sess5Time,sess5col,showOr5,'GMT+1') trLib.drawSessionHiLo(sess5Time, showRectangle5, showLabel5, sess5colLabel, sess5Label, 'GMT+1', rectStyle) else trLib.drawOpenRange(sess5Time,sess5col,showOr5,'GMT+0') trLib.drawSessionHiLo(sess5Time, showRectangle5, showLabel5, sess5colLabel, sess5Label, 'GMT+0', rectStyle) //eu brinks is for london if ukDST trLib.drawOpenRange(sess6Time,sess6col,showOr6,'GMT+1') trLib.drawSessionHiLo(sess6Time, showRectangle6, showLabel6, sess6colLabel, sess6Label, 'GMT+1', rectStyle) else trLib.drawOpenRange(sess6Time,sess6col,showOr6,'GMT+0') trLib.drawSessionHiLo(sess6Time, showRectangle6, showLabel6, sess6colLabel, sess6Label, 'GMT+0', rectStyle) //us brinks is ny if nyDST trLib.drawOpenRange(sess7Time,sess7col,showOr7,'GMT+1') trLib.drawSessionHiLo(sess7Time, showRectangle7, showLabel7, sess7colLabel, sess7Label, 'GMT+1', rectStyle) else trLib.drawOpenRange(sess7Time,sess7col,showOr7,'GMT+0') trLib.drawSessionHiLo(sess7Time, showRectangle7, showLabel7, sess7colLabel, sess7Label, 'GMT+0', rectStyle) //becuase frankfurt changes with london if ukDST trLib.drawOpenRange(sess8Time,sess8col,showOr8,'GMT+1') trLib.drawSessionHiLo(sess8Time, showRectangle8, showLabel8, sess8colLabel, sess8Label, 'GMT+1', rectStyle) else trLib.drawOpenRange(sess8Time,sess8col,showOr8,'GMT+0') trLib.drawSessionHiLo(sess8Time, showRectangle8, showLabel8, sess8colLabel, sess8Label, 'GMT+0', rectStyle) //************// // Psy Levels // //************// var int oneWeekMillis = (7 * 24 * 60 * 60 * 1000) [psyHi, psyLo, psyHiLabel, psyLoLabel, psySessionStartTime] = trLib.calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST) // Draw Psy Level Lines if (barstate.islast) and not showAllPsy and showPsylevels // Extend line back to the previous start time (after Psy-Hi/Lo have been calculated) psyHiLine = line.new(time, psyHi, psySessionStartTime, psyHi, xloc.bar_time, extend.none, psyColH) line.delete(psyHiLine[1]) psyLoLine = line.new(time, psyLo, psySessionStartTime, psyLo, xloc.bar_time, extend.none, psyColL) line.delete(psyLoLine[1]) // Write Psy Level Labels - same label regardless if line.new or plot used trLib.rLabelLastBar(psyHi, psyHiLabel, label.style_none, psyColH, showPsylabel, labelXOffset) trLib.rLabelLastBar(psyLo, psyLoLabel, label.style_none, psyColL, showPsylabel, labelXOffset) // Plot Historical Psy Level plot(showPsy and showPsylevels and showAllPsy ? psyHi : na, color=psyColH, style=plot.style_stepline, linewidth=2, editable=false, title="Psy-Hi") //, offset=psy_plot_offset) plot(showPsy and showPsylevels and showAllPsy ? psyLo : na, color=psyColL, style=plot.style_stepline, linewidth=2, editable=false, title="Psy-Lo") //, offset=psy_plot_offset) alertcondition(ta.crossunder(close,psyHi) and not na(psyHi) and psyHi != 0 , "PA crossed under Psy Hi", "PA has crossed under the Psy Hi") alertcondition(ta.crossover(close,psyHi) and not na(psyHi) and psyHi != 0 , "PA crossed over Psy Hi", "PA has crossed over the Psy Hi") alertcondition(ta.crossunder(close,psyLo) and not na(psyLo) and psyLo != 0 , "PA crossed under Psy Lo", "PA has crossed under the Psy Lo") alertcondition(ta.crossover(close,psyLo) and not na(psyLo) and psyLo != 0 , "PA crossed over Psy Lo", "PA has crossed over the Psy Lo") //*********** // Daily open //*********** dailyOpen = trLib.getdayOpen() //this plot is only to show historical values when the option is selected. plot(showRectangle9 and validTimeFrame and showallDly ? dailyOpen : na, color=sess9col, style=plot.style_stepline, linewidth=2, editable=false, title="Daily Open") if showallDly //if historical values are selected to be shown - then add a label to the plot trLib.rLabel(dailyOpen, 'Daily Open', label.style_none, sess9col, validTimeFrame and showLabel9, labelXOffset) showallDly else if showRectangle9 //othewise we draw the line and label together - showing only todays line. trLib.drawLineDO(dailyOpen, 'D', 'Daily Open', sess9col, line.style_solid, 1, extend.none, validTimeFrame and showLabel9, labelXOffset, validTimeFrame) alertcondition(ta.cross(close,dailyOpen) and not na(dailyOpen) and dailyOpen != 0 , "PA crossed Daily open", "PA has crossed the Daily open") //London DST Starts Last Sunday of March DST Edns Last Sunday of October //New York DST Starts 2nd Sunday of March DST Edns 1st Sunday of November //Sydney DST Start on 1st Sunday of October DST ends 1st Sunday of Arpil //Frankfurt DST Starts Last Sunday of March DST Edns Last Sunday of October if barstate.islast and showDstTable var table dstTable = table.new(choiceDstTable, 2, 8, bgcolor=dstTableBgColor) //general table.cell(dstTable, 0, 0, 'London DST Starts Last Sunday of March | DST Ends Last Sunday of October', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 1, 'New York DST Starts 2nd Sunday of March | DST Ends 1st Sunday of November', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 2, 'Tokyo does not observe DST', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 3, 'Hong Kong does not observe DST', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 4, 'Sydney DST Start on 1st Sunday of October | DST Ends 1st Sunday of Arpil', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 5, 'EU Brinks DST Starts Last Sunday of March | DST Ends Last Sunday of October', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 6, 'US Brinks DST Starts 2nd Sunday of March | DST Ends 1st Sunday of November', text_color=adrTableTxtColor, text_halign=text.align_left) table.cell(dstTable, 0, 7, 'Frankfurt DST Starts Last Sunday of March | DST Ends Last Sunday of October', text_color=adrTableTxtColor, text_halign=text.align_left) //Vector Candle Zones var zoneBoxesAbove = array.new_box() var zoneBoxesBelow = array.new_box() if showVCZ pvsra = trLib.getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, regularCandleUpColor) trLib.updateZones(pvsra, 0, zoneBoxesBelow, zonesMax, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneUpdateType, zoneColor, zoneType, borderWidth, colorOverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor) trLib.updateZones(pvsra, 1, zoneBoxesAbove, zonesMax, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneUpdateType, zoneColor, zoneType, borderWidth, colorOverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor) trLib.cleanarr(zoneBoxesAbove) trLib.cleanarr(zoneBoxesBelow)
Spider Lines For Bitcoin (Daily And Weekly)
https://www.tradingview.com/script/fdSLB8oI-Spider-Lines-For-Bitcoin-Daily-And-Weekly/
chinmaysk1
https://www.tradingview.com/u/chinmaysk1/
108
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/ // © chinmaysk1 //@version=5 indicator("Daily and Weekly Spider Lines For Bitcoin", overlay=true) if timeframe.isweekly // CANDLE POSITIONS yeartd = year(timenow) monthtd = month(timenow) daytd = dayofmonth(timenow) timestamp_today = timestamp("GMT",yeartd,monthtd,daytd,00,00,00) timestamp_july = timestamp("GMT",2019,07,01,00,00,00) days = (timestamp_today - timestamp_july) / (24 * 60 * 60 * 1000) weeks = days / 7 connection_candle = weeks //connection_candle = input(135, title="If on weekly chart, number of weeks since 01 July 2019: ") candle0 = connection_candle + 32 candle0_ = connection_candle + 33 candle1 = connection_candle + 34 candle2 = connection_candle + 36 candle3 = connection_candle + 38 candle4 = connection_candle + 40 candle5 = connection_candle + 42 candle6 = connection_candle + 44 candle7 = connection_candle + 46 candle8 = connection_candle + 48 candle9 = connection_candle + 50 candle10 = connection_candle + 52 candle11 = connection_candle + 54 candle12 = connection_candle + 56 candle13 = connection_candle + 58 candle14 = connection_candle + 60 // RAYS if barstate.islast ray = line.new(x1=bar_index[candle0], y1=high[candle0], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle0_], y1=high[candle0_], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle1], y1=high[candle1], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle2], y1=high[candle2], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle3], y1=high[candle3], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle4], y1=high[candle4], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle5], y1=high[candle5], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle6], y1=high[candle6], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle7], y1=high[candle7], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle8], y1=high[candle8], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle9], y1=high[candle9], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle10], y1=high[candle10], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle11], y1=high[candle11], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle12], y1=high[candle12], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle13], y1=high[candle13], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle14], y1=high[candle14], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if timeframe.isdaily // CANDLE POSITIONS yeartd = year(timenow) monthtd = month(timenow) daytd = dayofmonth(timenow) timestamp_today = timestamp("GMT",yeartd,monthtd,daytd,00,00,00) timestamp_july = timestamp("GMT",2019,07,01,00,00,00) days = (timestamp_today - timestamp_july) / (24 * 60 * 60 * 1000) connection_candle = days candle0 = connection_candle + 224 candle0_ = connection_candle + 238 candle1 = connection_candle + 252 candle2 = connection_candle + 266 candle3 = connection_candle + 280 candle4 = connection_candle + 294 candle5 = connection_candle + 308 candle6 = connection_candle + 322 candle7 = connection_candle + 336 candle8 = connection_candle + 350 candle9 = connection_candle + 364 candle10 = connection_candle + 378 candle11 = connection_candle + 392 candle12 = connection_candle + 406 candle13 = connection_candle + 420 candle14 = connection_candle + 434 // RAYS if barstate.islast ray = line.new(x1=bar_index[candle0], y1=high[candle0], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle0_], y1=high[candle0_], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle1], y1=high[candle1], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle2], y1=high[candle2], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle3], y1=high[candle3], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle4], y1=high[candle4], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle5], y1=high[candle5], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle6], y1=high[candle6], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle7], y1=high[candle7], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle8], y1=high[candle8], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle9], y1=high[candle9], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle10], y1=high[candle10], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle11], y1=high[candle11], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle12], y1=high[candle12], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle13], y1=high[candle13], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1]) if barstate.islast ray = line.new(x1=bar_index[candle14], y1=high[candle14], x2=bar_index[connection_candle], y2=close[connection_candle]) line.set_color(ray, color.white) line.set_extend(ray, extend.right) line.set_style(ray, line.style_dashed) line.set_width(ray, 1) line.delete(ray[1])
Newzage - Fed Net Liquidity
https://www.tradingview.com/script/uEdoudsx-Newzage-Fed-Net-Liquidity/
azurablev
https://www.tradingview.com/u/azurablev/
391
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/ // © azurablev //@version=5 indicator(title='Fed Net Liquidity', shorttitle='Net Liq.', overlay=false) factor = input.float(1.5,"factor: ",1,2,0.01) minus_value = input.float(1655,"minus value: ",1000,20000,10) fairVal = request.security("((FRED:WALCL-FRED:WTREGEN-FRED:RRPONTSYD)/100000000)","", ta.ema(close, 1)) fv = (fairVal / factor - minus_value) / 10 spx = request.security("SPX","D", ta.ema(close, 3)) lema = spx - fv spy = request.security("SPY","D", ta.ema(close, 1)) len = input.int(12, minval=1, title="RSI Length") len2 = input.int(9, minval=1, title="EMA of RSI Length") emaRSI = ta.ema(ta.rsi(spy,len),len2) plot(lema, title='Net Liquidity', style=plot.style_line, linewidth=2, color=color.new(color.white, 0)) band1 = hline(280, title='Upper Line', linestyle=hline.style_dashed, linewidth=1, color=color.gray) band3 = hline(-40, title='Lower Line', linestyle=hline.style_dashed, linewidth=1, color=color.white) band0 = hline(-150, title='Lower Line', linestyle=hline.style_dashed, linewidth=1, color=color.gray) rsi_col1 = lema>=281 and emaRSI>=50 ? color.red : lema<=-150 and emaRSI<=42.5 ? color.green : color.black bgcolor(rsi_col1, transp=30) mult1 = spx < fv and emaRSI <= 36 ? 1.08: (spx < fv and emaRSI >= 36 ? 1.035 : 1) mult2 = spx > fv and emaRSI >= 60 ? 0.94: (spx < fv and emaRSI <= 60 ? 0.97 : 1) lblTxt = spx < fv ? str.tostring(math.round(spx/10)) + "->" + str.tostring(math.round(fv/10*mult1)) : str.tostring(math.round(spx/10)) + "->" + str.tostring(math.round(fv/10*mult2)) showLabel = (lema >= 281 and emaRSI >= 50) or (lema <= -150 and emaRSI <= 38.5) if showLabel and not showLabel[1] label.new(bar_index, lema, text=lblTxt, style=label.style_label_down, color=color.orange, size=size.small)
Keltner Channel Volatility Filter
https://www.tradingview.com/script/IpKGSxLv-Keltner-Channel-Volatility-Filter/
bjr117
https://www.tradingview.com/u/bjr117/
55
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © bjr117 //@version=5 indicator(title = "Keltner Channel Volatility Filter", shorttitle = "KCVF", overlay = true) //============================================================================== // Function: Calculate a given type of moving average //============================================================================== get_ma_out(type, src, len, alma_offset, alma_sigma, kama_fastLength, kama_slowLength, vama_vol_len, vama_do_smth, vama_smth, mf_beta, mf_feedback, mf_z, eit_alpha, ssma_pow, ssma_smooth, rsrma_pw, svama_method, svama_vol_or_volatility, wrma_smooth) => float baseline = 0.0 if type == 'SMA | Simple MA' baseline := ta.sma(src, len) else if type == 'EMA | Exponential MA' baseline := ta.ema(src, len) else if type == 'DEMA | Double Exponential MA' e = ta.ema(src, len) baseline := 2 * e - ta.ema(e, len) else if type == 'TEMA | Triple Exponential MA' e = ta.ema(src, len) baseline := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) else if type == 'TMA | Triangular MA' // by everget baseline := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) else if type == 'WMA | Weighted MA' baseline := ta.wma(src, len) else if type == 'VWMA | Volume-Weighted MA' baseline := ta.vwma(src, len) else if type == 'SMMA | Smoothed MA' w = ta.wma(src, len) baseline := na(w[1]) ? ta.sma(src, len) : (w[1] * (len - 1) + src) / len else if type == 'RMA | Rolling MA' baseline := ta.rma(src, len) else if type == 'HMA | Hull MA' baseline := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) else if type == 'LSMA | Least Squares MA' baseline := ta.linreg(src, len, 0) else if type == 'Kijun' //Kijun-sen kijun = math.avg(ta.lowest(len), ta.highest(len)) baseline := kijun else if type == 'MD | McGinley Dynamic' mg = 0.0 mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4)) baseline := mg else if type == 'JMA | Jurik MA' // by everget DEMAe1 = ta.ema(src, len) DEMAe2 = ta.ema(DEMAe1, len) baseline := 2 * DEMAe1 - DEMAe2 else if type == 'ALMA | Arnaud Legoux MA' baseline := ta.alma(src, len, alma_offset, alma_sigma) else if type == 'VAR | Vector Autoregression MA' valpha = 2 / (len+1) vud1 = (src > src[1]) ? (src - src[1]) : 0 vdd1 = (src < src[1]) ? (src[1] - src) : 0 vUD = math.sum(vud1, 9) vDD = math.sum(vdd1, 9) vCMO = nz( (vUD - vDD) / (vUD + vDD) ) baseline := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(baseline[1]) else if type == 'ZLEMA | Zero-Lag Exponential MA' // by HPotter xLag = (len) / 2 xEMAData = (src + (src - src[xLag])) baseline := ta.ema(xEMAData, len) else if type == 'AHMA | Ahrens Moving Average' // by everget baseline := nz(baseline[1]) + (src - (nz(baseline[1]) + nz(baseline[len])) / 2) / len else if type == 'EVWMA | Elastic Volume Weighted MA' volumeSum = math.sum(volume, len) baseline := ( (volumeSum - volume) * nz(baseline[1]) + volume * src ) / volumeSum else if type == 'SWMA | Sine Weighted MA' // by everget sum = 0.0 weightSum = 0.0 for i = 0 to len - 1 weight = math.sin(i * math.pi / (len + 1)) sum := sum + nz(src[i]) * weight weightSum := weightSum + weight baseline := sum / weightSum else if type == 'LMA | Leo MA' baseline := 2 * ta.wma(src, len) - ta.sma(src, len) else if type == 'VIDYA | Variable Index Dynamic Average' // by KivancOzbilgic mom = ta.change(src) upSum = math.sum(math.max(mom, 0), len) downSum = math.sum(-math.min(mom, 0), len) out = (upSum - downSum) / (upSum + downSum) cmo = math.abs(out) alpha = 2 / (len + 1) baseline := src * alpha * cmo + nz(baseline[1]) * (1 - alpha * cmo) else if type == 'FRAMA | Fractal Adaptive MA' length2 = math.floor(len / 2) hh2 = ta.highest(length2) ll2 = ta.lowest(length2) N1 = (hh2 - ll2) / length2 N2 = (hh2[length2] - ll2[length2]) / length2 N3 = (ta.highest(len) - ta.lowest(len)) / len D = (math.log(N1 + N2) - math.log(N3)) / math.log(2) factor = math.exp(-4.6 * (D - 1)) baseline := factor * src + (1 - factor) * nz(baseline[1]) else if type == 'VMA | Variable MA' // by LazyBear k = 1.0/len pdm = math.max((src - src[1]), 0) mdm = math.max((src[1] - src), 0) pdmS = float(0.0) mdmS = float(0.0) pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm) mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm) s = pdmS + mdmS pdi = pdmS/s mdi = mdmS/s pdiS = float(0.0) mdiS = float(0.0) pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi) mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi) d = math.abs(pdiS - mdiS) s1 = pdiS + mdiS iS = float(0.0) iS := ((1 - k)*nz(iS[1]) + k*d/s1) hhv = ta.highest(iS, len) llv = ta.lowest(iS, len) d1 = hhv - llv vI = (iS - llv)/d1 baseline := (1 - k*vI)*nz(baseline[1]) + k*vI*src else if type == 'GMMA | Geometric Mean MA' lmean = math.log(src) smean = math.sum(lmean, len) baseline := math.exp(smean / len) else if type == 'CMA | Corrective MA' // by everget sma = ta.sma(src, len) baseline := sma v1 = ta.variance(src, len) v2 = math.pow(nz(baseline[1], baseline) - baseline, 2) v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2) var tolerance = math.pow(10, -5) float err = 1 // Gain Factor float kPrev = 1 float k = 1 for i = 0 to 5000 by 1 if err > tolerance k := v3 * kPrev * (2 - kPrev) err := kPrev - k kPrev := k kPrev baseline := nz(baseline[1], src) + k * (sma - nz(baseline[1], src)) else if type == 'MM | Moving Median' // by everget baseline := ta.percentile_nearest_rank(src, len, 50) else if type == 'QMA | Quick MA' // by everget peak = len / 3 num = 0.0 denom = 0.0 for i = 1 to len + 1 mult = 0.0 if i <= peak mult := i / peak else mult := (len + 1 - i) / (len + 1 - peak) num := num + src[i - 1] * mult denom := denom + mult baseline := (denom != 0.0) ? (num / denom) : src else if type == 'KAMA | Kaufman Adaptive MA' // by everget mom = math.abs(ta.change(src, len)) volatility = math.sum(math.abs(ta.change(src)), len) // Efficiency Ratio er = volatility != 0 ? mom / volatility : 0 fastAlpha = 2 / (kama_fastLength + 1) slowAlpha = 2 / (kama_slowLength + 1) alpha = math.pow(er * (fastAlpha - slowAlpha) + slowAlpha, 2) baseline := alpha * src + (1 - alpha) * nz(baseline[1], src) else if type == 'VAMA | Volatility Adjusted MA' // by Joris Duyck (JD) mid = ta.ema(src, len) dev = src - mid vol_up = ta.highest(dev, vama_vol_len) vol_down = ta.lowest(dev, vama_vol_len) vama = mid + math.avg(vol_up, vol_down) baseline := vama_do_smth ? ta.wma(vama, vama_smth) : vama else if type == 'Modular Filter' // by alexgrover //---- b = 0.0, c = 0.0, os = 0.0, ts = 0.0 //---- alpha = 2/(len+1) a = mf_feedback ? mf_z*src + (1-mf_z)*nz(baseline[1],src) : src //---- b := a > alpha*a+(1-alpha)*nz(b[1],a) ? a : alpha*a+(1-alpha)*nz(b[1],a) c := a < alpha*a+(1-alpha)*nz(c[1],a) ? a : alpha*a+(1-alpha)*nz(c[1],a) os := a == b ? 1 : a == c ? 0 : os[1] //---- upper = mf_beta*b+(1-mf_beta)*c lower = mf_beta*c+(1-mf_beta)*b baseline := os*upper+(1-os)*lower else if type == 'EIT | Ehlers Instantaneous Trendline' // by Franklin Moormann (cheatcountry) baseline := bar_index < 7 ? (src + (2 * nz(src[1])) + nz(src[2])) / 4 : ((eit_alpha - (math.pow(eit_alpha, 2) / 4)) * src) + (0.5 * math.pow(eit_alpha, 2) * nz(src[1])) - ((eit_alpha - (0.75 * math.pow(eit_alpha, 2))) * nz(src[2])) + (2 * (1 - eit_alpha) * nz(baseline[1])) - (math.pow(1 - eit_alpha, 2) * nz(baseline[2])) else if type == 'ESD | Ehlers Simple Decycler' // by everget // High-pass Filter alphaArg = 2 * math.pi / (len * math.sqrt(2)) alpha = 0.0 alpha := math.cos(alphaArg) != 0 ? (math.cos(alphaArg) + math.sin(alphaArg) - 1) / math.cos(alphaArg) : nz(alpha[1]) hp = 0.0 hp := math.pow(1 - (alpha / 2), 2) * (src - 2 * nz(src[1]) + nz(src[2])) + 2 * (1 - alpha) * nz(hp[1]) - math.pow(1 - alpha, 2) * nz(hp[2]) baseline := src - hp else if type == 'SSMA | Shapeshifting MA' // by alexgrover //---- ssma_sum = 0.0 ssma_sumw = 0.0 alpha = ssma_smooth ? 2 : 1 power = ssma_smooth ? ssma_pow - ssma_pow % 2 : ssma_pow //---- for i = 0 to len-1 x = i/(len-1) n = ssma_smooth ? -1 + x*2 : x w = 1 - 2*math.pow(n,alpha)/(math.pow(n,power) + 1) ssma_sumw := ssma_sumw + w ssma_sum := ssma_sum + src[i] * w baseline := ssma_sum/ssma_sumw //---- else if type == 'RSRMA | Right Sided Ricker MA' // by alexgrover //---- rsrma_sum = 0.0 rsrma_sumw = 0.0 rsrma_width = rsrma_pw/100*len for i = 0 to len-1 w = (1 - math.pow(i/rsrma_width,2))*math.exp(-(i*i/(2*math.pow(rsrma_width,2)))) rsrma_sumw := rsrma_sumw + w rsrma_sum := rsrma_sum + src[i] * w baseline := rsrma_sum/rsrma_sumw //---- else if type == 'DSWF | Damped Sine Wave Weighted Filter' // by alexgrover //---- dswf_sum = 0.0 dswf_sumw = 0.0 for i = 1 to len w = math.sin(2.0*math.pi*i/len)/i dswf_sumw := dswf_sumw + w dswf_sum := dswf_sum + w*src[i-1] //---- baseline := dswf_sum/dswf_sumw else if type == 'BMF | Blackman Filter' // by alexgrover //---- bmf_sum = 0.0 bmf_sumw = 0.0 for i = 0 to len-1 k = i/len w = 0.42 - 0.5 * math.cos(2 * math.pi * k) + 0.08 * math.cos(4 * math.pi * k) bmf_sumw := bmf_sumw + w bmf_sum := bmf_sum + w*src[i] //---- baseline := bmf_sum/bmf_sumw else if type == 'HCF | Hybrid Convolution Filter' // by alexgrover //---- sum = 0. for i = 1 to len sgn = .5*(1 - math.cos((i/len)*math.pi)) sum := sum + (sgn*(nz(baseline[1],src)) + (1 - sgn)*src[i-1]) * ( (.5*(1 - math.cos((i/len)*math.pi))) - (.5*(1 - math.cos(((i-1)/len)*math.pi))) ) baseline := sum //---- else if type == 'FIR | Finite Response Filter' // by alexgrover //---- var b = array.new_float(0) if barstate.isfirst for i = 0 to len-1 w = len-i array.push(b,w) den = array.sum(b) //---- sum = 0.0 for i = 0 to len-1 sum := sum + src[i]*array.get(b,i) baseline := sum/den else if type == 'FLSMA | Fisher Least Squares MA' // by alexgrover //---- b = 0.0 //---- e = ta.sma(math.abs(src - nz(b[1])),len) z = ta.sma(src - nz(b[1],src),len)/e r = (math.exp(2*z) - 1)/(math.exp(2*z) + 1) a = (bar_index - ta.sma(bar_index,len))/ta.stdev(bar_index,len) * r b := ta.sma(src,len) + a*ta.stdev(src,len) baseline := b else if type == 'SVAMA | Non-Parametric Volume Adjusted MA' // by alexgrover and bjr117 //---- h = 0.0 l = 0.0 c = 0.0 //---- a = svama_vol_or_volatility == 'Volume' ? volume : ta.tr h := a > nz(h[1], a) ? a : nz(h[1], a) l := a < nz(l[1], a) ? a : nz(l[1], a) //---- b = svama_method == 'Max' ? a / h : l / a c := b * close + (1 - b) * nz(c[1], close) baseline := c else if type == 'RPMA | Repulsion MA' // by alexgrover baseline := ta.sma(close, len*3) + ta.sma(close, len*2) - ta.sma(close, len) else if type == 'WRMA | Well Rounded MA' // by alexgrover //---- alpha = 2/(len+1) p1 = wrma_smooth ? len/4 : 1 p2 = wrma_smooth ? len/4 : len/2 //---- a = float(0.0) b = float(0.0) y = ta.ema(a + b,p1) A = src - y B = src - ta.ema(y,p2) a := nz(a[1]) + alpha*nz(A[1]) b := nz(b[1]) + alpha*nz(B[1]) baseline := y baseline //============================================================================== //============================================================================== // Inputs //============================================================================== // Calculation Settins kc_length = input.int(title = "Keltner Channel Length", defval = 20, minval = 1, group = "Keltner Channel Volatility Filter Settings") kc_mult = input.float(title = "Keltner Channel Multiplier", defval = 1.0, minval = 0.00001, step = 0.25, group = "Keltner Channel Volatility Filter Settings") kc_src = input.source(title = "Keltner Channel Calculation Source", defval = close, group = "Keltner Channel Volatility Filter Settings") kcvf_src = input.source(title = "Keltner Channel Price Filter Source", defval = hl2, group = "Keltner Channel Volatility Filter Settings") kc_ma_type = input.string('EMA | Exponential MA', 'MA Type', options=[ 'EMA | Exponential MA', 'SMA | Simple MA', 'WMA | Weighted MA', 'DEMA | Double Exponential MA', 'TEMA | Triple Exponential MA', 'TMA | Triangular MA', 'VWMA | Volume-Weighted MA', 'SMMA | Smoothed MA', 'HMA | Hull MA', 'LSMA | Least Squares MA', 'Kijun', 'MD | McGinley Dynamic', 'RMA | Rolling MA', 'JMA | Jurik MA', 'ALMA | Arnaud Legoux MA', 'VAR | Vector Autoregression MA', 'ZLEMA | Zero-Lag Exponential MA', 'AHMA | Ahrens Moving Average', 'EVWMA | Elastic Volume Weighted MA', 'SWMA | Sine Weighted MA', 'LMA | Leo MA', 'VIDYA | Variable Index Dynamic Average', 'FRAMA | Fractal Adaptive MA', 'VMA | Variable MA', 'GMMA | Geometric Mean MA', 'CMA | Corrective MA', 'MM | Moving Median', 'QMA | Quick MA', 'KAMA | Kaufman Adaptive MA', 'VAMA | Volatility Adjusted MA', 'Modular Filter', 'EIT | Ehlers Instantaneous Trendline', 'ESD | Ehlers Simple Decycler', 'SSMA | Shapeshifting MA', 'RSRMA | Right Sided Ricker MA', 'DSWF | Damped Sine Wave Weighted Filter', 'BMF | Blackman Filter', 'HCF | Hybrid Convolution Filter', 'FIR | Finite Response Filter', 'FLSMA | Fisher Least Squares MA', 'SVAMA | Non-Parametric Volume Adjusted MA', 'RPMA | Repulsion MA', 'WRMA | Well Rounded MA' ], group = "Keltner Channel Volatility Filter Settings") kc_band_style = input.string( title="Bands Style", defval = "Average True Range", options = ["Average True Range", "True Range", "Range"], group = "Keltner Channel Volatility Filter Settings") kc_atr_length = input(title = "ATR Length", defval = 10, group = "Keltner Channel Volatility Filter Settings") // Display Settings kcvf_do_box = input.bool(title = "Display Grey Box Around Low Volatility Candles", defval = true, group = "Keltner Channel Volatility Filter Settings") kcvf_do_barcolor = input.bool(title = "Color Low Volatility Candles Gray", defval = false, group = "Keltner Channel Volatility Filter Settings") // Specific MA settings kc_alma_offset = input.float(title = "Offset", defval = 0.85, step = 0.05, group = 'KCVF ALMA Settings') kc_alma_sigma = input.int(title = 'Sigma', defval = 6, group = 'KCVF ALMA Settings') kc_kama_fastLength = input(title = 'Fast EMA Length', defval=2, group = 'KCVF KAMA Settings') kc_kama_slowLength = input(title = 'Slow EMA Length', defval=30, group = 'KCVF KAMA Settings') kc_vama_vol_len = input.int(title = 'Volatality Length', defval = 51, group = 'KCVF VAMA Settings') kc_vama_do_smth = input.bool(title = 'Do Smoothing?', defval = false, group = 'KCVF VAMA Settings') kc_vama_smth = input.int(title = 'Smoothing length', defval = 5, minval = 1, group = 'KCVF VAMA Settings') kc_mf_beta = input.float(title = 'Beta', defval = 0.8, step = 0.1, minval = 0, maxval=1, group = 'KCVF Modular Filter Settings') kc_mf_feedback = input.bool(title = 'Feedback?', defval = false, group = 'KCVF Modular Filter Settings') kc_mf_z = input.float(title = 'Feedback Weighting', defval = 0.5, step = 0.1, minval = 0, maxval = 1, group = 'KCVF Modular Filter Settings') kc_eit_alpha = input.float(title = 'Alpha', defval = 0.07, step = 0.01, minval = 0.0, group = 'KCVF Ehlers Instantaneous Trendline Settings') kc_ssma_pow = input.float(title = 'Power', defval = 4.0, step = 0.5, minval = 0.0, group = 'KCVF SSMA Settings') kc_ssma_smooth = input.bool(title = 'Smooth', defval = false, group = 'KCVF SSMA Settings') kc_rsrma_pw = input.float(title = "Percent Width", defval = 60.0, step = 10.0, minval = 0.0, maxval = 100.0, group = 'KCVF RSRMA Settings') kc_svama_method = input.string(title = 'Max', options=['Max', 'Min'], defval = 'Max', group = 'KCVF SVAMA Settings') kc_svama_vol_or_volatility = input.string(title = 'Use Volume or Volatility?', options = ['Volume', 'Volatility'], defval = 'Volatility', group = 'KCVF SVAMA Settings') kc_wrma_smooth = input.bool(title = "Extra Smoothing?", defval = false, group = 'KCVF WRMA Settings') //============================================================================== //============================================================================== // Keltner Channels Indicator //============================================================================== kc_ma = get_ma_out(kc_ma_type, kc_src, kc_length, kc_alma_offset, kc_alma_sigma, kc_kama_fastLength, kc_kama_slowLength, kc_vama_vol_len, kc_vama_do_smth, kc_vama_smth, kc_mf_beta, kc_mf_feedback, kc_mf_z, kc_eit_alpha, kc_ssma_pow, kc_ssma_smooth, kc_rsrma_pw, kc_svama_method, kc_svama_vol_or_volatility, kc_wrma_smooth) kc_rangema = kc_band_style == "True Range" ? ta.tr(true) : kc_band_style == "Average True Range" ? ta.atr(kc_atr_length) : ta.rma(high - low, kc_length) kc_upper = kc_ma + kc_rangema * kc_mult kc_lower = kc_ma - kc_rangema * kc_mult //============================================================================== //============================================================================== // Determining if price is within the keltner channels //============================================================================== price_within_kc = kcvf_src <= kc_upper and kcvf_src >= kc_lower ? true : false //============================================================================== //============================================================================== // Plotting the grey box/changing bar color if price is within the KC //============================================================================== // Plotting grey box kc_upper_plot = plot(kcvf_do_box ? kc_upper : na, title = "KCVF Upper", color = color.new(#000000, 100)) kc_lower_plot = plot(kcvf_do_box ? kc_lower : na, title = "KCVF Lower", color = color.new(#000000, 100)) fill(kc_upper_plot, kc_lower_plot, title = "KCVF Background", color = kcvf_do_box and price_within_kc ? color.new(#000000, 70) : color.new(#000000, 100)) // Changing bar color kcvf_barcolor = kcvf_do_barcolor and price_within_kc ? color.new(color.gray, 0) : na barcolor(kcvf_barcolor, title = "KCVF Barcolor") //==============================================================================
Abnormal bar % v.1
https://www.tradingview.com/script/W3N0eFIl-abnormal-bar-v-1/
EmoeTeam
https://www.tradingview.com/u/EmoeTeam/
60
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/ // © EmoeTeam //@version=5 indicator(title = "AbNorBar & VolBar", shorttitle="Bares", overlay=true) //1. Блок по ATR //1.1 Общие исходные данные которые можно менять //Модуль про другие акции и их трендовое движение на выбраннном тайм фрейме emas = input.bool(true, 'Hide EMA', tooltip = "EMA10, EMA20, EMA50, EMA100, EMA200") blue_chips = input(false, 'Show blue chips', tooltip = "Show values of ablue chips") tracking = input.timeframe('60', 'Time frame tracking', options = ['30', '60', '120', '240', 'D', '3D', 'W']) // ATR period = input.int(title="ATR Period", defval=14, minval=1, group = "ATR module input data", tooltip = "Select the number of bars on the basis of which the calculation will take place") decimalsAtr = input.int(3, options=[1,2,3,4,5,6], title="Character count", tooltip = 'Number of decimal places and color on the ATR direction: green for rising ATRs, red for falling ones)', inline = 'ATR_group') up_col_atr = input.color(#55b843ec,'Colors', inline = 'ATR_group') dn_col_atr = input.color(#bc372d,'', inline = 'ATR_group') neu_col_atr = input.color(#e3b80a,'', inline = 'ATR_group') viewATR = input(false, 'Hide ATR', tooltip = 'Hide ATR data') //1.2 Расчет Atr. Выделение цветом и абсолютные показатели atr, для рабочего ТФ. atr_calc = ta.atr(period) atr_view = math.round(atr_calc, decimalsAtr) SL_x1 = math.round(1.7 * atr_view, decimalsAtr) SL_x2 = math.round(2.2 * atr_view, decimalsAtr) SL_x3 = math.round(3.2 * atr_view, decimalsAtr) timeframe = "60" atr_day = ta.atr(5) ticker = ticker.new(syminfo.prefix, syminfo.ticker, session = session.regular) atr60 = request.security(ticker, "60", atr_day, gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on) //2. Блок про VolColor (выделяем разным цветом бары взависимости от текущего объема) //VolBar is based on the script Vol Color Bars (2015) by IldarAkhmetgaleev //2.1 Общие исходные данные которые можно менять std_period = input.int(49, minval=6, title='Period volume', group = "The color of the bars depending on the volume", tooltip = "The volume calculation will be for the specified number of bars. Defolt : 49 bars = 240 min + 1 bar (for 5 min Time Frame") col1 = input.color(#E62117, title = "Extr", inline = "col_group") col2 = input.color(#E66F17, title = "High", inline = "col_group") col3 = input.color(#ffffff, title = "Norm", inline = "col_group") col4 = input.color(#0E8F81, title = "Low", inline = "col_group") col5 = input.color(#12B225, title = "No", tooltip = 'Extr - extrime high volume * High - volume is high Norm - volume is normal * Low - volume is low ***** No - almost no volume', inline = "col_group") thresshold1 = input.int(200, minval=0, title='h', inline = "thress") / 100 thresshold2 = input.int(300, minval=0, title='h2', inline = "thress") / 100 thresshold3 = input.int(50, minval=0, title='L', inline = "thress") / 100 thresshold4 = input.int(25, minval=0, title='L2', inline = "thress", tooltip = "Volume levels") / 100 colBar = input(false, 'Show Color Bar', tooltip = 'Выделять бары цветом (bar color)') //2.2 Расчет и определение цвета бара на основание объема. avg = ta.stdev(volume, std_period) highvol1 = volume > avg * thresshold1 highvol2 = volume > avg * thresshold2 lowvol1 = volume < avg * thresshold3 lowvol2 = volume < avg * thresshold4 color_bar = colBar ? highvol2 ? col1 : highvol1 ? col2 : lowvol2 ? col5 : lowvol1 ? col4 : col3 : na //2.3 Вывод данных о цвете на экран barcolor (color_bar, editable = false) //2.4 Сигнал alertcondition(volume < avg * thresshold3, title = "Low volume", message = "Low volume, maybe there is accumulation before the next impulse. Низкий объем, возможено идет накопление перед импульсом.") //3. Блок про аномальный бар (Abnormal Bar) //3.1 Исходные данные для расчета аномального бара bar_period = input.int(14, minval=5, title='Calculate the average for the period', group = "Input data for the search for anomalous bars", tooltip = "Select the number of bars, but on the basis of which the calculation will be made") decimals = input.int(2, title="character count", tooltip = 'Number of decimal places, when displaying data on the graph') abnormal = input.int(50, title ="anomalous bar", tooltip = 'Bar greater than the average value by a specified value (in %) - consider an abnormal bar') Ext_col = input.color(#da3434f5,'Extr', inline = 'Abnorm_group') //Hi_col = input.color(#dc8e1a,'High', inline = 'Abnorm_group') //Low_col = input.color(#27ace1,'Low', inline = 'Abnorm_group', tooltip = "Color: abnormal bar > avg.bar more than 105% - ext_color; > avg.bar 40-75% - hi_color; > avg.bar up to 40% - low_color") abnormallyBar = input(false, 'Show normal bars', tooltip = "Show values of abnormal bars") //3.2 Расчеты для определения аномальных баров. avg_bar_abs = ta.rma((high-low), bar_period) avg_bar = ta.rma((high*100/low)-100, bar_period) //Средний размер бара, за выбранный период (в процентах) avg_bar_dec = math.round(avg_bar, decimals) sup_res = avg_bar_abs * 2 abnorm_bar = (avg_bar + avg_bar * abnormal/100) //определение аномального бара abnorm_bar_dec = math.round(avg_bar, decimals) //округление, значения анамального бара cur_bar = ((high*100/low)-100) cur_bar_dec = math.round(cur_bar, decimals) cur_bar_abs = (high-low) up_atr_text_col = cur_bar_abs < atr_calc dn_atr_text_col = cur_bar_abs > atr_calc atr_text_col = up_atr_text_col ? up_col_atr : dn_atr_text_col ? dn_col_atr : neu_col_atr //3.3 Вывод данных на график //1.3 Вывод на экран. Значение текущего ATR, значения для SL и направление движения ATR (цвет - зеленый atr растет, красный - atr, снижается) var CELL_TOOLTIP = "Cell color depends on the ATR direction: green for rising ATRs, red for falling one. Not to be confused with the direction of the TREND. ATR - shows the volatility !!!" color_bg_atr = (atr_calc > atr_calc[2] and atr_calc[2] > atr_calc[4] and atr_calc > atr_calc[4] ? up_col_atr : atr_calc < atr_calc[2] and atr_calc[2] < atr_calc[4] and atr_calc < atr_calc[4] ? dn_col_atr : neu_col_atr) var tb_ATR = table.new(position.bottom_left, 7, 7, border_width = 2) if barstate.islast and not viewATR headerColor = color.new(#42434c, 50) table.cell(tb_ATR, 0, 0, (str.tostring(atr60, '#.##')), text_color = color.yellow, text_size = size.small, tooltip = "ATR ticker - 1H") table.cell(tb_ATR, 1, 0, (str.tostring(atr_view, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "ATR ticker !!!" + CELL_TOOLTIP) //table.cell(tb_ATR, 0, 1, "ATR", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP) table.cell(tb_ATR, 2, 0, (str.tostring(SL_x1, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "1.7 x ATR ticker") //table.cell(tb_ATR, 1, 1, "1,5x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP) table.cell(tb_ATR, 3, 0, (str.tostring(SL_x2, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "2.2 x ATR ticker") //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP) table.cell(tb_ATR, 4, 0, (str.tostring(SL_x3, '#.######')), bgcolor = color_bg_atr, text_size = size.small, tooltip = "3.2 x ATR ticker") //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP) table.cell(tb_ATR, 5, 0, "🪫 ", text_size = size.small, text_halign = text.align_right) //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP) table.cell(tb_ATR, 6, 0, (str.tostring(cur_bar_abs, '#.####')), text_color = atr_text_col, text_size = size.normal, text_halign = text.align_left, tooltip ="ATR progress of the current bar") //table.cell(tb_ATR, 2, 1, "2x", bgcolor = headerColor, text_color = #d9e4ef, text_size = size.small, tooltip = CELL_TOOLTIP) //table.cell(tb_ATR, 0, 1, '' , height = 2.5) //table.cell(tb_ATR, 0, 5, '' , height = 3) if abnormallyBar ? cur_bar > avg_bar and cur_bar >= abnorm_bar and cur_bar > avg_bar + avg_bar * 1.05 : na label_perc = label.new(bar_index, low, text=str.tostring(cur_bar_dec)+"\n", yloc=yloc.abovebar, textcolor = Ext_col, size = size.small, tooltip = "bar(%) more than average > 105% - ext_color", textalign = text.align_right) label.set_style(label_perc, label.style_none) label.set_text_font_family(label_perc, font.family_default) //else if abnormallyBar ? cur_bar > avg_bar and cur_bar >= abnorm_bar and cur_bar > avg_bar + avg_bar * 0.75 : na //label_perc = label.new(bar_index, low, text=str.tostring(cur_bar_dec)+"\n", yloc=yloc.abovebar, textcolor = Hi_col, size = size.small, tooltip = "bar(%) over average value between 40 and 75% - hi_color", textalign = text.align_right) //label.set_style(label_perc, label.style_none) //label.set_text_font_family(label_perc, font.family_default) //else if abnormallyBar ? cur_bar > avg_bar and cur_bar >= abnorm_bar and cur_bar > avg_bar + avg_bar * 0.4 : na //label_perc = label.new(bar_index, low, text=str.tostring(cur_bar_dec)+"\n", yloc=yloc.abovebar, textcolor = Low_col, size = size.small, tooltip = "bar(%) more than average value up to 40% - low_color", textalign = text.align_right) //label.set_style(label_perc, label.style_none) //label.set_text_font_family(label_perc, font.family_default) //var tb_temp = table.new(position.top_right, 5, 5) //if barstate.islast //table.cell (tb_temp, 0, 0, "avg_bar : " +(str.tostring(avg_bar, '#.##')) + "%", text_size = size.small) //table.cell (tb_temp, 0, 0, "", height = 2.5, text_size = size.small) //table.cell (tb_temp, 1, 0, (str.tostring(avg_bar_abs, '#.####')), text_size = size.small) //table.cell (tb_temp, 1, 0, "x2 - " + (str.tostring(sup_res, '#.####')), text_size = size.small, text_color = color.yellow) //3.4 Сигналы alertcondition(cur_bar > avg_bar + avg_bar * 1.05, title = "ExTreme abnormal Bar", message = "ExTreme abnormal Bar, the current value is 105% higher than the average value - Экстримальный бар") //alertcondition(cur_bar > avg_bar + avg_bar * 0.75, title = "Abnormal Bar", message = "Abnormal Bar, the current value is 75% higher than the average value - Высокий бар") alertcondition(color_bg_atr == up_col_atr, title = "Волотильность растет" , message = "Волатильность растет") alertcondition(color_bg_atr == dn_col_atr, title = "Волотильность падает" , message = "Волатильность падает") alertcondition(color_bar == col5, title = "Нет объемов" , message = "Объемов практически нет, оценить ситуацию по тикеру") // 4 Ориентация по другим тикерам // code author - @AzzraelCode fn(ticker) => request.security(ticker, tracking, open/close) var per = 9 var tickers = array.from('LKOH', 'SBER', 'GAZP', 'GMKN', 'NLMK', 'NVTK', 'YNDX', 'ROSN', 'TATN', 'SNGS', 'MGNT', 'TCSG', 'PLZL', 'POLY', 'IMOEX', 'RTSI', 'ALRS', 'CHMF', 'RUAL', 'MAGN', 'VTBR', 'VKCO', 'OZON', 'FIVE', 'RASP', 'MX1') vals = array.from(fn('LKOH'), fn('SBER'), fn('GAZP'), fn('GMKN'), fn('NLMK'), fn('NVTK'), fn('YNDX'), fn('ROSN'), fn('TATN'), fn('SNGS'), fn('MGNT'), fn('TCSG'), fn('PLZL'), fn('POLY'), fn('IMOEX'), fn('RTSI'), fn('ALRS'), fn('CHMF'), fn('RUAL'), fn ('MAGN'), fn('VTBR'), fn('VKCO'), fn('OZON'), fn('FIVE'), fn('RASP'), fn('MX1')) var size = array.size(tickers) var tbl3 = table.new(position.bottom_right, 30, 30, border_width=1) if barstate.islast and blue_chips for i=0 to array.size(tickers)-1 col = i % per row = math.ceil((i+1)/per)-1 //col = math.ceil((i+1)/per)-1 //row = i % per ticker := array.get(tickers, i) val = array.get(vals, i) table.cell(tbl3, col, row, ticker, text_halign=text.align_center, bgcolor=val > 1 ? color.rgb(156, 57, 57, 10):color.rgb(48, 150, 51, 10), text_color=color.white, text_size=size.small) /// EMAS /// //вводные данные out1 = ta.ema(close, 8) out2 = ta.ema(close, 21) out3 = ta.ema(close, 50) out4 = ta.ema(close, 18) out5 = ta.ema(close, 200) //Вывод на экран view10 = plot(emas ? out1 : na, title="ema 8", color=color.rgb(29, 120, 15, 2), linewidth=2, offset = 3) view20 = plot(emas ? out2 : na, title="ema 21", color=color.rgb(193, 27, 27, 12), linewidth=2, offset = 5) view50 = plot(emas ? out3 : na, title="ema 50", color=color.rgb(43, 27, 227, 10), linewidth=2, offset = 5) view100 = plot(emas ? out4 : na, title="ema 18", color=color.rgb(30, 207, 227, 14), linewidth=2, offset = 3) view200 = plot(emas ? out5 : na, title="ema 200", color=color.rgb(207, 139, 22, 11), linewidth=2, offset = 8) //Границы недели useGMTOffsetInput = input.bool(false, "Use GMT Offset?", group="Timezone") gmtOffsetInput = input.int(0, "GMT Offset", minval=-24, maxval=24, step=1, group="Timezone") showMon = input(true, title="Show Monday?") stateSession = syminfo.session timezoneString = "GMT" + (gmtOffsetInput > 0 ? "+" : "") + str.tostring(gmtOffsetInput) stateTimeZone = useGMTOffsetInput ? timezoneString : syminfo.timezone isMon() => dayofweek(time('D', stateSession, stateTimeZone)) == dayofweek.monday defTransp = 70 bgcolor(showMon and isMon() ? color.new(color.silver, defTransp) : na, title="Monday color")
Coppock Unchanged
https://www.tradingview.com/script/6BK2MLoH-Coppock-Unchanged/
TraderLeibniz
https://www.tradingview.com/u/TraderLeibniz/
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/ // © TraderLeibniz //@version=5 indicator("Coppock Unchanged", overlay=true, timeframe="", timeframe_gaps=true) coppock_curve(_expr, _roc_short, _roc_long, _wma_len, _tf) => sum_expr = (ta.roc(_expr, _roc_short) + ta.roc(_expr, _roc_long))/100 out_expr = ta.wma(sum_expr, _wma_len) _out = request.security(symbol=syminfo.tickerid, timeframe=_tf, expression=out_expr) sma_expr = ta.sma(sum_expr, _wma_len) _sma = request.security(symbol=syminfo.tickerid, timeframe=_tf, expression=sma_expr) unch_data_expr = _expr[_roc_short]*_expr[_roc_long]*(2.0+_sma[1])/(_expr[_roc_short]+_expr[_roc_long]) _unch_data = request.security(symbol=syminfo.tickerid, timeframe=_tf, expression=unch_data_expr) [_out, _unch_data] cc_src = input.source(defval=close, title='Coppock Curve Input') roc1 = input.int(defval=11, title='RoC 1') roc2 = input.int(defval=14, title='RoC 2') wma_len = input.int(defval=10, title='WMA Length') [cc_out, data_cc_unch] = coppock_curve(cc_src, roc1, roc2, wma_len, timeframe.period) ar_tf = input.timeframe("3M", "Alt Coppock Resolution", options=["65","130","195","300","1D","2D","3D","1W","2W","1M","3M","12M"]) cc_src_AR = input.source(defval=close, title='Coppock Curve Input Alt Res') roc1_AR = input.int(defval=11, title='RoC 1 Alt Res') roc2_AR = input.int(defval=14, title='RoC 2 Alt Res') wma_len_AR = input.int(defval=10, title='WMA Length Alt Res') [cc_out_AR, data_cc_unch_AR] = coppock_curve(cc_src_AR, roc1_AR, roc2_AR, wma_len_AR, ar_tf) // ------------- plot(data_cc_unch, color=color.blue, title="Coppock Unchanged") plot(data_cc_unch_AR, color=color.orange, title="Coppock Unchanged Alt Resolution")
Tunable SWMA
https://www.tradingview.com/script/ej1ADd7r-Tunable-SWMA/
EsIstTurnt
https://www.tradingview.com/u/EsIstTurnt/
69
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/ // © EsIstTurnt //Modified From long form of ta.swma function : //pine_swma(source) => //source[3] * 1 / 6 + source[2] * 2 / 6 + //source[1] * 2 / 6 + source[0] * 1 / 6 //plot(pine_swma(close) //SYMMETRICALLY WEIGHTED // V //SELECTABLY WEIGHTED //@version=5 indicator("Tunable Selectably Weighed Moving Average",shorttitle='TSWMA',overlay=true) tf = input.timeframe('','TimeFrame') maInput = input.string(title="Input", defval="None", options=["None","EMA", "SMA", "VWMA", "WMA","VWAP","LRC"],group='Filter') maOutput = input.string(title="Output", defval="None", options=["None","EMA", "SMA", "VWMA", "WMA","VWAP","LRC"],group='Filter') length = input.int(64,'Input/Output Length',group="Filter") customsrc = input.source(close,'Source Input') togglesrc = input.bool(true,'Use User Selected Source',group="Source") input = maInput == "EMA"? ta.ema(customsrc, length) :maInput == "SMA" ? ta.sma (customsrc, length) :maInput == "VWMA"? ta.vwma (customsrc, length) :maInput == "WMA" ? ta.wma (customsrc, length) :maInput == "VWAP"? ta.vwap (customsrc) :maInput == "LRC" ? ta.linreg(customsrc, length,0) :maInput == "None"?customsrc:na Weight1 = input.int(16,'Weight for Bar 1 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight2 = input.int(15,'Weight for Bar 2 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight3 = input.int(14,'Weight for Bar 3 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight4 = input.int(13,'Weight for Bar 4 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight5 = input.int(12,'Weight for Bar 5 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight6 = input.int(11,'Weight for Bar 6 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight7 = input.int(10,'Weight for Bar 7 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight8 = input.int(9 ,'Weight for Bar 8 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight9 = input.int(8 ,'Weight for Bar 9 ',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight10 = input.int(8 ,'Weight for Bar 10',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight11 = input.int(7 ,'Weight for Bar 11',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight12 = input.int(7 ,'Weight for Bar 12',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight13 = input.int(6 ,'Weight for Bar 13',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight14 = input.int(6 ,'Weight for Bar 14',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight15 = input.int(5 ,'Weight for Bar 15',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Weight16 = input.int(5 ,'Weight for Bar 16',options=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16],group='Weights') Divisor1 = 1+2+2+1 // For default swma => Sum of Weight's (1,2,2,1) == Divisor Divisor2 = (Weight1+Weight2 +Weight3 +Weight4 +Weight5 +Weight6 +Weight7 +Weight8 +Weight9 + Weight10+ Weight11+ Weight12+ Weight13+ Weight14+ Weight15+ Weight16 ) //Add weight Selections From above int1 = input.int(0 ,' Most Recent Bar (#1)',group='Lookback') int2 = input.int(1 ,' Previous Bar (#2) ',group='Lookback') int3 = input.int(2 ,' Previous Bar (#3) ',group='Lookback') int4 = input.int(3 ,' Previous Bar (#4) ',group='Lookback') int5 = input.int(6 ,' Previous Bar (#5) ',group='Lookback') int6 = input.int(12 ,' Previous Bar (#6) ',group='Lookback') int7 = input.int(16 ,' Previous Bar (#7) ',group='Lookback') int8 = input.int(24 ,' Previous Bar (#8) ',group='Lookback') H = input.bool(true,'Use ta.highest value for 4 selections below ') L = input.bool(true,'Use ta.lowest value for 4 selections below ') intL = input.int(32 ,'Lowest' ,group='Lowest bar lookback ') intH = input.int(32 ,'Highest',group='Highest bar lookback ') int9 = input.int(64 ,' Previous Bar (#9 ) (Toggle Highest) ',group="Lookback Highest") int10 = input.int(64 ,' Previous Bar (#10) (Toggle Lowest ) ',group="Lookback Lowest ") int11 = input.int(96 ,' Previous Bar (#11) (Toggle Highest) ',group="Lookback Highest") int12 = input.int(96 ,' Previous Bar (#12) (Toggle Lowest ) ',group="Lookback Lowest ") int13 = input.int(128 ,' Previous Bar (#13) (Toggle Highest) ',group="Lookback Highest") int14 = input.int(128 ,' Previous Bar (#14) (Toggle Lowest ) ',group="Lookback Lowest ") int15 = input.int(256 ,' Previous Bar (#15) (Toggle Highest) ',group="Lookback Highest") int16 = input.int(256 ,' Previous Bar (#16) (Toggle Lowest ) ',group="Lookback Lowest ") src = ta.ema(togglesrc?input:ta.sma(math.avg(open,open[int3],open[int5])<math.avg(close,close[int3],close[int5]) ? math.avg(ta.lowest(low,16),ta.highest(high,8),close):math.avg(ta.highest(high,16),ta.lowest(low,8),close),int5),int6) srcH1 = H? ta.highest(src[int9 ],intH):src[int9 ] srcL1 = L? ta.lowest (src[int10],intL):src[int10] srcH2 = H? ta.highest(src[int11],intH):src[int11] srcL2 = L? ta.lowest (src[int12],intL):src[int12] srcH3 = H? ta.highest(src[int13],intH):src[int13] srcL3 = L? ta.lowest (src[int14],intL):src[int14] srcH4 = H? ta.highest(src[int15],intH):src[int15] srcL4 = L? ta.lowest (src[int16],intL):src[int16] //Default SWMA pine_swma(src) => src[int4] * 1 / Divisor1 + src[int3] * 2 / Divisor1 + src[int2] * 2 / Divisor1 + src[int1] * 1 / Divisor1 //Configurable SWMA tuned_swma(src) => //if Weight is Changed resulting in a different total when added together, you must change Divisor2 Above src[int1] * Weight1 / Divisor2 + src[int2] * Weight2 / Divisor2 + src[int3] * Weight3 / Divisor2 + src[int4] * Weight4 / Divisor2 + src[int5] * Weight5 / Divisor2 + src[int6] * Weight6 / Divisor2 + src[int7] * Weight7 / Divisor2 + src[int8] * Weight8 / Divisor2 + srcH1 * Weight9 / Divisor2 + srcL1 * Weight10 / Divisor2 + srcH2 * Weight11 / Divisor2 + srcL2 * Weight12 / Divisor2 + srcH3 * Weight13 / Divisor2 + srcL3 * Weight14 / Divisor2 + srcH4 * Weight15 / Divisor2 + srcL4 * Weight16 / Divisor2 basis = maOutput == "EMA"?ta.ema(tuned_swma(src), length) :maOutput == "SMA" ? ta.sma (tuned_swma(src), length) :maOutput == "VWMA"? ta.vwma (tuned_swma(src), length) :maOutput == "WMA" ? ta.wma (tuned_swma(src), length) :maOutput == "VWAP"? ta.vwap (tuned_swma(src)) :maOutput == "LRC" ? ta.linreg(tuned_swma(src), length,0) :maOutput == "None"? tuned_swma(src):na //Plot plot(request.security(syminfo.ticker,tf,pine_swma (src)),color=#acfb00,title='Stock SWMA ') plot(request.security(syminfo.ticker,tf,basis),color=#ff0000,title='Tuned SWMA')
Fed Net Liquidity Indicator (24-Oct-2022 update)
https://www.tradingview.com/script/smSewP0Z-Fed-Net-Liquidity-Indicator-24-Oct-2022-update/
PragmaticMonkey
https://www.tradingview.com/u/PragmaticMonkey/
117
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/ // © jlb05013 (updated by Pragmatic Monkey on 20-Oct-2022) //@version=5 indicator("Fed Net Liquidity Indicator", overlay=true, scale=scale.right) i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M']) unit_input = input.string('Millions', options=['Millions', 'Billions', 'Trillions']) units = unit_input == 'Billions' ? 1e3 : unit_input == 'Millions' ? 1e0 : unit_input == 'Trillions' ? 1e6 : na fed_bal = request.security('FRED:WALCL', i_res, close)*1e6 // trillions tga = request.security('FRED:WTREGEN', i_res, close)*1e6 // trillions rev_repo = request.security('FRED:RRPONTSYD', i_res, close)*1e6 // trillions std_repo = request.security('FRED:RPONTSYD', i_res, close)*1e3 // billions cb_liq_swaps = request.security('FRED:SWPT', i_res, close)*1e3 // billions net_liquidity = (fed_bal - (tga + rev_repo) + std_repo + cb_liq_swaps) / (units*1e12) var net_liquidity_offset = 10 // 2-week offset for use with daily charts if timeframe.isdaily net_liquidity_offset := 10 if timeframe.isweekly net_liquidity_offset := 2 if timeframe.ismonthly net_liquidity_offset := 0 plot(net_liquidity, title='Net Liquidity', color=color.new(color.blue, 80), style=plot.style_histogram, offset=net_liquidity_offset)
In Chart Currency Tickers
https://www.tradingview.com/script/TLISv42c-In-Chart-Currency-Tickers/
hjsjshs
https://www.tradingview.com/u/hjsjshs/
36
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public LiceFXCM 2.0 at https://mozilla.org/MPL/2.0/ // © hjsjshs//ASIF KERIM NADUVILAPARAMBIL// //@version=5 indicator(title='Currency Tickers', shorttitle='In Chart Currency Tickers', overlay=true) getCloses() => [close, close[1]] getArrow(bIsUp) => bIsUp ? ' ⯅' : ' ⯆' getSign(bIsUp) => bIsUp ? '[+' : '[' getColor(bIsUp) => bIsUp ? #00EE00 : #EE0000 index_0 = input.symbol('XAUUSD', 'Currency #1') index_1 = input.symbol('EURUSD', 'Currency #2') index_2 = input.symbol('GBPUSD', 'Currency #3') index_3 = input.symbol('USDCHF', 'Currency #4') index_4 = input.symbol('USDJPY', 'Currency #5') index_5 = input.symbol('USDCNH', 'Currency #6') index_6 = input.symbol('USDRUB', 'Currency #7') index_7 = input.symbol('AUDUSD', 'Currency #8') index_8 = input.symbol('USDNZD', 'Currency #9') index_9 = input.symbol('USDCAD', 'Currency #10') index_10 = input.symbol('GBPCHF', 'Currency #11') index_11 = input.symbol('GBPJPY', 'Currency #12') index_12 = input.symbol('AUDCAD', 'Currency #13') index_13 = input.symbol('AUDCHF', 'Currency #14') index_14 = input.symbol('AUDNZD', 'Currency #15') var table logo = table.new(position.bottom_right, 1, 1) if barstate.islast table.cell(logo, 0, 0, '|A|S|I|F||K|', text_size=size.normal, text_color=#0099FF,bgcolor=#00000080) [close_0, lastClose_0] = request.security(index_0, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_1, lastClose_1] = request.security(index_1, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_2, lastClose_2] = request.security(index_2, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_3, lastClose_3] = request.security(index_3, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_4, lastClose_4] = request.security(index_4, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_5, lastClose_5] = request.security(index_5, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_6, lastClose_6] = request.security(index_6, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_7, lastClose_7] = request.security(index_7, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_8, lastClose_8] = request.security(index_8, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_9, lastClose_9] = request.security(index_9, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_10, lastClose_10] = request.security(index_10, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_11, lastClose_11] = request.security(index_11, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_12, lastClose_12] = request.security(index_12, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_13, lastClose_13] = request.security(index_13, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) [close_14, lastClose_14] = request.security(index_14, 'D', getCloses(), barmerge.gaps_off, barmerge.lookahead_on) if barstate.islast diff_0 = close_0 - lastClose_0 perc_0 = ((close_0 - lastClose_0)/lastClose_0*100) isUp_0 = close_0 > lastClose_0 arrow0 = getArrow(isUp_0) color0 = getColor(isUp_0) sign_0 = getSign(isUp_0) diff_1 = close_1 - lastClose_1 perc_1 = ((close_1 - lastClose_1)/lastClose_1*100) isUp_1 = close_1 > lastClose_1 arrow1 = getArrow(isUp_1) color1 = getColor(isUp_1) sign_1 = getSign(isUp_1) diff_2 = close_2 - lastClose_2 perc_2 = ((close_2 - lastClose_2)/lastClose_2*100) isUp_2 = close_2 > lastClose_2 arrow2 = getArrow(isUp_2) color2 = getColor(isUp_2) sign_2 = getSign(isUp_2) diff_3 = close_3 - lastClose_3 perc_3 = ((close_3 - lastClose_3)/lastClose_3*100) isUp_3 = close_3 > lastClose_3 arrow3 = getArrow(isUp_3) color3 = getColor(isUp_3) sign_3 = getSign(isUp_3) diff_4 = close_4 - lastClose_4 perc_4 = ((close_4 - lastClose_4)/lastClose_4*100) isUp_4 = close_4 > lastClose_4 arrow4 = getArrow(isUp_4) color4 = getColor(isUp_4) sign_4 = getSign(isUp_4) diff_5 = close_5 - lastClose_5 perc_5 = ((close_5 - lastClose_5)/lastClose_5*100) isUp_5 = close_5 > lastClose_5 arrow5 = getArrow(isUp_5) color5 = getColor(isUp_5) sign_5 = getSign(isUp_5) diff_6 = close_6 - lastClose_6 perc_6 = ((close_6 - lastClose_6)/lastClose_6*100) isUp_6 = close_6 > lastClose_6 arrow6 = getArrow(isUp_6) color6 = getColor(isUp_6) sign_6 = getSign(isUp_6) diff_7 = close_7 - lastClose_7 perc_7 = ((close_7 - lastClose_7)/lastClose_7*100) isUp_7 = close_7 > lastClose_7 arrow7 = getArrow(isUp_7) color7 = getColor(isUp_7) sign_7 = getSign(isUp_7) diff_8 = close_8 - lastClose_8 perc_8 = ((close_8 - lastClose_8)/lastClose_8*100) isUp_8 = close_8 > lastClose_8 arrow8 = getArrow(isUp_8) color8 = getColor(isUp_8) sign_8 = getSign(isUp_8) diff_9 = close_9 - lastClose_9 perc_9 = ((close_9 - lastClose_9)/lastClose_9*100) isUp_9 = close_9 > lastClose_9 arrow9 = getArrow(isUp_9) color9 = getColor(isUp_9) sign_9 = getSign(isUp_9) diff_10 = close_10 - lastClose_10 perc_10 = ((close_10 - lastClose_10)/lastClose_10*100) isUp_10 = close_10 > lastClose_10 arrow10 = getArrow(isUp_10) color10 = getColor(isUp_10) sign_10 = getSign(isUp_10) diff_11 = close_11 - lastClose_11 perc_11 = ((close_11 - lastClose_11)/lastClose_11*100) isUp_11 = close_11 > lastClose_11 arrow11 = getArrow(isUp_11) color11 = getColor(isUp_11) sign_11 = getSign(isUp_11) diff_12 = close_12 - lastClose_12 perc_12 = ((close_12 - lastClose_12)/lastClose_12*100) isUp_12 = close_12 > lastClose_12 arrow12 = getArrow(isUp_12) color12 = getColor(isUp_12) sign_12 = getSign(isUp_12) diff_13 = close_13 - lastClose_13 perc_13 = ((close_13 - lastClose_13)/lastClose_13*100) isUp_13 = close_13 > lastClose_13 arrow13 = getArrow(isUp_13) color13 = getColor(isUp_13) sign_13 = getSign(isUp_13) diff_14 = close_14 - lastClose_14 perc_14 = ((close_14 - lastClose_14)/lastClose_14*100) isUp_14 = close_14 > lastClose_14 arrow14 = getArrow(isUp_14) color14 = getColor(isUp_14) sign_14 = getSign(isUp_14) var tTickerTable = table.new(position.bottom_left, 4, 15, bgcolor=#00000080, frame_width=1, frame_color=color.black) table.cell(tTickerTable, 0, 0, index_0, text_color=#0099FF) table.cell(tTickerTable, 1, 0, str.tostring(close_0,"#######.######") + arrow0, text_color=color0, text_halign=text.align_right) table.cell(tTickerTable, 2, 0, sign_0 + str.tostring(diff_0,"#######.######")+ ']'+ '[' + str.tostring(perc_0,"###.##") + '%]', text_color=color0, text_halign=text.align_left) table.cell(tTickerTable, 0, 1, index_1, text_color=#0099FF) table.cell(tTickerTable, 1, 1, str.tostring(close_1,"#######.#####") + arrow1, text_color=color1, text_halign=text.align_right) table.cell(tTickerTable, 2, 1, sign_1 + str.tostring(diff_1,"#######.#####")+ ']'+ '[' + str.tostring(perc_1,"###.##") + '%]', text_color=color1, text_halign=text.align_left) table.cell(tTickerTable, 0, 2, index_2, text_color=#0099FF) table.cell(tTickerTable, 1, 2, str.tostring(close_2,"#######.#####") + arrow2, text_color=color2, text_halign=text.align_right) table.cell(tTickerTable, 2, 2, sign_2 + str.tostring(diff_2,"#######.#####")+ ']'+ '[' + str.tostring(perc_2,"###.##") + '%]', text_color=color2, text_halign=text.align_left) table.cell(tTickerTable, 0, 3, index_3, text_color=#0099FF) table.cell(tTickerTable, 1, 3, str.tostring(close_3,"#######.#####") + arrow3, text_color=color3, text_halign=text.align_right) table.cell(tTickerTable, 2, 3, sign_3 + str.tostring(diff_3,"#######.######")+ ']'+ '[' + str.tostring(perc_3,"###.##") + '%]', text_color=color3, text_halign=text.align_left) table.cell(tTickerTable, 0, 4, index_4, text_color=#0099FF) table.cell(tTickerTable, 1, 4, str.tostring(close_4,"#######.#####") + arrow4, text_color=color4, text_halign=text.align_right) table.cell(tTickerTable, 2, 4, sign_4 + str.tostring(diff_4,"#######.######")+ ']'+ '[' + str.tostring(perc_4,"###.##") + '%]', text_color=color4, text_halign=text.align_left) table.cell(tTickerTable, 0, 5, index_5, text_color=#0099FF) table.cell(tTickerTable, 1, 5, str.tostring(close_5,"#######.#####") + arrow5, text_color=color5, text_halign=text.align_right) table.cell(tTickerTable, 2, 5, sign_5 + str.tostring(diff_5,"#######.######")+ ']'+ '[' + str.tostring(perc_5,"###.##") + '%]', text_color=color5, text_halign=text.align_left) table.cell(tTickerTable, 0, 6, index_6, text_color=#0099FF) table.cell(tTickerTable, 1, 6, str.tostring(close_6,"#######.#####") + arrow6, text_color=color6, text_halign=text.align_right) table.cell(tTickerTable, 2, 6, sign_6 + str.tostring(diff_6,"#######.######")+ ']'+ '[' + str.tostring(perc_6,"###.##") + '%]', text_color=color6, text_halign=text.align_left) table.cell(tTickerTable, 0, 7, index_7, text_color=#0099FF) table.cell(tTickerTable, 1, 7, str.tostring(close_7,"#######.#####") + arrow7, text_color=color7, text_halign=text.align_right) table.cell(tTickerTable, 2, 7, sign_7 + str.tostring(diff_7,"#######.######")+ ']'+ '[' + str.tostring(perc_7,"###.##") + '%]', text_color=color7, text_halign=text.align_left) table.cell(tTickerTable, 0, 8, index_8, text_color=#0099FF) table.cell(tTickerTable, 1, 8, str.tostring(close_8,"#######.#####") + arrow8, text_color=color8, text_halign=text.align_right) table.cell(tTickerTable, 2, 8, sign_8 + str.tostring(diff_8,"#######.######")+ ']'+ '[' + str.tostring(perc_8,"###.##") + '%]', text_color=color8, text_halign=text.align_left) table.cell(tTickerTable, 0, 9, index_9, text_color=#0099FF) table.cell(tTickerTable, 1, 9, str.tostring(close_9,"#######.#####") + arrow9, text_color=color9, text_halign=text.align_right) table.cell(tTickerTable, 2, 9, sign_9 + str.tostring(diff_9,"#######.######")+ ']'+ '[' + str.tostring(perc_9,"###.##") + '%]', text_color=color9, text_halign=text.align_left) table.cell(tTickerTable, 0, 10, index_10, text_color=#0099FF) table.cell(tTickerTable, 1, 10, str.tostring(close_10,"#######.#####") + arrow10, text_color=color10, text_halign=text.align_right) table.cell(tTickerTable, 2, 10, sign_10 + str.tostring(diff_10,"#######.######")+ ']'+ '[' + str.tostring(perc_10,"###.##") + '%]', text_color=color10, text_halign=text.align_left) table.cell(tTickerTable, 0, 11, index_11, text_color=#0099FF) table.cell(tTickerTable, 1, 11, str.tostring(close_11,"#######.#####") + arrow11, text_color=color11, text_halign=text.align_right) table.cell(tTickerTable, 2, 11, sign_11 + str.tostring(diff_11,"#######.######")+ ']'+ '[' + str.tostring(perc_11,"###.##") + '%]', text_color=color11, text_halign=text.align_left) table.cell(tTickerTable, 0, 12, index_12, text_color=#0099FF) table.cell(tTickerTable, 1, 12, str.tostring(close_12,"#######.#####") + arrow12, text_color=color12, text_halign=text.align_right) table.cell(tTickerTable, 2, 12, sign_12 + str.tostring(diff_12,"#######.######")+ ']'+ '[' + str.tostring(perc_12,"###.##") + '%]', text_color=color12, text_halign=text.align_left) table.cell(tTickerTable, 0, 13, index_13, text_color=#0099FF) table.cell(tTickerTable, 1, 13, str.tostring(close_13,"#######.#####") + arrow13, text_color=color13, text_halign=text.align_right) table.cell(tTickerTable, 2, 13, sign_13 + str.tostring(diff_13,"#######.######")+ ']'+ '[' + str.tostring(perc_13,"###.##") + '%]', text_color=color13, text_halign=text.align_left) table.cell(tTickerTable, 0, 14, index_14, text_color=#0099FF) table.cell(tTickerTable, 1, 14, str.tostring(close_14,"#######.#####") + arrow14, text_color=color14, text_halign=text.align_right) table.cell(tTickerTable, 2, 14, sign_14 + str.tostring(diff_14,"#######.######")+ ']'+ '[' + str.tostring(perc_14,"###.##") + '%]', text_color=color14, text_halign=text.align_left)
SPX Fair Value Bands V2
https://www.tradingview.com/script/qESp7ZZh-SPX-Fair-Value-Bands-V2/
TraderLeibniz
https://www.tradingview.com/u/TraderLeibniz/
84
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/ // © TraderLeibniz, an updated version of the script dharmatech and based on the liquidity concept by MaxJAnderson // described here: https://archive.ph/gwoBq https://archive.ph/AXuMn // Also check out the my fixed version of dharmatech's powershell script that grabs the same data: // https://pastebin.com/NK7D89kL //@version=5 indicator("SPX Fair Value Bands V2", overlay=true, timeframe="", timeframe_gaps=true) var float _SCALE = 0.000001/1000 // depends on the units that TradingView decides to set from FRED var string _NET_LIQUIDITY_EXPR = "(FRED:WALCL - FRED:WTREGEN - FRED:RRPONTSYD)" var string _TIMEFRAME = "1D" // only RRPONTSYD data is updated daily (TGA data from treasury updates daily, but FRED:WTREGEN is weekly) // Max J Anderson's regression of SPX vs. Net Liquidity (94% r-squared) var float _SLOPE = 1/1.1 var float _FAIR_VALUE_OFFSET = -1625.0 var float _UPPER_BAND_OFFSET = 350.0 var float _LOWER_BAND_OFFSET = 150.0 //------------------ fred_scale = input.float(defval=_SCALE, title='FRED Unit Scaling', group="Core Settings") netliq_expr = input.string(defval=_NET_LIQUIDITY_EXPR, title='Net Liquidity Expression', group="Core Settings") reg_slope = input.float(defval=_SLOPE, title='Regression Slope', group="Core Settings") reg_offset = input.float(defval=_FAIR_VALUE_OFFSET, title='Regression Offset', group="Core Settings") //------------------ hi_offset = input.float(defval=_UPPER_BAND_OFFSET, title='Offset for Sell Band', group="Std Band Settings") lo_offset = input.float(defval=_LOWER_BAND_OFFSET, title='Offset for Buy Band', group="Std Band Settings") bar_offset = input.int(defval=0, title='Bar (Temporal) Offset', group="Std Band Settings") //------------------ // Multi timeframe settings band_tf = input.timeframe(defval=_TIMEFRAME, title="Band Timeframe", options=["1D","2D","3D","4D","1W","2W","3W","1M","5D","6D","7D", "8D","9D","10D","11D","12D","13D","14D","15D","16D","17D","18D", "19D","20D","21D","22D","23D","24D"], group="Band Timeframe Settings") bb_tf = input.timeframe(defval=_TIMEFRAME, title="Bollinger Timeframe", options=["1D","2D","3D","4D","1W","2W","3W","1M","5D","6D","7D", "8D","9D","10D","11D","12D","13D","14D","15D","16D","17D","18D", "19D","20D","21D","22D","23D","24D"], group="Band Timeframe Settings") kc_tf = input.timeframe(defval=_TIMEFRAME, title="Keltner Timeframe", options=["1D","2D","3D","4D","1W","2W","3W","1M","5D","6D","7D","8D", "9D","10D","11D","12D","13D","14D","15D","16D","17D","18D", "19D","20D","21D","22D","23D","24D"], group="Band Timeframe Settings") //------------------ scaled_expr = close*fred_scale*reg_slope + reg_offset scaled_upper_expr = scaled_expr + hi_offset scaled_lower_expr = scaled_expr - lo_offset fv_band = request.security(symbol=netliq_expr, timeframe=band_tf, expression=scaled_expr) sell_band = request.security(symbol=netliq_expr, timeframe=band_tf, expression=scaled_upper_expr) buy_band = request.security(symbol=netliq_expr, timeframe=band_tf, expression=scaled_lower_expr) draw_sell_band = plot(series=sell_band, color=color.new(color.fuchsia,100), offset=bar_offset, title='Sell Band') draw_buy_band = plot(series=buy_band, color=color.new(color.teal,100), offset=bar_offset, title='Buy Band') draw_fv_band = plot(series=fv_band, color=color.new(color.gray,0), offset=bar_offset, title='Fair Value') //===================================== // bollinger bands bb_len = input.int(defval=14, title='BB (SMA) Period', group="Bollinger Band Settings") bb_hi_stdev = input.float(defval=2.5, title='BB Sell Mult', group="Bollinger Band Settings") bb_lo_stdev = input.float(defval=0.6, title='BB Buy Mult', group="Bollinger Band Settings") get_bol_bands(_hi_line, _lo_line, _sma_len, _std_dev_hi, _std_dev_lo) => [_bb_a_sma, _bb_a_hi, _bb_a_lo] = ta.bb(_hi_line, _sma_len, _std_dev_hi) [_bb_b_sma, _bb_b_hi, _bb_b_lo] = ta.bb(_lo_line, _sma_len, _std_dev_lo) [_bb_a_lo, _bb_b_hi] //===================================== // keltner channel bands kelt_len = input.int(defval=9, title='Keltner (EMA) Period', group="Keltner Channel Band Settings") kelt_hi_atr = input.float(defval=1.5, title='Keltner Sell Mult', group="Keltner Channel Band Settings") kelt_lo_atr = input.float(defval=0.5, title='Keltner Buy Mult', group="Keltner Channel Band Settings") get_kelt_bands(_hi_line, _lo_line, _ema_len, _atr_hi, _atr_lo) => [_kc_a_ema, _kc_a_hi, _kc_a_lo] = ta.kc(_hi_line, _ema_len, _atr_hi) [_kc_b_ema, _kc_b_hi, _kc_b_lo] = ta.kc(_lo_line, _ema_len, _atr_lo) [_kc_a_ema, _kc_b_ema] //===================================== sell_band_bb_tf = request.security(symbol=netliq_expr, timeframe=bb_tf, expression=scaled_upper_expr) buy_band_bb_tf = request.security(symbol=netliq_expr, timeframe=bb_tf, expression=scaled_lower_expr) sell_band_kc_tf = request.security(symbol=netliq_expr, timeframe=kc_tf, expression=scaled_upper_expr) buy_band_kc_tf = request.security(symbol=netliq_expr, timeframe=kc_tf, expression=scaled_lower_expr) // --------- [ bb_sell_band, bb_buy_band ] = get_bol_bands(sell_band_bb_tf,buy_band_bb_tf,bb_len,bb_hi_stdev,bb_lo_stdev) draw_bb_sell_band = plot(series=bb_sell_band, color=color.new(color.fuchsia,0), offset=bar_offset, title='BB Sell Band') draw_bb_buy_band = plot(series=bb_buy_band, color=color.new(color.teal,0), offset=bar_offset, title='BB Buy Band') // --------- [ kc_sell_band, kc_buy_band ] = get_kelt_bands(sell_band_kc_tf,buy_band_kc_tf,kelt_len,kelt_hi_atr,kelt_lo_atr) draw_kc_sell_band = plot(series=kc_sell_band, color=color.new(color.fuchsia,100), offset=bar_offset, title='KC Sell Band') draw_kc_buy_band = plot(series=kc_buy_band, color=color.new(color.teal,100), offset=bar_offset, title='KC Buy Band') //===================================== fill_color_src = input.source(defval=close, title='Band Fill Color Decision Source', group="Band Fill Settings") var color _USER_SELECT_STD_BAND_FILL_BELOW_BAND_COLOR = input.color(defval=color.new(color.white,100), title='Below Band', inline='Std Band Fill Color', group='Std Band Fill Settings') var color _USER_SELECT_STD_BAND_FILL_BELOW_FV_COLOR = input.color(defval=color.new(color.white,100), title='Below FV', inline='Std Band Fill Color', group='Std Band Fill Settings') var color _USER_SELECT_STD_BAND_FILL_ABOVE_FV_COLOR = input.color(defval=color.new(color.white,100), title='Above FV', inline='Std Band Fill Color', group='Std Band Fill Settings') var color _USER_SELECT_STD_BAND_FILL_ABOVE_BAND_COLOR = input.color(defval=color.new(color.white,100), title='Above Band', inline='Std Band Fill Color', group='Std Band Fill Settings') var color _USER_SELECT_BB_BAND_FILL_BELOW_BAND_COLOR = input.color(defval=color.new(color.white,100), title='Below Band', inline='BB Fill Color', group='BB Fill Settings') var color _USER_SELECT_BB_BAND_FILL_BELOW_FV_COLOR = input.color(defval=color.new(color.white,100), title='Below FV', inline='BB Fill Color', group='BB Fill Settings') var color _USER_SELECT_BB_BAND_FILL_ABOVE_FV_COLOR = input.color(defval=color.new(color.white,100), title='Above FV', inline='BB Fill Color', group='BB Fill Settings') var color _USER_SELECT_BB_BAND_FILL_ABOVE_BAND_COLOR = input.color(defval=color.new(color.white,100), title='Above Band', inline='BB Fill Color', group='BB Fill Settings') var color _USER_SELECT_KC_BAND_FILL_BELOW_BAND_COLOR = input.color(defval=color.new(color.white,100), title='Below Band', inline='KC Fill Color', group='KC Fill Settings') var color _USER_SELECT_KC_BAND_FILL_BELOW_FV_COLOR = input.color(defval=color.new(color.white,100), title='Below FV', inline='KC Fill Color', group='KC Fill Settings') var color _USER_SELECT_KC_BAND_FILL_ABOVE_FV_COLOR = input.color(defval=color.new(color.white,100), title='Above FV', inline='KC Fill Color', group='KC Fill Settings') var color _USER_SELECT_KC_BAND_FILL_ABOVE_BAND_COLOR = input.color(defval=color.new(color.white,100), title='Above Band', inline='KC Fill Color', group='KC Fill Settings') //---- var bool below_fv_cond = false var bool std_above_band_cond = false var bool std_below_band_cond = false var bool bb_above_band_cond = false var bool bb_below_band_cond = false var bool kc_above_band_cond = false var bool kc_below_band_cond = false below_fv_cond := na(fill_color_src) or na(fv_band) ? below_fv_cond[1] : fill_color_src < fv_band std_above_band_cond := na(fill_color_src) or na(sell_band) ? std_above_band_cond[1] : fill_color_src >= sell_band std_below_band_cond := na(fill_color_src) or na(buy_band) ? std_below_band_cond[1] : fill_color_src <= buy_band bb_above_band_cond := na(fill_color_src) or na(bb_sell_band) ? bb_above_band_cond[1] : fill_color_src >= bb_sell_band bb_below_band_cond := na(fill_color_src) or na(bb_buy_band) ? bb_below_band_cond[1] : fill_color_src <= bb_buy_band kc_above_band_cond := na(fill_color_src) or na(kc_sell_band) ? kc_above_band_cond[1] : fill_color_src >= kc_sell_band kc_below_band_cond := na(fill_color_src) or na(kc_buy_band) ? kc_below_band_cond[1] : fill_color_src <= kc_buy_band fill(draw_sell_band, draw_buy_band, color= std_below_band_cond ? _USER_SELECT_STD_BAND_FILL_BELOW_BAND_COLOR : std_above_band_cond ? _USER_SELECT_STD_BAND_FILL_ABOVE_BAND_COLOR : below_fv_cond ? _USER_SELECT_STD_BAND_FILL_BELOW_FV_COLOR: _USER_SELECT_STD_BAND_FILL_ABOVE_FV_COLOR, title='Std Band Fill', editable=true) fill(draw_bb_sell_band, draw_bb_buy_band, color= bb_below_band_cond ? _USER_SELECT_BB_BAND_FILL_BELOW_BAND_COLOR : bb_above_band_cond ? _USER_SELECT_BB_BAND_FILL_ABOVE_BAND_COLOR : below_fv_cond ? _USER_SELECT_BB_BAND_FILL_BELOW_FV_COLOR: _USER_SELECT_BB_BAND_FILL_ABOVE_FV_COLOR, title='Bollinger Band Fill', editable=true) fill(draw_kc_sell_band, draw_kc_buy_band, color= kc_below_band_cond ? _USER_SELECT_KC_BAND_FILL_BELOW_BAND_COLOR : kc_above_band_cond ? _USER_SELECT_KC_BAND_FILL_ABOVE_BAND_COLOR : below_fv_cond ? _USER_SELECT_KC_BAND_FILL_BELOW_FV_COLOR: _USER_SELECT_KC_BAND_FILL_ABOVE_FV_COLOR, title='Keltner Channel Fill', editable=true)
Overlay - HARSI + Divergences
https://www.tradingview.com/script/6pL2Y5U5-Overlay-HARSI-Divergences/
AlphaTurbo
https://www.tradingview.com/u/AlphaTurbo/
182
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/ // © LordKaan // All credit to © geneclash & VuManChu & Arty & TheThirdFloor for their original Scripts // TTF Based on the TMA Overlay by Arty // Many thanks to the original script where I've extracted some code lines : Arty and TheThirdFloor //https://www.tradingview.com/v/admGhVz7/ //https://www.tradingview.com/v/zX3fvduH/ // // This is a trimmed down version of the OG TMA Overlay with a focus on highlighting a couple specific candlestick patterns. // This script is organized in a way that allows each pattern to be commented-out (disabled) or uncommented (enabled) pretty easily. // // The original request was for 3-Line-Strike only, so that is what will be enabled/uncommented by default, // but the engulfing code will be left in as well so that it can be turned on easily if desired. // // TODO: Add in a trend filter based on the trend identification method Arty discusses in his video on this candle pattern. // // NOTE: As-written, the symbols and 'alert()' functions are subject to repainting (firing without a confirmed signal at bar close). // This was done deliberately as a way to give people early-warning on live charts to help give them time to prepare for an entry, // which can be especially significant when scalping on low timeframe (1-5m) charts. // This is open-source and open code, not to be private //@version=5 indicator('Overlay - HARSI + Divergences + TTF ', 'Overlay - HARSI + Divergences + TTF', format=format.price, precision=0, overlay=true) //////////////////////////////////////////////////////////////////////////////// // // // ====== ABOUT THIS INDICATOR // // // // - RSI based Heikin Ashi candle oscillator // // - Divergence based on the VuManChu Cipher B // // // // ====== ARTICLES and FURTHER READING // // // // - https://www.investopedia.com/terms/h/heikinashi.asp // // // // "Heikin-Ashi is a candlestick pattern technique that aims to reduce // // some of the market noise, creating a chart that highlights trend // // direction better than typical candlestick charts" // // // // ====== IDEA AND USE // // - The use of the HA RSI indicator when in the OverSold and OverBought // // area combined to a Divergence & a OB/OS buy/sell // // on the Cipher B by VuManChu. // // Can be usefull as a confluence at S/R levels. // // Tip = 1 minute timeframe seems to work the best on FOREX // // // // Contributions : // // --> Total conditions for an alert and a dot to display, resumed : // // - Buy/Sell in OB/OS // // - Divergence Buy/Sell // // - RSI Overlay is in OB/OS on current bar (or was the bar before) // // when both Buy/Sell dots from VMC appears. // // // // ====== DISCLAIMER // // For Tradingview & Pinescript moderators = // // This follow a strategy where RSI Overlay from @JayRogers script shall be // // in OB/OS zone, while combining it with the VuManChu Cipher B Divergences // // Buy&Sell + Buy/sell alerts In OB/OS areas. // // Any trade decisions you make are entirely your own responsibility. // // // // Thanks to dynausmaux for the code // Thanks to falconCoin for https://www.tradingview.com/script/KVfgBvDd-Market-Cipher-B-Free-version-with-Buy-and-sell/ inspired me to start this. // Thanks to LazyBear for WaveTrend Oscillator https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/ // Thanks to RicardoSantos for https://www.tradingview.com/script/3oeDh0Yq-RS-Price-Divergence-Detector-V2/ // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // // ====== TOOLTIPS ====== // // // //////////////////////////////////////////////////////////////////////////////// string TT_HARSI = 'Period for the RSI calculations used to generate the' + 'candles. This seperate from the RSI plot/histogram length.' string TT_PBIAS = 'Smoothing feature for the OPEN of the HARSI candles.' + '\n\nIncreases bias toward the prior open value which can' + ' help provide better visualisation of trend strength.' + '\n\n** By changing the Open values, High and Low can also' + ' be distorted - however Close will remain unchanged.' string TT_SMRSI = 'This option smoothes the RSI in a manner similar to HA' + ' open, but uses the realtime rsi rather than the prior' + ' close value.' string TT_STOCH = 'Uses the RSI generated by the above settings, and as such' + ' will be affected by the smoothing option.' string TT_STFIT = 'Adjusts the vertical scaling of the stochastic, can help' + ' to prevent distortion of other data in the channel.' + '\n\nHas no impact cross conditions.' //////////////////////////////////////////////////////////////////////////////// // // // ====== INPUTS ====== // // // //////////////////////////////////////////////////////////////////////////////// // -- RSI plot config string GROUP_PLOT = 'Config » RSI Plot' i_source = ohlc4, group=GROUP_PLOT i_lenRSI = 7 i_mode = true i_showPlot = true i_showHist = true // -- Channel OB/OS config string GROUP_CHAN = 'Config » OB/OS Boundaries' i_upper = 50 i_upperx = 30 i_lower = -50 i_lowerx = -30 // Settings // WaveTrend wtShow = true wtBuyShow = true wtGoldShow = true wtSellShow =true wtDivShow = true vwapShow = true wtChannelLen = 9 wtAverageLen = 12 wtMASource = hlc3 wtMALen = 3 // WaveTrend Overbought & Oversold lines obLevel = 53 obLevel2 = 60 obLevel3 = 100 osLevel = -53 osLevel2 = -60 osLevel3 = -75 // Divergence WT wtShowDiv = true wtShowHiddenDiv = false showHiddenDiv_nl = true wtDivOBLevel = 45 wtDivOSLevel = -65 // Divergence extra range wtDivOBLevel_addshow = true wtDivOBLevel_add = 15 wtDivOSLevel_add = -40 // RSI rsiShow = false rsiSRC = close rsiLen = 14 rsiOversold = 30 rsiOverbought = 60 // Divergence RSI rsiShowDiv = false rsiShowHiddenDiv = false rsiDivOBLevel = 60 rsiDivOSLevel = 30 // Colors colorRed = #ff0000 colorPurple = #e600e6 colorGreen = #3fff00 colorOrange = #e2a400 colorYellow = #ffe500 colorWhite = #ffffff colorPink = #ff00f0 colorBluelight = #31c0ff colorWT1 = #49536151 colorWT2 = #7b9fd596 colorWT2_ = #131722 // FUNCTIONS // Divergences f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and src[2] > src[0] f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and src[2] < src[0] f_fractalize(src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0 f_findDivs(src, topLimit, botLimit, useLimits) => fractalTop = f_fractalize(src) > 0 and (useLimits ? src[2] >= topLimit : true) ? src[2] : na fractalBot = f_fractalize(src) < 0 and (useLimits ? src[2] <= botLimit : true) ? src[2] : na highPrev = ta.valuewhen(fractalTop, src[2], 0)[2] highPrice = ta.valuewhen(fractalTop, high[2], 0)[2] lowPrev = ta.valuewhen(fractalBot, src[2], 0)[2] lowPrice = ta.valuewhen(fractalBot, low[2], 0)[2] bearSignal = fractalTop and high[2] > highPrice and src[2] < highPrev bullSignal = fractalBot and low[2] < lowPrice and src[2] > lowPrev bearDivHidden = fractalTop and high[2] < highPrice and src[2] > highPrev bullDivHidden = fractalBot and low[2] > lowPrice and src[2] < lowPrev [fractalTop, fractalBot, lowPrev, bearSignal, bullSignal, bearDivHidden, bullDivHidden] // WaveTrend f_wavetrend(src, chlen, avg, malen, tf) => tfsrc = request.security(syminfo.tickerid, tf, src) esa = ta.ema(tfsrc, chlen) de = ta.ema(math.abs(tfsrc - esa), chlen) ci = (tfsrc - esa) / (0.015 * de) wt1 = request.security(syminfo.tickerid, tf, ta.ema(ci, avg)) wt2 = request.security(syminfo.tickerid, tf, ta.sma(wt1, malen)) wtVwap = wt1 - wt2 wtOversold = wt2 <= osLevel wtOverbought = wt2 >= obLevel wtCross = ta.cross(wt1, wt2) wtCrossUp = wt2 - wt1 <= 0 wtCrossDown = wt2 - wt1 >= 0 wtCrosslast = ta.cross(wt1[2], wt2[2]) wtCrossUplast = wt2[2] - wt1[2] <= 0 wtCrossDownlast = wt2[2] - wt1[2] >= 0 [wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCrosslast, wtCrossUplast, wtCrossDownlast, wtVwap] // Get higher timeframe candle f_getTFCandle(_tf) => _open = request.security(ticker.heikinashi(syminfo.tickerid), _tf, open, barmerge.gaps_off, barmerge.lookahead_on) _close = request.security(ticker.heikinashi(syminfo.tickerid), _tf, close, barmerge.gaps_off, barmerge.lookahead_on) _high = request.security(ticker.heikinashi(syminfo.tickerid), _tf, high, barmerge.gaps_off, barmerge.lookahead_on) _low = request.security(ticker.heikinashi(syminfo.tickerid), _tf, low, barmerge.gaps_off, barmerge.lookahead_on) hl2 = (_high + _low) / 2.0 newBar = ta.change(_open) candleBodyDir = _close > _open [candleBodyDir, newBar] // zero median rsi helper function, just subtracts 50. f_zrsi(_source, _length) => ta.rsi(_source, _length) - 50 // zero median stoch helper function, subtracts 50 and includes % scaling f_zstoch(_source, _length, _smooth, _scale) => float _zstoch = ta.stoch(_source, _source, _source, _length) - 50 float _smoothed = ta.sma(_zstoch, _smooth) float _scaled = _smoothed / 100 * _scale _scaled // mode selectable rsi function for standard, or smoothed output f_rsi(_source, _length, _mode) => // get base rsi float _zrsi = f_zrsi(_source, _length) // smoothing in a manner similar to HA open, but rather using the realtime // rsi in place of the prior close value. var float _smoothed = na _smoothed := na(_smoothed[1]) ? _zrsi : (_smoothed[1] + _zrsi) / 2 // return the requested mode _mode ? _smoothed : _zrsi // RSI Heikin-Ashi generation function f_rsiHeikinAshi(_length) => // get close rsi float _closeRSI = f_zrsi(close, _length) // emulate "open" simply by taking the previous close rsi value float _openRSI = nz(_closeRSI[1], _closeRSI) // the high and low are tricky, because unlike "high" and "low" by // themselves, the RSI results can overlap each other. So first we just go // ahead and get the raw results for high and low, and then.. float _highRSI_raw = f_zrsi(high, _length) float _lowRSI_raw = f_zrsi(low, _length) // ..make sure we use the highest for high, and lowest for low float _highRSI = math.max(_highRSI_raw, _lowRSI_raw) float _lowRSI = math.min(_highRSI_raw, _lowRSI_raw) // ha calculation for close float _close = (_openRSI + _highRSI + _lowRSI + _closeRSI) / 4 // Indicators // ### 3 Line Strike // showBear3LS = true showBull3LS = true // RSI rsi = ta.rsi(rsiSRC, rsiLen) rsiColor = rsi <= rsiOversold ? colorGreen : rsi >= rsiOverbought ? colorRed : colorPurple // Calculates WaveTrend [wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCross_last, wtCrossUp_last, wtCrossDown_last, wtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, timeframe.period) // WT Divergences [wtFractalTop, wtFractalBot, wtLow_prev, wtBearDiv, wtBullDiv, wtBearDivHidden, wtBullDivHidden] = f_findDivs(wt2, wtDivOBLevel, wtDivOSLevel, true) [wtFractalTop_add, wtFractalBot_add, wtLow_prev_add, wtBearDiv_add, wtBullDiv_add, wtBearDivHidden_add, wtBullDivHidden_add] = f_findDivs(wt2, wtDivOBLevel_add, wtDivOSLevel_add, true) [wtFractalTop_nl, wtFractalBot_nl, wtLow_prev_nl, wtBearDiv_nl, wtBullDiv_nl, wtBearDivHidden_nl, wtBullDivHidden_nl] = f_findDivs(wt2, 0, 0, false) wtBearDivHidden_ = showHiddenDiv_nl ? wtBearDivHidden_nl : wtBearDivHidden wtBullDivHidden_ = showHiddenDiv_nl ? wtBullDivHidden_nl : wtBullDivHidden wtBearDivColor = wtShowDiv and wtBearDiv or wtShowHiddenDiv and wtBearDivHidden_ ? colorRed : na wtBullDivColor = wtShowDiv and wtBullDiv or wtShowHiddenDiv and wtBullDivHidden_ ? colorGreen : na wtBearDivColor_add = wtShowDiv and wtDivOBLevel_addshow and wtBearDiv_add or wtShowHiddenDiv and wtDivOBLevel_addshow and wtBearDivHidden_add ? #9a0202 : na wtBullDivColor_add = wtShowDiv and wtDivOBLevel_addshow and wtBullDiv_add or wtShowHiddenDiv and wtDivOBLevel_addshow and wtBullDivHidden_add ? #1b5e20 : na // RSI Divergences [rsiFractalTop, rsiFractalBot, rsiLow_prev, rsiBearDiv, rsiBullDiv, rsiBearDivHidden, rsiBullDivHidden] = f_findDivs(rsi, rsiDivOBLevel, rsiDivOSLevel, true) [rsiFractalTop_nl, rsiFractalBot_nl, rsiLow_prev_nl, rsiBearDiv_nl, rsiBullDiv_nl, rsiBearDivHidden_nl, rsiBullDivHidden_nl] = f_findDivs(rsi, 0, 0, false) rsiBearDivHidden_ = showHiddenDiv_nl ? rsiBearDivHidden_nl : rsiBearDivHidden rsiBullDivHidden_ = showHiddenDiv_nl ? rsiBullDivHidden_nl : rsiBullDivHidden rsiBearDivColor = rsiShowDiv and rsiBearDiv or rsiShowHiddenDiv and rsiBearDivHidden_ ? colorRed : na rsiBullDivColor = rsiShowDiv and rsiBullDiv or rsiShowHiddenDiv and rsiBullDivHidden_ ? colorGreen : na // Buy signal. buySignal = wtCross and wtCrossUp and wtOversold buySignalDiv = wtShowDiv and wtBullDiv or wtShowDiv and wtBullDiv_add or rsiShowDiv and rsiBullDiv buySignalDiv_color = wtBullDiv ? colorGreen : wtBullDiv_add ? color.new(colorGreen, 10) : rsiShowDiv ? colorGreen : na // Sell signal sellSignal = wtCross and wtCrossDown and wtOverbought sellSignalDiv = wtShowDiv and wtBearDiv or wtShowDiv and wtBearDiv_add or rsiShowDiv and rsiBearDiv sellSignalDiv_color = wtBearDiv ? colorRed : wtBearDiv_add ? color.new(colorRed, 10) : rsiBearDiv ? colorRed : na // Indicators // standard, or ha smoothed rsi for the line plot and/or histogram float RSI = f_rsi(i_source, i_lenRSI, i_mode) // shadow, invisible color colShadow = color.rgb(0, 0, 0, 20) color colNone = color.rgb(0, 0, 0, 100) // rsi color //color colRSI = RSI >=30 ? color.red : color.gray color colRSI = RSI < -31 ? #00e6774a : RSI > 31 ? #ff52521a : #ffffff //Crosses cross_up = RSI[1] > 30 cross_down = RSI[1] < -30 crossd_up = RSI > 30 crossd_down = RSI < -30 getCandleColorIndex(barIndex) => int ret = na if (close[barIndex] > open[barIndex]) ret := 1 else if (close[barIndex] < open[barIndex]) ret := -1 else ret := 0 ret // // Check for engulfing candles isEngulfing(checkBearish) => // In an effort to try and make this a bit more consistent, we're going to calculate and compare the candle body sizes // to inform the engulfing or not decision, and only use the open vs close comparisons to identify the candle "color" ret = false sizePrevCandle = close[1] - open[1] // negative numbers = red, positive numbers = green, 0 = doji sizeCurrentCandle = close - open // negative numbers = red, positive numbers = green, 0 = doji isCurrentLagerThanPrevious = (math.abs(sizeCurrentCandle) > math.abs(sizePrevCandle)) ? true : false // We now have the core info to evaluate engulfing candles switch checkBearish true => // Check for bearish engulfing (green candle followed by a larger red candle) isGreenToRed = ((getCandleColorIndex(0) < 0) and (getCandleColorIndex(1) > 0)) ? true : false ret := (isCurrentLagerThanPrevious and isGreenToRed) ? true : false false => // Check for bullish engulfing (red candle followed by a larger green candle) isRedToGreen = ((getCandleColorIndex(0) > 0) and (getCandleColorIndex(1) < 0)) ? true : false ret := (isCurrentLagerThanPrevious and isRedToGreen) ? true : false => ret := false // This should be impossible to trigger... ret // // Helper functions that wraps the isEngulfing above... isBearishEngulfuing() => ret = isEngulfing(true) ret // isBullishEngulfuing() => ret = isEngulfing(false) ret // // Functions to check for 3 consecutive candles of one color, followed by an engulfing candle of the opposite color // // Bearish 3LS = 3 green candles immediately followed by a bearish engulfing candle is3LSBear() => ret = false is3LineSetup = ((getCandleColorIndex(1) > 0) and (getCandleColorIndex(2) > 0) and (getCandleColorIndex(3) > 0)) ? true : false ret := (is3LineSetup and isBearishEngulfuing()) ? true : false ret // // Bullish 3LS = 3 red candles immediately followed by a bullish engulfing candle is3LSBull() => ret = false is3LineSetup = ((getCandleColorIndex(1) < 0) and (getCandleColorIndex(2) < 0) and (getCandleColorIndex(3) < 0)) ? true : false ret := (is3LineSetup and isBullishEngulfuing()) ? true : false ret // ### 3 Line Strike is3LSBearSig = is3LSBear() and crossd_up is3LSBullSig = is3LSBull() and crossd_down /// Plots // Standard plots for the 3LS signal plotshape(showBull3LS ? is3LSBullSig : na, style=shape.triangleup, color=color.rgb(0, 255, 0, 0), location=location.belowbar, size=size.small, text='3LS-Bull', title='3 Line Strike Up') plotshape(showBear3LS ? is3LSBearSig : na, style=shape.triangledown, color=color.rgb(255, 0, 0, 0), location=location.abovebar, size=size.small, text='3LS-Bear', title='3 Line Strike Down') plotchar(cross_down[1] and wtBuyShow and buySignal[2] and wtDivShow and buySignalDiv ? -20 : na, title='Divergence buy circle + Buy + RSI OS', char='·', color=color.new(colorGreen, 0), location=location.belowbar, size=size.large, offset=-2) plotchar(cross_up[1] and wtSellShow and sellSignal[2] and wtDivShow and sellSignalDiv ? 20 : na, title='Divergence sell circle + Sell + RSI OB', char='·', color=color.new(colorRed, 0), location=location.abovebar, size=size.large, offset=-2) plotchar(cross_down[1] and wtBuyShow and buySignal[2] ? -20 : na, title='Buy + RSI OS', char='·', color=color.new(colorGreen, 70), location=location.belowbar, size=size.normal, offset=-2) plotchar(cross_up[1] and wtSellShow and sellSignal[2] ? 20 : na, title='Sell + RSI OB', char='·', color=color.new(colorRed, 70), location=location.abovebar, size=size.normal, offset=-2) /// Alerts alertcondition((cross_down[1] and wtBuyShow and buySignal[2] and wtDivShow and buySignalDiv) or (cross_up[1] and wtSellShow and sellSignal[2] and wtDivShow and sellSignalDiv), title='Buy/Sell Signal Triggered', message='Buy/Sell Signal {{exchange}}:{{ticker}}') alertcondition(is3LSBear() and crossd_up or is3LSBull() and crossd_down, title='3LineStrike Buy/Sell alert', message='3Line Strike Buy or Sell triggered on {{exchange}}:{{ticker}}' )
HL-Average
https://www.tradingview.com/script/T2NIEzDR/
Shinichi-Kagami
https://www.tradingview.com/u/Shinichi-Kagami/
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/ // © Shinichi-Kagami //@version=5 indicator("HL-Average",overlay=true,shorttitle="HLA") LLngth=input(70,title="Period") plot(ta.highest(LLngth),title="High",color=color.orange,style=plot.style_circles) plot(ta.lowest(LLngth),title="Low",color=color.orange,style=plot.style_circles) plot((ta.highest(LLngth)+ta.lowest(LLngth))/2,title="Average",color=color.green,style=plot.style_circles)
Mega Pendulum Indicator
https://www.tradingview.com/script/XwIHoaZZ-Mega-Pendulum-Indicator/
Sofien-Kaabar
https://www.tradingview.com/u/Sofien-Kaabar/
60
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/ // © Sofien-Kaabar //@version=5 indicator("Mega Pendulum Indicator") width = input(defval = 13, title = 'Width') lookback = input(defval = 5, title = 'Lookback') difference = close - close[width] variation = ta.stdev(difference, width) ratio = difference / variation pendul = ta.sma(ratio, lookback) pendulum = ta.rsi(pendul, 14) signal = ta.sma(pendulum, 5) upside_momentum_gauge = 0 if high > high[1] and close > open upside_momentum_gauge := 2 if high > high[1] and close < open upside_momentum_gauge := 1 if high < high[1] and close > open upside_momentum_gauge := 1 if high < high[1] and close < open upside_momentum_gauge := 0 downside_momentum_gauge = 0 if low > low[1] and close > open downside_momentum_gauge := 0 if low > low[1] and close < open downside_momentum_gauge := 1 if low < low[1] and close > open downside_momentum_gauge := 1 if low < low[1] and close < open downside_momentum_gauge := 2 raw_swing = upside_momentum_gauge - downside_momentum_gauge swing_indicator = raw_swing + raw_swing[1] + raw_swing[2] + raw_swing[3] + raw_swing[4] + raw_swing[5] + raw_swing[6] + raw_swing[7] plot(swing_indicator, color = color.black) hline(10, color = color.red) hline(-10, color = color.red) plot(pendulum, color = color.green) plot(signal, color = color.purple) hline(80, color = color.blue) hline(20, color = color.blue)
Yield Curve (2-10yr)
https://www.tradingview.com/script/5KNJX8XN-Yield-Curve-2-10yr/
capriole_charles
https://www.tradingview.com/u/capriole_charles/
109
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/ // © charles edwards //@version=4 study("Yield Curve (2-10yr)", overlay=false) TwoYear = security("DGS2", "D", close) TenYear = security("DGS10", "D", close) YC = (TenYear - TwoYear) curveO = plot(YC) lineO = plot(0, color=color.gray) fill(plot1=curveO, plot2=lineO, color= YC<0 ? color.new(color.red,70): na, title="Inverted") // Sourcing var table_source = table(na) table_source := table.new(position=position.bottom_left, columns=1, rows=1, bgcolor=color.white, border_width=1) table.cell(table_source, 0, 0, text="Source: Capriole Investments Limited", bgcolor=color.white, text_color=color.black, width=20, height=7, text_size=size.normal, text_halign=text.align_left)
Higher Time Frame Average True Ranges
https://www.tradingview.com/script/gNqLclP0-Higher-Time-Frame-Average-True-Ranges/
UnknownUnicorn30488523
https://www.tradingview.com/u/UnknownUnicorn30488523/
58
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/ // © ssxsnowboarder inspired by TOS users 7of9 and John J. Smith //This code compares the calculates the daily, weekly, and monthly true ranges and compares it to their average true ranges using a higher time frame function. //The goal is to help traders select the most probable strike price for an given expiration and determine possible exit strategies. //@version=5 indicator(title="Higher Time Frame Average True Ranges", shorttitle="HTF ATR", overlay=true) //Average True Range length = input.int(title="ATR Length", defval=1, minval=1) ATRlength = input.int(title="ATR Length", defval=14, minval=1) DTR = ta.atr(length) ATR = ta.atr(ATRlength) //Defines higher time frames for ATR string tf = "" security(sym, res, src) => request.security(sym, res, src) //DTR/ATR DTRpct = math.round(DTR/ATR*100, 0) //WTR/ATR float WATR = security(syminfo.tickerid, 'W', ATR) float WTR = security(syminfo.tickerid, 'W', DTR) WTRpct = math.round(WTR/WATR*100, 0) //MTR/ATR float MATR = security(syminfo.tickerid, 'M', ATR) float MTR = security(syminfo.tickerid, 'M', DTR) MTRpct = math.round(MTR/MATR*100, 0) //QTR/ATR float QATR = security(syminfo.tickerid, '3M', ATR) float QTR = security(syminfo.tickerid, '3M', DTR) QTRpct = math.round(QTR/QATR*100, 0) //Initialize color variables DCLR=input.color(color.orange) WCLR=input.color(color.orange) MCLR=input.color(color.orange) QCLR=input.color(color.orange) //Selects DTR Color if(DTRpct<81) DCLR:=input.color(color.green) else if(DTRpct>=100) DCLR:=input.color(color.red) else DCLR:=input.color(color.orange) //Selects WTR Color if(WTRpct<81) WCLR:=input.color(color.green) else if(WTRpct>=100) WCLR:=input.color(color.red) else WCLR:=input.color(color.orange) //Selects MTR Color if(MTRpct<81) MCLR:=input.color(color.green) else if(MTRpct>=100) MCLR:=input.color(color.red) else MCLR:=input.color(color.orange) //Selects QTR Color if(QTRpct<81) QCLR:=input.color(color.green) else if(QTRpct>=100) QCLR:=input.color(color.red) else QCLR:=input.color(color.orange) //Creates a table for the ratios var table table = table.new(position.top_right, 7, 4) //Creates DTR/ATR Row table.cell(table, 0, 0, str.tostring("DTR"), bgcolor=DCLR)//Titles and fills table table.cell(table, 1, 0, str.tostring(math.round(DTR,2)), bgcolor=DCLR)//Titles and fills table table.cell(table, 2, 0, str.tostring("vs"), bgcolor=DCLR)//Titles and fills table table.cell(table, 3, 0, str.tostring("DATR"), bgcolor=DCLR)//Titles and fills table table.cell(table, 4, 0, str.tostring(math.round(ATR,2)), bgcolor=DCLR)//Titles and fills table table.cell(table, 5, 0, str.tostring(DTRpct), bgcolor=DCLR)//Titles and fills table table.cell(table, 6, 0, str.tostring("%"), bgcolor=DCLR)//Titles and fills table //Creates WTR/ATR Row table.cell(table, 0, 1, str.tostring("WTR"), bgcolor=WCLR)//Titles and fills table table.cell(table, 1, 1, str.tostring(math.round(WTR,2)), bgcolor=WCLR)//Titles and fills table table.cell(table, 2, 1, str.tostring("vs"), bgcolor=WCLR)//Titles and fills table table.cell(table, 3, 1, str.tostring("WATR"), bgcolor=WCLR)//Titles and fills table table.cell(table, 4, 1, str.tostring(math.round(WATR,2)), bgcolor=WCLR)//Titles and fills table table.cell(table, 5, 1, str.tostring(WTRpct), bgcolor=WCLR)//Titles and fills table table.cell(table, 6, 1, str.tostring("%"), bgcolor=WCLR)//Titles and fills table //Creates MTR/ATR Row table.cell(table, 0, 2, str.tostring("MTR"), bgcolor=MCLR)//Titles and fills table table.cell(table, 1, 2, str.tostring(math.round(MTR,2)), bgcolor=MCLR)//Titles and fills table table.cell(table, 2, 2, str.tostring("vs"), bgcolor=MCLR)//Titles and fills table table.cell(table, 3, 2, str.tostring("MATR"), bgcolor=MCLR)//Titles and fills table table.cell(table, 4, 2, str.tostring(math.round(MATR,2)), bgcolor=MCLR)//Titles and fills table table.cell(table, 5, 2, str.tostring(MTRpct), bgcolor=MCLR)//Titles and fills table table.cell(table, 6, 2, str.tostring("%"), bgcolor=MCLR)//Titles and fills table //Creates QTR/ATR Row table.cell(table, 0, 3, str.tostring("QTR"), bgcolor=QCLR)//Titles and fills table table.cell(table, 1, 3, str.tostring(math.round(QTR,2)), bgcolor=QCLR)//Titles and fills table table.cell(table, 2, 3, str.tostring("vs"), bgcolor=QCLR)//Titles and fills table table.cell(table, 3, 3, str.tostring("QATR"), bgcolor=QCLR)//Titles and fills table table.cell(table, 4, 3, str.tostring(math.round(QATR,2)), bgcolor=QCLR)//Titles and fills table table.cell(table, 5, 3, str.tostring(QTRpct), bgcolor=QCLR)//Titles and fills table table.cell(table, 6, 3, str.tostring("%"), bgcolor=QCLR)//Titles and fills table //DTR, WTR, MTR, and QTR Plots float UpperDTR=open+ATR float LowerDTR=open-ATR float UpperWTR = security(syminfo.tickerid, 'W', open)+WATR float LowerWTR = security(syminfo.tickerid, 'W', open)-WATR float UpperMTR = security(syminfo.tickerid, 'M', open)+MATR float LowerMTR = security(syminfo.tickerid, 'M', open)-MATR float UpperQTR = security(syminfo.tickerid, '3M', open)+QATR float LowerQTR = security(syminfo.tickerid, '3M', open)-QATR plot(UpperDTR, title="Upper DTR", color=color.red, linewidth=1, show_last = 1, trackprice = true) plot(LowerDTR, title="Lower DTR", color=color.red, linewidth=1, show_last = 1, trackprice = true) plot(UpperWTR, title="Upper WTR", color=color.green, linewidth=1, show_last = 1, trackprice = true) plot(LowerWTR, title="Lower WTR", color=color.green, linewidth=1, show_last = 1, trackprice = true) plot(UpperMTR, title="Upper MTR", color=color.blue, linewidth=1, show_last = 1, trackprice = true) plot(LowerMTR, title="Lower MTR", color=color.blue, linewidth=1, show_last = 1, trackprice = true) plot(UpperQTR, title="Upper QTR", color=color.purple, linewidth=1, show_last = 1, trackprice = true) plot(LowerQTR, title="Lower QTR", color=color.purple, linewidth=1, show_last = 1, trackprice = true)
MTF Fantastic Stochastic (FS+)
https://www.tradingview.com/script/XPJLyw3Q-MTF-Fantastic-Stochastic-FS/
tvenn
https://www.tradingview.com/u/tvenn/
133
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/ // © tvenn //@version=5 indicator(title="MTF Fantastic Stochastic (FS+)", shorttitle="FS+", overlay = true, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400) //=Constants green = #95BD5F red = #EA1889 // =MTF Stoch //================================================================================================================================== grp_MTFSRSI = "MTF Stoch RSI" smoothK = input.int(3, "K", minval=1, group=grp_MTFSRSI) smoothD = input.int(3, "D", minval=1, group=grp_MTFSRSI) lengthRSI = input.int(14, "RSI Length", minval=1, group=grp_MTFSRSI) lengthStoch = input.int(14, "Stochastic Length", minval=1, group=grp_MTFSRSI) rsi1 = ta.rsi(close, lengthRSI) k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = ta.sma(k, smoothD) grp_CTFSRSI1 = "Show current timeframe OB/OS in ribbon" includeCurrentTFOBOS = input(false, title="Show current timeframe OB/OS in ribbon", group=grp_CTFSRSI1, tooltip="this will include in the ribbon indications where the Stoch RSI is overbought or oversold on the current timeframe") CTF_1 = input.string("Chart", title="CTF", options=["Chart"], group=grp_CTFSRSI1, inline="tf1") CTF_OSTHRESH_1 = input(20, title="", group=grp_CTFSRSI1, inline="tf1") CTF_OBTHRESH_1 = input(80, title="", group=grp_CTFSRSI1, inline="tf1") //Primary MTF Stoch RSI confluences grp_MTFSRSI1 = "MTF Stoch RSI #1" enableOBOS_1 = input(true, title="Show MTF #1 Stoch RSI OB/OS in ribbon", group=grp_MTFSRSI1, tooltip="This will color a ribbon on the chart to indicate where the MTF Stoch RSI is oversold and overbought.") useBgColorMTFStochOBOS_1 = input(true, title="Color background where MTF #1 Stoch RSI OB/OS", group=grp_MTFSRSI1, tooltip="This will color the background of the chart to indicate where the MTF Stoch RSI is oversold and overbought.") useBarColorMTFStochOBOS_1 = input(false, title="Color candles where MTF #1 Stoch RSI OB/OS", group=grp_MTFSRSI1, tooltip="This will color the candles on the chart to indicate where the MTF Stoch RSI is oversold and overbought.") overboughtColor_1 = input.color(red, title="Stoch overbought color", group=grp_MTFSRSI1) oversoldColor_1 = input.color(green, title="Stoch oversold color", group=grp_MTFSRSI1) grp_MTFSRSI1_ = "Stoch RSI MTF #1 [Timeframe] [OS level] [OB level]" TF_1 = input.string("1", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1_, inline="mtf1") TF_2 = input.string("5", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1_, inline="mtf2") TF_3 = input.string("15", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI1_, inline="mtf3") MTF_OSTHRESH_1 = input(20, title="", group=grp_MTFSRSI1_, inline="mtf1") MTF_OSTHRESH_2 = input(20, title="", group=grp_MTFSRSI1_, inline="mtf2") MTF_OSTHRESH_3 = input(20, title="", group=grp_MTFSRSI1_, inline="mtf3") MTF_OBTHRESH_1 = input(80, title="", group=grp_MTFSRSI1_, inline="mtf1") MTF_OBTHRESH_2 = input(80, title="", group=grp_MTFSRSI1_, inline="mtf2") MTF_OBTHRESH_3 = input(80, title="", group=grp_MTFSRSI1_, inline="mtf3") MTF1 = request.security(syminfo.tickerid, TF_1 == "Chart" ? "" : TF_1, k, barmerge.gaps_off) MTF2 = request.security(syminfo.tickerid, TF_2 == "Chart" ? "" : TF_2, k, barmerge.gaps_off) MTF3 = request.security(syminfo.tickerid, TF_3 == "Chart" ? "" : TF_3, k, barmerge.gaps_off) allMTFStochOB_1 = (MTF1 > MTF_OBTHRESH_1 and MTF2 > MTF_OBTHRESH_2 and MTF3 > MTF_OBTHRESH_3) allMTFStochOS_1 = (MTF1 < MTF_OSTHRESH_1 and MTF2 < MTF_OSTHRESH_2 and MTF3 < MTF_OSTHRESH_3) obColor_1 = (k > CTF_OBTHRESH_1+10 ? color.new(overboughtColor_1, 50) : enableOBOS_1 and k > CTF_OBTHRESH_1 ? color.new(overboughtColor_1, 70) : na) osColor_1 = (k < CTF_OSTHRESH_1-10 ? color.new(oversoldColor_1, 50) : enableOBOS_1 and k < CTF_OSTHRESH_1 ? color.new(oversoldColor_1, 70) : na) allOBColor_1 = (allMTFStochOB_1 ? overboughtColor_1 : na) allOSColor_1 = (allMTFStochOS_1 ? oversoldColor_1 : na) plotchar(k, title="Current TF SRSI overbought", color=(includeCurrentTFOBOS ? obColor_1 : na), char="■", location=location.bottom) plotchar(k, title="Current TF SRSI oversold", color=(includeCurrentTFOBOS ? osColor_1 : na), char="■", location=location.bottom) plotchar(k, title="3x TF all overbought", color=(enableOBOS_1 ? allOBColor_1 : na), char="■", location=location.bottom) plotchar(k, title="3x TF all oversold", color=(enableOBOS_1 ? allOSColor_1 : na), char="■", location=location.bottom) //bgcolor bgcolor((useBgColorMTFStochOBOS_1 and allMTFStochOB_1 ? color.new(allOBColor_1, 90) : (useBgColorMTFStochOBOS_1 and allMTFStochOS_1 ? color.new(allOSColor_1, 90) : na)), title='Stoch RSI OB/OS background colour') barcolor(useBarColorMTFStochOBOS_1 and allMTFStochOB_1 ? allOBColor_1 : (useBarColorMTFStochOBOS_1 and allMTFStochOS_1 ? allOSColor_1 : na)) //Secondary MTF Stoch RSI confluences grp_MTFSRSI2 = "MTF Stoch RSI #2" enableOBOS_2 = input(true, title="Show MTF #2 Stoch RSI OB/OS in ribbon", group=grp_MTFSRSI2, tooltip="This will color a ribbon on the chart to indicate where the MTF Stoch RSI is oversold and overbought.") useBgColorMTFStochOBOS_2 = input(false, title="Color background where MTF #2 Stoch RSI OB/OS", group=grp_MTFSRSI2, tooltip="This will color the background of the chart to indicate where the MTF Stoch RSI is oversold and overbought.") useBarColorMTFStochOBOS_2 = input(false, title="Color candles where MTF #2 Stoch RSI OB/OS", group=grp_MTFSRSI2, tooltip="This will color the candles on the chart to indicate where the MTF Stoch RSI is oversold and overbought.") overboughtColor_2 = input.color(color.rgb(255, 68, 68, 50), title="Stoch overbought color", group=grp_MTFSRSI2) oversoldColor_2 = input.color(color.rgb(43, 117, 46, 50), title="Stoch oversold color", group=grp_MTFSRSI2) grp_MTFSRSI2_= "Stoch RSI MTF #2 [Timeframe] [OS level] [OB level]" TF_1_2 = input.string("15", title="TF1", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2_, inline="mtf1") TF_2_2 = input.string("30", title="TF2", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2_, inline="mtf2") TF_3_2 = input.string("120", title="TF3", options=["Chart", "1", "2", "3", "4", "5", "8", "10", "15", "20", "30", "45", "60", "120", "240"], group=grp_MTFSRSI2_, inline="mtf3") MTF_OSTHRESH_1_2 = input(20, title="", group=grp_MTFSRSI2_, inline="mtf1") MTF_OSTHRESH_2_2 = input(20, title="", group=grp_MTFSRSI2_, inline="mtf2") MTF_OSTHRESH_3_2 = input(20, title="", group=grp_MTFSRSI2_, inline="mtf3") MTF_OBTHRESH_1_2 = input(80, title="", group=grp_MTFSRSI2_, inline="mtf1") MTF_OBTHRESH_2_2 = input(80, title="", group=grp_MTFSRSI2_, inline="mtf2") MTF_OBTHRESH_3_2 = input(80, title="", group=grp_MTFSRSI2_, inline="mtf3") MTF1_2 = request.security(syminfo.tickerid, TF_1_2 == "Chart" ? "" : TF_1_2, k, barmerge.gaps_off) MTF2_2 = request.security(syminfo.tickerid, TF_2_2 == "Chart" ? "" : TF_2_2, k, barmerge.gaps_off) MTF3_2 = request.security(syminfo.tickerid, TF_3_2 == "Chart" ? "" : TF_3_2, k, barmerge.gaps_off) allMTFStochOB_2 = (MTF1_2 > MTF_OBTHRESH_1_2 and MTF2_2 > MTF_OBTHRESH_2_2 and MTF3_2 > MTF_OBTHRESH_3_2) allMTFStochOS_2 = (MTF1_2 < MTF_OSTHRESH_1_2 and MTF2_2 < MTF_OSTHRESH_2_2 and MTF3_2 < MTF_OSTHRESH_3_2) obColor_2 = (k > 90 ? color.new(overboughtColor_2, 50) : enableOBOS_2 and k > 80 ? color.new(overboughtColor_2, 70) : na) osColor_2 = (k < 10 ? color.new(oversoldColor_2, 50) : enableOBOS_2 and k < 20 ? color.new(oversoldColor_2, 70) : na) allOBColor_2 = (allMTFStochOB_2 ? overboughtColor_2 : na) allOSColor_2 = (allMTFStochOS_2 ? oversoldColor_2 : na) plotchar(k, title="3x TF all overbought", color=(enableOBOS_2 ? allOBColor_2 : na), char="■", location=location.bottom) plotchar(k, title="3x TF all oversold", color=(enableOBOS_2 ? allOSColor_2 : na), char="■", location=location.bottom) bgcolor((useBgColorMTFStochOBOS_2 and allMTFStochOB_2 ? color.new(allOBColor_2, 90) : (useBgColorMTFStochOBOS_2 and allMTFStochOS_2 ? color.new(allOSColor_2, 90) : na)), title='Stoch RSI OB/OS background colour') barcolor(useBarColorMTFStochOBOS_2 and allMTFStochOB_2 ? allOBColor_2 : (useBarColorMTFStochOBOS_2 and allMTFStochOS_2 ? allOSColor_1 : na)) //Alerts alertcondition((allMTFStochOB_1 and not allMTFStochOB_1[1]) or (allMTFStochOS_1 and not allMTFStochOS_1[1]), title="MTF #1 Stoch OB/OS Detected in FS+", message="MTF #1 Stoch OB/OS Detected in FS+") alertcondition((allMTFStochOB_1 and not allMTFStochOB_1[1]), title="MTF #1 Stoch Overbought Detected in FS+", message="MTF #1 Stoch Overbought Detected in FS+") alertcondition((allMTFStochOS_1 and not allMTFStochOS_1[1]), title="MTF #1 Stoch Oversold Detected in FS+", message="MTF #1 Stoch Oversold Detected in FS+") alertcondition((allMTFStochOB_2 and not allMTFStochOB_2[1]) or (allMTFStochOS_2 and not allMTFStochOS_2[1]), title="MTF #2 Stoch OB/OS Detected in FS+", message="MTF #2 Stoch OB/OS Detected in FS+") alertcondition((allMTFStochOB_2 and not allMTFStochOB_2[1]), title="MTF #2 Stoch Overbought Detected in FS+", message="MTF #2 Stoch Overbought Detected in FS+") alertcondition((allMTFStochOS_2 and not allMTFStochOS_2[1]), title="MTF #2 Stoch Oversold Detected in FS+", message="MTF #2 Stoch Oversold Detected in FS+") //Oscillator value table grp_TABLE = "MTF Table" showMTFVals = input(false, title="Show MTF table for", group=grp_TABLE, inline="table") MTFTableType = input.string("MTF #1 & #2", options=["MTF #1", "MTF #2", "MTF #1 & #2"], title="", group=grp_TABLE, inline="table") dashboardSize = input.string(title='', defval='Mobile', options=['Mobile', 'Desktop'], group=grp_TABLE, inline="table") labelPos = input.string(title="Table position", defval='Top right', options=['Top right', 'Top left', 'Bottom right', 'Bottom left'], group=grp_TABLE) MTFLabelColor = input(color.new(color.white, 100), title="Table color", group=grp_TABLE) valueColor = color.new(color.white, 30) labelColor = color.new(color.white, 70) _MTF1labelColor(val, ob, os) => val > ob ? overboughtColor_1 : (val < os ? oversoldColor_1 : valueColor) _MTF2labelColor(val, ob, os) => val > ob ? overboughtColor_2 : (val < os ? oversoldColor_2 : valueColor) _labelPos = switch labelPos "Top right" => position.top_right "Top left" => position.top_left "Bottom right" => position.bottom_right "Bottom left" => position.bottom_left _size = switch dashboardSize "Mobile" => size.small "Desktop" => size.normal //Oscillator value label var table label = table.new(position.top_right, 4, 4, bgcolor = MTFLabelColor, frame_width = 0, frame_color = color.new(color.gray, 100)) // We only populate the table on the last bar. if barstate.islast and showMTFVals if (MTFTableType=="MTF #1") table.cell(label, 0, 0, text="StochRSI", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 1, text=TF_1+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 1, text=str.tostring(math.floor(MTF1)), width=3, text_color=_MTF1labelColor(MTF1, MTF_OBTHRESH_1, MTF_OSTHRESH_1), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 2, text=TF_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 2, text=str.tostring(math.floor(MTF2)), width=3, text_color=_MTF1labelColor(MTF2, MTF_OBTHRESH_2, MTF_OSTHRESH_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 3, text=TF_3+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 3, text=str.tostring(math.floor(MTF3)), width=3, text_color=_MTF1labelColor(MTF3, MTF_OBTHRESH_3, MTF_OSTHRESH_3), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) else if (MTFTableType=="MTF #2") table.cell(label, 0, 0, text="StochRSI", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 1, text=TF_1_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 1, text=str.tostring(math.floor(MTF1_2)), width=3, text_color=_MTF2labelColor(MTF1_2, MTF_OBTHRESH_1_2, MTF_OSTHRESH_1_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 2, text=TF_2_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 2, text=str.tostring(math.floor(MTF2_2)), width=3, text_color=_MTF2labelColor(MTF2_2, MTF_OBTHRESH_2_2, MTF_OSTHRESH_2_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 3, text=TF_3_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 3, text=str.tostring(math.floor(MTF3_2)), width=3, text_color=_MTF2labelColor(MTF3_2, MTF_OBTHRESH_3_2, MTF_OSTHRESH_3_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) else if (MTFTableType=="MTF #1 & #2") table.cell(label, 0, 0, text="StochRSI", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 1, text=TF_1+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 1, text=str.tostring(math.floor(MTF1)), width=3, text_color=_MTF1labelColor(MTF1, MTF_OBTHRESH_1, MTF_OSTHRESH_1), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 2, text=TF_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 2, text=str.tostring(math.floor(MTF2)), width=3, text_color=_MTF1labelColor(MTF2, MTF_OBTHRESH_2, MTF_OSTHRESH_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 0, 3, text=TF_3+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 1, 3, text=str.tostring(math.floor(MTF3)), width=3, text_color=_MTF1labelColor(MTF3, MTF_OBTHRESH_3, MTF_OSTHRESH_3), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 2, 1, text=TF_1_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 3, 1, text=str.tostring(math.floor(MTF1_2)), width=3, text_color=_MTF2labelColor(MTF1_2, MTF_OBTHRESH_1_2, MTF_OSTHRESH_1_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 2, 2, text=TF_2_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 3, 2, text=str.tostring(math.floor(MTF2_2)), width=3, text_color=_MTF2labelColor(MTF2_2, MTF_OBTHRESH_2_2, MTF_OSTHRESH_2_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100)) table.cell(label, 2, 3, text=TF_3_2+"m", text_color=labelColor, text_halign=text.align_left, text_size=size.small, bgcolor=color.new(#000000, 100)) table.cell(label, 3, 3, text=str.tostring(math.floor(MTF3_2)), width=3, text_color=_MTF2labelColor(MTF3_2, MTF_OBTHRESH_3_2, MTF_OSTHRESH_3_2), text_halign=text.align_right, text_size=_size, bgcolor=color.new(#000000, 100))
ICT IPDA Look Back
https://www.tradingview.com/script/rTJEJb5v-ICT-IPDA-Look-Back/
toodegrees
https://www.tradingview.com/u/toodegrees/
1,690
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/ // © toodegrees //@version=5 indicator("ICT IPDA Look Back°", shorttitle = "ICT IPDA LB°", overlay = true) //#region [Functions & Errors] percenter(top, bottom) => math.round(((close - bottom) / (top - bottom)) * 100, 1) //#endregion //#region [Settings] plotType = input.string("Boxes", title = "IPDA Plot Format", group = "PLOT SETTINGS", inline = 'tt', options = ["Boxes", "Table A", "Table B"], tooltip = "'Boxes' plots proper IPDA ranges;\n" + "'Table A' shows Discount / Premium label;\n" + "'Table B' shows the distance from Equilibirum in %.") _showT = input.bool(true, title = "Show Text", group = "PLOT SETTINGS", inline = 'tt') discountC = input.color(color.new(color.maroon, 80), title = "Discount", group = "PLOT SETTINGS" , inline = "pd") equilibriumC = input.color(color.new(#000000, 0), title = "Equilibrium", group = "PLOT SETTINGS" , inline = "pd") premiumC = input.color(color.new(color.navy, 80), title = "Premium", group = "PLOT SETTINGS" , inline = "pd") ipda20 = input.bool(true, title = "IPDA20", group = "IPDA INTERVALS", inline = "int") ipda40 = input.bool(true, title = "IPDA40", group = "IPDA INTERVALS", inline = "int") ipda60 = input.bool(true, title = "IPDA60", group = "IPDA INTERVALS", inline = "int") _ipdaType = input.string("CLASSIC", title = "IPDA Data Ranges Type", group = "IPDA INTERVALS", options = ["CLASSIC", "CLASSIC+LTF", "LTF"], tooltip = "CLASSIC: standard Daily IPDA Data Ranges visible only on 1D timeframe.\n\nCLASSIC+LTF: plots the Daily 20, 40, 60 IPDA Data Ranges regardless of timeframe.\n\nLTF: plots last 20, 40, 60 IPDA Data Ranges of the current timeframe." ) _showDLTF = _ipdaType == "CLASSIC+LTF" _showLTF = _ipdaType == "LTF" //#endregion //#region [Logic] _showDLTF := _showLTF ? true : _showDLTF time20 = _showLTF ? time[20] : request.security(syminfo.tickerid, "D", time[20]) low20 = _showLTF ? ta.lowest(low, 20)[1] : request.security(syminfo.tickerid, "D", ta.lowest(low, 20))[1] high20 = _showLTF ? ta.highest(high, 20)[1] : request.security(syminfo.tickerid, "D", ta.highest(high, 20))[1] eq20 = (low20 + high20) / 2 time40 = _showLTF ? time[40] : request.security(syminfo.tickerid, "D", time[40]) low40 = _showLTF ? ta.lowest(low, 40)[1] : request.security(syminfo.tickerid, "D", ta.lowest(low, 40))[1] high40 = _showLTF ? ta.highest(high, 40)[1] : request.security(syminfo.tickerid, "D", ta.highest(high, 40))[1] eq40 = (low40 + high40) / 2 time60 = _showLTF ? time[60] : request.security(syminfo.tickerid, "D", time[60]) low60 = _showLTF ? ta.lowest(low, 60)[1] : request.security(syminfo.tickerid, "D", ta.lowest(low, 60))[1] high60 = _showLTF ? ta.highest(high, 60)[1] : request.security(syminfo.tickerid, "D", ta.highest(high, 60))[1] eq60 = (low60 + high60) / 2 loc20 = close < eq20 loc40 = close < eq40 loc60 = close < eq60 percent20 = percenter(high20, low20) percent40 = percenter(high40, low40) percent60 = percenter(high60, low60) //#endregion //#region [Plot] var box ipda20P = na var line ipda20E = na var box ipda20D = na var box ipda40P = na var line ipda40E = na var box ipda40D = na var box ipda60P = na var line ipda60E = na var box ipda60D = na if barstate.islast and plotType == "Boxes" and (_showDLTF ? true : timeframe.period == "D") if ipda60 ipda60P := box.new(time60, high60, time[1], eq60, xloc = xloc.bar_time, border_color = color.new(color.black,100), bgcolor = premiumC) ipda60E := line.new(time60, eq60, time[1], eq60, xloc = xloc.bar_time, color = equilibriumC) ipda60D := box.new(time60, eq60, time[1], low60, xloc = xloc.bar_time, border_color = color.new(color.black,100), bgcolor = discountC, text = "IPDA60", text_size = size.small, text_color = _showT ? #000000 : color.new(#000000,100), text_halign = text.align_left, text_valign = text.align_bottom) box.delete(ipda60P[1]) line.delete(ipda60E[1]) box.delete(ipda60D[1]) if ipda40 ipda40P := box.new(time40, high40, time[1], eq40, xloc = xloc.bar_time, border_color = color.new(color.black,100), bgcolor = premiumC) ipda40E := line.new(time40, eq40, time[1], eq40, xloc = xloc.bar_time, color = equilibriumC) ipda40D := box.new(time40, eq40, time[1], low40, xloc = xloc.bar_time, border_color = color.new(color.black,100), bgcolor = discountC, text = "IPDA40", text_size = size.small, text_color = _showT ? #000000 : color.new(#000000,100), text_halign = text.align_left, text_valign = text.align_bottom) box.delete(ipda40P[1]) line.delete(ipda40E[1]) box.delete(ipda40D[1]) if ipda20 ipda20P := box.new(time20, high20, time[1], eq20, xloc = xloc.bar_time, border_color = color.new(color.black,100), bgcolor = premiumC) ipda20E := line.new(time20, eq20, time[1], eq20, xloc = xloc.bar_time, color = equilibriumC) ipda20D := box.new(time20, eq20, time[1], low20, xloc = xloc.bar_time, border_color = color.new(color.black,100), bgcolor = discountC, text = "IPDA20", text_size = size.small, text_color = _showT ? #000000 : color.new(#000000,100), text_halign = text.align_left, text_valign = text.align_bottom) box.delete(ipda20P[1]) line.delete(ipda20E[1]) box.delete(ipda20D[1]) locTable = table.new("top_right", 2, 3, frame_color = #000000, frame_width = 1) if plotType == "Table A" table.cell(locTable, 0, 0, "IPDA60", 0, 0, #000000, "center", text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 0, 1, "IPDA40", 0, 0, #000000, "center", text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 0, 2, "IPDA20", 0, 0, #000000, "center", text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 1, 0, loc60 ? "Discount" : "Premium", text_color = loc60 ? color.maroon : color.navy,text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 1, 1, loc40 ? "Discount" : "Premium", text_color = loc40 ? color.maroon : color.navy,text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 1, 2, loc20 ? "Discount" : "Premium", text_color = loc20 ? color.maroon : color.navy,text_size = size.normal, bgcolor = #d1d4dc) if plotType == "Table B" table.cell(locTable, 0, 0, "IPDA60", 0, 0, #000000, "center", text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 0, 1, "IPDA40", 0, 0, #000000, "center", text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 0, 2, "IPDA20", 0, 0, #000000, "center", text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 1, 0, str.tostring(percent60) + "%", text_color = loc60 ? color.maroon : color.navy,text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 1, 1, str.tostring(percent40) + "%", text_color = loc40 ? color.maroon : color.navy,text_size = size.normal, bgcolor = #d1d4dc) table.cell(locTable, 1, 2, str.tostring(percent20) + "%", text_color = loc20 ? color.maroon : color.navy,text_size = size.normal, bgcolor = #d1d4dc) //#endregion
HARSI + Divergences
https://www.tradingview.com/script/j72znNy7-HARSI-Divergences/
AlphaTurbo
https://www.tradingview.com/u/AlphaTurbo/
107
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/ // © LordKaan // All credit to © geneclash & VuManChu for their original Scripts // This is open-source and open code, not to be private //@version=5 indicator('HARSI + Divergences', 'HARSI + Divergences', false, format.price, 2) //////////////////////////////////////////////////////////////////////////////// // // // ====== ABOUT THIS INDICATOR // // // // - RSI based Heikin Ashi candle oscillator // // - Divergence based on the VuManChu Cipher B // // // // ====== ARTICLES and FURTHER READING // // // // - https://www.investopedia.com/terms/h/heikinashi.asp // // // // "Heikin-Ashi is a candlestick pattern technique that aims to reduce // // some of the market noise, creating a chart that highlights trend // // direction better than typical candlestick charts" // // // // ====== IDEA AND USE // // - The use of the HA RSI indicator when in the OverSold and OverBought // // area combined to a Divergence & a OB/OS buy/sell // // on the Cipher B by VuManChu. // // Can be usefull as a confluence at S/R levels. // // Tip = 1 minute timeframe seems to work the best on FOREX // // // // Contributions : // // --> Total conditions for an alert and a dot to display, resumed : // // - Buy/Sell in OB/OS // // - Divergence Buy/Sell // // - RSI Overlay is in OB/OS on current bar (or was the bar before) // // when both Buy/Sell dots from VMC appears. // // // // ====== DISCLAIMER // // For Tradingview & Pinescript moderators = // // This follow a strategy where RSI Overlay from @JayRogers script shall be // // in OB/OS zone, while combining it with the VuManChu Cipher B Divergences // // Buy&Sell + Buy/sell alerts In OB/OS areas. // // Any trade decisions you make are entirely your own responsibility. // // // // Thanks to dynausmaux for the code // Thanks to falconCoin for https://www.tradingview.com/script/KVfgBvDd-Market-Cipher-B-Free-version-with-Buy-and-sell/ inspired me to start this. // Thanks to LazyBear for WaveTrend Oscillator https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/ // Thanks to RicardoSantos for https://www.tradingview.com/script/3oeDh0Yq-RS-Price-Divergence-Detector-V2/ // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // // ====== TOOLTIPS ====== // // // //////////////////////////////////////////////////////////////////////////////// string TT_HARSI = 'Period for the RSI calculations used to generate the' + 'candles. This seperate from the RSI plot/histogram length.' string TT_PBIAS = 'Smoothing feature for the OPEN of the HARSI candles.' + '\n\nIncreases bias toward the prior open value which can' + ' help provide better visualisation of trend strength.' + '\n\n** By changing the Open values, High and Low can also' + ' be distorted - however Close will remain unchanged.' string TT_SMRSI = 'This option smoothes the RSI in a manner similar to HA' + ' open, but uses the realtime rsi rather than the prior' + ' close value.' string TT_STOCH = 'Uses the RSI generated by the above settings, and as such' + ' will be affected by the smoothing option.' string TT_STFIT = 'Adjusts the vertical scaling of the stochastic, can help' + ' to prevent distortion of other data in the channel.' + '\n\nHas no impact cross conditions.' //////////////////////////////////////////////////////////////////////////////// // // // ====== INPUTS ====== // // // //////////////////////////////////////////////////////////////////////////////// // -- Candle config string GROUP_CAND = 'Config » HARSI Candles' i_lenHARSI = input.int(10, 'Length', group=GROUP_CAND, minval=1, tooltip=TT_HARSI) i_smoothing = input.int(5, 'Open Smoothing', group=GROUP_CAND, minval=1, maxval=100, tooltip=TT_PBIAS) string INLINE_COL = 'Colour Pallette' i_colUp = input.color(color.teal, 'Colour Pallette  ', group=GROUP_CAND, inline=INLINE_COL) i_colDown = input.color(color.red, ' ', group=GROUP_CAND, inline=INLINE_COL) i_colWick = input.color(color.gray, ' ', group=GROUP_CAND, inline=INLINE_COL) // -- RSI plot config string GROUP_PLOT = 'Config » RSI Plot' i_source = input.source(ohlc4, 'Source', group=GROUP_PLOT) i_lenRSI = input.int(7, 'Length', group=GROUP_PLOT, minval=1) i_mode = input.bool(true, 'Smoothed Mode RSI?', group=GROUP_PLOT, tooltip=TT_SMRSI) i_showPlot = input.bool(true, 'Show RSI Plot?', group=GROUP_PLOT) i_showHist = input.bool(true, 'Show RSI Histogram?', group=GROUP_PLOT) // -- Channel OB/OS config string GROUP_CHAN = 'Config » OB/OS Boundaries' i_upper = input.int(50, 'OB', group=GROUP_CHAN, inline='OB', minval=1, maxval=50) i_upperx = input.int(30, 'OB Extreme', group=GROUP_CHAN, inline='OB', minval=1, maxval=50) i_lower = input.int(-50, 'OS', group=GROUP_CHAN, inline='OS', minval=-50, maxval=-1) i_lowerx = input.int(-30, 'OS Extreme', group=GROUP_CHAN, inline='OS', minval=-50, maxval=-1) // Settins // WaveTrend wtShow = input(true, title='Show WaveTrend') wtBuyShow = input(true, title='Show Buy dots') wtGoldShow = input(true, title='Show Gold dots') wtSellShow = input(true, title='Show Sell dots') wtDivShow = input(true, title='Show Div. dots') vwapShow = input(true, title='Show Fast WT') wtChannelLen = input(9, title='WT Channel Length') wtAverageLen = input(12, title='WT Average Length') wtMASource = input(hlc3, title='WT MA Source') wtMALen = input(3, title='WT MA Length') // WaveTrend Overbought & Oversold lines obLevel = input(53, title='WT Overbought Level 1') obLevel2 = input(60, title='WT Overbought Level 2') obLevel3 = input(100, title='WT Overbought Level 3') osLevel = input(-53, title='WT Oversold Level 1') osLevel2 = input(-60, title='WT Oversold Level 2') osLevel3 = input(-75, title='WT Oversold Level 3') // Divergence WT wtShowDiv = input(true, title='Show WT Regular Divergences') wtShowHiddenDiv = input(false, title='Show WT Hidden Divergences') showHiddenDiv_nl = input(true, title='Not apply OB/OS Limits on Hidden Divergences') wtDivOBLevel = input(45, title='WT Bearish Divergence min') wtDivOSLevel = input(-65, title='WT Bullish Divergence min') // Divergence extra range wtDivOBLevel_addshow = input(true, title='Show 2nd WT Regular Divergences') wtDivOBLevel_add = input(15, title='WT 2nd Bearish Divergence') wtDivOSLevel_add = input(-40, title='WT 2nd Bullish Divergence 15 min') // RSI+MFI rsiMFIShow = input(true, title='Show MFI') rsiMFIperiod = input(60, title='MFI Period') rsiMFIMultiplier = input.float(150, title='MFI Area multiplier') rsiMFIPosY = input(2.5, title='MFI Area Y Pos') // RSI rsiShow = input(false, title='Show RSI') rsiSRC = input(close, title='RSI Source') rsiLen = input(14, title='RSI Length') rsiOversold = input.int(30, title='RSI Oversold', minval=29, maxval=100) rsiOverbought = input.int(60, title='RSI Overbought', minval=0, maxval=60) // Divergence RSI rsiShowDiv = input(false, title='Show RSI Regular Divergences') rsiShowHiddenDiv = input(false, title='Show RSI Hidden Divergences') rsiDivOBLevel = input(60, title='RSI Bearish Divergence min') rsiDivOSLevel = input(30, title='RSI Bullish Divergence min') // macd Colors macdWTColorsShow = input(false, title='Show MACD Colors') macdWTColorsTF = input('240', title='MACD Colors MACD TF') //darkMode = input(false, title='Dark mode') // Colors colorRed = #ff0000 colorPurple = #e600e6 colorGreen = #3fff00 colorOrange = #e2a400 colorYellow = #ffe500 colorWhite = #ffffff colorPink = #ff00f0 colorBluelight = #31c0ff colorWT1 = #49536195 colorWT2 = #7b9fd596 colorWT2_ = #131722 colormacdWT1a = #4caf58 colormacdWT1b = #af4c4c colormacdWT1c = #7ee57e colormacdWT1d = #ff3535 colormacdWT2a = #305630 colormacdWT2b = #310101 colormacdWT2c = #132213 colormacdWT2d = #770000 //////////////////////////////////////////////////////////////////////////////// // // // ====== FUNCTIONS ====== // // // //////////////////////////////////////////////////////////////////////////////// // FUNCTIONS // zero median rsi helper function, just subtracts 50. f_zrsi(_source, _length) => ta.rsi(_source, _length) - 50 // zero median stoch helper function, subtracts 50 and includes % scaling f_zstoch(_source, _length, _smooth, _scale) => float _zstoch = ta.stoch(_source, _source, _source, _length) - 50 float _smoothed = ta.sma(_zstoch, _smooth) float _scaled = _smoothed / 100 * _scale _scaled // mode selectable rsi function for standard, or smoothed output f_rsi(_source, _length, _mode) => // get base rsi float _zrsi = f_zrsi(_source, _length) // smoothing in a manner similar to HA open, but rather using the realtime // rsi in place of the prior close value. var float _smoothed = na _smoothed := na(_smoothed[1]) ? _zrsi : (_smoothed[1] + _zrsi) / 2 // return the requested mode _mode ? _smoothed : _zrsi // RSI Heikin-Ashi generation function f_rsiHeikinAshi(_length) => // get close rsi float _closeRSI = f_zrsi(close, _length) // emulate "open" simply by taking the previous close rsi value float _openRSI = nz(_closeRSI[1], _closeRSI) // the high and low are tricky, because unlike "high" and "low" by // themselves, the RSI results can overlap each other. So first we just go // ahead and get the raw results for high and low, and then.. float _highRSI_raw = f_zrsi(high, _length) float _lowRSI_raw = f_zrsi(low, _length) // ..make sure we use the highest for high, and lowest for low float _highRSI = math.max(_highRSI_raw, _lowRSI_raw) float _lowRSI = math.min(_highRSI_raw, _lowRSI_raw) // ha calculation for close float _close = (_openRSI + _highRSI + _lowRSI + _closeRSI) / 4 // ha calculation for open, standard, and smoothed/lagged var float _open = na _open := na(_open[i_smoothing]) ? (_openRSI + _closeRSI) / 2 : (_open[1] * i_smoothing + _close[1]) / (i_smoothing + 1) // ha high and low min-max selections float _high = math.max(_highRSI, math.max(_open, _close)) float _low = math.min(_lowRSI, math.min(_open, _close)) // return the OHLC values [_open, _high, _low, _close] // Divergences f_top_fractal(src) => src[4] < src[2] and src[3] < src[2] and src[2] > src[1] and src[2] > src[0] f_bot_fractal(src) => src[4] > src[2] and src[3] > src[2] and src[2] < src[1] and src[2] < src[0] f_fractalize(src) => f_top_fractal(src) ? 1 : f_bot_fractal(src) ? -1 : 0 f_findDivs(src, topLimit, botLimit, useLimits) => fractalTop = f_fractalize(src) > 0 and (useLimits ? src[2] >= topLimit : true) ? src[2] : na fractalBot = f_fractalize(src) < 0 and (useLimits ? src[2] <= botLimit : true) ? src[2] : na highPrev = ta.valuewhen(fractalTop, src[2], 0)[2] highPrice = ta.valuewhen(fractalTop, high[2], 0)[2] lowPrev = ta.valuewhen(fractalBot, src[2], 0)[2] lowPrice = ta.valuewhen(fractalBot, low[2], 0)[2] bearSignal = fractalTop and high[2] > highPrice and src[2] < highPrev bullSignal = fractalBot and low[2] < lowPrice and src[2] > lowPrev bearDivHidden = fractalTop and high[2] < highPrice and src[2] > highPrev bullDivHidden = fractalBot and low[2] > lowPrice and src[2] < lowPrev [fractalTop, fractalBot, lowPrev, bearSignal, bullSignal, bearDivHidden, bullDivHidden] // RSI+MFI f_rsimfi(_period, _multiplier, _tf) => request.security(syminfo.tickerid, _tf, ta.sma((close - open) / (high - low) * _multiplier, _period) - rsiMFIPosY) // WaveTrend f_wavetrend(src, chlen, avg, malen, tf) => tfsrc = request.security(syminfo.tickerid, tf, src) esa = ta.ema(tfsrc, chlen) de = ta.ema(math.abs(tfsrc - esa), chlen) ci = (tfsrc - esa) / (0.015 * de) wt1 = request.security(syminfo.tickerid, tf, ta.ema(ci, avg)) wt2 = request.security(syminfo.tickerid, tf, ta.sma(wt1, malen)) wtVwap = wt1 - wt2 wtOversold = wt2 <= osLevel wtOverbought = wt2 >= obLevel wtCross = ta.cross(wt1, wt2) wtCrossUp = wt2 - wt1 <= 0 wtCrossDown = wt2 - wt1 >= 0 wtCrosslast = ta.cross(wt1[2], wt2[2]) wtCrossUplast = wt2[2] - wt1[2] <= 0 wtCrossDownlast = wt2[2] - wt1[2] >= 0 [wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCrosslast, wtCrossUplast, wtCrossDownlast, wtVwap] // MACD f_macd(src, fastlen, slowlen, sigsmooth, tf) => fast_ma = request.security(syminfo.tickerid, tf, ta.ema(src, fastlen)) slow_ma = request.security(syminfo.tickerid, tf, ta.ema(src, slowlen)) macd = fast_ma - slow_ma signal = request.security(syminfo.tickerid, tf, ta.sma(macd, sigsmooth)) hist = macd - signal [macd, signal, hist] // MACD Colors on WT f_macdWTColors(tf) => hrsimfi = f_rsimfi(rsiMFIperiod, rsiMFIMultiplier, tf) [macd, signal, hist] = f_macd(close, 28, 42, 9, macdWTColorsTF) macdup = macd >= signal macddown = macd <= signal macdWT1Color = macdup ? hrsimfi > 0 ? colormacdWT1c : colormacdWT1a : macddown ? hrsimfi < 0 ? colormacdWT1d : colormacdWT1b : na macdWT2Color = macdup ? hrsimfi < 0 ? colormacdWT2c : colormacdWT2a : macddown ? hrsimfi < 0 ? colormacdWT2d : colormacdWT2b : na [macdWT1Color, macdWT2Color] // Get higher timeframe candle f_getTFCandle(_tf) => _open = request.security(ticker.heikinashi(syminfo.tickerid), _tf, open, barmerge.gaps_off, barmerge.lookahead_on) _close = request.security(ticker.heikinashi(syminfo.tickerid), _tf, close, barmerge.gaps_off, barmerge.lookahead_on) _high = request.security(ticker.heikinashi(syminfo.tickerid), _tf, high, barmerge.gaps_off, barmerge.lookahead_on) _low = request.security(ticker.heikinashi(syminfo.tickerid), _tf, low, barmerge.gaps_off, barmerge.lookahead_on) hl2 = (_high + _low) / 2.0 newBar = ta.change(_open) candleBodyDir = _close > _open [candleBodyDir, newBar] //////////////////////////////////////////////////////////////////////////////// // // // ====== SERIES, LINES and LABELS ====== // // // //////////////////////////////////////////////////////////////////////////////// // CALCULATE INDICATORS { // RSI rsi = ta.rsi(rsiSRC, rsiLen) rsiColor = rsi <= rsiOversold ? colorGreen : rsi >= rsiOverbought ? colorRed : colorPurple // Calculates WaveTrend [wt1, wt2, wtOversold, wtOverbought, wtCross, wtCrossUp, wtCrossDown, wtCross_last, wtCrossUp_last, wtCrossDown_last, wtVwap] = f_wavetrend(wtMASource, wtChannelLen, wtAverageLen, wtMALen, timeframe.period) // macd colors [macdWT1Color, macdWT2Color] = f_macdWTColors(macdWTColorsTF) // WT Divergences [wtFractalTop, wtFractalBot, wtLow_prev, wtBearDiv, wtBullDiv, wtBearDivHidden, wtBullDivHidden] = f_findDivs(wt2, wtDivOBLevel, wtDivOSLevel, true) [wtFractalTop_add, wtFractalBot_add, wtLow_prev_add, wtBearDiv_add, wtBullDiv_add, wtBearDivHidden_add, wtBullDivHidden_add] = f_findDivs(wt2, wtDivOBLevel_add, wtDivOSLevel_add, true) [wtFractalTop_nl, wtFractalBot_nl, wtLow_prev_nl, wtBearDiv_nl, wtBullDiv_nl, wtBearDivHidden_nl, wtBullDivHidden_nl] = f_findDivs(wt2, 0, 0, false) wtBearDivHidden_ = showHiddenDiv_nl ? wtBearDivHidden_nl : wtBearDivHidden wtBullDivHidden_ = showHiddenDiv_nl ? wtBullDivHidden_nl : wtBullDivHidden wtBearDivColor = wtShowDiv and wtBearDiv or wtShowHiddenDiv and wtBearDivHidden_ ? colorRed : na wtBullDivColor = wtShowDiv and wtBullDiv or wtShowHiddenDiv and wtBullDivHidden_ ? colorGreen : na wtBearDivColor_add = wtShowDiv and wtDivOBLevel_addshow and wtBearDiv_add or wtShowHiddenDiv and wtDivOBLevel_addshow and wtBearDivHidden_add ? #9a0202 : na wtBullDivColor_add = wtShowDiv and wtDivOBLevel_addshow and wtBullDiv_add or wtShowHiddenDiv and wtDivOBLevel_addshow and wtBullDivHidden_add ? #1b5e20 : na // RSI Divergences [rsiFractalTop, rsiFractalBot, rsiLow_prev, rsiBearDiv, rsiBullDiv, rsiBearDivHidden, rsiBullDivHidden] = f_findDivs(rsi, rsiDivOBLevel, rsiDivOSLevel, true) [rsiFractalTop_nl, rsiFractalBot_nl, rsiLow_prev_nl, rsiBearDiv_nl, rsiBullDiv_nl, rsiBearDivHidden_nl, rsiBullDivHidden_nl] = f_findDivs(rsi, 0, 0, false) rsiBearDivHidden_ = showHiddenDiv_nl ? rsiBearDivHidden_nl : rsiBearDivHidden rsiBullDivHidden_ = showHiddenDiv_nl ? rsiBullDivHidden_nl : rsiBullDivHidden rsiBearDivColor = rsiShowDiv and rsiBearDiv or rsiShowHiddenDiv and rsiBearDivHidden_ ? colorRed : na rsiBullDivColor = rsiShowDiv and rsiBullDiv or rsiShowHiddenDiv and rsiBullDivHidden_ ? colorGreen : na // Buy signal. buySignal = wtCross and wtCrossUp and wtOversold buySignalDiv = wtShowDiv and wtBullDiv or wtShowDiv and wtBullDiv_add or rsiShowDiv and rsiBullDiv buySignalDiv_color = wtBullDiv ? colorGreen : wtBullDiv_add ? color.new(colorGreen, 60) : rsiShowDiv ? colorGreen : na // Sell signal sellSignal = wtCross and wtCrossDown and wtOverbought sellSignalDiv = wtShowDiv and wtBearDiv or wtShowDiv and wtBearDiv_add or rsiShowDiv and rsiBearDiv sellSignalDiv_color = wtBearDiv ? colorRed : wtBearDiv_add ? color.new(colorRed, 60) : rsiBearDiv ? colorRed : na // standard, or ha smoothed rsi for the line plot and/or histogram float RSI = f_rsi(i_source, i_lenRSI, i_mode) // get OHLC values to use in the plotcandle() [O, H, L, C] = f_rsiHeikinAshi(i_lenHARSI) // shadow, invisible color colShadow = color.rgb(0, 0, 0, 100) color colNone = color.rgb(0, 0, 0, 100) // rsi color //color colRSI = RSI >=30 ? color.red : color.gray color colRSI = RSI < -31 ? color.lime : RSI > 31 ? color.red : color.gray cross_up = RSI[1] > 30 cross_down = RSI[1] < -30 // candle body colouring color bodyColour = C > O ? i_colUp : i_colDown color wickColour = i_colWick //////////////////////////////////////////////////////////////////////////////// // // // ====== DRAWING and PLOTTING ====== // // // //////////////////////////////////////////////////////////////////////////////// // WT Areas plot(wtShow ? wt1 : na, style=plot.style_area, title='WT Wave 1', color=macdWTColorsShow ? macdWT1Color : colorWT1, transp=20) // WT Div plot(series=wtFractalTop ? wt2[2] : na, title='WT Bearish Divergence', color=wtBearDivColor, linewidth=2, offset=-2) plot(series=wtFractalBot ? wt2[2] : na, title='WT Bullish Divergence', color=wtBullDivColor, linewidth=2, offset=-2) // WT 2nd Div plot(series=wtFractalTop_add ? wt2[2] : na, title='WT 2nd Bearish Divergence', color=wtBearDivColor_add, linewidth=2, offset=-2) plot(series=wtFractalBot_add ? wt2[2] : na, title='WT 2nd Bullish Divergence', color=wtBullDivColor_add, linewidth=2, offset=-2) plotchar(cross_down[1] and wtBuyShow and buySignal ? -107 : na, title='Buy circle', char='·', color=color.new(colorGreen, 10), location=location.absolute, size=size.small) plotchar(cross_up[1] and wtSellShow and sellSignal ? 105 : na, title='Sell circle', char='·', color=color.new(colorRed, 10), location=location.absolute, size=size.small) plotchar(cross_down[1] and wtDivShow and buySignalDiv and wtBuyShow and buySignal[2] ? -106 : na, title='Divergence buy circle', char='•', color=buySignalDiv_color, location=location.absolute, size=size.small, offset=-2, transp=10) plotchar(cross_up[1] and wtDivShow and sellSignalDiv and wtSellShow and sellSignal[2] ? 106 : na, title='Divergence sell circle', char='•', color=sellSignalDiv_color, location=location.absolute, size=size.small, offset=-2, transp=10) // zero median RSI channel hlines upperx = hline(i_upperx, 'OB Extreme', color.new(color.red, 10)) //upper = hline(i_upper, 'OB', color.new(color.silver, 80)) //median = hline( 0, "Median", color.orange, hline.style_dotted ) //lower = hline(i_lower, 'OS', color.new(color.silver, 80)) lowerx = hline(i_lowerx, 'OS Extreme', color.new(color.green, 10)) // make our HA rsi candles plotcandle(O, H, L, C, 'HARSI', bodyColour, wickColour, bordercolor=bodyColour) // RSI overlay plot // plot(i_showPlot ? RSI : na, 'RSI Shadow', colShadow, 3) // plot_rsi = plot(i_showPlot ? RSI : na, 'RSI Overlay', colRSI, 1) //Alerts alertcondition((cross_down[1] and wtBuyShow and buySignal[2] and wtDivShow and buySignalDiv) or (cross_up[1] and wtSellShow and sellSignal[2] and wtDivShow and sellSignalDiv), title='Buy/Sell Signal', message='Buy/Sell Signal')
Daily Chart Pattern
https://www.tradingview.com/script/ItrjBZ6P-Daily-Chart-Pattern/
HastaAdhidaya
https://www.tradingview.com/u/HastaAdhidaya/
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/ // Created by @jayallways for Tom //@version=5 indicator("Daily Chart Pattern") bullColor = input.color(color.white, "Bull Candle") bearColor = input.color(color.black, "Bear Candle") timeRange1 = input.string("1000-1100", "Visible #1 Time Range") firstCandleRange1 = input.string("1000-1005", "First Bar #1 Time Range") isShowLabel = input.bool(true, "Show Time Label") oddBgColor = input.color(color.new(color.silver, 75), "Background Color 1") evenBgColor = input.color(color.new(color.white, 75), "Background Color 2") labelColor = input.color(color.new(color.white, 100), "Label Color") M5TimeIndex = 5 * 60 * 1000 // 5 minutes tr1 = time(timeframe.period, timeRange1) fcr1 = time(timeframe.period, firstCandleRange1) var float lowestX = 0 var bool isNewDay = false if (na(tr1)) lowestX := 0 if (not na(fcr1)) lowestX := low isNewDay := true else isNewDay := false var float[] vOpenList = array.new_float(0) var float[] vHighList = array.new_float(0) var float[] vLowList = array.new_float(0) var float[] vCloseList = array.new_float(0) var string[] vTimeList = array.new_string(0) var bool[] vNewDayList = array.new_bool(0) if (not na(tr1)) array.push(vOpenList, open - lowestX) array.push(vHighList, high - lowestX) array.push(vLowList, low - lowestX) array.push(vCloseList, close - lowestX) array.push(vTimeList, str.format("{0,date, y-MM-d}", time)) array.push(vNewDayList, isNewDay) lastXCandleIndex = array.size(vOpenList) isStartDraw = time > timenow - (lastXCandleIndex * M5TimeIndex) var arrIdx = -1 if (isStartDraw) arrIdx := arrIdx + 1 getPrice(arrayy, flagg, indexx) => flagg ? array.get(arrayy, indexx) : 0 vOpen = isStartDraw ? array.get(vOpenList, arrIdx) : 0 vHigh = isStartDraw ? array.get(vHighList, arrIdx) : 0 vLow = isStartDraw ? array.get(vLowList, arrIdx) : 0 vClose = isStartDraw ? array.get(vCloseList, arrIdx) : 0 vTime = isStartDraw ? array.get(vTimeList, arrIdx) : "" vNewDay = isStartDraw ? array.get(vNewDayList, arrIdx) : false plotcandle(vOpen, vHigh, vLow, vClose, color = vOpen > vClose ? bearColor : bullColor) var oddBg = false if (vNewDay) if (isShowLabel) label.new(bar_index, vHigh, text = vTime, color = labelColor) oddBg := not oddBg bgcolor(isStartDraw ? oddBg ? oddBgColor : evenBgColor : na)
Daily Profile (Nephew_Sam_)
https://www.tradingview.com/script/ZnyqUIJp-Daily-Profile-Nephew-Sam/
nephew_sam_
https://www.tradingview.com/u/nephew_sam_/
2,367
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/ // © Nephew_Sam_ //@version=5 indicator('Daily Profile (Nephew_Sam_)', overlay=true, max_bars_back=500, max_lines_count=500, max_boxes_count=500, max_labels_count=500) // --------------- INPUTS --------------- var GRP0 = "=============== INITIALIZE ===============" hoursOffsetInput = input.string('-4', "Timezone offset (GMT)", group=GRP0, tooltip="Enter your time zone's offset (+ or -). Eg. +5 / -3 / +9:30") newDayHr = input.int(17, title='Day starts at what hour?', minval=0, maxval=23, group=GRP0) autoDay = input.bool(false, title='Ignore above hour and use exchange day start hour', group=GRP0, tooltip="This comes in handy when looking at different asset classes. Ie, for Forex the daily close is at 1700 (GMT-4), but for cryptos, some exhanges are at 0800 and some are at 0000") var GRP1 = "=============== ASIA RANGE SETTINGS ===============" asianUseRange = input.bool(true, title='Asia Range', inline='1', group=GRP1) asianShowBg = input(title='Show Background ?', defval=true, inline='1', group=GRP1) asianShowMid = input(title='Show Middle Line ?', defval=true, inline='2', group=GRP1) asianExtendLines = input(title='Extend Lines ?', defval=false, inline='2', group=GRP1) asianRangeTime = input.session(title='Session Time', defval='1700-0259', group=GRP1) asianExtendTime = input.session(title='Extended Lines Time', defval='1700-1600', group=GRP1) asianMaxRanges = input.int(2, title='Max Asian Ranges to show', minval=1, maxval=200, group=GRP1) var GRP2 = "ASIA RANGE STYLES" asianBorderWidth = input.int(1, 'Box Width', minval=1, maxval=4, inline="1", group=GRP2) asianBoxBg = input(color.new(color.aqua, 90), 'BG Color', inline="1", group=GRP2) asianBoxBorderColor = input(color.new(color.blue, 50), 'Border Color', inline="1", group=GRP2) asianExtendStyle = input.string(title="Extend Style", defval="Dotted", options=["Solid", "Dashed", "Dotted"],inline="2", group=GRP2) asianExtendLineWidth = input.int(1, 'Width', minval=1, maxval=4, inline="2", group=GRP2) asianExtendLineColor = input(color.blue, 'Color', inline="2", group=GRP2) asianMiddleLineWidth = input.int(1, 'Width', minval=1, maxval=4, inline="3", group=GRP2) asianMiddleLineColor = input(color.red, 'Middle Line Color', inline="3", group=GRP2) var GRP3 = "=============== OPEN LINES SETTINGS ===============" showDailyOpen = input.bool(true, title='Daily Open', inline='1', group=GRP3) dailyColor = input.color(color.red, title='', inline="1", group=GRP3) dailyExtendHours = input.int(12, title='Line Extend hours', minval=1, maxval=48, inline="1", group=GRP3) showMidnightOpen = input.bool(true, title='Midnight Open', inline="2", group=GRP3) midnightColor = input.color(color.green, title='', inline="2", group=GRP3) midnightExtendHours = input.int(12, title='Line Extend hours', minval=1, maxval=48, inline="2", group=GRP3) showWeeklyOpen = input.bool(true, title='Weekly Open', inline="3", group=GRP3) weeklyColor = input.color(color.green, title='', inline="3", group=GRP3) showMonthlyOpen = input.bool(true, title='Monthly Open', inline="4", group=GRP3) monthlyColor = input.color(color.green, title='', inline="4", group=GRP3) var GRP4 = "OPEN LINES STYLES" openWidth = input.int(1, title='Width', minval=1, maxval=4, inline='1', group=GRP4) openMaxLines = input.int(3, title='Max Lines to show', minval=1, maxval=200, inline='1', group=GRP4) openLabelSize = input.string("Small", title='Label Size', options=['Auto', 'Tiny', 'Small', 'Normal'], inline='2', group=GRP4) openLineStyle = input.string(title="Extend Style", defval="Dashed", options=["Solid", "Dashed", "Dotted"], inline="2", group=GRP4) var GRP5 = "=============== SESSIONS SETTINGS ===============" session1Time = input.session(title='', defval='0200-0400', inline='1', group=GRP5) session1Color = input.color(color.new(color.blue, 0), title='', inline='1', group=GRP5) session1Show = input.bool(true, title='', inline='1', group=GRP5) session2Time = input.session(title='', defval='0700-0900', inline='2', group=GRP5) session2Color = input.color(color.new(color.red, 0), title='', inline='2', group=GRP5) session2Show = input.bool(true, title='', inline='2', group=GRP5) session3Time = input.session(title='', defval='1000-1100', inline='3', group=GRP5) session3Color = input.color(color.new(color.lime, 0), title='', inline='3', group=GRP5) session3Show = input.bool(true, title='', inline='3', group=GRP5) session4Time = input.session(title='', defval='1900-2000', inline='4', group=GRP5) session4Color = input.color(color.new(color.gray, 0), title='', inline='4', group=GRP5) session4Show = input.bool(false, title='', inline='4', group=GRP5) sessionsLinePosition = input.string(title='Dots Position', defval='Top', options=['Top', 'Bottom'], inline='5', group=GRP5) showDailyDividers = input.bool(true, title='Show Dividers', inline='6', group=GRP5) dividerLineTextColor = input(color.gray, 'Divider and Text Color', inline='6', group=GRP5) dayLabelOffset = input.int(4, title='Label Offset', minval=1, maxval=48, inline="7", group=GRP5) var GRP6 = "=============== PREVIOUS OHLC SETTINGS ===============" line1 = input.bool(false, title="---------- DAILY ----------", group=GRP6) showDaily = input.string(title='View', defval='HL', options=['Off', 'HL', 'OC', 'OHLC'], group=GRP6) dailyHText = input.string(defval='PDH', title='H', inline="1", group=GRP6) dailyLText = input.string(defval='PDL', title='L', inline="1", group=GRP6) dailyOText = input.string(defval='PDO', title='O', inline="1", group=GRP6) dailyCText = input.string(defval='PDC', title='C', inline="1", group=GRP6) line2 = input.bool(false, title="---------- WEEKLY ----------", group=GRP6) showWeekly = input.string(title='View', defval='Off', options=['Off', 'HL', 'OC', 'OHLC'], group=GRP6) weeklyHText = input.string(defval='PWH', title='H', inline="2", group=GRP6) weeklyLText = input.string(defval='PWL', title='L', inline="2", group=GRP6) weeklyCText = input.string(defval='PWC', title='C', inline="2", group=GRP6) weeklyOText = input.string(defval='PWO', title='O', inline="2", group=GRP6) line3 = input.bool(false, title="---------- MONTHLY ----------", group=GRP6) showMonthly = input.string(title='View', defval='Off', options=['Off', 'HL', 'OC', 'OHLC'], group=GRP6) monthlyHText = input.string(defval='PMH', title='H', inline="3", group=GRP6) monthlyLText = input.string(defval='PML', title='L', inline="3", group=GRP6) monthlyCText = input.string(defval='PMC', title='C', inline="3", group=GRP6) monthlyOText = input.string(defval='PMO', title='O', inline="3", group=GRP6) var GRP7 = "---------- PREVIOUS OHLC STYLES ----------" o_color = input.color(color.new(color.gray, 50), "Open Color", inline="1", group = GRP7) c_color = input.color(color.new(color.gray, 50), "Close Color", inline="1", group = GRP7) h_color = input.color(color.new(color.red, 50), "High Color", inline="2", group = GRP7) l_color = input.color(color.new(color.lime, 50), "Low Color", inline="2", group = GRP7) ohlcLabelPosition = input.string(title='Label Position', defval='End', options=['Start', 'End'], inline="2", group=GRP2) ohlcLineStyle = input.string(title="Extend Style", defval="Solid", options=["Solid", "Dashed", "Dotted"], inline="2", group=GRP7) ohlcOffset = input.int(1, title='Offset', minval=0, maxval=2, inline='3', group=GRP7) ohlcMaxLines = input.int(3, title='Max Lines to show', minval=1, maxval=200, inline='3', group=GRP7) ohlcExtendToCurrent = input.bool(true, title='Extend lines only to current candle', group=GRP7) // --------------- INPUTS --------------- // --------------- CONSTANTS --------------- TIMEZONE = "GMT"+hoursOffsetInput ISNEWDAY = dayofweek != dayofweek[1] TRANSPARENT = color.new(color.white, 100) exchangeOffset = hour(timenow, TIMEZONE) - hour(timenow, syminfo.timezone) HOUR = hour + exchangeOffset <= 23 ? hour + exchangeOffset : (hour + exchangeOffset) - 24 // label.new(bar_index, high, str.tostring(HOUR)) // --------------- CONSTANTS --------------- // --------------- FUNCTIONS --------------- reso(exp, res) => request.security(syminfo.tickerid, res, exp, lookahead=barmerge.lookahead_on) getLineStyle(_style) => _linestyle = _style == "Solid" ? line.style_solid : _style == "Dashed" ? line.style_dashed : line.style_dotted _linestyle getlabelSize(_labelSize) => _size = _labelSize == "auto" ? size.auto : _labelSize == "Tiny" ? size.tiny : _labelSize == "Small" ? size.small : _labelSize == "Normal" ? size.normal : size.huge _size addToArray(_array, _val) => array.push(_array, _val) resolutionInMinutes() => resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na) int(resInMinutes) tfInMinutes(simple string tf = "") => float chartTf = timeframe.multiplier * ( timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na) float result = tf == "" ? chartTf : request.security(syminfo.tickerid, tf, chartTf) inTimeframe(_t) => tfInMinutes(_t) > tfInMinutes(timeframe.period) getOhlcData(_t, _var, _offset) => o = reso(open[_offset], _t) h = reso(high[_offset], _t) l = reso(low[_offset], _t) c = reso(close[_offset], _t) show = _var != "Off" and inTimeframe(_t) _time = time(_t) newbar = na(_time[1]) or _time > _time[1] hl = _var == 'HL' or _var == 'OHLC' oc = _var == 'OC' or _var == 'OHLC' [o, h, l, c, show, newbar, hl, oc] vline(_bar_index, _col, _style=line.style_dashed, _width=2) => LineLengthMult = 10 LineLength = ta.atr(100) * 100 line.new(_bar_index, low-LineLength, _bar_index, high+LineLength, extend=extend.both, color=_col, style=_style, width=_width) getOhlcLabelPos(_tf) => ohlcLabelPosition == "End" and not ohlcExtendToCurrent ? time_close(_tf) : time getLastElementInArray(_arr) => _size = array.size(_arr) _el = _size > 0 ? array.get(_arr, _size-1) : na _el // --------------- FUNCTIONS --------------- // --------------- ASIAN RANGE --------------- if asianUseRange inAsianSession = not na(time(timeframe.period, asianRangeTime, TIMEZONE)) inAsianExtendSession = not na(time(timeframe.period, asianExtendTime, TIMEZONE)) startTime = 0 startTime := inAsianSession and not inAsianSession[1] ? time : startTime[1] extendStartTime = 0 extendStartTime := inAsianExtendSession and not inAsianExtendSession[1] ? time : extendStartTime[1] var box[] asianBoxes = array.new_box(0) var line[] topLines = array.new_line(0) var line[] bottomLines = array.new_line(0) var line[] middleLines = array.new_line(0) var highVal = 0.0 var lowVal = 0.0 if inAsianSession and not inAsianSession[1] highVal := high lowVal := low if inAsianSession and timeframe.isintraday if inAsianSession[1] if array.size(asianBoxes) > 0 box.delete(array.pop(asianBoxes)) if array.size(topLines) > 0 line.delete(array.pop(topLines)) if array.size(bottomLines) > 0 line.delete(array.pop(bottomLines)) if array.size(middleLines) > 0 line.delete(array.pop(middleLines)) if low < lowVal lowVal := low if high > highVal highVal := high addToArray(asianBoxes, box.new(left=startTime, top=highVal, right=time, bottom=lowVal, xloc=xloc.bar_time, bgcolor=asianShowBg ? asianBoxBg : TRANSPARENT, border_width=asianBorderWidth, border_color=asianBoxBorderColor)) if asianExtendLines addToArray(topLines, line.new(startTime, highVal, time, highVal, xloc=xloc.bar_time, color=asianExtendLineColor, style=getLineStyle(asianExtendStyle), width=asianExtendLineWidth)) addToArray(bottomLines, line.new(startTime, lowVal, time, lowVal, xloc=xloc.bar_time, color=asianExtendLineColor, style=getLineStyle(asianExtendStyle), width=asianExtendLineWidth)) if asianShowMid midVal = (highVal + lowVal) / 2 addToArray(middleLines, line.new(startTime, midVal, time, midVal, xloc=xloc.bar_time, color=asianMiddleLineColor, style=line.style_dotted, width=asianMiddleLineWidth)) if asianExtendLines and inAsianExtendSession and not inAsianSession line.delete(array.pop(topLines)) line.delete(array.pop(bottomLines)) line.delete(array.pop(middleLines)) addToArray(topLines, line.new(startTime, highVal, time, highVal, xloc=xloc.bar_time, color=asianExtendLineColor, style=getLineStyle(asianExtendStyle), width=asianExtendLineWidth)) addToArray(bottomLines, line.new(startTime, lowVal, time, lowVal, xloc=xloc.bar_time, color=asianExtendLineColor, style=getLineStyle(asianExtendStyle), width=asianExtendLineWidth)) if asianShowMid midVal = (highVal + lowVal) / 2 addToArray(middleLines, line.new(startTime, midVal, time, midVal, xloc=xloc.bar_time, color=asianMiddleLineColor, style=line.style_dotted, width=asianMiddleLineWidth)) // Delete lines if more than max if array.size(asianBoxes) > asianMaxRanges box.delete(array.shift(asianBoxes)) if array.size(topLines) > asianMaxRanges line.delete(array.shift(topLines)) if array.size(bottomLines) > asianMaxRanges line.delete(array.shift(bottomLines)) if array.size(middleLines) > asianMaxRanges line.delete(array.shift(middleLines)) // --------------- ASIAN RANGE --------------- // --------------- TIME LINES --------------- var line[] dailyLines = array.new_line(0) var line[] midnightLines = array.new_line(0) var line[] weeklyLines = array.new_line(0) var line[] monthlyLines = array.new_line(0) var label[] dailyLabels = array.new_label(0) var label[] midnightLabels = array.new_label(0) var label[] weeklyLabels = array.new_label(0) var label[] monthlyLabels = array.new_label(0) inDaily = HOUR == 17 and minute == 0 inMidnight = HOUR == 0 and minute == 0 inWeek = weekofyear != weekofyear[1] inMonth = month != month[1] [ohlc_w_o, ohlc_w_h, ohlc_w_l, ohlc_w_c, ohlc_w_show, ohlc_w_newbar, ohlc_w_hl, ohlc_w_oc] = getOhlcData("W", showWeeklyOpen ? "OC" : "Off", 0) [ohlc_m_o, ohlc_m_h, ohlc_m_l, ohlc_m_c, ohlc_m_show, ohlc_m_newbar, ohlc_m_hl, ohlc_m_oc] = getOhlcData("M", showMonthlyOpen ? "OC" : "Off", 0) LABEL_SPACE = " " if inDaily and not inDaily[1] and showDailyOpen _extend = dailyExtendHours * 3600000 array.push(dailyLines, line.new(time, open, time + _extend, open, xloc=xloc.bar_time, color=dailyColor, style=getLineStyle(openLineStyle), width=openWidth)) array.push(dailyLabels, label.new(time + _extend, open, "Daily Open" + LABEL_SPACE, xloc=xloc.bar_time, style=label.style_none, size=getlabelSize(openLabelSize), textcolor=dailyColor)) if inMidnight and not inMidnight[1] and showMidnightOpen _extend = midnightExtendHours * 3600000 array.push(midnightLines, line.new(time, open, time + _extend, open, xloc=xloc.bar_time, color=midnightColor, style=getLineStyle(openLineStyle), width=openWidth)) array.push(midnightLabels, label.new(time + _extend, open, "Midnight Open" + LABEL_SPACE, xloc=xloc.bar_time, style=label.style_none, size=getlabelSize(openLabelSize), textcolor=midnightColor)) if ohlc_w_show and ohlc_w_newbar array.push(weeklyLines, line.new(time, ohlc_w_o, time, ohlc_w_o, xloc=xloc.bar_time, color=weeklyColor, style=getLineStyle(openLineStyle), width=openWidth)) array.push(weeklyLabels, label.new(time, ohlc_w_o, "Weekly Open" + LABEL_SPACE, xloc=xloc.bar_time, style=label.style_none, size=getlabelSize(openLabelSize), textcolor=weeklyColor)) if ohlc_m_show and ohlc_m_newbar array.push(monthlyLines, line.new(time, open, time, open, xloc=xloc.bar_time, color=monthlyColor, style=getLineStyle(openLineStyle), width=openWidth)) array.push(monthlyLabels, label.new(time, open, "Monthly Open" + LABEL_SPACE, xloc=xloc.bar_time, style=label.style_none, size=getlabelSize(openLabelSize), textcolor=monthlyColor)) // EXTEND if ohlc_w_show and not ohlc_w_newbar _line = getLastElementInArray(weeklyLines) _label = getLastElementInArray(weeklyLabels) if not na(_line) line.set_x2(_line, time) if not na(_label) label.set_x(_label, time) if ohlc_m_show and not ohlc_m_newbar _line = getLastElementInArray(monthlyLines) _label = getLastElementInArray(monthlyLabels) if not na(_line) line.set_x2(_line, time) if not na(_label) label.set_x(_label, time) // DELETE OLD if array.size(dailyLines) > openMaxLines line.delete(array.shift(dailyLines)) if array.size(dailyLabels) > openMaxLines label.delete(array.shift(dailyLabels)) if array.size(midnightLines) > openMaxLines line.delete(array.shift(midnightLines)) if array.size(midnightLabels) > openMaxLines label.delete(array.shift(midnightLabels)) if array.size(weeklyLines) > openMaxLines line.delete(array.shift(weeklyLines)) if array.size(weeklyLabels) > openMaxLines label.delete(array.shift(weeklyLabels)) if array.size(monthlyLines) > openMaxLines line.delete(array.shift(monthlyLines)) if array.size(monthlyLabels) > openMaxLines label.delete(array.shift(monthlyLabels)) // --------------- TIME LINES --------------- // --------------- SESSIONS --------------- sess1 = session1Show ? time(timeframe.period, session1Time, TIMEZONE) : na sess2 = session2Show ? time(timeframe.period, session2Time, TIMEZONE) : na sess3 = session3Show ? time(timeframe.period, session3Time, TIMEZONE) : na sess4 = session4Show ? time(timeframe.period, session4Time, TIMEZONE) : na _linPos = sessionsLinePosition == 'Top' ? location.top : location.bottom plotshape(not na(sess1) and timeframe.isintraday, title='Session 1', style=shape.square, location=_linPos, color=session1Color, size=size.auto) plotshape(not na(sess2) and timeframe.isintraday, title='Session 2', style=shape.square, location=_linPos, color=session2Color, size=size.auto) plotshape(not na(sess3) and timeframe.isintraday, title='Session 3', style=shape.square, location=_linPos, color=session3Color, size=size.auto) plotshape(not na(sess4) and timeframe.isintraday, title='Session 4', style=shape.square, location=_linPos, color=session4Color, size=size.auto) // Divider tickerExchangeOffset = 5 int dayLabelStartTime = 1 _rin = resolutionInMinutes() if syminfo.timezone == 'Etc/UTC' dayLabelStartTime += tickerExchangeOffset dayLabelStartTime isStartTime = autoDay ? ISNEWDAY : HOUR == newDayHr and HOUR[1] != newDayHr //and minute == 0 _inTimeframe = _rin <= 180 and timeframe.isintraday // if barstate.islastHOUR // label.new(bar_index, high, str.tostring(hour) + "\n" + str.tostring(exchangeOffset)) txtMonH = "Monday" txtTueH = "Tuesday" txtWedH = "Wednesday" txtThuH = "Thursday" txtFriH = "Friday" txtSatH = "Saturday" txtSunH = "Sunday" txtMonV = "M\no\nn\nd\na\ny" txtTueV = "T\nu\ne\ns\nd\na\ny" txtWedV = "W\ne\nd\nn\ne\ns\nd\na\ny" txtThuV = "T\nh\nu\nr\ns\nd\na\ny" txtFriV = "F\nr\ni\nd\na\ny" txtSatV = "S\na\nt\nu\nr\nd\na\ny" txtSunV = "S\nu\nn\nd\na\ny" isMon() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.monday : false isTue() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.tuesday : false isWed() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.wednesday : false isThu() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.thursday : false isFri() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.friday : false isSat() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.saturday : false isSun() => _inTimeframe and showDailyDividers ? HOUR == dayLabelStartTime and minute == 0 and dayofweek == dayofweek.sunday : false if isStartTime and showDailyDividers vline(bar_index, dividerLineTextColor, line.style_dashed, 1) _offset = _rin <= 7 ? math.round(dayLabelOffset * 12) : _rin <= 14 ? math.round(dayLabelOffset * 6) : _rin <= 20 ? math.round(dayLabelOffset * 4) : _rin <= 30 ? math.round(dayLabelOffset * 2) : _rin <= 60 ? math.round(dayLabelOffset * 1) : math.round(dayLabelOffset * 0.2) plotshape(isMon(), text=txtMonH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) plotshape(isTue(), text=txtTueH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) plotshape(isWed(), text=txtWedH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) plotshape(isThu(), text=txtThuH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) plotshape(isFri(), text=txtFriH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) plotshape(isSat(), text=txtSatH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) plotshape(isSun(), text=txtSunH, color=TRANSPARENT, offset=_offset, style=shape.circle, location=location.bottom, textcolor=dividerLineTextColor, size=size.tiny, editable=false) // --------------- SESSIONS --------------- // --------------- PREVIOUS OHLC --------------- // Daily var line[] dailyOpenLines = array.new_line(0) var line[] dailyCloseLines = array.new_line(0) var line[] dailyHighLines = array.new_line(0) var line[] dailyLowLines = array.new_line(0) var label[] dailyOpenLabels = array.new_label(0) var label[] dailyCloseLabels = array.new_label(0) var label[] dailyHighLabels = array.new_label(0) var label[] dailyLowLabels = array.new_label(0) [d_o, d_h, d_l, d_c, d_show, d_newbar, d_hl, d_oc] = getOhlcData("D", showDaily, ohlcOffset) if d_show and d_newbar _timeTo = ohlcExtendToCurrent ? time : time_close("D") if d_oc addToArray(dailyOpenLines, line.new(x1=time, y1=d_o, x2=_timeTo, y2=d_o, xloc=xloc.bar_time, style=line.style_solid, color=o_color)) addToArray(dailyCloseLines, line.new(x1=time, y1=d_c, x2=_timeTo, y2=d_c, xloc=xloc.bar_time, style=line.style_solid, color=c_color)) addToArray(dailyOpenLabels, label.new(x=getOhlcLabelPos("D"), y= d_o, xloc=xloc.bar_time, text=dailyOText + " ", textcolor=o_color, style=label.style_none)) addToArray(dailyCloseLabels, label.new(x=getOhlcLabelPos("D"), y= d_c, xloc=xloc.bar_time, text=dailyCText + " ", textcolor=c_color, style=label.style_none)) if d_hl addToArray(dailyHighLines, line.new(x1=time, y1=d_h, x2=_timeTo, y2=d_h, xloc=xloc.bar_time, style=line.style_solid, color=h_color)) addToArray(dailyLowLines, line.new(x1=time, y1=d_l, x2=_timeTo, y2=d_l, xloc=xloc.bar_time, style=line.style_solid, color=l_color)) addToArray(dailyHighLabels, label.new(x=getOhlcLabelPos("D"), y= d_h, xloc=xloc.bar_time, text=dailyHText + " ", textcolor=h_color, style=label.style_none)) addToArray(dailyLowLabels, label.new(x=getOhlcLabelPos("D"), y= d_l, xloc=xloc.bar_time, text=dailyLText + " ", textcolor=l_color, style=label.style_none)) // Weekly var line[] weeklyOpenLines = array.new_line(0) var line[] weeklyCloseLines = array.new_line(0) var line[] weeklyHighLines = array.new_line(0) var line[] weeklyLowLines = array.new_line(0) var label[] weeklyOpenLabels = array.new_label(0) var label[] weeklyCloseLabels = array.new_label(0) var label[] weeklyHighLabels = array.new_label(0) var label[] weeklyLowLabels = array.new_label(0) [w_o, w_h, w_l, w_c, w_show, w_newbar, w_hl, w_oc] = getOhlcData("W", showWeekly, ohlcOffset) if w_newbar and w_show _timeTo = ohlcExtendToCurrent ? time : time_close("W") if w_oc addToArray(weeklyOpenLines, line.new(x1=time, y1=w_o, x2=_timeTo, y2=w_o, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=o_color)) addToArray(weeklyCloseLines, line.new(x1=time, y1=w_c, x2=_timeTo, y2=w_c, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=c_color)) addToArray(weeklyOpenLabels, label.new(x=getOhlcLabelPos("W"), y= w_o, xloc=xloc.bar_time, text=weeklyOText + " ", textcolor=o_color, style=label.style_none)) addToArray(weeklyCloseLabels, label.new(x=getOhlcLabelPos("W"), y= w_c, xloc=xloc.bar_time, text=weeklyCText + " ", textcolor=c_color, style=label.style_none)) if w_hl addToArray(weeklyHighLines, line.new(x1=time, y1=w_h, x2=_timeTo, y2=w_h, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=h_color)) addToArray(weeklyLowLines, line.new(x1=time, y1=w_l, x2=_timeTo, y2=w_l, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=l_color)) addToArray(weeklyHighLabels, label.new(x=getOhlcLabelPos("W"), y= w_h, xloc=xloc.bar_time, text=weeklyHText + " ", textcolor=h_color, style=label.style_none)) addToArray(weeklyLowLabels, label.new(x=getOhlcLabelPos("W"), y= w_l, xloc=xloc.bar_time, text=weeklyLText + " ", textcolor=l_color, style=label.style_none)) // Weekly var line[] monthlyOpenLines = array.new_line(0) var line[] monthlyCloseLines = array.new_line(0) var line[] monthlyHighLines = array.new_line(0) var line[] monthlyLowLines = array.new_line(0) var label[] monthlyOpenLabels = array.new_label(0) var label[] monthlyCloseLabels = array.new_label(0) var label[] monthlyHighLabels = array.new_label(0) var label[] monthlyLowLabels = array.new_label(0) [m_o, m_h, m_l, m_c, m_show, m_newbar, m_hl, m_oc] = getOhlcData("M", showMonthly, ohlcOffset) if m_newbar and m_show _timeTo = ohlcExtendToCurrent ? time : time_close("M") if m_oc addToArray(monthlyOpenLines, line.new(x1=time, y1=m_o, x2=_timeTo, y2=m_o, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=o_color)) addToArray(monthlyCloseLines, line.new(x1=time, y1=m_c, x2=_timeTo, y2=m_c, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=c_color)) addToArray(monthlyOpenLabels, label.new(x=getOhlcLabelPos("M"), y= m_o, xloc=xloc.bar_time, text=monthlyOText + " ", textcolor=o_color, style=label.style_none)) addToArray(monthlyCloseLabels, label.new(x=getOhlcLabelPos("M"), y= m_c, xloc=xloc.bar_time, text=monthlyCText + " ", textcolor=c_color, style=label.style_none)) if m_hl addToArray(monthlyHighLines, line.new(x1=time, y1=m_h, x2=_timeTo, y2=m_h, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=h_color)) addToArray(monthlyLowLines, line.new(x1=time, y1=m_l, x2=_timeTo, y2=m_l, xloc=xloc.bar_time, style=getLineStyle(ohlcLineStyle), color=l_color)) addToArray(monthlyHighLabels, label.new(x=getOhlcLabelPos("M"), y= m_h, xloc=xloc.bar_time, text=monthlyHText + " ", textcolor=h_color, style=label.style_none)) addToArray(monthlyLowLabels, label.new(x=getOhlcLabelPos("M"), y= m_l, xloc=xloc.bar_time, text=monthlyLText + " ", textcolor=l_color, style=label.style_none)) // EXTEND LINES if d_show and not d_newbar and ohlcExtendToCurrent _lineO = getLastElementInArray(dailyOpenLines) _lineH = getLastElementInArray(dailyHighLines) _lineL = getLastElementInArray(dailyLowLines) _lineC = getLastElementInArray(dailyCloseLines) _labelO = getLastElementInArray(dailyOpenLabels) _labelH = getLastElementInArray(dailyHighLabels) _labelL = getLastElementInArray(dailyLowLabels) _labelC = getLastElementInArray(dailyCloseLabels) if not na(_lineO) line.set_x2(_lineO, time) if not na(_labelO) label.set_x(_labelO, time) if not na(_lineH) line.set_x2(_lineH, time) if not na(_labelH) label.set_x(_labelH, time) if not na(_lineL) line.set_x2(_lineL, time) if not na(_labelL) label.set_x(_labelL, time) if not na(_lineC) line.set_x2(_lineC, time) if not na(_labelC) label.set_x(_labelC, time) if w_show and not w_newbar and ohlcExtendToCurrent _lineO = getLastElementInArray(weeklyOpenLines) _lineH = getLastElementInArray(weeklyHighLines) _lineL = getLastElementInArray(weeklyLowLines) _lineC = getLastElementInArray(weeklyCloseLines) _labelO = getLastElementInArray(weeklyOpenLabels) _labelH = getLastElementInArray(weeklyHighLabels) _labelL = getLastElementInArray(weeklyLowLabels) _labelC = getLastElementInArray(weeklyCloseLabels) if not na(_lineO) line.set_x2(_lineO, time) if not na(_labelO) label.set_x(_labelO, time) if not na(_lineH) line.set_x2(_lineH, time) if not na(_labelH) label.set_x(_labelH, time) if not na(_lineL) line.set_x2(_lineL, time) if not na(_labelL) label.set_x(_labelL, time) if not na(_lineC) line.set_x2(_lineC, time) if not na(_labelC) label.set_x(_labelC, time) if m_show and not m_newbar and ohlcExtendToCurrent _lineO = getLastElementInArray(monthlyOpenLines) _lineH = getLastElementInArray(monthlyHighLines) _lineL = getLastElementInArray(monthlyLowLines) _lineC = getLastElementInArray(monthlyCloseLines) _labelO = getLastElementInArray(monthlyOpenLabels) _labelH = getLastElementInArray(monthlyHighLabels) _labelL = getLastElementInArray(monthlyLowLabels) _labelC = getLastElementInArray(monthlyCloseLabels) if not na(_lineO) line.set_x2(_lineO, time) if not na(_labelO) label.set_x(_labelO, time) if not na(_lineH) line.set_x2(_lineH, time) if not na(_labelH) label.set_x(_labelH, time) if not na(_lineL) line.set_x2(_lineL, time) if not na(_labelL) label.set_x(_labelL, time) if not na(_lineC) line.set_x2(_lineC, time) if not na(_labelC) label.set_x(_labelC, time) // DELETE OLD LINES // Daily if array.size(dailyOpenLines) > ohlcMaxLines line.delete(array.shift(dailyOpenLines)) if array.size(dailyOpenLabels) > ohlcMaxLines label.delete(array.shift(dailyOpenLabels)) if array.size(dailyCloseLines) > ohlcMaxLines line.delete(array.shift(dailyCloseLines)) if array.size(dailyCloseLabels) > ohlcMaxLines label.delete(array.shift(dailyCloseLabels)) if array.size(dailyHighLines) > ohlcMaxLines line.delete(array.shift(dailyHighLines)) if array.size(dailyHighLabels) > ohlcMaxLines label.delete(array.shift(dailyHighLabels)) if array.size(dailyLowLines) > ohlcMaxLines line.delete(array.shift(dailyLowLines)) if array.size(dailyLowLabels) > ohlcMaxLines label.delete(array.shift(dailyLowLabels)) // Weekly if array.size(weeklyOpenLines) > ohlcMaxLines line.delete(array.shift(weeklyOpenLines)) if array.size(weeklyOpenLabels) > ohlcMaxLines label.delete(array.shift(weeklyOpenLabels)) if array.size(weeklyCloseLines) > ohlcMaxLines line.delete(array.shift(weeklyCloseLines)) if array.size(weeklyCloseLabels) > ohlcMaxLines label.delete(array.shift(weeklyCloseLabels)) if array.size(weeklyHighLines) > ohlcMaxLines line.delete(array.shift(weeklyHighLines)) if array.size(weeklyHighLabels) > ohlcMaxLines label.delete(array.shift(weeklyHighLabels)) if array.size(weeklyLowLines) > ohlcMaxLines line.delete(array.shift(weeklyLowLines)) if array.size(weeklyLowLabels) > ohlcMaxLines label.delete(array.shift(weeklyLowLabels)) // Monthly if array.size(monthlyOpenLines) > ohlcMaxLines line.delete(array.shift(monthlyOpenLines)) if array.size(monthlyOpenLabels) > ohlcMaxLines label.delete(array.shift(monthlyOpenLabels)) if array.size(monthlyCloseLines) > ohlcMaxLines line.delete(array.shift(monthlyCloseLines)) if array.size(monthlyCloseLabels) > ohlcMaxLines label.delete(array.shift(monthlyCloseLabels)) if array.size(monthlyHighLines) > ohlcMaxLines line.delete(array.shift(monthlyHighLines)) if array.size(monthlyHighLabels) > ohlcMaxLines label.delete(array.shift(monthlyHighLabels)) if array.size(monthlyLowLines) > ohlcMaxLines line.delete(array.shift(monthlyLowLines)) if array.size(monthlyLowLabels) > ohlcMaxLines label.delete(array.shift(monthlyLowLabels)) // --------------- PREVIOUS OHLC ---------------
MACD + EMA System with Alerts
https://www.tradingview.com/script/HJXXKfjk-MACD-EMA-System-with-Alerts/
andryrads
https://www.tradingview.com/u/andryrads/
145
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/ // © andryrads //@version=5 indicator(title='MACD + EMA System with Alerts') source = close // Input Parameter emaPeriod = input(200) fastLength = input(12) slowLength = input(26) signalLength = input(9) // EMA Logic ema = ta.ema(source, emaPeriod) isTrendUp = close > ema isTrendDown = close < ema // MACD Logic fastMA = ta.ema(source, fastLength) slowMA = ta.ema(source, slowLength) macd = fastMA - slowMA signal = ta.sma(macd, signalLength) hist = macd - signal outMACD = request.security(syminfo.tickerid, timeframe.period, macd) outSignal = request.security(syminfo.tickerid, timeframe.period, signal) outHist = request.security(syminfo.tickerid, timeframe.period, hist) // MACD Area Logic isMACDupside = signal > 0 isMACDdownside = signal < 0 // Histogram 4 Color Logic histA_IsUp = outHist > outHist[1] and outHist > 0 histA_IsDown = outHist < outHist[1] and outHist > 0 histB_IsDown = outHist < outHist[1] and outHist <= 0 histB_IsUp = outHist > outHist[1] and outHist <= 0 // MACD Cross Color Logic macd_IsAbove = outMACD >= outSignal macd_IsBelow = outMACD < outSignal // Indicator Color Definition macd_color = #2963ff signal_color = #ff9901 hist_color = histA_IsUp ? #4caf50 : histA_IsDown ? #1b5e20 : histB_IsDown ? #f33645 : histB_IsUp ? #801923 : color.gray cross_color = macd_IsAbove ? color.rgb(0, 230, 118) : color.rgb(235, 92, 92) // Y position of crossing signal YPosition = outSignal // Chart Plotting Section plot(outMACD, title='Main Line', color=color.new(macd_color, 0), style=plot.style_line, linewidth=1) plot(outSignal, title='Signal Line', color=color.new(signal_color, 0), style=plot.style_line, linewidth=1) plot(outHist, title='Histogram', color=hist_color, style=plot.style_columns, linewidth=1) plot(isTrendUp and isMACDdownside and ta.crossover(outMACD, outSignal) ? YPosition : na, title='MACD Crossover', style=plot.style_circles, linewidth=2, color=cross_color) plot(isTrendDown and isMACDupside and ta.crossunder(outMACD, outSignal) ? YPosition : na, title='MACD Crossunder', style=plot.style_circles, linewidth=2, color=cross_color) hline(0, 'Middle Line', linestyle=hline.style_solid, linewidth=1, color=color.white) // Signal & Alerting section entryLong = isTrendUp and isMACDdownside and ta.crossover(outMACD, outSignal) entryShort = isTrendDown and isMACDupside and ta.crossunder(outMACD, outSignal) alertcondition(entryLong, 'Buy Signal', '{{ticker}} : Buy Entry!') alertcondition(entryShort, 'Sell Signal', '{{ticker}} : Sell Entry!')
REVE Markers
https://www.tradingview.com/script/6Gggf2pK-REVE-Markers/
eykpunter
https://www.tradingview.com/u/eykpunter/
90
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © eykpunter //@version=5 indicator("REVE Markers", overlay=true) eventnorm=input.int(title="more than ### percent of usual is deemed considerable", defval=130, minval=100, step=5, group="For both range and volume:")/100 eventadd =input.int(title="add ### percent to this for excessive", defval=120, minval=10, step=5, group="For both range and volume:")/100 usual=input.int(title="as usual take the median of previous ## periods", defval=20, minval=5, group="For both range and volume:") barwish = input.bool(title='show volume markers above and range markers below candles', defval=false, group="For both range and volume:") //colors scol=input.color(color.rgb(85,154,29,0), "considerable volume expansion, normal range (institutional traders)", group="Situational Colors") //green bcol=input.color(color.new(color.aqua, 0), "excessive volume expansion, normal range (institutional traders)", group="Situational Colors") //blue //nvcol=input.color(color.rgb(67,70,81, 0), "Beyond normal range extension, normal volume", group="Situational Colors") //dark gray when volume data provided nvcol=input.color(color.rgb(74,20,140, 0), "Beyond normal range extension, neutral color", group="Situational Colors") //dark purple when no volume data provided cscol=input.color(color.new(color.red, 0), "combination of considerable events (effective volume expansion, occasional traders)", group="Situational Colors") //red cbcol=input.color(color.new(color.fuchsia, 0), "combination of considerable and excessive event (fierce trading, occasional traders)", group="Situational Colors") //fuchsia climcol=input.color(color.new(color.maroon, 0), "combination of excessive events (climactic trading, occasional traders)", group="Situational Colors") //maroon //calculate presence and context of events curvol=na(volume)? 0:volume //If no volume reported, indicator will show all range extensions because curvol allways has a numerical value //nvna=na(volume) //true if no volume reported, false when volume is provided morevol=ta.median(curvol[1], usual)*eventnorm //small volume level at least ### times recently usual i.e. median hugevol=ta.median(curvol[1], usual)*(eventnorm+eventadd) //big volume level at least #small + #add times recently usual barrange=ta.tr(true) moreran=ta.median(barrange[1], usual)*eventnorm hugeran=ta.median(barrange[1], usual)*(eventnorm+eventadd) //small and big volume expansions vsevent1=curvol != 0 and curvol>=morevol and curvol<=hugevol //considerable volume expansion vbevent1=curvol != 0 and curvol>hugevol //excessive volume expansion vsevent=vsevent1 and barrange<moreran //considerable volume expansion without range effect vbevent=vbevent1 and barrange<moreran //excessive volume expansion without range effect //small and big range extensions rsevent1=barrange>moreran and barrange<hugeran //limited range extension rbevent1=barrange>=hugeran //big range extension rsevent=barrange>moreran and barrange<hugeran and (curvol<=morevol or curvol==0)//limited range extension without volume support rbevent=barrange>=hugeran and (curvol<=morevol or curvol==0) //big range extension wthout volume support //small and big combination of volume and range expansions or extensions csevent=vsevent1 and rsevent1 //combination of small events cbevent=(vsevent1 and rbevent1) or (vbevent1 and rsevent1) //combination containing a big and small event (heated) climevent=vbevent1 and rbevent1 //combination of big events (climactic) //bar situations barup=close>open and close>close[1] bardown=close<open and close<close[1] barsame=not barup and not bardown //calculate event situations //bottom markers vseventup= vsevent and barup //event leading to rize vseventdown=vsevent and bardown //event leading to fall vseventnone=vsevent and barsame //event without effect on price vbeventup= vbevent and barup //event leading to rize vbeventdown=vbevent and bardown //event leading to fall vbeventnone=vbevent and barsame //event without effect on price rseventup= rsevent and barup //event leading to rize rseventdown=rsevent and bardown //event leading to fall rseventnone=rsevent and barsame //event without effect on price rbeventup= rbevent and barup //event leading to rize rbeventdown=rbevent and bardown //event leading to fall rbeventnone=rbevent and barsame //event without effect on price cseventup= csevent and barup //event leading to rize cseventdown=csevent and bardown //event leading to fall cseventnone=csevent and barsame //event without effect on price cbeventup= cbevent and barup //event leading to rize cbeventdown=cbevent and bardown //event leading to fall cbeventnone=cbevent and barsame //event without effect on price climeventup= climevent and barup //event leading to rize climeventdown=climevent and bardown //event leading to fall climeventnone=climevent and barsame //event without effect on price //bar markers marking volume events barvs= barwish? vsevent1:na //small volume event barvb= barwish? vbevent1:na //big volume event //bar markers marking range events barrsup= barwish? rsevent1 and barup : na //limitied range event up barrsdown= barwish? rsevent1 and bardown : na //limited range event down barrsnone= barwish? rsevent1 and barsame : na //limited range event without effect on price barrbup= barwish? rbevent1 and barup : na //big range event up barrbdown= barwish? rbevent1 and bardown : na //big range event down barrbnone= barwish? rbevent1 and barsame : na //big range event without effect on price //plot markers //bottom volume markers plotshape(vseventup, style=shape.triangleup, location=location.bottom, size=size.tiny, color=scol) plotshape(vseventdown, style=shape.triangledown, location=location.bottom, size=size.tiny, color=scol) plotshape(vseventnone, style=shape.square, location=location.bottom, size=size.tiny, color=scol) plotshape(vbeventup, style=shape.triangleup, location=location.bottom, size=size.tiny, color=bcol) plotshape(vbeventdown, style=shape.triangledown, location=location.bottom, size=size.tiny, color=bcol) plotshape(vbeventnone, style=shape.square, location=location.bottom, size=size.tiny, color=bcol) //bottom range markers (all cross) //plotshape(rseventup, style=shape.arrowup, location=location.bottom, size=size.tiny, color=color.blue )// color=nvna?nvnacol:nvcol ) plotchar(rseventup, char="↑", location=location.bottom, size=size.tiny, color=color.blue ) //plotshape(rseventdown, style=shape.labeldown, location=location.bottom, size=size.tiny, color=color.red )// color=nvna?nvnacol:nvcol) plotchar(rseventdown, char="↓", location=location.bottom, size=size.tiny, color=color.red) plotshape(rseventnone, style=shape.cross, location=location.bottom, size=size.tiny, color=nvcol ) //color=nvna?nvnacol:nvcol) //plotshape(rbeventup, style=shape.xcross, location=location.bottom, size=size.tiny, color=color.blue )// color=nvna?nvnacol:nvcol ) plotchar(rbeventup, char="Λ", location=location.bottom, size=size.tiny, color=color.blue ) //plotshape(rbeventdown, style=shape.xcross, location=location.bottom, size=size.tiny, color=color.red )// color=nvna?nvnacol:nvcol) plotchar(rbeventdown, char="V", location=location.bottom, size=size.tiny, color=color.red ) plotshape(rbeventnone, style=shape.xcross, location=location.bottom, size=size.tiny, color=nvcol ) //color=nvna?nvnacol:nvcol) //bottom combination markers plotshape(cseventup, style=shape.triangleup, location=location.bottom, size=size.tiny, color=cscol) plotshape(cseventdown, style=shape.triangledown, location=location.bottom, size=size.tiny, color=cscol) plotshape(cseventnone, style=shape.square, location=location.bottom, size=size.tiny, color=cscol) plotshape(cbeventup, style=shape.triangleup, location=location.bottom, size=size.tiny, color=cbcol) plotshape(cbeventdown, style=shape.triangledown, location=location.bottom, size=size.tiny, color=cbcol) plotshape(cbeventnone, style=shape.square, location=location.bottom, size=size.tiny, color=cbcol) plotshape(climeventup, style=shape.triangleup, location=location.bottom, size=size.tiny, color=climcol) plotshape(climeventdown, style=shape.triangledown, location=location.bottom, size=size.tiny, color=climcol) plotshape(climeventnone, style=shape.square, location=location.bottom, size=size.tiny, color=climcol) //bar volume markers (all cross) plotshape(barvs, style=shape.cross, location=location.abovebar, size=size.tiny, color=nvcol) plotshape(barvb, style=shape.xcross, location=location.abovebar, size=size.tiny, color=nvcol) //bar range markers plotshape(barrsup, style=shape.triangleup, location=location.belowbar, size=size.tiny, color=nvcol) plotshape(barrsdown, style=shape.triangledown, location=location.belowbar, size=size.tiny, color=nvcol) plotshape(barrsnone, style=shape.cross, location=location.belowbar, size=size.tiny, color=nvcol) plotshape(barrbup, style=shape.triangleup, location=location.belowbar, size=size.small, color=nvcol) plotshape(barrbdown, style=shape.triangledown, location=location.belowbar, size=size.small, color=nvcol) plotshape(barrbnone, style=shape.cross, location=location.belowbar, size=size.small, color=nvcol)
Directional Movement Indicator (DMI and ADX) - Tartigradia
https://www.tradingview.com/script/5jVJuobZ-Directional-Movement-Indicator-DMI-and-ADX-Tartigradia/
tartigradia
https://www.tradingview.com/u/tartigradia/
126
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/ // © BeikabuOyaji // This is an extended indicator, from the original one by BeikabuOyaji: https://www.tradingview.com/script/VTPMMOrx-ADX-and-DI/ // extended by tartigradia (plot DMX, added second threshold as per Welles Wilder original indicator, added background highlighting depending on ADX and thresholds to ease interpretation of trends vs ranging market, converted to pinescript v5, changed color scheme to work on black theme) // for more infos on how to use this indicator, read (in french): https://www.leguideboursier.com/apprendre-bourse/analyse-technique/indicateur-adx.php and https://www.leguideboursier.com/apprendre-bourse/analyse-technique/dmi-indicateur.php // // Description: Direction Movement Indicator (DMI) is a trend indicator invented by J. Welles Wilder, who also authored RSI. // DMI+ and DMI- respectively indicate pressure towards bullish or bearish trends. // ADX is the average directional movement, which indicates whether the market is currently trending (high values above 25) or ranging (below 20) or undecided (between 20 and 25). // DMX is the non smoothed ADX, which allows to detect transitions from trending to ranging markets and inversely with zero lag, but at the expense of having much more noise. // // Usage: To use this indicator for entry: when DMI+ crosses over DMI-, there is a bullish sentiment, however ADX also needs to be above 25 to be significant, otherwise the market is not trending. // When ADX is below 20, the market is ranging (no trend), and when ADX is between 20 and 25, the market is undecided (we don't know if it's trending or ranging). // Inversely, when DMI+ crosses under DMI- and ADX is above 25, then the sentiment is significantly bearish, but if ADX is below 20, the signal should be disregarded, since market is ranging. // This indicator automatically highlights the background in purple when ADX is above 25 to indicate that there is a trend, regardless of its direction, and in dark blue when ADX is below 20, indicating that the market is ranging. When the market is undecided, the background is not highlighted. // There is a "Trend bar" at the bottom that allows for easy interpretation: // * it is colored in green when the market is bullishly trending (DMI+ over DMI- and ADX > 25). // * in red when market is bearishly trending (DMI+ under DMI- and ADX > 25). // * in dark blue when market is ranging (ADX < 20). // * in gray when market is undecided (20 <= ADX < 25). // To make trend changes signals appear faster, the default SMA calculations embedded inside the ADX and DMI calculations are replaceable by other types of moving averages. By default, a Zero-Lag Moving Average (ZLMA) is selected, as it provides a smooth yet very reactive signal. // To get the most reactive signal, smoothing can be disabled by highlighting the background and trend bar using DMX, which is the non-smoothed ADX, and is hence much more reactive but also much more noisy (disabled by default). // Finally, arrows can be activated in the Style menu to automatically show when the two conditions described above are met, or these can be used in a strategy. // By default, this indicator is set to always calculate on the weekly timeframe, as this is when the signals appear to be the most reliable. The timeframe can however be changed in the parameters, and can be set to "Chart" to adapt to currently user selected timeframe in TradingView. //@version=5 indicator('Directional Movement Indicator (DMI and ADX) - Tartigradia', shorttitle='ADX_DMI', timeframe="W", timeframe_gaps=false) // AUX FUNCTIONS // zema(src, len) => // Zero-lag EMA // by DreamsDefined in: https://www.tradingview.com/script/pFyPlM8z-Reverse-Engineered-RSI-Key-Levels-MTF/ ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) d = ema1 - ema2 zlema = ema1 + d zlema approximate_sma(x, ma_length) => // Approximate SMA, which substracts the average instead of popping the oldest element // This is the original SMA used in this indicator // For some reason, this appears to give the same results as a standard RMA sma = 0.0 sma := nz(sma[1]) - (nz(sma[1] / ma_length)) + x sma f_maSelect(serie, ma_type="sma", ma_length=14) => switch ma_type "sma" => ta.sma(serie, ma_length) "ema" => ta.ema(serie, ma_length) "rma" => ta.rma(serie, ma_length) "wma" => ta.wma(serie, ma_length) "vwma" => ta.vwma(serie, ma_length) "swma" => ta.swma(serie) "hma" => ta.hma(serie, ma_length) "alma" => ta.alma(serie, ma_length, 0.85, 6) "zlma" => zema(serie, ma_length) "approximate_sma" => approximate_sma(serie, ma_length) => runtime.error("No matching MA type found.") float(na) detect_switch(series bool x) => // Detects when a series turn from false to true, this is useful to detect abrupt transitions and mark them with plotshape x and not x[1] // PARAMETERS // ma_length_dmi = input.int(14, title='Smoothing length for DMI+ and DMI-', minval=1, step=1, maxval=300) ma_type_dmi = input.string('approximate_sma', 'Moving Average Type for DMI+ and DMI-', options=['sma', 'ema', 'rma', 'wma', 'vwma', 'swma', 'hma', 'alma', 'zlma', 'approximate_sma'], tooltip='What kind of smoothing algorithm do we apply on the signals? For the original DMI+ and DMI- as defined by Welles Wilder, set approximate_sma.') th = input.float(20, title='ADX No trend threshold', step=1.0) th2 = input.float(25, title='ADX trend threshold', step=1.0) ma_length_adx = input.int(14, "SMA Length for ADX", minval=1, maxval=300, step=1) ma_type_adx = input.string('zlma', 'Moving Average Type for ADX', options=['sma', 'ema', 'rma', 'wma', 'vwma', 'swma', 'hma', 'alma', 'zlma', 'approximate_sma'], tooltip='What algorithm to use to smooth out the signals? Default: zlma, as it provides the most reactive signal while still being smooth (less noisy, less false positives). For the original ADX as defined by Welles Wilder, select sma.') bg_highlight = input.bool(true, title='Highlight background depending on ADX thresholds?', tooltip='Highlight background when ADX is below the no trend threshold (ranging market) or above the trend threshold (trending market). Between both thresholds, the market is undecided.') show_trend_bar = input.bool(true, title='Show trend bar based on DMI+/DMI- crossover direction with ADX filtering?', tooltip='Display a bar with color indicating trend direction or lack of trend: bullish if DMI+ is above DMI- and ADX > trend threshold (default green), bearish if DMI+ is below DMI- and ADX > trend threshold (default red), otherwise if ADX < no-trend threshold then there is no trend (default orange) and if ADX is between the no-trend threshold and the trend threshold then the market is uncertain whether it is trending or ranging (default gray).') bg_highlight_dmx = input.bool(false, title='Use DMX (non-smoothed ADX) instead of ADX in calculations to highlight background and trend bar?', tooltip='This allows to experience no lag in trend changes, but there is much more noise than with the smoothed ADX, hence lots of false positives.') // CALCULATIONS // TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1]))) DirectionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0 DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0 SmoothedTrueRange = f_maSelect(TrueRange, ma_type_dmi, ma_length_dmi) SmoothedDirectionalMovementPlus = f_maSelect(DirectionalMovementPlus, ma_type_dmi, ma_length_dmi) SmoothedDirectionalMovementMinus = f_maSelect(DirectionalMovementMinus, ma_type_dmi, ma_length_dmi) DMIPlus = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100 DMIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100 DMX = math.abs(DMIPlus - DMIMinus) / (DMIPlus + DMIMinus) * 100 ADX = f_maSelect(DMX, ma_type_adx, ma_length_adx) // PLOTS // plot(DMIPlus, color=color.new(color.green, 0), title='DI+') plot(DMIMinus, color=color.new(color.red, 0), title='DI-') plot(ADX, color=color.new(color.white, 0), title='ADX', linewidth=2) plot(DMX, color=color.new(color.gray, 0), title='DMX') hline(th, color=color.new(color.white, 50), title="ADX no trend threshold level") hline(th2, color=color.new(color.white, 50), title="ADX trend threshold level") // Background highlight of trends trend_val = bg_highlight_dmx ? DMX : ADX bgcolor(not bg_highlight ? na : trend_val < th ? color.new(color.blue, 70) : trend_val >= th2 ? color.new(color.purple, 70) : na, title='Background highlight of trend existence according to ADX or DMX (not direction)') trendbar1 = hline(0.0, title='Trend bar top line', linewidth=1, color=color.new(color.white, 100)) // use invisible color lines instead of display.none to ensure chart is scaled to include bar, otherwise with display.none the fill will still be displayed but the chart won't necessarily get scaled to display it trendbar2 = hline(-5.0, title='Trend bar bottom line', linewidth=1, color=color.new(color.white, 100)) fill(trendbar1, trendbar2, color= not show_trend_bar ? na : trend_val < th ? color.blue : trend_val >= th and trend_val < th2 ? color.gray : trend_val >= th2 and DMIPlus > DMIMinus ? color.green : trend_val >= th2 and DMIPlus < DMIMinus ? color.red : na , title='Trend bar (DMI+/DMI- crossover combined with ADX filtering)') // Plot abrupt changes as arrows dmibullish = DMIPlus > DMIMinus and trend_val >= th2 dmibearish = DMIPlus < DMIMinus and trend_val >= th2 trend_val_unsignificant = trend_val < th2 //plotarrow(detect_switch(dmibullish) ? 1 : detect_switch(dmibearish) ? -1 : na, title="DMI+ crosses DMI-", display=display.none) // TODO: display scaling is totally off for some unknown reason plotshape(detect_switch(dmibullish), title='Signal: DMI+ crossover DMI-', style=shape.triangleup, location=location.top, color=color.new(color.green, 0), size=size.auto, display=display.pane) plotshape(detect_switch(dmibearish), title='Signal: DMI+ crossunder DMI-', style=shape.triangledown, location=location.top, color=color.new(color.red, 0), size=size.auto, display=display.pane) plotshape(detect_switch(trend_val_unsignificant), title='Signal: Trend disappears', style=shape.xcross, location=location.top, color=color.new(color.gray, 0), size=size.auto, display=display.pane)
Swing Failure Pattern
https://www.tradingview.com/script/oY9eHyso-Swing-Failure-Pattern/
Greg_007
https://www.tradingview.com/u/Greg_007/
919
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/ // © Greg_007 //@version=5 indicator("Swing Failure Pattern", overlay=true) lookback = input.int(100, "Bars to look back") ignore = input.int(10, "Ignore last ... bars") char = input.string('👀', "Character to show (only 1 is allowed)") char_color = input.color(color.blue, "Character Color") last_high = ta.highest(lookback) last_low = ta.lowest(lookback) ignored_high = ta.highest(ignore) ignored_low = ta.lowest(ignore) plotchar(high > last_high[1] and close < last_high[1] and last_high[1] != ignored_high[1] ? close : na, char=char, color = char_color, location=location.abovebar, size=size.small) plotchar(low < last_low[1] and close > last_low[1] and last_low[1] != ignored_low[1] ? close : na, char=char, color = char_color, location=location.belowbar, size=size.small)
Fed Net Liquidity Indicator v2
https://www.tradingview.com/script/UCqiVU4F-Fed-Net-Liquidity-Indicator-v2/
TaxShields
https://www.tradingview.com/u/TaxShields/
256
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/ // © jlb05013 //@version=5 indicator("Fed Net Liquidity Indicator", overlay=true) i_res = input.timeframe('D', "Resolution", options=['D', 'W', 'M']) fed_bal = request.security('FRED:WALCL', i_res, close)/1e9 // millions tga = request.security('FRED:WTREGEN', i_res, close)/1e9 // billions rev_repo = request.security('FRED:RRPONTSYD', i_res, close)/1e9 // billions net_liquidity = (fed_bal - (tga + rev_repo)) / 1.1 - 1625 var net_liquidity_offset = 10 // 2-week offset for use with daily charts if timeframe.isdaily net_liquidity_offset := 10 if timeframe.isweekly net_liquidity_offset := 2 if timeframe.ismonthly net_liquidity_offset := 0 plot(net_liquidity, title='Net Liquidity', color=color.new(color.blue, 80), style=plot.style_area, offset=net_liquidity_offset)
SpreadTrade - Auto-Cointegration (ps5)
https://www.tradingview.com/script/k60icAir-SpreadTrade-Auto-Cointegration-ps5/
capissimo
https://www.tradingview.com/u/capissimo/
161
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/ // © capissimo //@version=5 indicator('SpreadTrade - Auto-Cointegration (ps5)', 'ST-AutoCI', false) // Auto-Cointegration-Based Pair Trading Strategy (revised version) // There are three popular styles of Pair trading: distance-based pair trading, // correlation-based pair trading and cointegration-based pair trading. Typically, // they require preliminary statistical estimation of the viability of the // corresponding strategy. // The Cointegration strategy boild down to shorting the outperforming instrument // and going long on the underperforming instrument whenever the temporary correlation // weakens which means one instrument is going up and another is going down. // Apart from the typical cointegration strategy which employs two cointegrated // instruments, this script uses just one instrument, in base timeframe and in // lagged timeframe. So in fact this an auto-cointegration strategy, or better // still, an auto-correlation strategy. // Notice that each moving average function may require different Threshold // settings.Thr orange cross symbol indicates the exit points. To filter out // the signals use higher values for the LongWindow and the Threshold parameters. // Also pay attention that in some cases with some moving averages the color of // the signals has to be inverted. //-- Inputs Dataset = input.source (close, 'Dataset') Tframe = input.timeframe('', 'Timeframe', tooltip='A timeframe of the lagged dataset used as a devisor in ratio') ShortWindow = input.int (2, 'Short Window [2..n]', 2, tooltip='A lookback period for the first moving average') LongWindow = input.int (1500, 'Long Window [3..m]', 3, tooltip='A lookback period for the second moving average') Maverage = input.string ('SMA', 'Moving Average Function', ['EMA','HMA','SMA','VWAP','WMA']) Threshold = input.float (20.0, 'Z-Score Threshold [0.1..400.0]', minval=0.1, maxval=400.0, step=0.1) // 0.1 for vwap Ticks = input.int (252, 'Tick Threshold [2..500]', 2, 500, tooltip='Used for deciding on what bar to exit a trade') Invert = input.bool (true, 'Invert the Color', tooltip='Occasionally signal color inversion is required') //-- Constants var int BUY = 1 var int SELL =-1 var int CLEAR = 0 //-- Variables var int signal = CLEAR var array<int> ticks = array.new<int>(1, 0) // array used as a container for inter-bar variables //-- Logic float lagged_dataset = request.security('', Tframe, Dataset[1]) float ratios = math.log(Dataset / lagged_dataset) float mov_avg1 = switch Maverage 'EMA' => ta.ema (ratios, ShortWindow) 'HMA' => ta.hma (ratios, ShortWindow) 'VWAP' => ta.vwap(ratios) 'WMA' => ta.wma (ratios, ShortWindow) => ta.sma(ratios, ShortWindow) float mov_avg2 = switch Maverage 'EMA' => ta.ema (ratios, LongWindow) 'HMA' => ta.hma (ratios, LongWindow) 'VWAP' => ta.vwap(ratios[1]) 'WMA' => ta.wma (ratios, LongWindow) => ta.sma(ratios, LongWindow) float std_deviation = ta.stdev(mov_avg2, math.round(math.avg(ShortWindow, LongWindow))) float z_score = (mov_avg1 - mov_avg2) / std_deviation // brings out the mean reverting nature of the ratio! bool long = z_score < -Threshold bool short = z_score > Threshold bool clear = not(long and short) // Ratio is BUY (+1) whenever the z-score is below -Threshold because we expect z-score to go back up to 0, hence ratio to increase // Ratio is SELL(-1) whenever the z-score is above +Threshold because we expect z-score to go back down to 0, hence ratio to decrease signal := long ? BUY : short ? SELL : clear ? CLEAR : nz(signal[1]) if array.get(ticks, 0)==Ticks signal := CLEAR array.set(ticks, 0, 0) if signal == BUY array.set(ticks, 0, array.get(ticks, 0) + 1) if signal == SELL array.set(ticks, 0, array.get(ticks, 0) + 1) int changed = ta.change(signal) bool long_condition = changed and signal==BUY bool short_condition = changed and signal==SELL bool clear_condition = changed and signal==CLEAR color clr_green = Invert ? color.red : color.green color clr_red = Invert ? color.green : color.red //-- Visuals hline(Threshold, 'Upper Bound', color.red) hline(-Threshold, 'Lower Bound', color.green) plot(CLEAR, 'Midline', color.silver, 1) plot(z_score, 'Z-Score') plot(long_condition ? z_score : na, 'Sell Signal', clr_green, 3, plot.style_circles) plot(short_condition ? z_score : na, 'Buy Signal', clr_red, 3, plot.style_circles) plot(clear_condition ? z_score : na, 'Clear Position', color.orange, 2, plot.style_cross) //-- Notification if changed and signal==BUY alert('Buy Alert', alert.freq_once_per_bar) // alert.freq_once_per_bar_close if changed and signal==SELL alert('Sell Alert', alert.freq_once_per_bar) alertcondition(long_condition, 'Buy', 'Go long!') alertcondition(short_condition, 'Sell', 'Go short!') //alertcondition(long_condition or short_condition, 'Alert', 'Deal Time!') // :End:
The Godfather
https://www.tradingview.com/script/kZAxfkPD-The-Godfather/
JOJOGLO
https://www.tradingview.com/u/JOJOGLO/
60
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/ // © JOJOGLO //@version=5 indicator("The Godfather", "ABBA", overlay=true) useColorUp = input(color.rgb(28, 139, 230), title = "UP") useColorDn = input(color.rgb(224, 67, 67), title = "DN") useColorIk = input(color.new(color.black,15), title = "WI") useColorDr = input(color.new(color.black,15), title = "BO") useMA = input(88, title = "MA") //-----OLHCRange-----// h = high l = low c = close o = c[1] r = (ta.highest(h,3) + ta.lowest(l,3) ) / 2 //----AM-BETTER-MA-----// ma0 = (ta.sma(hlc3,3) + ta.sma(hlc3,4)[3] + (ta.sma(open, 16) + ta.sma(open, 19)[3]) ) / 4 sig = ta.lowest(ma0, 2) < ma0 ? color.rgb(28, 139, 230,0) : ta.highest(ma0,2) > ma0 ? color.new(color.red,0) : color.new(color.black,0) //-----RSI-----// rsiLine = ta.rsi(c, 7) //-----SHOW-RSI-FLIPS-----// upCon1 = rsiLine[1] <= 50 and rsiLine > 50 dnCon1 = rsiLine[1] > 50 and rsiLine <= 50 sigCon = upCon1 or dnCon1 upClr1 = color.new(color.blue,72) dnClr1 = color.new(color.blue,72) //-----CANDLE-COLOR-----// sig2up = sigCon[2] and c[2] < c sig3up = sigCon[3] and c[3] < c sig2dn = sigCon[2] and c[2] > c sig3dn = sigCon[3] and c[3] > c signal = r < ma0 ? "dn" : r > ma0 ? "up" : "none" signal := sig2up or sig3up ? "up" : signal signal := sig2dn or sig3dn ? "dn" : signal signal := not sig2up and not sig2dn and not sig3up and not sig3dn and sigCon[1] and ma0 < c ? "up" : signal signal := not sig2up and not sig2dn and not sig3up and not sig3dn and sigCon[1] and ma0 > c ? "dn" : signal ///-----FINISHING-TOUCHES------/// plot(ma0, color = color.new(sig,useMA), style = plot.style_line, linewidth = 3,editable = false) plotshape(upCon1, style = shape.triangleup, location = location.abovebar, color = upClr1,editable = false) plotshape(dnCon1, style = shape.triangledown, location = location.belowbar, color = dnClr1,editable = false) transpStamp = c[1] > c ? 0 : 50 palette = signal == "up" ? color.new(useColorUp,transpStamp) : signal == "dn" ? color.new(useColorDn,transpStamp) : signal == "none" ? color.new(color.yellow,transpStamp) : color.new(color.fuchsia,transpStamp) plotcandle(o,h,l,c, color = color.new(palette, transpStamp), wickcolor = useColorIk , bordercolor = useColorDr, editable = false)
Spread Chart
https://www.tradingview.com/script/TEUP88cy-Spread-Chart/
konidtaly88
https://www.tradingview.com/u/konidtaly88/
51
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/ // © konidtaly88 //@version=5 indicator("Spread Chart") masterQuantity = input.int(1) tickerName = input.symbol("M2K1!") tickerQuantity = input.float(-1, step=1) tickerPointvalue = input.float(5, minval=0) secondTickerName = input.symbol("ZB1!") secondTickerQuantity = input.float(0, step=1) secondTickerPointvalue = input.float(1000, minval=0) invert = input.bool(false) debug = input.bool(false) rowColor(qty) => qty>0? color.green : color.red var table tableInfo = na if na(tableInfo) rowCount = 2 + (tickerQuantity!=0 ? 1 : 0) + (secondTickerQuantity!=0 ? 1 : 0) tableInfo := table.new(position.top_right, 3, rowCount, frame_color=color.gray, frame_width=1, border_color=color.gray, border_width=1) tableTextColor = color.white table.cell(tableInfo, 0, 0, "Qty", text_color=tableTextColor) table.cell(tableInfo, 1, 0, "Ticker", text_color=tableTextColor) table.cell(tableInfo, 2, 0, syminfo.currency+"/Handle", text_color=tableTextColor) table.cell(tableInfo, 0, 1, str.tostring(math.sign(invert?-1:1)*masterQuantity), text_color=rowColor(masterQuantity)) table.cell(tableInfo, 1, 1, syminfo.tickerid, text_color=rowColor(masterQuantity)) table.cell(tableInfo, 2, 1, str.tostring(syminfo.pointvalue), text_color=rowColor(masterQuantity)) currentRow = 2 if tickerQuantity != 0 table.cell(tableInfo, 0, currentRow, str.tostring(math.sign(invert?-1:1)*tickerQuantity), text_color=rowColor(tickerQuantity)) table.cell(tableInfo, 1, currentRow, tickerName, text_color=rowColor(tickerQuantity)) table.cell(tableInfo, 2, currentRow, str.tostring(tickerPointvalue), text_color=rowColor(tickerQuantity)) currentRow += 1 if secondTickerQuantity != 0 table.cell(tableInfo, 0, currentRow, str.tostring(math.sign(invert?-1:1)*secondTickerQuantity), text_color=rowColor(secondTickerQuantity)) table.cell(tableInfo, 1, currentRow, secondTickerName, text_color=rowColor(secondTickerQuantity)) table.cell(tableInfo, 2, currentRow, str.tostring(secondTickerPointvalue), text_color=rowColor(secondTickerQuantity)) tickerHigh = request.security(tickerName, timeframe.period, high) tickerLow = request.security(tickerName, timeframe.period, low) tickerOpen = request.security(tickerName, timeframe.period, open) tickerClose = request.security(tickerName, timeframe.period, close) // tickerPointvalue = request.security(secondTickerName, timeframe.period, syminfo.pointvalue) barOpen = masterQuantity*open*syminfo.pointvalue + tickerQuantity*tickerOpen*tickerPointvalue barClose = masterQuantity*close*syminfo.pointvalue + tickerQuantity*tickerClose*tickerPointvalue barHigh = masterQuantity*high*syminfo.pointvalue + tickerQuantity*tickerHigh*tickerPointvalue barLow = masterQuantity*low*syminfo.pointvalue + tickerQuantity*tickerLow*tickerPointvalue secondTickerHigh = request.security(secondTickerName, timeframe.period, high) secondTickerLow = request.security(secondTickerName, timeframe.period, low) secondTickerOpen = request.security(secondTickerName, timeframe.period, open) secondTickerClose = request.security(secondTickerName, timeframe.period, close) // secondTickerPointvalue = request.security(secondTickerName, timeframe.period, syminfo.pointvalue) barOpen += secondTickerQuantity*secondTickerOpen*secondTickerPointvalue barClose += secondTickerQuantity*secondTickerClose*secondTickerPointvalue barHigh += secondTickerQuantity*secondTickerHigh*secondTickerPointvalue barLow += secondTickerQuantity*secondTickerLow*secondTickerPointvalue if invert barOpen *= -1 barClose *= -1 barHigh *= -1 barLow *= -1 plotbar(barOpen, barHigh, barLow, barClose, color=barOpen>barClose?color.red:(barOpen<barClose?color.green:color.white)) plot(debug?tickerClose:na, color=color.red) plot(debug?tickerQuantity*tickerClose:na, color=color.green) plot(debug?tickerQuantity*tickerClose*tickerPointvalue:na, color=color.blue)
Educational: lines, linefill, labels & boxes
https://www.tradingview.com/script/q3MOxW22-Educational-lines-linefill-labels-boxes/
fikira
https://www.tradingview.com/u/fikira/
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/ // © fikira //@version=5 indicator ("Educational: lines, linefill, labels & boxes" , max_lines_count=200, overlay=true) selection = input.string ('Linefill' , options=['Linefill' ]) options = input.string ('extend lines', options=['extend lines', 'none']) // –––––––––––––––––––––[ Fetch previous Weekly high/low ]––––––––––––––––––––– prevHigh_W = request.security(syminfo.tickerid, 'W', nz(high[1]), barmerge.gaps_off, barmerge.lookahead_on) prevLow_W = request.security(syminfo.tickerid, 'W', nz(low [1]), barmerge.gaps_off, barmerge.lookahead_on) // –––––––––––––––––––––[ Create array's ]––––––––––––––––––––– var linefill[] lnF = array.new <linefill> () var int [] dir = array.new < int > () // –––––––––––––––––––––[ Add 1 linefill.new() ]––––––––––––––––––––– if barstate.isfirst or timeframe.change('W') line1 = line.new(bar_index, prevHigh_W, bar_index +1, prevHigh_W, color= color.new(color.silver, 50) ) line2 = line.new(bar_index, prevLow_W , bar_index +1, prevLow_W , color= color.new(color.silver, 50) ) array.unshift (lnF , linefill.new(line1, line2, color.new(color.blue , 75))) array.unshift (dir , 0 ) // –––––––––––––––––––––[ If broken, change color, // otherwise, make lines // 1 bar_index longer ]––––––––––––––––––––– getDir = array.get(dir, 0) if getDir == 0 getLineF = array.get(lnF, 0) getLine1 = linefill.get_line1(getLineF) getLine2 = linefill.get_line2(getLineF) // if close > top line -> change color -> lime , set dir to 1 if close > line.get_price (getLine1, bar_index ) linefill.set_color (getLineF, color.new(color.lime, 75)) array.set (dir , 0 , 1) else // if close < bottom line -> change color -> red , set dir to -1 if close < line.get_price(getLine2, bar_index ) linefill.set_color (getLineF, color.new(#FF0000 , 75)) array.set (dir , 0 , -1) // // notice the 'difference' and 'simularity' between 'extend lines' & 'none' if options == 'extend lines' line.set_x2 (getLine1, bar_index ) line.set_x2 (getLine2, bar_index ) plot( array.size(linefill.all), display = display.status_line)
Auto Fibo Multi Timeframe [Misu]
https://www.tradingview.com/script/G0CVkca5-Auto-Fibo-Multi-Timeframe-Misu/
Fontiramisu
https://www.tradingview.com/u/Fontiramisu/
662
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/ // © Misu //@version=5 indicator("Auto Fibo Multi Timeframe [Misu]", shorttitle="Auto Fibo Multi TF [Misu]", overlay = true, max_lines_count = 500, max_labels_count = 500) import Fontiramisu/fontilab/12 as fontilab // ] —————— Input Vars —————— [ timeframe = input.timeframe(defval = '240', group="Pivot Settings") leftBars = input.int(defval = 2, title = "Left Bars", minval = 1, group="Pivot Settings") rightBars = input.int(defval = 2, title = "Right Bars", minval = 1, group="Pivot Settings") // Fibo. isColorAll = input.bool(true, "", group="UI Settings", inline="color") colorAll = input.color(color.white, "Color All Lines ----", group="UI Settings", inline="color") rightOffset = input.int(20, "Label Offset Right", group="UI Settings", inline="offset") isfib0000 = input.bool(true, "", group="UI Settings", inline="0") nFib0000 = input.float(0, "", step=0.01, group="UI Settings", inline="0") colorFib0000 = input.color(color.white, "", group="UI Settings", inline="0") isfib0206 = input.bool(false, "", group="UI Settings", inline="0") nFib0206 = input.float(0.206, "", step=0.01, group="UI Settings", inline="0") colorFib0206 = input.color(color.white, "", group="UI Settings", inline="0") isfib0382 = input.bool(true, "", group="UI Settings", inline="0.382") nFib0382 = input.float(0.382, "", step=0.01, group="UI Settings", inline="0.382") colorFib0382 = input.color(color.white, "", group="UI Settings", inline="0.382") isfib0500 = input.bool(false, "", group="UI Settings", inline="0.382") nFib0500 = input.float(0.5, "", step=0.01, group="UI Settings", inline="0.382") colorFib0500 = input.color(color.white, "", group="UI Settings", inline="0.382") isfib0618 = input.bool(true, "", group="UI Settings", inline="0.618") nFib0618 = input.float(0.618, "", step=0.01, group="UI Settings", inline="0.618") colorFib0618 = input.color(color.white, "", group="UI Settings", inline="0.618") isfib0786 = input.bool(true, "", group="UI Settings", inline="0.618") nFib0786 = input.float(0.718, "", step=0.01, group="UI Settings", inline="0.618") colorFib0786 = input.color(color.white, "", group="UI Settings", inline="0.618") isfib1000 = input.bool(true, "", group="UI Settings", inline="1") nFib1000 = input.float(1, "", step=0.01, group="UI Settings", inline="1") colorFib1000 = input.color(color.white, "", group="UI Settings", inline="1") isfib1414 = input.bool(false, "", group="UI Settings", inline="1") nFib1414 = input.float(1.414, "", step=0.01, group="UI Settings", inline="1") colorFib1414 = input.color(color.white, "", group="UI Settings", inline="1") isfib1618 = input.bool(false, "", group="UI Settings", inline="1.618") nFib1618 = input.float(1.618, "", step=0.01, group="UI Settings", inline="1.618") colorFib1618 = input.color(color.white, "", group="UI Settings", inline="1.618") isfib2000 = input.bool(false, "", group="UI Settings", inline="1.618") nFib2000 = input.float(2, "", step=0.01, group="UI Settings", inline="1.618") colorFib2000 = input.color(color.white, "", group="UI Settings", inline="1.618") isfib2618 = input.bool(false, "", group="UI Settings", inline="2.618") nFib2618 = input.float(2.618, "", step=0.01, group="UI Settings", inline="2.618") colorFib2618 = input.color(color.white, "", group="UI Settings", inline="2.618") // ] —————— Vars —————— [ var fib0000 = close var fib0206 = close var fib0382 = close var fib0500 = close var fib0618 = close var fib0786 = close var fib1000 = close var fib1414 = close var fib1618 = close var fib2000 = close var fib2618 = close // ] —————— Find Dev Pivots —————— [ getMultiTfPivots()=> float ph = ta.pivothigh(leftBars, rightBars) float pl = ta.pivotlow(leftBars, rightBars) phBIndexS = ph ? time[rightBars] : na plBIndexS = pl ? time[rightBars] : na [ph, phBIndexS, pl, plBIndexS] // get if there if Pivot High/low and their start/end times [ph, phBIndexS, pl, plBIndexS] = request.security(syminfo.tickerid, timeframe, getMultiTfPivots(), lookahead = barmerge.lookahead_on) // ] —————— Fibs Handles —————— [ // Get last highs/lows. pivothigh = na(ph[1]) and ph ? ph : na pivotlow = na(pl[1]) and pl ? pl : na var isHighLast = true var curPivotP = 0. var lastPivotP = 0. var curPivotBi = 0 var lastPivotBi = 0 // Special case: where high & low detected at the same time. if not na(pivothigh) and not na(pivotlow) lastPivotP := isHighLast ? pl : ph curPivotP := isHighLast ? ph : pl lastPivotBi := isHighLast ? plBIndexS : phBIndexS curPivotBi := isHighLast ? phBIndexS : plBIndexS // All cases else isHighLast := not na(pivothigh) ? true : not na(pivotlow) ? false : isHighLast lastPivotP := not na(pivothigh) and not isHighLast[1] or not na(pivotlow) and isHighLast[1] ? curPivotP : lastPivotP curPivotP := not na(pivothigh) ? ph : not na(pivotlow) ? pl : curPivotP lastPivotBi := not na(pivothigh) and not isHighLast[1] or not na(pivotlow) and isHighLast[1] ? curPivotBi : lastPivotBi curPivotBi := not na(pivothigh) ? phBIndexS : not na(pivotlow) ? plBIndexS : curPivotBi // Logic fibo direction. fiboDirUp = isHighLast // Last Update Barindex. var barLastUpdate = 0 barLastUpdate := lastPivotBi // Calculate fibs levels. rangeD = isHighLast ? curPivotP - lastPivotP : lastPivotP - curPivotP fib0000 := fiboDirUp ? curPivotP - nFib0000 * rangeD : curPivotP + nFib0000 * rangeD fib0206 := fiboDirUp ? curPivotP - nFib0206 * rangeD : curPivotP + nFib0206 * rangeD fib0382 := fiboDirUp ? curPivotP - nFib0382 * rangeD : curPivotP + nFib0382 * rangeD fib0500 := fiboDirUp ? curPivotP - nFib0500 * rangeD : curPivotP + nFib0500 * rangeD fib0618 := fiboDirUp ? curPivotP - nFib0618 * rangeD : curPivotP + nFib0618 * rangeD fib0786 := fiboDirUp ? curPivotP - nFib0786 * rangeD : curPivotP + nFib0786 * rangeD fib1000 := fiboDirUp ? curPivotP - nFib1000 * rangeD : curPivotP + nFib1000 * rangeD fib1414 := fiboDirUp ? curPivotP - nFib1414 * rangeD : curPivotP + nFib1414 * rangeD fib1618 := fiboDirUp ? curPivotP - nFib1618 * rangeD : curPivotP + nFib1618 * rangeD fib2000 := fiboDirUp ? curPivotP - nFib2000 * rangeD : curPivotP + nFib2000 * rangeD fib2618 := fiboDirUp ? curPivotP - nFib2618 * rangeD : curPivotP + nFib2618 * rangeD // ] —————— Plot —————— [ var fib0000Line = line.new(0, low, bar_index, high) var fib0000Label = label.new(bar_index, low, text="Init") var fib0206Line = line.new(0, low, bar_index, high) var fib0206Label = label.new(bar_index, low, text="Init") var fib0382Line = line.new(0, low, bar_index, high) var fib0382Label = label.new(bar_index, low, text="Init") var fib0500Line = line.new(0, low, bar_index, high) var fib0500Label = label.new(bar_index, low, text="Init") var fib0618Line = line.new(0, low, bar_index, high) var fib0618Label = label.new(bar_index, low, text="Init") var fib0786Line = line.new(0, low, bar_index, high) var fib0786Label = label.new(bar_index, low, text="Init") var fib1000Line = line.new(0, low, bar_index, high) var fib1000Label = label.new(bar_index, low, text="Init") var fib1414Line = line.new(0, low, bar_index, high) var fib1414Label = label.new(bar_index, low, text="Init") var fib1618Line = line.new(0, low, bar_index, high) var fib1618Label = label.new(bar_index, low, text="Init") var fib2000Line = line.new(0, low, bar_index, high) var fib2000Label = label.new(bar_index, low, text="Init") var fib2618Line = line.new(0, low, bar_index, high) var fib2618Label = label.new(bar_index, low, text="Init") labelOffset = rightOffset if isfib0000 line.delete(fib0000Line) label.delete(fib0000Label) fib0000Line := line.new(barLastUpdate, fib0000, time, fib0000, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib0000, width=1) fib0000Label := label.new(x=bar_index + labelOffset, y = fib0000, xloc=xloc.bar_index, text=str.tostring(nFib0000), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0000, textalign=text.align_center) if isfib0206 line.delete(fib0206Line) label.delete(fib0206Label) fib0206Line := line.new(barLastUpdate, fib0206, time, fib0206, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib0206, width=1) fib0206Label := label.new(x=bar_index + labelOffset, y = fib0206, xloc=xloc.bar_index, text=str.tostring(nFib0206), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0206, textalign=text.align_center) if isfib0382 line.delete(fib0382Line) label.delete(fib0382Label) fib0382Line := line.new(barLastUpdate, fib0382, time, fib0382, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib0382, width=1) fib0382Label := label.new(x=bar_index + labelOffset, y = fib0382, xloc=xloc.bar_index, text=str.tostring(nFib0382), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0382, textalign=text.align_center) if isfib0500 line.delete(fib0500Line) label.delete(fib0500Label) fib0500Line := line.new(barLastUpdate, fib0500, time, fib0500, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib0500, width=1) fib0500Label := label.new(x=bar_index + labelOffset, y = fib0500, xloc=xloc.bar_index, text=str.tostring(nFib0500), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0500, textalign=text.align_center) if isfib0618 line.delete(fib0618Line) label.delete(fib0618Label) fib0618Line := line.new(barLastUpdate, fib0618, time, fib0618, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib0618, width=1) fib0618Label := label.new(x=bar_index + labelOffset, y = fib0618, xloc=xloc.bar_index, text=str.tostring(nFib0618), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0618, textalign=text.align_center) if isfib0786 line.delete(fib0786Line) label.delete(fib0786Label) fib0786Line := line.new(barLastUpdate, fib0786, time, fib0786, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib0786, width=1) fib0786Label := label.new(x=bar_index + labelOffset, y = fib0786, xloc=xloc.bar_index, text=str.tostring(nFib0786), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib0786, textalign=text.align_center) if isfib1000 line.delete(fib1000Line) label.delete(fib1000Label) fib1000Line := line.new(barLastUpdate, fib1000, time, fib1000, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib1000, width=1) fib1000Label := label.new(x=bar_index + labelOffset, y = fib1000, xloc=xloc.bar_index, text=str.tostring(nFib1000), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib1000, textalign=text.align_center) if isfib1414 line.delete(fib1414Line) label.delete(fib1414Label) fib1414Line := line.new(barLastUpdate, fib1414, time, fib1414, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib1414, width=1) fib1414Label := label.new(x=bar_index + labelOffset, y = fib1414, xloc=xloc.bar_index, text=str.tostring(nFib1414), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib1414, textalign=text.align_center) if isfib1618 line.delete(fib1618Line) label.delete(fib1618Label) fib1618Line := line.new(barLastUpdate, fib1618, time, fib1618, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib1618, width=1) fib1618Label := label.new(x=bar_index + labelOffset, y = fib1618, xloc=xloc.bar_index, text=str.tostring(nFib1618), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib1618, textalign=text.align_center) if isfib2000 line.delete(fib2000Line) label.delete(fib2000Label) fib2000Line := line.new(barLastUpdate, fib2000, time, fib2000, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib2000, width=1) fib2000Label := label.new(x=bar_index + labelOffset, y = fib2000, xloc=xloc.bar_index, text=str.tostring(nFib2000), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib2000, textalign=text.align_center) if isfib2618 line.delete(fib2618Line) label.delete(fib2618Label) fib2618Line := line.new(barLastUpdate, fib2618, time, fib2618, xloc=xloc.bar_time, color=isColorAll ? colorAll : colorFib2618, width=1) fib2618Label := label.new(x=bar_index + labelOffset, y = fib2618, xloc=xloc.bar_index, text=str.tostring(nFib2618), style=label.style_none, size=size.small, textcolor=isColorAll ? colorAll : colorFib2618, textalign=text.align_center) // linefill.new(fib0786Line, fib1000Line, color.blue) // ]
Relatively Good Adviser
https://www.tradingview.com/script/xomUtcVw-Relatively-Good-Adviser/
JOJOGLO
https://www.tradingview.com/u/JOJOGLO/
47
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/ // © JOJOGLO //@version=4 study("Relatively Good Adviser", "RGA", overlay=true) //-----Chart-Colors-----// upColor = input(color.rgb(0, 230, 118,5), title = "upColor") dnColor = input(color.rgb(255, 82, 82,5), title ="dnColor") sdColor = input(color.rgb(223, 234, 120,8), title ="sdColor") rsiColor = input(color.rgb(223, 234, 120,8), title ="sdColor") //input(color.rgb(54, 58, 69,5), title = "rsiColor") maColor = input(color.rgb(134, 174, 221,55), title = "maColor") //-----Smoothed Moving Average-----// getSMMA(len) => smma = 0.0 smma := na(smma[1]) ? sma(hlc3, len) : (smma[1] * (len - 1) + hlc3) / len smma smma = getSMMA(3) //-----Finger-Weighted-Price-----// upPrice = (high + high + low) / 3 dnPrice = (low + low + high) / 3 //-----RSI-----// rsiLine = rsi(close, 7) //-----RSI-LOGIC-----// signal = rsiLine > 50 ? "buy" : rsiLine <= 50 ? "sell" : "none" //-----FWA-LOGIC----// signal := signal == "buy" and smma > upPrice or signal == "sell" and smma < dnPrice ? "none" : signal //-----RSI-BAR-FLIP-----// signal := rsiLine[1] <= 50 and rsiLine > 50 or rsiLine[1] > 50 and rsiLine <= 50 ? "burnt" : signal //-----RSI-LIMITER-----// signal := signal[2] == "burnt" and signal == "burnt" or signal[1] == "burnt" and signal == "burnt" ? "none" : signal limCon = signal == "burnt" ? true : false //-----RSI-LAW-----// signal := signal[2] == "burnt" and signal == "none" and close > smma and smma < upPrice ? "buy" : signal signal := signal[2] == "burnt" and signal == "none" and close < smma and smma > dnPrice ? "sell" : signal signal := signal[1] == "burnt" and signal == "none" and close > smma and smma < upPrice ? "buy" : signal signal := signal[1] == "burnt" and signal == "none" and close < smma and smma > dnPrice ? "sell" : signal //-----Color-&-Plot-----// palette = signal == "buy" ? upColor :signal == "sell" ? dnColor : signal == "burnt" ? rsiColor : signal == "test" ? color.fuchsia : sdColor plotbar(open, high, low, close, color=palette) plot(smma, linewidth=1, color = maColor) //-----Show-RSI-Flips-----// upCon1 = rsiLine[1] <= 50 and rsiLine > 50 and limCon dnCon1 = rsiLine[1] > 50 and rsiLine <= 50 and limCon upCon2 = rsiLine[1] <= 50 and rsiLine > 50 and not limCon dnCon2 = rsiLine[1] > 50 and rsiLine <= 50 and not limCon upClr1 = color.rgb(0, 230, 118,5) dnClr1 = color.rgb(255, 82, 82,5) upClr2 = color.rgb(223, 234, 120,64) dnClr2 = color.rgb(223, 234, 120,64) plotshape(upCon1, style = shape.triangleup, location = location.abovebar, color = upClr1 , transp = 92) plotshape(dnCon1, style = shape.triangledown, location = location.belowbar, color = dnClr1 , transp = 92) plotshape(upCon2, style = shape.triangleup, location = location.abovebar, color = upClr2 , transp = 92) plotshape(dnCon2, style = shape.triangledown, location = location.belowbar, color = dnClr2 , transp = 92)
Simple Sessions - [TTF]
https://www.tradingview.com/script/hTlCjlYV-Simple-Sessions-TTF/
TheTrdFloor
https://www.tradingview.com/u/TheTrdFloor/
970
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/ // © TheTrdFloor // // Over the years of working with people eager to learn the art and science of day-trading, one of the most common challenges // new traders struggle with is visualizing trading sessions for various parts of the world. They generally get the idea of // what they are and how they work - the biggest struggle is really around the time-conversion elements. // // Most people are pretty adept at understanding the session window for the session closest to them (e.g. EU residents can easily grasp the EU // (London/Frankfurt) sessions), but have a harder time translating foreign sessions (e.g. the US session) into their local time // easily and consistently. While there are a plethora of "sessions indicators" in the wild here on TradingView, most of them // don't really solve this problem for users as they still require the user to do manual time-conversion to convert the sessions // into their local time and don't account for regional differences like daylight savings time shifts, as well as equatorial differences in seasons. // // To help alleviate this issue (as well as automatically account for regional time shifts due to Daylight // Savings Time), by building those session windows directly into this indicator (a.k.a. hard-coding) using the most commonly-accepted // trading time windows for each included region. This is by no means ideal, but we feel it's a much-needed first-step to assist newcomers // with forex sessions. // // As a final addition, we have also added a single user-customizable session that they can configure to also reference their local timezone. // We feel this adds a nice bit of additional freedom for people that are working a full-time job and want to dip into trading outside of work. // In this way, they can set the custom session to their personal available trading window to help with backtesting strategies that are likely // not tested to that degree of customization to help ensure that they remain profitable. // //@version=5 indicator(title='Simple Sessions - [TTF]', shorttitle='Simple Sessions', overlay=true, max_labels_count=500) /////////////////////////////////////////////// // // Debugging/Troubleshooting Extras... // /////////////////////////////////////////////// // // This is very helpful when doing dev work on this as it will print a table showing some of the raw data/calculations on the chart, // but it's not needed for normal operation. Therefore, we're commenting out the input and forcing debug-mode to be disabled... // // enableDebug = input.bool(defval=true, title="Enable Debug Mode", group="Debug") enableDebug = false // // Table for "debug logging" output... // t = table.new(position=position.top_right, columns=2, rows=25, frame_color=color.yellow, border_color=color.yellow, frame_width=3, border_width=2) // if (enableDebug) table.cell(t, column=0, row=0, text="syminfo.timezone", text_color=color.lime) table.cell(t, column=1, row=0, text=syminfo.timezone, text_color=color.lime) table.cell(t, column=0, row=4, text="timeframe.isintraday", text_color=color.lime) table.cell(t, column=1, row=4, text=str.tostring(timeframe.isintraday), text_color=color.lime) table.cell(t, column=0, row=5, text="bar time", text_color=color.lime) table.cell(t, column=1, row=5, text=str.format("{0,date,MM-dd-YYYY HH:mm:ss (zz)}", time), text_color=color.lime) // // /////////////////////////////////////////////// // // Standard/Main Code Starts Here... // /////////////////////////////////////////////// ///////////////////////////////////////////// // // First, let's handle our user input settings... Each session will have 3 configs... // 1. A toggle to enable/disable the session display // 2. A color-picker to control the session fill color (since we can't use the Style tab for that) // 3. 2 session inputs to define the start and end time // showUSSession = input.bool(title="US (New York) Session", defval=true, group="US Session Display Settings", inline="us1") usSessionColor = input.color(title="", defval=color.rgb(255, 150, 150,85), group="US Session Display Settings", inline="us1", tooltip="Check the box to " + "enable the session highlight for the US session.\n\n" + "If you wish to change the default session highlight color, you may do so here as well.") usSessInput = input.session(title="Local Time (America/New_York)", defval="0800-1600", group="US Session Display Settings") // showEUSession = input.bool(title="Europe (London) Session", defval=true, group="EU Session Display Settings", inline="eu") euSessionColor = input.color(title="", defval=color.rgb(150, 255, 150,85), group="EU Session Display Settings", inline="eu", tooltip="Check the box to " + "enable the session highlight for the EU session.\n\n" + "If you wish to change the default session highlight color, you may do so here as well.") euSessInput = input.session(title="Local Time (Europe/London)", defval="0800-1700", group="EU Session Display Settings") // showMixedSession = input.bool(title="Mixed (US/Europe) Session", defval=true, group="EU/US Mixed Session Display Settings", inline="mix") mixedSessionColor = input.color(title="", defval=color.rgb(150, 150, 255,85), group="EU/US Mixed Session Display Settings", inline="mix", tooltip="Check the box to " + "enable the session highlight for the US/EU Mixed session.\n\n" + "If you wish to change the default session highlight color, you may do so here as well.\n\n" + "Note: This session is the calculated overlap of the US and EU sessions above, so there is no custom time window for this session") // // Per feedback from testers, permanently hiding the AUS session... showAUSession = false auSessionColor = color.rgb(0, 0, 0, 100) auSessInput = "0000-0000" //showAUSession = input.bool(title="Australia (Sydney) Session", defval=false, group="AU Session Display Settings", inline="au") //auSessionColor = input.color(title="", defval=color.rgb(255, 150, 255,85), group="AU Session Display Settings", inline="au", tooltip="Check the box to " + // "enable the session highlight for the Australia (Sydney) session.\n\n" + // "If you wish to change the default session highlight color, you may do so here as well.") //auSessInput = input.session(title="Local Time (Australia/Sydney)", defval="0800-1600", group="AU Session Display Settings") // showJPSession = input.bool(title="Asia/Japan (Tokyo) Session", defval=true, group="JP Session Display Settings", inline="jp") jpSessionColor = input.color(title="", defval=color.rgb(91, 156, 246, 75), group="JP Session Display Settings", inline="jp", tooltip="Check the box to " + "enable the session highlight for the Tokyo/Asia/Japan session.\n\n" + "If you wish to change the default session highlight color, you may do so here as well.") jpSessInput = input.session(title="Local Time (Asia/Tokyo)", defval="0800-1600", group="JP Session Display Settings") // // // // As an added bonus (and for more advanced users that have a personalized trading window), we'll also add in the ability for users to define their own "personal trading session" // showCustomSession = input.bool(title="User-Defined Custom Session", defval=false, group="User-Defined (Custom) Session", inline="cust") custSessionColor = input.color(title="", defval=color.rgb(125, 125, 125, 85), group="User-Defined (Custom) Session", inline="cust", tooltip="If checked, will display an additional session in the selected color.\n\n" + "The settings for configuring this custom session are all below.") custSessionSession = input.session(defval="0800-1600", title="Custom Session Time Window", group="User-Defined (Custom) Session", tooltip="This setting is to define a custom time window/session along with the time zone setting below and the Session Days Of The Week above.") custSessTimezone = input.string(defval="Etc/UTC", title="Custom Session Timezone", options=["UTC", "America/Los_Angeles", "America/Phoenix", "America/Vancouver", "America/El_Salvador", "America/Bogota", "America/Chicago", "America/New_York", "America/Toronto", "America/Argentina/Buenos_Aires", "America/Sao_Paulo", "Etc/UTC", "GMT", "Europe/London", "Europe/Berlin", "Europe/Madrid", "Europe/Paris", "Europe/Warsaw", "Europe/Athens", "Europe/Moscow", "Asia/Tehran", "Asia/Dubai", "Asia/Ashkhabad", "Asia/Kolkata", "Asia/Almaty", "Asia/Bangkok", "Asia/Hong_Kong", "Asia/Shanghai", "Asia/Singapore", "Asia/Taipei", "Asia/Seoul", "Asia/Tokyo", "Australia/ACT", "Australia/Adelaide", "Australia/Brisbane", "Australia/Sydney", "Pacific/Auckland", "Pacific/Fakaofo", "Pacific/Chatham", "Pacific/Honolulu"], group="User-Defined (Custom) Session", tooltip="This setting controls the reference timezone for the custom session window configured above.\n\n" + "If the time window above is configured for your personal timezone, then this should be your personal timezone as well.") // // Now that we have the custom session inputs, we need to create the proper custom session string with the DOW selections... // // *** This block handles the session day-of-week selection *** // // incSun = input.bool(defval=false, title="Sunday", group="Session Days of the Week") incMon = input.bool(defval=true, title="Monday", group="Session Days of the Week") incTue = input.bool(defval=true, title="Tuesday", group="Session Days of the Week") incWed = input.bool(defval=true, title="Wednesday", group="Session Days of the Week") incThur = input.bool(defval=true, title="Thursday", group="Session Days of the Week") incFri = input.bool(defval=true, title="Friday", group="Session Days of the Week") incSat = input.bool(defval=false, title="Saturday", group="Session Days of the Week") // // *** This block converts the user-inputs above into the "days of the week" portion of a session string *** // // sessionDays = "" if (incSun) sessionDays := sessionDays + "1" if (incMon) sessionDays := sessionDays + "2" if (incTue) sessionDays := sessionDays + "3" if (incWed) sessionDays := sessionDays + "4" if (incThur) sessionDays := sessionDays + "5" if (incFri) sessionDays := sessionDays + "6" if (incSat) sessionDays := sessionDays + "7" /////////////////////////////////////////////// // // // US Eastern (NY - America/New_York) // usSession = usSessInput + ":" + sessionDays // if (enableDebug) table.cell(t, column=0, row=7, text='usSession', text_color=color.lime) table.cell(t, column=1, row=7, text=str.tostring(usSession), text_color=color.lime) /////////////////////////////////////////////// // // // UK (London - Europe/London) - We're adding an hour to this to also cover the Frankfurt session // euSession = euSessInput + ":" + sessionDays // if (enableDebug) table.cell(t, column=0, row=8, text='euSession', text_color=color.lime) table.cell(t, column=1, row=8, text=str.tostring(euSession), text_color=color.lime) /////////////////////////////////////////////// // // // AU (Sydney - Australia/Sydney) // auSession = auSessInput + ":" + sessionDays // if (enableDebug) table.cell(t, column=0, row=9, text='auSession', text_color=color.lime) table.cell(t, column=1, row=9, text=str.tostring(auSession), text_color=color.lime) /////////////////////////////////////////////// // // // JP (Tokyo - Asia/Tokyo) // jpSession = jpSessInput + ":" + sessionDays // if (enableDebug) table.cell(t, column=0, row=10, text='jpSession', text_color=color.lime) table.cell(t, column=1, row=10, text=str.tostring(jpSession), text_color=color.lime) ///////////////////////////////////////////// // // Now that we have our sessions defined, we can build some flag variables to easily tell // if the current bar time falls within our sessions... // // Start with a helper function to handle the logical evaluation... isInSession(session, ref_timezone) => ret = false // The 'time' function will return 'na' if the test_time is not in the session window, // and will return a Unix timestamp of the bar-time of test_time if it is, so we'll // use the 'na' function to check if the time function returns "na" and effectively // "flip" the value (if the test-time returns "na" (not in session), the "na" function // will return "true", and we instead want this function to return "false"). temp = time(timeframe.period, session, ref_timezone) ret := na(temp) ? false : true ret isUSSession = isInSession(usSession, "America/New_York") if (enableDebug) table.cell(t, column=0, row=11, text='isUSSession', text_color=color.lime) table.cell(t, column=1, row=11, text=str.tostring(isUSSession), text_color=color.lime) // isEUSession = isInSession(euSession, "Europe/London") if (enableDebug) table.cell(t, column=0, row=12, text='isEUSession', text_color=color.lime) table.cell(t, column=1, row=12, text=str.tostring(isEUSession), text_color=color.lime) // isAUSession = isInSession(auSession, "Australia/Sydney") if (enableDebug) table.cell(t, column=0, row=13, text='isAUSession', text_color=color.lime) table.cell(t, column=1, row=13, text=str.tostring(isAUSession), text_color=color.lime) // isJPSession = isInSession(jpSession, "Asia/Tokyo") if (enableDebug) table.cell(t, column=0, row=14, text='isJPSession', text_color=color.lime) table.cell(t, column=1, row=14, text=str.tostring(isJPSession), text_color=color.lime) // isUSEUMixedSession = isUSSession and isEUSession ? true : false if (enableDebug) table.cell(t, column=0, row=15, text='isUSEUMixedSession', text_color=color.lime) table.cell(t, column=1, row=15, text=str.tostring(isUSEUMixedSession), text_color=color.lime) custSession = custSessionSession + ":" + sessionDays if (enableDebug) table.cell(t, column=0, row=16, text='custSession', text_color=color.lime) table.cell(t, column=1, row=16, text=str.tostring(custSession), text_color=color.lime) isCustomSession = isInSession(custSession, custSessTimezone) if (enableDebug) table.cell(t, column=0, row=17, text='isCustomSession', text_color=color.lime) table.cell(t, column=1, row=17, text=str.tostring(isCustomSession), text_color=color.lime) // // Since we can't apply backgrounds inside a conditional like an 'if' block, we'll have // to use the 'color' arg and alter the transparency to 100 when it's not in that particular session. // // To make this a bit easier, we'll define a 'null' color (black with 100% opacity). nullColor = color.rgb(0, 0, 0, 100) // bgcolor(title="US Session", color=showUSSession ? isUSSession ? usSessionColor : nullColor : nullColor, editable=false) bgcolor(title="EU Session", color=showEUSession ? isEUSession ? euSessionColor : nullColor : nullColor, editable=false) bgcolor(title="AU Session", color=showAUSession ? isAUSession ? auSessionColor : nullColor : nullColor, editable=false) bgcolor(title="JP Session", color=showJPSession ? isJPSession ? jpSessionColor : nullColor : nullColor, editable=false) // Since TV by default draws later objects on top of previous ones when there's an overlap, draw the mixed session last bgcolor(title="US/EU Mixed Session", color=showMixedSession ? isUSEUMixedSession ? mixedSessionColor : nullColor : nullColor, editable=false) // And our custom session last (see above for layer precedence) bgcolor(title="User-Defined Session", color=showCustomSession ? isCustomSession ? custSessionColor : nullColor : nullColor, editable=false)
Quarter Theory Levels
https://www.tradingview.com/script/3VPI5tMB-Quarter-Theory-Levels/
melodicfish
https://www.tradingview.com/u/melodicfish/
128
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/ // © melodicfish //@version=5 indicator("Quarter Theory Levels",overlay = true,max_labels_count = 110,max_lines_count = 110) incrementVal=input.float(defval=1, title="Unit Place Rounding Value/ Major Point Line Spacing ", tooltip = " The Unit Place that a number will be rounded and distance between Major Point levels. Example Value setting of 100 and a price of 225.00 would result in a line level value of 200.00; Where a price of 265.00 would result in a line level value of 300 with the same value setting of 100. If you do not see the lines reduce the Value by one unit place( 1000.0 reduce to 100.0 1.0 reduce to 0.1) ",confirm = true) lQty=input.int(defval=2,minval=1,maxval=15, title="Line Amount",tooltip = "Each Line Amount increase will add a line level above and below baseline level; Baseline = line nearest to price) ") offset=input.int(defval=100,minval=0, maxval=490,step=10, title="Line Price Horizontal Offset",inline = "a") textCol=input.color(defval = color.white,title="Price Label Text Color",tooltip = "Use Horizontal Offset to adjust the X position of the price labels. To hide price labels disable Labels on the style tab",inline = "a") showhalf= input.bool(true,title="Show 1/2 Line levels ",inline = "a2") showquarter= input.bool(true,title="Show 1/4 Line levels ",inline = "a2") belowColor=input.color(defval = #2962ff,title="Line Color Below price: ",inline="b") belowColor2=input.color(defval = #2998ff,title=" 1/2: ",inline="b") belowColor3=input.color(defval = #29e1ff,title=" 1/4: ",inline="b") aboveColor=input.color(defval = #ff7b00,title="Line Color Above price: ",inline="b2") aboveColor2=input.color(defval = #ffb700,title=" 1/2: ",inline="b2") aboveColor3=input.color(defval = #ffea00,title=" 1/4: ",inline="b2") ext1=input.string(defval = "Both",options = ["To Right","Both"],title="Extend lines: ", inline="c") ext2=input.string(defval = "To Right",options = ["To Right","Both"],title="1/2: ", inline="c") ext3=input.string(defval = "To Right",options = ["To Right","Both"],title="1/4: ", inline="c") l1Wit=input.int(5,title="Line Width: ", inline="d") l2Wit=input.int(2,title=" 1/2: ",inline="d") l3Wit=input.int(1,title=" 1/4: ",inline="d") style1=input.string(defval = "Solid",options = ["Solid","Dotted","Dashed"],title=" Line Style ", inline="e") style2=input.string(defval = "Dotted",options = ["Solid","Dotted","Dashed"],title=" 1/2: ", inline="e") style3=input.string(defval = "Dotted",options = ["Solid","Dotted","Dashed"],title=" 1/4: ", inline="e") float iv= incrementVal lQty:=lQty+1 var lines=array.new_line(lQty*2) var labels=array.new_label(lQty*2) var lines_half=array.new_line(lQty*2) var labels_half=array.new_label(lQty*2) var lines_quarter=array.new_line(lQty*2) var labels_quarter=array.new_label(lQty*2) var line baseLine=na RoundValue(value) => math.round(value / iv) * iv baseVal=RoundValue(close) if barstate.isconfirmed and baseVal!= baseVal[1] for i = 0 to (lQty*2) - 1 line.delete(array.get(lines,i)) label.delete(array.get(labels,i)) line.delete(array.get(lines_half,i)) label.delete(array.get(labels_half,i)) line.delete(array.get(lines_quarter,i)) label.delete(array.get(labels_quarter,i)) lines:=array.new_line(lQty*2) labels:=array.new_label(lQty*2) lines_half:=array.new_line(lQty*2) labels_half:=array.new_label(lQty*2) lines_quarter:=array.new_line(lQty*2) labels_quarter:=array.new_label(lQty*2) for j = 0 to lQty - 1 newLine=line.new(bar_index,baseVal+(j*iv),bar_index+1,baseVal+(j*iv),extend=ext1=="Both"?extend.both:extend.right,color=close>baseVal+(j*iv)?belowColor:aboveColor,style=style1=="Dotted"?line.style_dotted:style1=="Dashed"?line.style_dashed:line.style_solid,width=l1Wit) newLabel=label.new(bar_index+1+offset,baseVal+(j*iv),text=str.tostring(baseVal+(j*iv)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines,j,newLine) array.insert(labels,j,newLabel) halfVal=(iv/2) if showhalf==true newLine_half=line.new(bar_index,baseVal+halfVal+(j*(iv)),bar_index+1,baseVal+halfVal+(j*iv),extend=ext2=="Both"?extend.both:extend.right,color=aboveColor2,style=style2=="Dotted"?line.style_dotted:style2=="Dashed"?line.style_dashed:line.style_solid,width=l2Wit) //ext=="Both"?extend.both:extend.right newLabel_half=label.new(bar_index+1+offset,baseVal+halfVal+(j*iv),text=str.tostring(baseVal+halfVal+(j*iv)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines_half,j,newLine_half) array.insert(labels_half,j,newLabel_half) quarterVal=(halfVal/2) if showquarter==true newLine_quarter=line.new(bar_index,baseVal+quarterVal+(j*(halfVal)),bar_index+1,baseVal+quarterVal+(j*halfVal),extend=ext3=="Both"?extend.both:extend.right,color=aboveColor3,style=style3=="Dotted"?line.style_dotted:style3=="Dashed"?line.style_dashed:line.style_solid,width=l3Wit) newLabel_quarter=label.new(bar_index+1+offset,baseVal+quarterVal+(j*halfVal),text=str.tostring(baseVal+quarterVal+(j*halfVal)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines_quarter,j,newLine_quarter) array.insert(labels_quarter,j,newLabel_quarter) for k = 0 to lQty - 1 if k!=0 newLine=line.new(bar_index,baseVal-(k*iv),bar_index+1,baseVal-(k*iv),extend=ext1=="Both"?extend.both:extend.right,color=belowColor,style=style1=="Dotted"?line.style_dotted:style1=="Dashed"?line.style_dashed:line.style_solid,width=l1Wit) newLabel=label.new(bar_index+1+offset,baseVal-(k*iv),text=str.tostring(baseVal-(k*iv)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines,k+lQty,newLine) array.insert(labels,k+lQty,newLabel) halfVal=(iv/2) if showhalf==true newLine_half=line.new(bar_index,baseVal-halfVal-(k*(iv)),bar_index+1,baseVal-halfVal-(k*iv),extend=ext2=="Both"?extend.both:extend.right,color=belowColor2,style=style2=="Dotted"?line.style_dotted:style2=="Dashed"?line.style_dashed:line.style_solid,width=l2Wit) newLabel_half=label.new(bar_index+1+offset,baseVal-halfVal-(k*iv),text=str.tostring(baseVal-halfVal-(k*iv)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines_half,k+lQty,newLine_half) array.insert(labels_half,k+lQty,newLabel_half) quarterVal=(halfVal/2) if showquarter==true newLine_quarter=line.new(bar_index,baseVal-quarterVal-(k*(halfVal)),bar_index+1,baseVal-quarterVal-(k*halfVal),extend=ext3=="Both"?extend.both:extend.right,color=belowColor3,style=style3=="Dotted"?line.style_dotted:style3=="Dashed"?line.style_dashed:line.style_solid,width=l3Wit) newLabel_quarter=label.new(bar_index+1+offset,baseVal-quarterVal-(k*halfVal),text=str.tostring(baseVal-quarterVal-(k*halfVal)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines_quarter,k+lQty,newLine_quarter) array.insert(labels_quarter,k+lQty,newLabel_quarter) else if baseVal== baseVal[1] for l=0 to array.size(lines)-1 line.set_color(array.get(lines,l),color=close>line.get_y1(array.get(lines,l))?belowColor:aboveColor) if showhalf==true for m=0 to array.size(lines)-1 line.set_color(array.get(lines_half,m),color=close>line.get_y1(array.get(lines_half,m))?belowColor2:aboveColor2) if showquarter==true for n=0 to array.size(lines)-1 line.set_color(array.get(lines_quarter,n),color=close>line.get_y1(array.get(lines_quarter,n))?belowColor3:aboveColor3) for o = 0 to (lQty*2)-1 label.set_x(array.get(labels,o),bar_index+1+offset) label.set_x(array.get(labels_half,o),bar_index+1+offset) label.set_x(array.get(labels_quarter,o),bar_index+1+offset)
Price Correction to fix data manipulation and mispricing
https://www.tradingview.com/script/RGa1yeCB-Price-Correction-to-fix-data-manipulation-and-mispricing/
Techotomy
https://www.tradingview.com/u/Techotomy/
42
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/ // © Techotomy //@version=5 indicator(title="Price Correction to fix data manipulation and mispricing", shorttitle='Price Correction', overlay=true) preset_tooltip = "Select this option to automatically correct mispricing issues specific to the SPY and NYA" intraday_tooltip = "Use intraday OHLC data to build daily OHLC candles" timeframe_tooltip = "Daily Price Correction relies on intraday data, which is limited by TradingView. Increasing the timeframe increases the number of historical daily bars that can be corrected, but may hinder price correction accuracy for symbols that have intraday mispricing as well (e.g., NYA)" start_tooltip = "Select this option to see the start date of Price Correction. If more historical price bars need to be corrected, increase the intraday time frame." deviation_tooltip = "Select this option to show daily OHLC bars that differ from intraday data by the specified percent difference. Bars or candles that deviate are painted with the specified discrepancy color" use_presets = input.bool(defval=true, title='Use Presets', group='Price Correction Settings', tooltip=preset_tooltip) use_intraday_opens = input.bool(defval=false, title='Use Intraday Open', group='Price Correction Settings', tooltip=intraday_tooltip) use_intraday_highs = input.bool(defval=false, title='Use Intraday High', group='Price Correction Settings', tooltip=intraday_tooltip) use_intraday_lows = input.bool(defval=false, title='Use Intraday Low', group='Price Correction Settings', tooltip=intraday_tooltip) use_intraday_closes = input.bool(defval=false, title='Use Intraday Close', group='Price Correction Settings', tooltip=intraday_tooltip) show_start_date = input.bool(defval=false, title='Show Start Date', group='Price Correction Settings', tooltip=start_tooltip) ltf = input.int(defval=1, title='Intraday Time Frame', minval=1, group='Price Correction Settings', tooltip=timeframe_tooltip) lower_tf = str.tostring(ltf) chart_type = input.string(defval='Candle', title='Chart Type', options=['Candle', 'Bar'], group='Chart Settings') body_color_up = input.color(defval=#26a69a, inline='body', title='Body Color       Up', group='Chart Settings') body_color_dn = input.color(defval=#ef5350, inline='body', title='Down', group='Chart Settings') wick_color_up = input.color(defval=#26a69a, inline='wick', title='Wick Color       Up', group='Chart Settings') wick_color_dn = input.color(defval=#ef5350, inline='wick', title='Down', group='Chart Settings') border_color_up = input.color(defval=#26a69a, inline='border', title='Border Color     Up', group='Chart Settings') border_color_dn = input.color(defval=#ef5350, inline='border', title='Down', group='Chart Settings') close_based = input.bool(defval=false, title='Color by previous close', group='Chart Settings') use_dev = input.bool(defval=false, title='Show Discrepancies (On/Off)', group='Discrepancy Reporting', tooltip=deviation_tooltip) thresh_dev = input.float(defval=0.1, title='Percent Discrepancy', group='Discrepancy Reporting', tooltip=deviation_tooltip) color_dev = input.color(defval=color.blue, title='Discrepancy Color', group='Discrepancy Reporting', tooltip=deviation_tooltip) updn_color(is_deviation, open_0, close_0, close_1, color_up, color_dn, color_dev, close_based) => _color = color_dn if is_deviation _color := color_dev else if (close_0 >= close_1 and close_based) or (close_0 >= open_0 and not close_based) _color := color_up _color percent_difference(v0, v1) => 100 * math.abs(v0 - v1) / v0 [intraday_opens, intraday_highs, intraday_lows, intraday_closes] = request.security_lower_tf( syminfo.ticker, lower_tf, [open, high, low, close]) [daily_open, daily_high, daily_low, daily_close] = request.security( syminfo.ticker, "D", [open, high, low, close]) _open = open _high = high _low = low _close = close var start_correction = false if array.size(intraday_opens) > 0 and not start_correction and show_start_date label.new(bar_index, high, "Start\nPrice\nCorrection", color=color_dev) start_correction := true is_deviation = false if timeframe.isdaily and array.size(intraday_opens) > 0 intraday_open = array.get(intraday_opens, 0) intraday_high = array.max(intraday_highs) intraday_low = array.min(intraday_lows) intraday_close = array.get(intraday_closes, array.size(intraday_closes)-1) if use_dev and syminfo.ticker != "NYA" if percent_difference(open, intraday_open) >= thresh_dev or percent_difference(high, intraday_high) >= thresh_dev or percent_difference(low, intraday_low) >= thresh_dev or percent_difference(close, intraday_close) >= thresh_dev is_deviation := true if use_intraday_opens _open := intraday_open if use_intraday_highs _high := intraday_high if use_intraday_lows _low := intraday_low if use_intraday_closes _close := intraday_close if use_presets if syminfo.ticker == "SPY" _low := intraday_low _high := intraday_high else if syminfo.ticker == "NYA" if math.round(daily_close[1]) == math.round(array.get(intraday_opens, 0)) array.remove(intraday_opens, 0) array.remove(intraday_lows, 0) array.remove(intraday_highs, 0) _open := array.get(intraday_opens, 0) _low := array.min(intraday_lows) _high := array.max(intraday_highs) if use_dev if percent_difference(open, array.get(intraday_opens, 0)) >= thresh_dev or percent_difference(high, array.max(intraday_highs)) >= thresh_dev or percent_difference(low, array.min(intraday_lows)) >= thresh_dev or percent_difference(close, intraday_close) >= thresh_dev is_deviation := true if timeframe.isintraday if use_presets if syminfo.ticker == "NYA" t = time("D", session=session.regular) if not na(t) and (na(t[1]) or t > t[1]) if math.round(daily_close[0]) == math.round(open) _open := _close _high := _close _low := _close plotcandle(chart_type == "Candle" ? _open : na, _high, _low, _close, color=updn_color( is_deviation, _open[0], _close[0], _close[1], body_color_up, body_color_dn, color_dev, close_based), bordercolor=updn_color( is_deviation, _open[0], _close[0], _close[1], border_color_up, border_color_dn, color_dev, close_based), wickcolor=updn_color( is_deviation, _open[0], _close[0], _close[1], wick_color_up, wick_color_dn, color_dev, close_based), display=display.all - display.price_scale, editable=false) plotbar(chart_type == "Bar" ? _open : na, _high, _low, _close, color=updn_color( is_deviation, _open[0], _close[0], _close[1], body_color_up, body_color_dn, color_dev, close_based), display=display.all - display.price_scale, editable=false)
Swing Ribbon
https://www.tradingview.com/script/5KZy279l-Swing-Ribbon/
Electrified
https://www.tradingview.com/u/Electrified/
347
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/ // © Electrified //@version=5 //@description=The fast and slow moving average combine to help visualize the current trend and potential changes in trend. indicator("Swing Ribbon", overlay = true) // - Is used for both fast and slow moving averages. // - Allows for selecting a moving average by a string parameter instead of having to define a switch locally. import Electrified/MovingAverages/10 as MA // - Time.spanToIntLen is used repeatedly here to simplify getting the number bars for a given timeframe. // - If "Minutes" or "Days" are selected, changing the timeframe on the chart, this indicator should still look about the same. import Electrified/Time/7 // Constants SMA = 'SMA', EMA = 'EMA', WMA = 'WMA', VWMA = 'VWMA', VAWMA = 'VAWMA' MINUTES = "Minutes", DAYS = "Days", BARS = "Bars" MOVING_AVERAGES = "Moving Averages" FAST = "Fast", SLOW = "Slow" // HLCC4 is typically very near the close. This is just a default. source = input.source(hlcc4, "Source") // fastMA default: WMA of 5 days. fastMA = MA.get( input.string(WMA, FAST, options = [SMA, EMA, WMA, VWMA, VAWMA], inline = FAST, group = MOVING_AVERAGES), Time.spanToIntLen( input.float(5, "", inline = FAST, group = MOVING_AVERAGES), input.string(DAYS, "", options = [BARS, MINUTES, DAYS], inline = FAST, group = MOVING_AVERAGES)), source) // slowMA default: WMA of 7 days. // This can also be set to SMA of 5 days to create a useful divergence and visualization to demonstrate the difference in the two. slowMA = MA.get( input.string(WMA, SLOW, options = [SMA, EMA, WMA, VWMA, VAWMA], inline = SLOW, group = MOVING_AVERAGES), Time.spanToIntLen( input.float(7, "", inline = SLOW, group = MOVING_AVERAGES), input.string(DAYS, "", options = [BARS, MINUTES, DAYS], inline = SLOW, group = MOVING_AVERAGES)), source) // As the tooltip says, this gives a volatility tolerance that when set to something greater than one, will need more than one bar before a change in direction is confirmed. tolerance = input.int(2, "Tolerance", 1, tooltip = "The number of bars to measure the direction of the moving averages.") // Simply a way of forcing a fixed integer value in order to measure a valid signal. quantize(float k, int value = 1) => k > 0 ? value : k < 0 ? -value : 0 // Where is the close (live value) relative to the fastMA closeP = close - fastMA // What is the fastMA's direction? fastD = quantize(ta.change(fastMA, tolerance)) // What is the slowMA's direction? slowD = quantize(ta.change(slowMA, tolerance)) if input.bool(true, "Include price in warning condition", tooltip = "When this is checked, the visual warning condition will displayed if the price is on the opposite side of the fast moving average even if the direction hasn't changed.") if closeP < 0 fastD := math.min(fastD, -1) if closeP > 0 fastD := math.max(fastD, +1) D = fastD + slowD THEME = "Theme" clearColor = color.new(color.gray, 100) upColor = input.color(color.green, "▲", group = THEME, inline = THEME) dnColor = input.color(color.red, "▼", group = THEME, inline = THEME) warnColor = input.color(color.yellow, "⚠", group = THEME, inline = THEME) dirctionColor(value) => value > 0 ? upColor : value < 0 ? dnColor : warnColor fillColor = dirctionColor(D) slowPlot = plot(slowMA, "Slow", clearColor, 2) fastPlot = plot(fastMA, "Fast", fillColor, 2) fill(fastPlot, slowPlot, fastMA, slowMA, color.new(fillColor, 20), color.new(fillColor, 90))
Expected SPX Movement by timeframe
https://www.tradingview.com/script/t6D43IF3-Expected-SPX-Movement-by-timeframe/
rhvarelav
https://www.tradingview.com/u/rhvarelav/
58
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/ // © rhvarelav //THIS INDICATOR ONLY WORKS FOR SPX CHART //This code will help you to measure the expected movement of SPX in a previous selected timeframe based on the current value of VIX index //E.g. if the current value of VIX is 30 we calculate first the expected move of the Fwd TM. // If you selected the Daily timeframe it will calculate the expected move of SPX in the next Day by dividing the current VIX Value by the squared root of 252 // (THe 252 value corresponds to the approximate amount of trading sessions of the year) // If you selected the Weekly timeframe it will calculate the expected move of SPX in the next Week by dividing the current VIX Value by the squared root of 52 // (THe 52 value corresponds to the amount of weeks of the year) // If you selected the Monthly timeframe it will calculate the expected move of SPX in the next Week by dividing the current VIX Value by the squared root of 12 // (THe 12 value corresponds to the amount of months of the year) //// For lower timeframes you have to calculate the amount of ticks in each trading session of the year in order to get that specific range //Once you have that calculation it it'll provide the range expressed as percentage of the expected move for the following period. //This script will plot that information in a range of 2 lines which represents the expected move of the SPX for the next period //The red flag indicator tells if that period closed between the 2 previous values marked by the range //@version=5 indicator(title="Expected SPX Movement by timeframe", overlay=true) print(txt) => // Create label on the first bar. var lbl = label.new(bar_index, na, txt, xloc.bar_index, yloc.price, color(na), label.style_none, color.gray, size.large, text.align_left) // On next bars, update the label's x and y position, and the text it displays. label.set_xy(lbl, bar_index, ta.highest(10)[1]) label.set_text(lbl, txt) //print("Period per timeframe: " +timeframe.period) //print("Hello world!\n\n\n\n") vixData = request.security("CBOE:VIX", timeframe.period, close) scaleFreq = if timeframe.period == "D" math.sqrt(252) else if timeframe.period == "W" math.sqrt(52) else if timeframe.period == "M" math.sqrt(12) else if timeframe.period == "15" math.sqrt(6552) else if timeframe.period == "60" math.sqrt(1638) else if timeframe.period == "120" math.sqrt(819) else if timeframe.period == "240" math.sqrt(409) else math.sqrt(252) probPercMove = vixData / scaleFreq changeUpper = close + (close * (probPercMove/100)) changeLower = close - (close * (probPercMove/100)) p1 = plot(changeUpper,'Probable Upper Level',#ffffff) p2 = plot(changeLower,'Probable Lower Level',#ffffff) fill(p1, p2, color=color.new(#ffffff, 90)) plotshape(not(close<= changeUpper[1] and close >= changeLower[1]), style=shape.flag, location=location.belowbar, color=color.rgb(188, 76, 76), size=size.small)
Nadaraya-Watson non repainting [LPWN]
https://www.tradingview.com/script/YyeIcFNh-Nadaraya-Watson-non-repainting-LPWN/
Lupown
https://www.tradingview.com/u/Lupown/
1,194
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/ // © Lupown //@version=5 // The non-repainting implementation of Nadaraya–Watson Regression using a Rational Quadratic Kernel is an original idea from @jdehorty i added the upper band an lower band using ATR, with this // we get an aproximation of Nadaraya-Watson Envelope indicator('Nadaraya-Watson non repainting', overlay=true, timeframe="") src = input.source(close, 'Source') h = input.float(8., 'Lookback Window', minval=3., tooltip='The number of bars used for the estimation. This is a sliding value that represents the most recent historical bars. Recommended range: 3-50') r = input.float(8., 'Relative Weighting', step=0.25, tooltip='Relative weighting of time frames. As this value approaches zero, the longer time frames will exert more influence on the estimation. As this value approaches infinity, the behavior of the Rational Quadratic Kernel will become identical to the Gaussian kernel. Recommended range: 0.25-25') x_0 = input.int(25, "Start Regression at Bar", tooltip='Bar index on which to start regression. The first bars of a chart are often highly volatile, and omission of these initial bars often leads to a better overall fit. Recommended range: 5-25') showMiddle = input(true, "Show middle band") smoothColors = input.bool(false, "Smooth Colors", tooltip="Uses a crossover based mechanism to determine colors. This often results in less color transitions overall.", inline='1', group='Colors') lag = input.int(2, "Lag", tooltip="Lag for crossover detection. Lower values result in earlier crossovers. Recommended range: 1-2", inline='1', group='Colors') lenjeje = input(32, "ATR Period", tooltip= 'Period to calculate upper and lower band', group='Bands') coef = input(2.7,"Multiplier",tooltip= 'Multiplier to calculate upper and lower band', group='Bands') float y1 = 0. float y2 = 0. srcArray = array.new<float>(0) array.push(srcArray, src) size = array.size(srcArray) kernel_regression1(_src, _size, _h) => float _currentWeight = 0. float _cumulativeWeight = 0. for i = 0 to _size + x_0 y = _src[i] w = math.pow(1 + (math.pow(i, 2) / ((math.pow(_h, 2) * 2 * r))), -r) _currentWeight += y*w _cumulativeWeight += w [_currentWeight, _cumulativeWeight] [currentWeight1, cumulativeWeight1] = kernel_regression1(src, size, h) yhat1 = currentWeight1 / cumulativeWeight1 [currentWeight2, cumulativeWeight2] = kernel_regression1(src, size, h-lag) yhat2 = currentWeight2 / cumulativeWeight2 // Rates of Change bool wasBearish = yhat1[2] > yhat1[1] bool wasBullish = yhat1[2] < yhat1[1] bool isBearish = yhat1[1] > yhat1 bool isBullish = yhat1[1] < yhat1 bool isBearishChange = isBearish and wasBullish bool isBullishChange = isBullish and wasBearish // Crossovers bool isBullishCross = ta.crossover(yhat2, yhat1) bool isBearishCross = ta.crossunder(yhat2, yhat1) bool isBullishSmooth = yhat2 > yhat1 bool isBearishSmooth = yhat2 < yhat1 // Colors color c_bullish = input.color(#3AFF17, 'Bullish Color', group='Colors') color c_bearish = input.color(#FD1707, 'Bearish Color', group='Colors') color colorByCross = isBullishSmooth ? c_bullish : c_bearish color colorByRate = isBullish ? c_bullish : c_bearish color plotColor = smoothColors ? colorByCross : colorByRate // Plot plot(showMiddle ? yhat1 : na, "Rational Quadratic Kernel Estimate", color=plotColor, linewidth=2) upperjeje = yhat1 + coef*ta.atr(lenjeje) lowerjeje = yhat1 - coef*ta.atr(lenjeje) upperje = plot(upperjeje , "Rational Quadratic Kernel Upper", color=color.rgb(0, 247, 8), linewidth=2) lowerje = plot(lowerjeje, "Rational Quadratic Kernel Lower", color=color.rgb(255, 0, 0), linewidth=2) //plot(yhat1 + multi, "Rational Quadratic Kernel Estimate", color=color.silver, linewidth=2) plotchar(ta.crossover(close,upperjeje),char = "🥀", location = location.abovebar, size = size.tiny) plotchar(ta.crossunder(close,lowerjeje),char = "🍀",location = location.belowbar , size = size.tiny) // Alerts for Color Changes estimator alertcondition(smoothColors ? isBearishCross : isBearishChange, title='Bearish Color Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bearish ▼') alertcondition(smoothColors ? isBullishCross : isBullishChange, title='Bullish Color Change', message='Nadaraya-Watson: {{ticker}} ({{interval}}) turned Bullish ▲') // Alerts when price cross upper and lower band alertcondition(ta.crossunder(close,lowerjeje), title='Price close under lower band', message='Nadaraya-Watson: {{ticker}} ({{interval}}) crossed under lower band 🍀') alertcondition(ta.crossover(close,upperjeje), title='Price close above upper band', message='Nadaraya-Watson: {{ticker}} ({{interval}}) Crossed above upper band 🥀')
Gap Zones
https://www.tradingview.com/script/lC7ifYuS-Gap-Zones/
syntaxgeek
https://www.tradingview.com/u/syntaxgeek/
323
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © syntaxgeek //@version=5 indicator(title="Gap Zones", shorttitle="GZ", overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500) // <inputs> i_maxZones = input.int(title='Max Zones', defval=10, maxval=50, minval=1) i_zoneColor = input.color(title='Zone', defval=color.gray, group='Style') i_timeframe = input.timeframe(title='Timeframe', defval='', inline='Timeframe', group='Timeframe') i_timeframeGapsOn = input.bool(title='Timeframe Gaps?', defval=false, inline='Timeframe', group='Timeframe') // </inputs> // <funcs> f_renderGaps() => i_timeframeGapsOn ? barmerge.gaps_on : barmerge.gaps_off f_regSec(f) => request.security(syminfo.tickerid, i_timeframe, f, f_renderGaps(), barmerge.lookahead_on) f_isNewTimeframeBar(res) => t = time(res) not na(t) and (na(t[1]) or t > t[1]) // </funcs> // <vars> var v_boxes = array.new_box(0) var v_topLines = array.new_line(0) var v_midLines = array.new_line(0) var v_bottomLines = array.new_line(0) var v_labels = array.new_label(0) v_box_a = 0.0 v_box_b = 0.0 if f_isNewTimeframeBar(i_timeframe) v_box_a := f_regSec(close[1]) v_box_b := f_regSec(open) v_range = v_box_a > v_box_b ? v_box_a - v_box_b : v_box_b - v_box_a v_mid = v_box_a > v_box_b ? v_box_a - (v_range / 2) : v_box_b - (v_range / 2) v_boxes_size = array.size(v_boxes) if v_boxes_size == i_maxZones box.delete(array.remove(v_boxes, 0)) label.delete(array.remove(v_labels, 0)) line.delete(array.remove(v_topLines, 0)) line.delete(array.remove(v_midLines, 0)) line.delete(array.remove(v_bottomLines, 0)) array.push(v_boxes, box.new(bar_index, v_box_a, bar_index + 1, v_box_b, border_color = color.new(color.white,100), bgcolor = color.new(i_zoneColor, 90), extend = extend.right)) array.push(v_labels, label.new(bar_index + 20, v_mid, text = str.tostring(i_timeframe) + " Zone", style=label.style_text_outline, size = size.normal, textcolor = color.white, color=color.black)) array.push(v_topLines, line.new(bar_index, v_box_a, bar_index + 1, v_box_a, extend=extend.right, color=i_zoneColor)) array.push(v_midLines, line.new(bar_index, v_mid, bar_index + 1, v_mid, extend=extend.right, color=color.new(i_zoneColor, 50), style=line.style_dashed)) array.push(v_bottomLines, line.new(bar_index, v_box_b, bar_index + 1, v_box_b, extend=extend.right, color=i_zoneColor)) // </vars>
Three Linear Regression Channels
https://www.tradingview.com/script/RQ3PgXqh-Three-Linear-Regression-Channels/
Fuwn
https://www.tradingview.com/u/Fuwn/
121
study
5
CC-BY-SA-4.0
// This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License https://creativecommons.org/licenses/by-sa/4.0/ // © alexgrover import Fuwn/StringToNumber/1 //@version=5 indicator('Three Linear Regression Channels', overlay = true) int N = bar_index int length = input.int(100,"Length") float source = input.source(close) bool e0 = input.bool(true, "Midline Visibility") color midline = input.color(color.white, "Midline Colour") bool e1 = input.bool(true, "Channel One Visibility") float m1 = input.float(1, "Channel One Multiplicative Factor") color c1 = input.color(color.green, "Channel One Colour") bool e2 = input.bool(true, "Channel Two Visibility") float m2 = input.float(2, "Channel Two Multiplicative Factor") color c2 = input.color(color.yellow, "Channel Two Colour") bool e3 = input.bool(true, "Channel Three Visibility") float m3 = input.float(3, "Channel Three Multiplicative Factor") color c3 = input.color(color.red, "Channel Three Colour") float a = ta.wma(source, length) float b = ta.sma(source, length) float A = 4 * b - 3 * a float B = 3 * a - 2 * b float m = (A - B) / (length - 1) float d = 0 for i = 0 to length - 1 by 1 l = B + m * i d += math.pow(source[i] - l, 2) d l(color c, float k, s = line.style_solid) => line.delete(line.new(N - length + 1, A + k, N, B + k, extend = extend.right, color = c, style = s)[1]) c(float mf, color c) => rmse = math.sqrt(d / (length - 1)) * mf l(c, rmse) l(c, -rmse) if e0 l(midline, 0, line.style_dashed) if e1 c(m1, c1) if e2 c(m2, c2) if e3 c(m3, c3)
Time Range Bar Pattern
https://www.tradingview.com/script/Trtwm1qU-Time-Range-Bar-Pattern/
HastaAdhidaya
https://www.tradingview.com/u/HastaAdhidaya/
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/ // Created by @jayallways for Tom //@version=5 indicator("Time Range Bar Pattern") bullColor = input.color(color.white, "Bull Candle") bearColor = input.color(color.black, "Bear Candle") londonColor = input.color(color.new(color.blue, 70), "London Session Color") newyorkColor = input.color(color.new(color.red, 70), "New York Session Color") timeRange1 = input.string("1000-1100", "Visible #1 Time Range") firstCandleRange1 = input.string("1000-1005", "First Bar #1 Time Range") timeRange2 = input.string("1630-1730", "Visible #2 Time Range") firstCandleRange2 = input.string("1630-1635", "First Bar #2 Time Range") var string[] dateList = array.new_string(0) tr1 = time(timeframe.period, timeRange1) tr2 = time(timeframe.period, timeRange2) fcr1 = time(timeframe.period, firstCandleRange1) fcr2 = time(timeframe.period, firstCandleRange2) var count = bar_index number = bar_index % 10 var float lowestX = 0 if (na(tr1) and na(tr2)) lowestX := 0 if (not na(fcr1) or not na(fcr2)) lowestX := low c_open = (na(tr1) and na(tr2)) ? 0 : open - lowestX c_high = (na(tr1) and na(tr2)) ? 0 : high - lowestX c_low = (na(tr1) and na(tr2)) ? 0 : low - lowestX c_close = (na(tr1) and na(tr2)) ? 0 : close - lowestX plotcandle(c_open, c_high, c_low, c_close, color = close >= open ? bullColor : bearColor) bgcolor(not na(tr1) ? londonColor : not na(tr2) ? newyorkColor : na)
Chef Momentum
https://www.tradingview.com/script/5zuQz4XB/
Chef_Bull
https://www.tradingview.com/u/Chef_Bull/
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/ // © Chef_Bull //@version=5 indicator("Chef Momentum",format=format.price, overlay=false) //STOCH// periodK = input.int(21, title="%K Length", minval=1) smoothK = input.int(100, title="%K Smoothing", minval=1) //periodD = input.int(5, title="%D Smoothing", minval=1) // k = ta.hma(ta.stoch(close, high, low, periodK), smoothK) //d = ta.hma(k, periodD) plot(k, title="%K", color=#FFFFFF) //plot(d, title="%D", color=#FF6D00) h0 = hline(80, "Upper Band", color=#787B86) h1 = hline(20, "Lower Band", color=#787B86) h2 = hline(50, "Lower Band", color=#787B86) fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background") //CONDITION// buy = ta.crossover(k,25) sell = ta.crossover(k,80) plotshape(buy, title = "BUY", color = color.green, style = shape.circle, textcolor = color.white, location = location.bottom, size = size.small) plotshape(sell, title = "SELL", color = color.red, style = shape.circle, textcolor = color.white, location = location.top, size = size.small) alertcondition(buy, title="Bull signal", message="Bull signal @ ${{close}}") alertcondition(sell, title="Bear signal", message="Bear signal @ ${{close}}")
One Minute Algo Run (OMAR)
https://www.tradingview.com/script/KkwuK008-One-Minute-Algo-Run-OMAR/
senpai_noticeme
https://www.tradingview.com/u/senpai_noticeme/
232
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org/MPL/2.0/ // Author: @ senpai_noticeme (emansenpai, doc). ack: @ silenThunderr, @ dixitsoham7, @ colejustice //@version=5 // One Minute Algo Run (OMAR) will mark High Low of the opening candle (1min is recommended default) based on the current time frame in current session // There are also recommended 1x and 2x extensions of the ranges for taking profit that may also be adjusted as needed. indicator('One Minute Algo Run', shorttitle='OMAR', overlay=true) baseOnOneMinuteCandles = input.bool(title='Base on 1 Minute Candles', defval=true, tooltip="If checked, opening range high/low will be based on 1 minute candles instead of the chart settings. Useful for short ranges, e.g. the opening minute.") SessionInput = input.session('0930-1005') var target1Long = 0.0 var target2Long = 0.0 var target1Short = 0.0 var target2Short = 0.0 var OmarRange = 0.0 var OmarMid = 0.0 var longT1 = line.new(na, na, na, na, extend=extend.right) var longT2 = line.new(na, na, na, na, extend=extend.right) var shortT1 = line.new(na, na, na, na, extend=extend.right) var shortT2 = line.new(na, na, na, na, extend=extend.right) var longT1Label = label.new(na, na, textcolor=color.blue, style=label.style_none) var longT2Label = label.new(na, na, textcolor=color.blue, style=label.style_none) var shortT1Label = label.new(na, na, textcolor=color.blue, style=label.style_none) var shortT2Label = label.new(na, na, textcolor=color.blue, style=label.style_none) var longT1Line = input.bool(title='Show Long T1', defval=true, group='Long') var longT2Line = input.bool(title='Show Long T2', defval=true, group='Long') var shortT1Line = input.bool(title='Show Short T1', defval=true, group='Short') var shortT2Line = input.bool(title='Show Short T2', defval=true, group='Short') var longT1Range = input.float(title='Long T1', defval=1, group='Long (x times above range of OMAR)', tooltip='Line will be plotted above high of OMAR. If value entered is 1, then T1 = range of OMAR x 1') var longT2Range = input.float(title='Long T2', defval=2, group='Long (x times above range of OMAR)', tooltip='Line will be plotted above high of OMAR. If value entered is 2, then T2 = range of OMAR x 2') var shortT1Range = input.float(title='Short T1', defval=1, group='Short (x times below range of OMAR)', tooltip='Line will be plotted below low of OMAR. If value entered is 1, then T1 = range of OMAR x 1') var shortT2Range = input.float(title='Short T2', defval=2, group='Short (x times below range of OMAR)', tooltip='Line will be plotted below low of OMAR. If value entered is 2, then T2 = range of OMAR x 1') // Section below defines what an active session is var tz = "America/New_York" sessionBegins(sess) => t = time(timeframe.period, sess,tz) timeframe.isintraday and (not barstate.isfirst) and na(t[1]) and not na(t) timeframe_high = baseOnOneMinuteCandles ? request.security(syminfo.ticker, "1", high, barmerge.gaps_off, barmerge.lookahead_on) : high timeframe_low = baseOnOneMinuteCandles ? request.security(syminfo.ticker, "1", low, barmerge.gaps_off, barmerge.lookahead_on) : low var float high_value = na var float low_value = na //Set required variable values during active session if sessionBegins(SessionInput) high_value := timeframe_high low_value := timeframe_low OmarRange := high_value - low_value OmarMid := low_value + OmarRange/2 target1Long := high_value + longT1Range * OmarRange target2Long := high_value + longT2Range * OmarRange target1Short := low_value - shortT1Range * OmarRange target2Short := low_value - shortT2Range * OmarRange // Only plot the high, low and mid suring active session plot(not(true and not time(timeframe.period, SessionInput,tz)) ? high_value : na, style=plot.style_circles, linewidth=3, color=color.new(color.orange, 0), title='High') plot(not(true and not time(timeframe.period, SessionInput,tz)) ? low_value : na, style=plot.style_circles, linewidth=3, color=color.new(color.orange, 0), title='Low') plot(not(true and not time(timeframe.period, SessionInput,tz)) ? OmarMid : na, style=plot.style_linebr, linewidth=2, color=color.new(color.orange, 0), title='Middle') //long target 1 plot(not(true and not time(timeframe.period, SessionInput,tz)) ? (longT1Line ? target1Long : na) : na, style=plot.style_linebr, linewidth=2, color=color.new(color.blue, 0), title='LongT1') if not(true and not time(timeframe.period, SessionInput,tz)) label.set_xy(longT1Label, bar_index + 15, target1Long) label.set_text(id=longT1Label, text='T1 - ' + str.tostring(target1Long) + ' (' + str.tostring(longT1Range * OmarRange) + ') points') //long target 2 plot(not(true and not time(timeframe.period, SessionInput,tz)) ? (longT2Line ? target2Long : na) : na, style=plot.style_linebr, linewidth=2, color=color.new(color.blue, 0), title='LongT2') if not(true and not time(timeframe.period, SessionInput,tz)) label.set_xy(longT2Label, bar_index + 15, target2Long) label.set_text(id=longT2Label, text='T2 - ' + str.tostring(target2Long) + ' (' + str.tostring(longT2Range * OmarRange) + ') points') //short target 1 plot(not(true and not time(timeframe.period, SessionInput,tz)) ? (shortT1Line ? target1Short : na) : na, style=plot.style_linebr, linewidth=2, color=color.new(color.blue, 0), title='ShortT1') if not(true and not time(timeframe.period, SessionInput,tz)) label.set_xy(shortT1Label, bar_index + 15, target1Short) label.set_text(id=shortT1Label, text='T1 - ' + str.tostring(target1Short) + ' (' + str.tostring(shortT1Range * OmarRange) + ') points') //short target 2 plot(not(true and not time(timeframe.period, SessionInput,tz)) ? (shortT2Line ? target2Short : na) : na, style=plot.style_linebr, linewidth=2, color=color.new(color.blue, 0), title='ShortT2') if not(true and not time(timeframe.period, SessionInput,tz)) label.set_xy(shortT2Label, bar_index + 15, target2Short) label.set_text(id=shortT2Label, text='T2 - ' + str.tostring(target2Short) + ' (' + str.tostring(shortT2Range * OmarRange) + ') points')
Directional Slope Strength Index
https://www.tradingview.com/script/Z0lWFtte-Directional-Slope-Strength-Index/
Mik3Christ3ns3n
https://www.tradingview.com/u/Mik3Christ3ns3n/
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/ // © Mik3Christ3ns3n //@version=5 indicator("Directional Slope Strength Index", shorttitle = "DSSI", format = format.price, precision = 1) length = input.int(20, minval=1, title = "ROC Length") source = input(hlc3, "ROC Source") stdlength = input.int(1000, minval=1, title = "Sample Length") roc = 100 * (source - source[length])/source[length] rocstd = ta.stdev(roc, stdlength) zscore = (roc - ta.sma(roc, stdlength)) / rocstd zscore_color = zscore > 0 ? #4CAF50 : #FF5252 getHighest(dataSeries) => var highest = dataSeries if dataSeries >= nz(highest, 0) highest := dataSeries highest getLowest(dataSeries) => var lowest = dataSeries if dataSeries < nz(lowest, 1e10) lowest := dataSeries lowest plot(zscore, title="Slope Strength", style=plot.style_line, color=zscore_color, linewidth = 2) hline(2, color=#787B86, linestyle = hline.style_dotted, title="2 STDEV") hline(0, color=#787B86, title="Zero Line") hline(-2, color=#787B86, linestyle = hline.style_dotted, title="-2 STDEV") plot(series=getHighest(zscore), color=#4CAF50, linewidth=1, style=plot.style_line, title="Highest Score") plot(series=getLowest(zscore), color=#FF5252, linewidth=1, style=plot.style_line, title="Lowest Score")
Market Beta/Beta Coefficient for CAPM [Loxx]
https://www.tradingview.com/script/A8CtHPxR-Market-Beta-Beta-Coefficient-for-CAPM-Loxx/
loxx
https://www.tradingview.com/u/loxx/
47
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © loxx //@version=5 // @description In finance, the beta (β or market beta or beta coefficient) is a measure of how an // individual asset moves (on average) when the overall stock market increases or decreases. // Thus, beta is a useful measure of the contribution of an individual asset to the risk // of the market portfolio when it is added in small quantity. Thus, beta is referred to // as an asset's non-diversifiable risk, its systematic risk, market risk, or hedge ratio. // Beta is not a measure of idiosyncratic risk. indicator('Market Beta/Beta Coefficient for CAPM [Loxx]', shorttitle ="BETACAPM [Loxx]", overlay = false) // @function beta = (Covarianc(x[], y[]) / Variance(y[])) // @param x float[], ticker on screen // @param y float[], benchmark of market, typically SPY // @return float, beta (β or market beta or beta coefficient) beta1(float x, float y, int per) => float avgX = ta.sma(x, per) float avgY = ta.sma(y, per) float sum1 = 0. float sum2 = 0. for i = 0 to per - 1 sum1 += (x[i] - avgX) * (y[i] - avgY) beta = (sum1 / per) / ta.variance(y, per) beta // Average sums of square differences from the mean // ssxm = mean( (x-mean(x))^2 ) // ssxym = mean( (x-mean(x)) * (y-mean(y)) ) // @function beta = Average sums of square differences from the mean // @param x float[], ticker on screen // @param y float[], benchmark of market, typically SPY // @return float, beta (β or market beta or beta coefficient) beta2(float x, float y, int per) => float avgX = ta.sma(x, per) float avgY = ta.sma(y, per) float sum1 = 0. float sum2 = 0. for i = 0 to per - 1 sum1 += math.pow(nz(x[i]) - avgX, 2) sum2 += (nz(x[i]) - avgX) * (nz(y[i]) - avgY) float ssxm = sum1 / per float ssxym = sum2 / per float slope = ssxym / ssxm slope per = input(60, "Period") string spyinput = input.symbol("SPY", "Benchmark") string timeframe = input.timeframe("", "Timeframe") float spyin = request.security(spyinput, timeframe, close) src = math.log(close/close[1]) spy = math.log(spyin/spyin[1]) float beta1 = beta1(src, spy, per) float beta2 = beta2(spy, src, per) plot(beta1) plot(beta2) var testTable = table.new(position = position.top_right, columns = 1, rows = 2, bgcolor = color.black, border_width = 1) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Current Market Beta/Beta Coefficient for CAPM (version 1): " + str.tostring(beta1, "#.####"), text_size = size.normal, bgcolor=color.yellow) table.cell(table_id = testTable, column = 0, row = 1, text = "Current Market Beta/Beta Coefficient for CAPM (version 2): " + str.tostring(beta2, "#.####"), text_size = size.normal, bgcolor=color.yellow)
Price Percent Change (O/C)
https://www.tradingview.com/script/rUs3hFnj-Price-Percent-Change-O-C/
LedzZz
https://www.tradingview.com/u/LedzZz/
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/ // © LedzZz //@version=5 indicator("Percent Change (LedzZz)") // ==================================================================================================== // ---------------------------------------------------------------------------------------------------- // INPUT-CHOICE => Method of Percent to calculate var Method_A = "Close Vs Open" var Method_B = "High vs Low" var Method_C = "Last Close vs Curent Open" method = input.string( title="type", defval=Method_A, options=[Method_A,Method_B,Method_C]) // declaring the proper final number for the selected Method, f=final, i=initial. // for example for option C: final price => "open", initial price => "yesterdays close" price_f = (Method_B == method) ? high : ((Method_C == method) ? open : close ) price_i = (Method_B == method) ? low : ((Method_C == method) ? close[1] : open ) // addition factor required for Method_B, due to high and low doesn't indicate if its a green day or red day. hi_lo_factor = (Method_B != method)?1:(close>open)?1:-1 // Percent change based on the selected method. perChange_MOD_A = (price_f-price_i)/price_i* 100 *hi_lo_factor // INPUT Minimum Percent TO SHOW min_Percent = input.float(title="Min Percent Move (%)", minval = 0, maxval = 100, defval = 0) to_show_factor = math.abs(perChange_MOD_A) > min_Percent? 1 : 0 // Applying to show factor to percentage perChange_MOD_B = perChange_MOD_A * to_show_factor // Bar Color plotStyle = plot.style_columns plotColor = ( perChange_MOD_B > 0 ? color.green : color.red ) plot(perChange_MOD_B,style=plotStyle,color= plotColor) // horizontal refrence lines. horLineColor = color.new(color.olive,1) plot(4,style=plot.style_line,color= horLineColor) plot(2,style=plot.style_line,color= horLineColor) plot(1,style=plot.style_line,color= horLineColor) plot(-1,style=plot.style_line,color= horLineColor) plot(-2,style=plot.style_line,color= horLineColor) plot(-4,style=plot.style_line,color= horLineColor)
Capital Asset Pricing Model (CAPM) [Loxx]
https://www.tradingview.com/script/MSkGC7BR-Capital-Asset-Pricing-Model-CAPM-Loxx/
loxx
https://www.tradingview.com/u/loxx/
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/ // © loxx //@version=5 indicator("Capital Asset Pricing Model (CAPM) [Loxx]", shorttitle ="CAPM [Loxx]", overlay = true) color darkGreenColor = #1B7E02 color greencolor = #2DD204 f_security(_symbol, _res, _src, _repaint) => out = request.security(_symbol, _res, _src[_repaint ? 0 : barstate.isrealtime ? 1 : 0])[_repaint ? 0 : barstate.isrealtime ? 0 : 1] out betaAlpha(float[] x, float[] y) => float avgX = array.avg(x) float avgY = array.avg(y) float sum1 = 0. float sum2 = 0. int per = array.size(x) for i = 0 to per - 1 sum1 += (array.get(x, i) - avgX) * (array.get(y, i) - avgY) beta = (sum1 / per) / array.variance(y) alpha = avgX - beta * avgY [beta, alpha] per = input(60, "Period in Months (5 years of data)", group = "Basic Settings") perlarge = input(29, "SPY Age in Years", group = "Basic Settings") string spyinput = input.symbol("SPY", "Benchmark", group = "Basic Settings") string timeframe = input.timeframe("1M", "Timeframe", group = "Basic Settings") string rfrtype = input.string("USD", "Option Base Currency", options = ['USD', 'GBP', 'JPY', 'CAD', 'CNH', 'SGD', 'INR', 'AUD', 'SEK', 'NOK', 'DKK'], group = "Risk-free Rate Settings", tooltip = "Automatically pulls 10-year bond yield from corresponding currency") float rfrman = input.float(3.97, "% Manual Risk-free Rate", group = "Risk-free Rate Settings") / 100 bool usdrsrman = input.bool(false, "Use manual input for Risk-free Rate?", group = "Risk-free Rate Settings") float rmman = input.float(10., "% Expected Equity Market Return", group = "Expected Equity Market Return Settings") / 100 bool usermman = input.bool(false, "Use manual input for Expected Equity Market Return?", group = "Expected Equity Market Return Settings") float spyt = request.security(spyinput, timeframe, close) float srct = request.security(syminfo.tickerid, timeframe, close) string byield = switch rfrtype "USD"=> 'US10Y' "GBP"=> 'GB10Y' "JPY"=> 'US10Y' "CAD"=> 'CA10Y' "CNH"=> 'CN10Y' "SGD"=> 'SG10Y' "INR"=> 'IN10Y' "AUD"=> 'AU10Y' "USEKSD"=> 'SE10Y' "NOK"=> 'NO10Y' "DKK"=> 'DK10Y' => 'US10Y' float beta = 0 float alpha = 0 [src0, src1, src2, src3, src4, src5, src6, src7, src8, src9, src10, src11, src12, src13, src14, src15, src16, src17, src18, src19, src20, src21, src22, src23, src24, src25, src26, src27, src28, src29, src30, src31, src32, src33, src34, src35, src36, src37, src38, src39, src40, src41, src42, src43, src44, src45, src46, src47, src48, src49, src50, src51, src52, src53, src54, src55, src56, src57, src58, src59] = request.security("", timeframe, [ math.log(close/close[1]), math.log(close[1]/close[2]), math.log(close[2]/close[3]), math.log(close[3]/close[4]), math.log(close[4]/close[5]), math.log(close[5]/close[6]), math.log(close[6]/close[7]), math.log(close[7]/close[8]), math.log(close[8]/close[9]), math.log(close[9]/close[10]), math.log(close[10]/close[11]), math.log(close[11]/close[12]), math.log(close[12]/close[13]), math.log(close[13]/close[14]), math.log(close[14]/close[15]), math.log(close[15]/close[16]), math.log(close[16]/close[17]), math.log(close[17]/close[18]), math.log(close[18]/close[19]), math.log(close[19]/close[20]), math.log(close[20]/close[21]), math.log(close[21]/close[22]), math.log(close[22]/close[23]), math.log(close[23]/close[24]), math.log(close[24]/close[25]), math.log(close[25]/close[26]), math.log(close[26]/close[27]), math.log(close[27]/close[28]), math.log(close[28]/close[29]), math.log(close[29]/close[30]), math.log(close[30]/close[31]), math.log(close[31]/close[32]), math.log(close[32]/close[33]), math.log(close[33]/close[34]), math.log(close[34]/close[35]), math.log(close[35]/close[36]), math.log(close[36]/close[37]), math.log(close[37]/close[38]), math.log(close[38]/close[39]), math.log(close[39]/close[40]), math.log(close[40]/close[41]), math.log(close[41]/close[42]), math.log(close[42]/close[43]), math.log(close[43]/close[44]), math.log(close[44]/close[45]), math.log(close[45]/close[46]), math.log(close[46]/close[47]), math.log(close[47]/close[48]), math.log(close[48]/close[49]), math.log(close[49]/close[50]), math.log(close[50]/close[51]), math.log(close[51]/close[52]), math.log(close[52]/close[53]), math.log(close[53]/close[54]), math.log(close[54]/close[55]), math.log(close[55]/close[56]), math.log(close[56]/close[57]), math.log(close[57]/close[58]), math.log(close[58]/close[59]), math.log(close[59]/close[60])]) [spy0, spy1, spy2, spy3, spy4, spy5, spy6, spy7, spy8, spy9, spy10, spy11, spy12, spy13, spy14, spy15, spy16, spy17, spy18, spy19, spy20, spy21, spy22, spy23, spy24, spy25, spy26, spy27, spy28, spy29, spy30, spy31, spy32, spy33, spy34, spy35, spy36, spy37, spy38, spy39, spy40, spy41, spy42, spy43, spy44, spy45, spy46, spy47, spy48, spy49, spy50, spy51, spy52, spy53, spy54, spy55, spy56, spy57, spy58, spy59] = request.security(spyinput, timeframe, [ math.log(close/close[1]), math.log(close[1]/close[2]), math.log(close[2]/close[3]), math.log(close[3]/close[4]), math.log(close[4]/close[5]), math.log(close[5]/close[6]), math.log(close[6]/close[7]), math.log(close[7]/close[8]), math.log(close[8]/close[9]), math.log(close[9]/close[10]), math.log(close[10]/close[11]), math.log(close[11]/close[12]), math.log(close[12]/close[13]), math.log(close[13]/close[14]), math.log(close[14]/close[15]), math.log(close[15]/close[16]), math.log(close[16]/close[17]), math.log(close[17]/close[18]), math.log(close[18]/close[19]), math.log(close[19]/close[20]), math.log(close[20]/close[21]), math.log(close[21]/close[22]), math.log(close[22]/close[23]), math.log(close[23]/close[24]), math.log(close[24]/close[25]), math.log(close[25]/close[26]), math.log(close[26]/close[27]), math.log(close[27]/close[28]), math.log(close[28]/close[29]), math.log(close[29]/close[30]), math.log(close[30]/close[31]), math.log(close[31]/close[32]), math.log(close[32]/close[33]), math.log(close[33]/close[34]), math.log(close[34]/close[35]), math.log(close[35]/close[36]), math.log(close[36]/close[37]), math.log(close[37]/close[38]), math.log(close[38]/close[39]), math.log(close[39]/close[40]), math.log(close[40]/close[41]), math.log(close[41]/close[42]), math.log(close[42]/close[43]), math.log(close[43]/close[44]), math.log(close[44]/close[45]), math.log(close[45]/close[46]), math.log(close[46]/close[47]), math.log(close[47]/close[48]), math.log(close[48]/close[49]), math.log(close[49]/close[50]), math.log(close[50]/close[51]), math.log(close[51]/close[52]), math.log(close[52]/close[53]), math.log(close[53]/close[54]), math.log(close[54]/close[55]), math.log(close[55]/close[56]), math.log(close[56]/close[57]), math.log(close[57]/close[58]), math.log(close[58]/close[59]), math.log(close[59]/close[60])]) if barstate.islast float[] srcarr = array.new_float(0) float[] spyarr = array.new_float(0) array.push(srcarr, src0) array.push(srcarr, src1) array.push(srcarr, src2) array.push(srcarr, src3) array.push(srcarr, src4) array.push(srcarr, src5) array.push(srcarr, src6) array.push(srcarr, src7) array.push(srcarr, src8) array.push(srcarr, src9) array.push(srcarr, src10) array.push(srcarr, src11) array.push(srcarr, src12) array.push(srcarr, src13) array.push(srcarr, src14) array.push(srcarr, src15) array.push(srcarr, src16) array.push(srcarr, src17) array.push(srcarr, src18) array.push(srcarr, src19) array.push(srcarr, src20) array.push(srcarr, src21) array.push(srcarr, src22) array.push(srcarr, src23) array.push(srcarr, src24) array.push(srcarr, src25) array.push(srcarr, src26) array.push(srcarr, src27) array.push(srcarr, src28) array.push(srcarr, src29) array.push(srcarr, src30) array.push(srcarr, src31) array.push(srcarr, src32) array.push(srcarr, src33) array.push(srcarr, src34) array.push(srcarr, src35) array.push(srcarr, src36) array.push(srcarr, src37) array.push(srcarr, src38) array.push(srcarr, src39) array.push(srcarr, src40) array.push(srcarr, src41) array.push(srcarr, src42) array.push(srcarr, src43) array.push(srcarr, src44) array.push(srcarr, src45) array.push(srcarr, src46) array.push(srcarr, src47) array.push(srcarr, src48) array.push(srcarr, src49) array.push(srcarr, src50) array.push(srcarr, src51) array.push(srcarr, src52) array.push(srcarr, src53) array.push(srcarr, src54) array.push(srcarr, src55) array.push(srcarr, src56) array.push(srcarr, src57) array.push(srcarr, src58) array.push(srcarr, src59) array.push(spyarr, spy0) array.push(spyarr, spy1) array.push(spyarr, spy2) array.push(spyarr, spy3) array.push(spyarr, spy4) array.push(spyarr, spy5) array.push(spyarr, spy6) array.push(spyarr, spy7) array.push(spyarr, spy8) array.push(spyarr, spy9) array.push(spyarr, spy10) array.push(spyarr, spy11) array.push(spyarr, spy12) array.push(spyarr, spy13) array.push(spyarr, spy14) array.push(spyarr, spy15) array.push(spyarr, spy16) array.push(spyarr, spy17) array.push(spyarr, spy18) array.push(spyarr, spy19) array.push(spyarr, spy20) array.push(spyarr, spy21) array.push(spyarr, spy22) array.push(spyarr, spy23) array.push(spyarr, spy24) array.push(spyarr, spy25) array.push(spyarr, spy26) array.push(spyarr, spy27) array.push(spyarr, spy28) array.push(spyarr, spy29) array.push(spyarr, spy30) array.push(spyarr, spy31) array.push(spyarr, spy32) array.push(spyarr, spy33) array.push(spyarr, spy34) array.push(spyarr, spy35) array.push(spyarr, spy36) array.push(spyarr, spy37) array.push(spyarr, spy38) array.push(spyarr, spy39) array.push(spyarr, spy40) array.push(spyarr, spy41) array.push(spyarr, spy42) array.push(spyarr, spy43) array.push(spyarr, spy44) array.push(spyarr, spy45) array.push(spyarr, spy46) array.push(spyarr, spy47) array.push(spyarr, spy48) array.push(spyarr, spy49) array.push(spyarr, spy50) array.push(spyarr, spy51) array.push(spyarr, spy52) array.push(spyarr, spy53) array.push(spyarr, spy54) array.push(spyarr, spy55) array.push(spyarr, spy56) array.push(spyarr, spy57) array.push(spyarr, spy58) array.push(spyarr, spy59) [b, a] = betaAlpha(srcarr, spyarr) alpha := a beta := b float Rf = usdrsrman ? rfrman : request.security(byield, timeframe.period, close) / 100 float rmt = ta.sma((close - close[1]) / close[1], perlarge) float spyyeardat = f_security(spyinput, "12M", rmt, true) float Rm = usermman ? rmman : spyyeardat r = Rf + beta * (Rm - Rf) + alpha var testTable = table.new(position = position.middle_right, columns = 1, rows = 9, bgcolor = color.gray, border_width = 1) if barstate.islast table.cell(table_id = testTable, column = 0, row = 0, text = "Capital Asset Pricing Model (CAPM)", bgcolor=darkGreenColor, text_color = color.white, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 1, text = "Cost of Equity (r): " + str.tostring(r * 100, format.percent), text_size = size.normal, bgcolor=color.yellow, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 2, text = "Expected Equity Market Return (Rm): " + str.tostring(Rm * 100, format.percent), text_size = size.normal, bgcolor=color.yellow, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 3, text = "Risk-free Rate (Rf): " + str.tostring(Rf * 100, format.percent), text_size = size.normal, bgcolor=color.yellow, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 4, text = "Market Risk Premium (Rm - Rf): " + str.tostring((Rm - Rf) * 100, format.percent), text_size = size.normal, bgcolor=color.yellow, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row = 5, text = "Beta (B): " + str.tostring(beta, "#.#####"), text_size = size.normal, bgcolor=color.yellow, text_halign = text.align_left) table.cell(table_id = testTable, column = 0, row =6, text = "Alpha (a): " + str.tostring(alpha, "#.#####"), text_size = size.normal, bgcolor=color.yellow, text_halign = text.align_left)
LowLag Channel Stoch
https://www.tradingview.com/script/dIxXPF0z-LowLag-Channel-Stoch/
capam
https://www.tradingview.com/u/capam/
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/ // © capam //@version=5 indicator("LowLag Channel Stoch", overlay=true) src = close length = input.int(10,'emalength') lengthATR = input.int(5,'ATRlength') lengthStoch = input.int(14,'stochlength') smoothK = input.int(5,'smoothK') gain = input.float(1.0,'gain') stochlimit = input.float(0.8,'stochlimit',maxval = 1.0) hullEMA(src,len) => out = ta.ema(2*ta.ema(src,len/2) - ta.ema(src,len),math.round(math.sqrt(len))) hema = hullEMA(src,length) ATRange = hullEMA(ta.tr(true),lengthATR) yup = hema + ATRange ydn = hema - ATRange // stochastic stoch1 = gain * (close - ta.lowest(low, lengthStoch)) / (ta.highest(high, lengthStoch) - ta.lowest(low, lengthStoch)) k = hullEMA(stoch1, smoothK) hemacol = hema > hema[1] ? color.green : color.red sellflag = hemacol==color.red and (ta.crossunder(k,0.8*gain) or ta.crossunder(k[1],stochlimit*gain) or ta.crossunder(k[2],0.8*gain)) buyflag = hemacol==color.green and (ta.crossover(k,0.2*gain) or ta.crossover(k[1],(1-stochlimit)*gain) or ta.crossover(k[2],0.2*gain)) plot(hema, color = hemacol,linewidth = 2) // plot(yup, linewidth = 2) // plot(ydn, linewidth = 2) ytr = hullEMA(src*1.005,400) plot(ytr+k, color=color.black, linewidth = 1) plot(ytr+0.8*gain , linewidth = 1) plot(ytr+0.2*gain, linewidth = 1) plotshape(sellflag, location.abovebar, style=shape.labeldown, color=color.new(color.red,10) , size=size.small) plotshape(buyflag, location.belowbar, style=shape.labelup, color=color.new(color.green,10) , size=size.small)
Oscillator Workbench — Chart [LucF]
https://www.tradingview.com/script/BY9mAioc-Oscillator-Workbench-Chart-LucF/
LucF
https://www.tradingview.com/u/LucF/
2,385
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/ // © LucF //@version=5 indicator("Oscillator Workbench — Chart [LucF]", "OWC", true, precision = 4, max_bars_back = 1000) // Oscillator Workbench — Chart [LucF] // v3, 2022.10.27 17:58 — LucF // This code was written using the recommendations from the Pine Script™ User Manual's Style Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html import TradingView/ta/4 as TvTa import LucF/ta/2 as LucfTa //#region ———————————————————— Constants // Colors color LIME = #00FF00ff color LIME_MD = #00FF0090 color LIME_LT = #00FF0040 color TEAL = #008080ff color TEAL_MD = #00808090 color TEAL_LT = #00808040 color PINK = #FF0080ff color PINK_MD = #FF008090 color PINK_LT = #FF008040 color MAROON = #800000ff color MAROON_MD = #80000090 color MAROON_LT = #80000040 color ORANGE = #c56606ff color ORANGE_BR = #FF8000ff color GRAY = #808080ff color GRAY_MD = #80808090 color GRAY_LT = #80808030 color WHITE = #FFFFFFff // Reference MAs string MA01 = "Simple MA" string MA02 = "Exponential MA" string MA03 = "Wilder MA" string MA04 = "Weighted MA" string MA05 = "Volume-weighted MA" string MA06 = "Arnaud Legoux MA" string MA07 = "Hull MA" string MA08 = "Symmetrically-weighted MA" // Oscillators string OS00 = "None" string OS01 = "RSI (SL)" string OS02 = "MACD (S)" string OS03 = "CCI (SL)" string OS04 = "Chande Momentum Oscillator (SL)" string OS05 = "Stochastic (SL)" string OS06 = "Stochastic RSI (SL)" string OS09 = "MFI (L)" string OS10 = "True Strength Index (SL)" string OS11 = "Williams % Range (L)" string OS12 = "Ultimate Oscillator (L)" string OS13 = "Klinger Volume Oscillator (L)" string OS14 = "Schaff Trend Cycle (SL)" string OS15 = "Volume Zone Oscillator (L)" string OS16 = "Price Zone Oscillator (L)" string OS17 = "Sentiment Zone Oscillator (SL)" string OS18 = "Wave Period Oscillator (L)" string OS19 = "Volume Buoyancy (L)" string OS20 = "Coppock Curve (SL)" string OS21 = "Aroon (L)" string OS22 = "DMI (L)" string OS23 = "TRIX (SL)" string OS24 = "Ease of Movement (L)" string OS25 = "Fisher Transform (SL)" string OS26 = "Signs of the Times" string OS27 = "Hilbert Transform (S)" string OS28 = "Intraday Intensity Index" string OS52 = "True Range" string OS54 = "Momentum (SL)" string OS55 = "Rate of Change (SL)" string OS90 = "Efficient Work (L)" // Oscillator Channel capping mode string CAP1 = "Standard deviations" string CAP2 = "Multiples of ATR" // Divergence detection mode string DIV1 = "Opposite directions of the weighted and reference lines" string DIV2 = "Opposite directions of the oscillator and the polarity of close to close" // Line styles string STL1 = "Line" string STL2 = "Circles" string STL3 = "Crosses" // Marker oscillator channel transitions string ST0 = "None" string ST1 = "Oscillator channel strong bull state" string ST2 = "Oscillator channel bull or strong bull state" string ST3 = "Oscillator channel strong bear state" string ST4 = "Oscillator channel bear or strong bear state" // Marker Divergence channel transitions string SV0 = "None" string SV1 = "Divergence channel strong bull state" string SV2 = "Divergence channel bull or strong bull state" string SV3 = "Divergence channel strong bear state" string SV4 = "Divergence channel bear or strong bear state" // Bar color choices string CB0 = "None" string CB1 = "On divergences only" string CB2 = "On divergences and on the state of the oscillator channel" string CB3 = "On divergences and on the state of the divergence channel" string CB4 = "On divergences and on the combined state of both channels" // Channel level sources string CH1 = "High and Low" string CH2 = "Open and Close" // Channel breach sources string BR1 = "`low` must breach channel's top, `high` must breach channel's bottom" string BR2 = "`high` must breach channel's top, `low` must breach channel's bottom" string BR3 = "Close" string BR4 = "Open" string BR5 = "The average of high and low (hl2)" string BR6 = "The average of high, low and close (hlc3)" string BR7 = "The average of high, low and two times the close (hlcc4)" string BR8 = "The average of high, low, close and open (ohlc4)" // Tooltips string TT_OSC1 = "To use one of the oscillators provided in the Workbench, select it here. \n\nThe 'S' or 'L' in parentheses indicates when the 'Source' or 'Length' fields of this line are taken into account when calculating the oscillator's value. \n\nNote that for some of the oscillators, assumptions are made concerning their different parameters when they are more complex than just a source and length. See the `oscCalc()` function in this indicator's code for all the details, and ask me in a comment if you can't find the information you need." string TT_OSC2 = "To use a second oscillator provided in the Workbench, select it here. If you select two oscillators, each of their weight will count for an equal part in the aggregate oscillator weight." string TT_OSCX = "To use an external oscillator, check the checkbox, select the external indicator you want to use, and specify its center value. \n\nIf you want only the external oscillator to be used, remember to select 'None' for the 'Oscillator 1' and 'Oscillator 2' choices above. If you do have oscillators selected for 'Oscillator 1' and/or 'Oscillator 2', their weight will be combined with that of the external oscillator. This way you can have up to three oscillator weights composing the aggregate oscillator weight." string TT_RVOL = "When checked, the aggregate weight of the oscillator(s) will be multiplied by the weight of the relative volume for the bar. This weight is determined using the percentile rank of the bar's volume in the number of bars you specify. The range of the weight is 0 to 1." string TT_REF = "Your choices here determine the reference that will be used as the oscillator channel's baseline. The MA type and length defined here are also used to calculate the MA of the weighted version of the reference's source." string TT_CAP = "This allows you to control the Oscillator channel's maximum height by limiting how far the weighted line can extend from the reference line. It is useful to keep the chart's vertical scale in check. The lower you set it, the less contours you will get in the weighted line.\n\n Keep in mind that this setting can also impact where divergences will occur on the chart.\n\n Using '" + CAP2 + "' will restrict the height more agressively. The ATR unit value used is its average over 20 bars." string TT_LTF = "Your selection here controls how many intrabars will be analyzed for each chart bar. The more intrabars you analyze per chart bar, the less chart bars will be covered by the indicator's calculations because a maximum of 100K intrabars can be analyzed.\n\n With the first four choices the quantity of intrabars is determined from the type of chart bar coverage you want. The last four choices allow you to select approximately how many intrabars you want analyzed per chart bar." string TT_BIAS = "This option enables a guess on the bull/bear bias of the channel before it is breached. It uses the number of changes of the top/bottom channel levels to determine a bias. When more changes of the top level occur, the bias is bullish. When more changes of the bottom level occur, the bias is bearish. \n\n Note that enabling this setting will make the channel's states less reliable." string TT_COLORS = "'🡑🡑' and '🡓🡓' indicate the colors used for strong bull/bear conditions. \n'🡑' and '🡓' indicate bull/bear conditions." string TT_MARKERS = "The conditions you use to determine when markers appear will also be used to trigger alerts created from this script. \n\nMarkers are non-repainting; they appear on the close of bars." string TT_DIV = "Using the second option here will produce less divergences with oscillators such as RSI, which closely follow price movements. It will also produce vastly different behaviors between oscillators." string TT_BARS = "If the coloring of bars on divergences is active, their body will always be colored in the divergence color, regardless of this checkbox's state." string TT_FILTERS = "The filters are additional conditions that must be true for a marker to appear. \n\n'Close-to-close polarity' means that the `close` must be higher than the previous one for an up marker, and vice versa. \n\n'Rising volume' means the volume of the bar must be higher than that of the previous one. This condition is the same for up/dn markers. \n\nThe filter on divergences requires a divergence to have occurred in the last number of bars you specify. \n\n'Bull/bear Oscillator' means that the value of the oscillator you select must be above/below its centerline. \n\nAs markers are non-repainting, keep in mind that marker conditions must be true on the bar's close, which is when the marker will appear." //#endregion //#region ———————————————————— Inputs string GRP1 = "Oscillators and relative volume" string osc1TypeInput = input.string(OS01, "Oscillator 1", group = GRP1, inline = "osc1", options = [OS00, OS21, OS03, OS04, OS20, OS22, OS24, OS90, OS25, OS27, OS28, OS13, OS02, OS09, OS54, OS16, OS55, OS01, OS14, OS17, OS26, OS05, OS06, OS23, OS52, OS10, OS12, OS19, OS15, OS18, OS11]) string osc1SourceInput = input.string("close", "", group = GRP1, inline = "osc1", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "volume"]) int osc1LengthInput = input.int(20, " Length", group = GRP1, inline = "osc1", minval = 2, tooltip = TT_OSC1) string osc2TypeInput = input.string(OS00, "Oscillator 2", group = GRP1, inline = "osc2", options = [OS00, OS21, OS03, OS04, OS20, OS22, OS24, OS90, OS25, OS27, OS28, OS13, OS02, OS09, OS54, OS16, OS55, OS01, OS14, OS17, OS26, OS05, OS06, OS23, OS52, OS10, OS12, OS19, OS15, OS18, OS11]) string osc2SourceInput = input.string("close", "", group = GRP1, inline = "osc2", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "volume"]) int osc2LengthInput = input.int(20, " Length", group = GRP1, inline = "osc2", minval = 2, tooltip = TT_OSC2) bool oscXInput = input.bool(false, "Oscillator 3 (external)", group = GRP1, inline = "oscX") float oscXSourceInput = input.source(close, "", group = GRP1, inline = "oscX") float oscXCenterInput = input.int(0, "Center", group = GRP1, inline = "oscX", tooltip = TT_OSCX) bool useRelVolWeightInput = input.bool(false, "Use weight of relative volume over n bars", group = GRP1, inline = "RelVolW", tooltip = TT_RVOL) int relVolLookbackInput = input.int(100, "", group = GRP1, inline = "RelVolW", minval = 2) string GRP2 = "Oscillator channel" bool reflLineShowInput = input.bool(false, "Reference line ", group = GRP2, inline = "refLine") int refLineWidthInput = input.int(1, " Width", group = GRP2, inline = "refLine", minval = 1) string refLineStyleInput = input.string(STL1, "", group = GRP2, inline = "refLine", options = [STL1, STL2, STL3]) color refLineUpUpColorInput = input.color(LIME, "  🡑🡑", group = GRP2, inline = "refLineColors") color refLineDnDnColorInput = input.color(PINK, "🡓🡓", group = GRP2, inline = "refLineColors") color refLineUpColorInput = input.color(TEAL, " 🡑", group = GRP2, inline = "refLineColors") color refLineDnColorInput = input.color(MAROON, "🡓", group = GRP2, inline = "refLineColors", tooltip = TT_COLORS) string refTypeInput = input.string(MA06, "  ", group = GRP2, inline = "ref", options = [MA01, MA02, MA03, MA04, MA05, MA06, MA07, MA08], tooltip = TT_REF) string refSourceInput = input.string("close", "", group = GRP2, inline = "ref", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "volume"]) int refLengthInput = input.int(20, " Length", group = GRP2, inline = "ref", minval = 2) bool osclLineShowInput = input.bool(false, "Weighted line", group = GRP2, inline = "oscLine") int oscLineWidthInput = input.int(2, "    Width", group = GRP2, inline = "oscLine", minval = 1) string oscLineStyleInput = input.string(STL1, "", group = GRP2, inline = "oscLine", options = [STL1, STL2, STL3]) color oscLineUpUpColorInput = input.color(LIME, "  🡑🡑", group = GRP2, inline = "oscLineColors") color oscLineDnDnColorInput = input.color(PINK, "🡓🡓", group = GRP2, inline = "oscLineColors") color oscLineUpColorInput = input.color(TEAL, " 🡑", group = GRP2, inline = "oscLineColors") color oscLineDnColorInput = input.color(MAROON, "🡓", group = GRP2, inline = "oscLineColors") float oscChannelCapInput = input.float(3.0, "  Cap the channel's height to", group = GRP2, inline = "cap", minval = 1, step = 0.5) string oscChannelCapModeInput = input.string(CAP1, "", group = GRP2, inline = "cap", options = [CAP1, CAP2], tooltip = TT_CAP) bool oscChannelShowInput = input.bool(false, "Oscillator channel", group = GRP2, inline = "oscChannel") color oscChannelUpUpColorInput= input.color(LIME_MD, "  🡑🡑", group = GRP2, inline = "oscChannelColors") color oscChannelDnDnColorInput= input.color(PINK_MD, "🡓🡓", group = GRP2, inline = "oscChannelColors") color oscChannelUpColorInput = input.color(TEAL_MD, " 🡑", group = GRP2, inline = "oscChannelColors") color oscChannelDnColorInput = input.color(MAROON_MD, "🡓", group = GRP2, inline = "oscChannelColors") string GRP3 = "Divergence channel" bool divLinesShowInput = input.bool(true, "Divergence levels", group = GRP3, inline = "divLines") int divLinesWidthInput = input.int(1, " Width", group = GRP3, inline = "divLines", minval = 1) string divLinesStyleInput = input.string(STL1, "", group = GRP3, inline = "divLines", options = [STL1, STL2, STL3]) color divLinesUpUpColorInput = input.color(LIME, "  🡑🡑", group = GRP3, inline = "divLinesColors") color divLinesDnDnColorInput = input.color(PINK, "🡓🡓", group = GRP3, inline = "divLinesColors") color divLinesUpColorInput = input.color(TEAL, " 🡑", group = GRP3, inline = "divLinesColors") color divLinesDnColorInput = input.color(MAROON, "🡓", group = GRP3, inline = "divLinesColors") color divLinesNtColorInput = input.color(GRAY, "N", group = GRP3, inline = "divLinesColors") bool divChannelShowInput = input.bool(false, "Divergence channel", group = GRP3, inline = "divChannel") color divChannelUpUpColorInput= input.color(LIME_MD, "  🡑🡑", group = GRP3, inline = "divChannelColors") color divChannelDnDnColorInput= input.color(PINK_MD, "🡓🡓", group = GRP3, inline = "divChannelColors") color divChannelUpColorInput = input.color(TEAL_MD, " 🡑", group = GRP3, inline = "divChannelColors") color divChannelDnColorInput = input.color(MAROON_MD, "🡓", group = GRP3, inline = "divChannelColors") color divChannelNtColorInput = input.color(GRAY_MD, "N", group = GRP3, inline = "divChannelColors") string divChannelLevelsInput = input.string(CH1, "  Levels are defined using", group = GRP3, options = [CH1, CH2]) string divChannelBreachesInput = input.string(BR1, "  Breaches are determined using", group = GRP3, options = [BR1, BR2, BR3, BR4, BR5, BR6, BR7, BR8]) string divDetectionModeInput = input.string(DIV1, "  Detect divergences on", group = GRP3, inline = "divDetection", options = [DIV1, DIV2], tooltip = TT_DIV) bool divChannelBiasInput = input.string("Off", "  Estimate unbreached channel bias", group = GRP3, options = ["On", "Off"], tooltip = TT_BIAS) == "On" bool charDivShowInput = input.bool(false, "Divergence mark", group = GRP3, inline = "divChar") string charDivInput = input.string("•", "", group = GRP3, inline = "divChar") color charDivColorInput = input.color(ORANGE, "", group = GRP3, inline = "divChar") bool charDivAboveInput = input.bool(true, "Above bar", group = GRP3, inline = "divChar") string GRP4 = "Bar coloring" bool barColorsShowInput = input.bool(true, "Color bars", group = GRP4, inline = "barMode") string colorBarModeInput = input.string(CB2, "", group = GRP4, inline = "barMode", options = [CB1, CB2, CB3, CB4]) bool barsEmptyOnDecVolInput = input.bool(false, "Don't color falling volume bars", group = GRP4, inline = "barMode", tooltip = TT_BARS) color barsUpUpColorInput = input.color(LIME, "  🡑🡑", group = GRP4, inline = "barColors") color barsDnDnColorInput = input.color(PINK, "🡓🡓", group = GRP4, inline = "barColors") color barsUpColorInput = input.color(TEAL, "🡑", group = GRP4, inline = "barColors") color barsDnColorInput = input.color(MAROON, "🡓", group = GRP4, inline = "barColors") color barsNtColorInput = input.color(GRAY, "N", group = GRP4, inline = "barColors") color barsDivColorInput = input.color(ORANGE, "D", group = GRP4, inline = "barColors") string GRP5 = "Markers & Alert conditions" string markerUpOscModeInput = input.string(ST0, "Up markers on transitions to  ", group = GRP5, inline = "upMarker", options = [ST0, ST1, ST2]) string markerUpDivModeInput = input.string(SV0, "", group = GRP5, inline = "upMarker", options = [SV0, SV1, SV2]) color markerUpColorInput = input.color(ORANGE_BR, "", group = GRP5, inline = "upMarker", tooltip = TT_MARKERS) string markerDnOscModeInput = input.string(ST0, "Down markers on transitions to", group = GRP5, inline = "dnMarker", options = [ST0, ST3, ST4]) string markerDnDivModeInput = input.string(SV0, "", group = GRP5, inline = "dnMarker", options = [SV0, SV3, SV4]) color markerDnColorInput = input.color(ORANGE_BR, "", group = GRP5, inline = "dnMarker") bool markerClosePolarityInput= input.bool(false, "Filter on close to close polarity  ", group = GRP5, inline = "Filters1", tooltip = TT_FILTERS) bool markerRisingVolInput = input.bool(false, "Filter on rising volume", group = GRP5, inline = "Filters1") bool markerDivInput = input.bool(false, "Filter on divergence in last n bars", group = GRP5, inline = "Filters2") int markerDivBarsInput = input.int(5, "", group = GRP5, inline = "Filters2", minval = 1) bool markerOscInput = input.bool(false, "Filter on bull/bear", group = GRP5, inline = "Filters3") string markerOscTypeInput = input.string(OS01, "", group = GRP5, inline = "Filters3", options = [OS21, OS03, OS04, OS20, OS22, OS24, OS90, OS25, OS27, OS28, OS13, OS02, OS09, OS54, OS16, OS55, OS01, OS14, OS17, OS05, OS06, OS23, OS52, OS10, OS12, OS19, OS15, OS18, OS11]) string markerOscSourceInput = input.string("close", "", group = GRP5, inline = "Filters3", options = ["open", "high", "low", "close", "hl2", "hlc3", "ohlc4", "hlcc4", "volume"]) int markerOscLengthInput = input.int(20, "", group = GRP5, inline = "Filters3", minval = 2) string alertUpMsgInput = input.text_area("▲", "Up alert text", group = GRP5) string alertDnMsgInput = input.text_area("▼", "Down alert text", group = GRP5) //#endregion //#region ———————————————————— Functions //@function Returns the centerline value for the `type` oscillator. //@param type (simple string) The type of oscillator (uses constants that must be defined earlier in the script). //@returns (series float) The centerline's value. oscCenter(simple string type) => float result = switch type OS01 => 50. OS05 => 50. OS06 => 50. OS09 => 50. OS11 => -50. OS12 => 50. OS14 => 50. => 0. //@function Returns the calculation of the `type` oscillator. //@param type (simple string) The type of oscillator (uses constants that must be defined earlier in the script). //@param src (series float) The source value used to calculate the oscillator, when one is needed. //@param length (simple int) The length value used to calculate the oscillator, when one is needed. //@returns (series float) The oscillator's value. oscCalc(simple string type, series float src, simple int length) => float result = switch type OS00 => na OS01 => ta.rsi(src, length) OS02 => [_, _, histLine] = ta.macd(src, 12, 26, 9) histLine OS03 => ta.cci(src, length) OS04 => ta.cmo(src, length) OS05 => ta.stoch(src, high, low, length) OS06 => float rsi = ta.rsi(src, length) ta.sma(ta.stoch(rsi, rsi, rsi, length), 3) OS09 => ta.mfi(hlc3, length) OS10 => ta.tsi(src, length, length * 2) OS11 => ta.wpr(length) OS12 => TvTa.uo(length / 2, length, length * 2) OS13 => [kvo, _] = TvTa.kvo(length, length * 2, length / 2) kvo OS14 => TvTa.stc(src, length, length * 2, length / 2, 3, 3) OS15 => TvTa.vzo(length) OS16 => TvTa.pzo(length) OS17 => TvTa.szo(src, length) OS18 => TvTa.wpo(length) OS19 => LucfTa.buoyancy(volume, length, 1000) OS20 => TvTa.coppock(src, length, length / 2, length / 2) OS21 => [up, dn] = TvTa.aroon(length) up - dn OS22 => [up, dn, _] = ta.dmi(length, length) up - dn OS23 => [trix, signal, hist] = TvTa.trix(src, length, int(length * 0.66)) trix OS24 => TvTa.eom(length) OS25 => TvTa.ft(src, length) OS26 => LucfTa.sott() OS27 => TvTa.ht(src) OS28 => ta.iii OS52 => ta.tr * math.sign(ta.change(close)) OS54 => ta.mom(src, length) OS55 => ta.roc(src, length) OS90 => LucfTa.efficientWork(length) => na //@function Returns the weight of an oscillator's value. //@param osc (series float) The oscillator's value. //@param center (simple float) The oscillator's centerline value. //@returns (series float) The weight (-1 to +1) of the oscillator's value. oscWeight(series float osc, simple float center = 0.0) => float normalizedOsc = osc - center float historicalMax = math.abs(ta.max(normalizedOsc)) float historicalMin = math.abs(ta.min(normalizedOsc)) float result = switch osc > center => normalizedOsc / historicalMax osc < center => - math.abs(normalizedOsc / historicalMin) => 0. //@function Throws a runtime error if the oscillator requires volume and none is available. //@param type (simple string) The type of oscillator (uses constants that must be defined earlier in the script). //@returns (void) Nothing. checkForNoVolume(simple string type) => bool oscUsesVolume = type == OS09 or type == OS15 or type == OS19 or type == OS24 if barstate.islast and ta.cum(nz(volume)) == 0 and oscUsesVolume runtime.error("No volume is provided by the data vendor.") //@function Determines when a state is entered on a bar where the previous state was different. //@param state (series bool) The state whose transition into must be identified. //@returns (series bool) `true` on the bar where we transition into the state, `false` otherwise. transitionTo(series bool state) => bool result = (not state[1] and state) //@function Determines a "plot_style" to be used from a user's input. //@param state (input string) The user selection string of his line style choice (depends on the `STL1`, `STL2` and `STL3` string constants). //@returns (plot_style) The `style` named argument required in `plot()`. lineStyleFromUserInput(userSelection) => result = switch userSelection STL1 => plot.style_line STL2 => plot.style_circles STL3 => plot.style_cross => plot.style_line //#endregion //#region ———————————————————— Calculations // Stop the indicator when the oscillator requires volume to calculate. checkForNoVolume(osc1TypeInput) checkForNoVolume(osc2TypeInput) // Oscillator value and weight. var float osc1Center = oscCenter(osc1TypeInput) var float osc2Center = oscCenter(osc2TypeInput) var float oscXCenter = oscXCenterInput float osc1 = oscCalc(osc1TypeInput, LucfTa.sourceStrToFloat(osc1SourceInput), osc1LengthInput) float osc2 = oscCalc(osc2TypeInput, LucfTa.sourceStrToFloat(osc2SourceInput), osc2LengthInput) float oscX = oscXInput ? oscXSourceInput : na int qtyOfOscillators = (not na(osc1) ? 1 : 0) + (not na(osc2) ? 1 : 0) + (not na(oscX) ? 1 : 0) float weight1 = oscWeight(osc1, osc1Center) float weight2 = oscWeight(osc2, osc2Center) float weightX = oscWeight(oscX, oscXCenter) float weight = (weight1 + weight2 + weightX) / qtyOfOscillators // Relative volume weight float relVolPctRank = ta.percentrank(volume, relVolLookbackInput) / 100. float relVolumeWeight = useRelVolWeightInput and not na(volume) ? relVolPctRank : 1. // Combined weight float combinedWeight = weight * relVolumeWeight // MAs of reference source and capped weighted source. float refSource = LucfTa.sourceStrToFloat(refSourceInput) float capUnits = oscChannelCapModeInput == CAP1 ? ta.stdev(refSource, refLengthInput) : ta.atr(20) float weightedSource = refSource + (math.sign(combinedWeight) * math.min(refSource * math.abs(combinedWeight), capUnits * oscChannelCapInput)) float reference = LucfTa.ma(refTypeInput, refSource, refLengthInput) float weightedRef = LucfTa.ma(refTypeInput, weightedSource, refLengthInput) // Determine bull/bear and strong bull/bear states of the oscillator channel. bool oscChannelBull = weightedRef > reference bool oscChannelBear = not oscChannelBull bool oscChannelBullStrong = oscChannelBull and close > reference and ta.rising(reference, 1) and ta.rising(weightedRef, 1) bool oscChannelBearStrong = oscChannelBear and close < reference and ta.falling(reference, 1) and ta.falling(weightedRef, 1) // ————— Divergence channel // Detect divergences between the slope of the reference line and that of the weighted line. bool divergence = divDetectionModeInput == DIV1 ? math.sign(ta.change(reference)) != math.sign(ta.change(weightedRef)) : math.sign(ta.change(combinedWeight)) != math.sign(ta.change(close)) // Level sources float divChannelHiSrc = divChannelLevelsInput == CH1 ? high : math.max(open, close) float divChannelLoSrc = divChannelLevelsInput == CH1 ? low : math.min(open, close) // Breach sources float divBreachHiSrc = na float divBreachLoSrc = na switch divChannelBreachesInput BR1 => divBreachHiSrc := low divBreachLoSrc := high BR2 => divBreachHiSrc := high divBreachLoSrc := low BR3 => divBreachHiSrc := close divBreachLoSrc := close BR4 => divBreachHiSrc := open divBreachLoSrc := open BR5 => divBreachHiSrc := hl2 divBreachLoSrc := hl2 BR6 => divBreachHiSrc := hlc3 divBreachLoSrc := hlc3 BR7 => divBreachHiSrc := hlcc4 divBreachLoSrc := hlcc4 BR8 => divBreachHiSrc := ohlc4 divBreachLoSrc := ohlc4 // Update the divergence channel. [divChannelHi, divChannelLo, divChannelBull, divChannelBear, divChannelBreached, newDivChannel, preBreachUpChanges, preBreachDnChanges] = LucfTa.divergenceChannel(divergence, divChannelHiSrc, divChannelLoSrc, divBreachHiSrc, divBreachLoSrc) // If needed, take a guess on the state of the channel when it has not yet been breached. bool preBreachBiasBull = not divChannelBreached and divChannelBiasInput and preBreachUpChanges > preBreachDnChanges bool preBreachBiasBear = not divChannelBreached and divChannelBiasInput and preBreachUpChanges < preBreachDnChanges // Strong bull/bear states occur when the divergence channel's bull/bear state matches that of the oscillator channel. bool divChannelBullStrong = divChannelBull and oscChannelBullStrong bool divChannelBearStrong = divChannelBear and oscChannelBearStrong // ————— Marker filters and triggers // Close-to-close polarity bool closeToCloseUp = ta.change(close) > 0 bool closeToCloseDn = ta.change(close) < 0 // Oscillator is bull/bear var float markerOscCenter = oscCenter(markerOscTypeInput) float markerOsc = oscCalc(markerOscTypeInput, LucfTa.sourceStrToFloat(markerOscSourceInput), markerOscLengthInput) bool oscBull = markerOsc > markerOscCenter bool oscBear = markerOsc < markerOscCenter // RIsing volume bool risingVolume = ta.change(volume) > 0 // Divergence in last n bars bool divPresent = ta.barssince(divergence) <= markerDivBarsInput // Base conditions for markers to appear. bool upMarkerOscCondition = switch markerUpOscModeInput ST1 => transitionTo(oscChannelBullStrong) ST2 => transitionTo(oscChannelBull) or transitionTo(oscChannelBullStrong) => false bool upMarkerDivCondition = switch markerUpDivModeInput SV1 => transitionTo(divChannelBullStrong) SV2 => transitionTo(divChannelBull) or transitionTo(divChannelBullStrong) => false bool dnMarkerOscCondition = switch markerDnOscModeInput ST3 => transitionTo(oscChannelBearStrong) ST4 => transitionTo(oscChannelBear) or transitionTo(oscChannelBearStrong) => false bool dnMarkerDivCondition = switch markerDnDivModeInput SV3 => transitionTo(divChannelBearStrong) SV4 => transitionTo(divChannelBear) or transitionTo(divChannelBearStrong) => false // Apply filters to base conditions. bool upMarker = upMarkerOscCondition or upMarkerDivCondition bool dnMarker = dnMarkerOscCondition or dnMarkerDivCondition upMarker := (markerUpOscModeInput != ST0 or markerUpDivModeInput != SV0) and upMarker and barstate.isconfirmed and (not markerClosePolarityInput or closeToCloseUp) and (not markerOscInput or oscBull) and (not markerRisingVolInput or risingVolume) and (not markerDivInput or divPresent) dnMarker := (markerDnOscModeInput != ST0 or markerDnDivModeInput != SV0) and dnMarker and barstate.isconfirmed and (not markerClosePolarityInput or closeToCloseDn) and (not markerOscInput or oscBear) and (not markerRisingVolInput or risingVolume) and (not markerDivInput or divPresent) //#endregion //#region ———————————————————— Visuals // ————— Oscillator Channel lines and fill. // Determine colors. color refLineColor = na color oscLineColor = na color oscChannelColor = na switch oscChannelBullStrong => refLineColor := refLineUpUpColorInput oscLineColor := oscLineUpUpColorInput oscChannelColor := oscChannelUpUpColorInput oscChannelBearStrong => refLineColor := refLineDnDnColorInput oscLineColor := oscLineDnDnColorInput oscChannelColor := oscChannelDnDnColorInput oscChannelBull => refLineColor := refLineUpColorInput oscLineColor := oscLineUpColorInput oscChannelColor := oscChannelUpColorInput oscChannelBear => refLineColor := refLineDnColorInput oscLineColor := oscLineDnColorInput oscChannelColor := oscChannelDnColorInput color oscColor = combinedWeight > 0 ? oscLineUpUpColorInput : combinedWeight < 0 ? oscLineDnDnColorInput : color.silver // Styles for lines. var refLineStyle = lineStyleFromUserInput(refLineStyleInput) var oscLineStyle = lineStyleFromUserInput(oscLineStyleInput) // Plot lines and fill them. var bool plotOscLineValues = reflLineShowInput or osclLineShowInput or oscChannelShowInput weightedPlot = plot(plotOscLineValues ? weightedRef : na, "Weighted Reference", osclLineShowInput ? oscLineColor : na, oscLineWidthInput, oscLineStyle) refPlot = plot(plotOscLineValues and not na(combinedWeight) ? reference : na, "Reference", reflLineShowInput ? refLineColor : na, refLineWidthInput, refLineStyle) fill(weightedPlot, refPlot, reference, weightedRef, oscChannelShowInput ? oscChannelColor : na, oscChannelShowInput ? color.new(oscChannelColor, 90) : na, "Fill") // ————— Divergence channel lines and fill. // Determine colors. color divLinesColor = na color divChannelColor = na if divChannelBreached switch divChannelBullStrong => divLinesColor := divLinesUpUpColorInput divChannelColor := divChannelUpUpColorInput divChannelBearStrong => divLinesColor := divLinesDnDnColorInput divChannelColor := divChannelDnDnColorInput divChannelBull => divLinesColor := divLinesUpColorInput divChannelColor := divChannelUpColorInput divChannelBear => divLinesColor := divLinesDnColorInput divChannelColor := divChannelDnColorInput => divLinesColor := divLinesNtColorInput divChannelColor := divChannelNtColorInput else switch divChannelBiasInput and preBreachBiasBull => divLinesColor := divLinesUpColorInput divChannelColor := divChannelUpColorInput divChannelBiasInput and preBreachBiasBear => divLinesColor := divLinesDnColorInput divChannelColor := divChannelDnColorInput => divLinesColor := divLinesNtColorInput divChannelColor := divChannelNtColorInput // Plot the channel levels and fill. var bool plotDivLineValues = divLinesShowInput or divChannelShowInput var divLineStyle = lineStyleFromUserInput(divLinesStyleInput) float divChannelMid = math.avg(divChannelHi, divChannelLo) divChannelHiPlot = plot(plotDivLineValues ? divChannelHi : na, "Divergence Channel Hi", not newDivChannel and divLinesShowInput ? divLinesColor : na, divLinesWidthInput, divLineStyle) divChannelLoPlot = plot(plotDivLineValues ? divChannelLo : na, "Divergence Channel Lo", not newDivChannel and divLinesShowInput ? divLinesColor : na, divLinesWidthInput, divLineStyle) // This midline is used to start/end the two different gradient fills used to fill the divergence channel. divChannelMidPlot = plot(plotDivLineValues ? divChannelMid : na, "Divergence Channel Mid", na, display = display.none) // Fill from the middle going up and down. fill(divChannelHiPlot, divChannelMidPlot, divChannelHi, divChannelMid, not newDivChannel and divChannelShowInput ? divChannelColor : na, not newDivChannel and divChannelShowInput ? color.new(divChannelColor, 99) : na) fill(divChannelMidPlot, divChannelLoPlot, divChannelMid, divChannelLo, not newDivChannel and divChannelShowInput ? color.new(divChannelColor, 99) : na, not newDivChannel and divChannelShowInput ? divChannelColor : na) // ————— Display key values in indicator values and Data Window. displayLocations = display.status_line + display.data_window color osc1Color = weight1 > 0 ? color.lime : color.fuchsia color osc2Color = weight2 > 0 ? color.lime : color.fuchsia color oscXColor = weightX > 0 ? color.lime : color.fuchsia color weightColor = weight > 0 ? color.lime : color.fuchsia plot(refSource, "Reference source", display = displayLocations, color = refLineColor) plot(weightedSource, "Weighted source", display = displayLocations, color = oscLineColor) plot(na, "═════════════════", display = displayLocations) plot(osc1, "Oscillator 1", display = displayLocations, color = osc1Color) plot(osc2, "Oscillator 2", display = displayLocations, color = osc2Color) plot(oscX, "Oscillator X", display = displayLocations, color = oscXColor) plot(weight1, "Weight 1", display = displayLocations, color = osc1Color) plot(weight2, "Weight 2", display = displayLocations, color = osc2Color) plot(weightX, "Weight X", display = displayLocations, color = oscXColor) plot(relVolumeWeight, "Relative Volume weight", display = displayLocations) plot(combinedWeight, "Combined weight", display = displayLocations, color = weightColor) plot(na, "═════════════════", display = displayLocations) // ————— Markers plotchar(upMarker, "Up Marker", "▲", location.belowbar, markerUpColorInput, size = size.tiny) plotchar(dnMarker, "Down Marker", "▼", location.abovebar, markerDnColorInput, size = size.tiny) // ————— Alerts switch upMarker => alert(alertUpMsgInput) dnMarker => alert(alertDnMsgInput) // ————— Chart bar coloring // Color color barColor = if barColorsShowInput switch colorBarModeInput CB1 => switch divergence => barsDivColorInput CB2 => switch divergence => barsDivColorInput oscChannelBullStrong => barsUpUpColorInput oscChannelBearStrong => barsDnDnColorInput oscChannelBull => barsUpColorInput oscChannelBear => barsDnColorInput => barsNtColorInput CB3 => switch divergence => barsDivColorInput divChannelBullStrong => barsUpUpColorInput divChannelBearStrong => barsDnDnColorInput divChannelBull => barsUpColorInput divChannelBear => barsDnColorInput => barsNtColorInput CB4 => switch divergence => barsDivColorInput oscChannelBullStrong and divChannelBullStrong => barsUpUpColorInput oscChannelBearStrong and divChannelBearStrong => barsDnDnColorInput (oscChannelBull or oscChannelBullStrong) and (divChannelBull or divChannelBullStrong) => barsUpColorInput (oscChannelBear or oscChannelBearStrong) and (divChannelBear or divChannelBearStrong) => barsDnColorInput => barsNtColorInput => na else na // Empty bodies on decreasing chart volume. if barsEmptyOnDecVolInput and ta.falling(volume, 1) and not divergence barColor := na barcolor(barColor) // ————— Plot character showing divergences. plotchar(charDivShowInput ? divergence : na, "Divergence character", charDivInput, charDivAboveInput ? location.abovebar : location.belowbar, charDivColorInput, size = size.tiny) //#endregion
Relative Volume Prices Index by @WilliamBelini
https://www.tradingview.com/script/ulGylFAr-Relative-Volume-Prices-Index-by-WilliamBelini/
wbelini
https://www.tradingview.com/u/wbelini/
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/ // © wbelini // Volume Price Course Belini - VPCB // This indicator is a part of a pack of indicators created by William Belini, that suppose the market move based from volume effects at prices. // !! My theory arguments are these: !! // >> The oscillation at prices compared with the volume that make it happen, can describe the market comportment. // >> Small oscillation with big volume denotes a stable market, and big oscillation with small volume denote a market course variation. // - The first indicator is the Relative Volume Prices Index Belini - RVPI, that denote how volume are impacting prices. Meas the sensibility of prices by volume; // - The second indicator is The Relative Market Status Belini - RMS, what denote the market feeling cicles; // - The third indicator its elaborated to traders, named Trade Trigger RVPI Belini - TTR, // that show the best moment to start a position trading. Do this based from a normal distribution analysis, // from previous values designed by the Relative Prices Index Belini indicator and its historical impact at the future prices. //Ps. These indicators are made based from commodities contracts environment and have adaptative mechanisms from their peculiarities. // To use for other markets could be necessary modifications. //Note: This site don´t recompense creators to their creations, and don´t promove the individual creativity because don´t permite we promote our work. // Even though our creations do money to their users. So, I´m disponibilize 2 of 3 indicators here, to have the third, you need contact whit me. //@version=5 indicator(title="Relative Volume Prices Index by @WilliamBelini", shorttitle="RVPI-B", format=format.price, precision=0, timeframe="", timeframe_gaps=true, overlay = false) vol = volume <= 0 ? 1 : math.pow(volume,1) /////NEGATIVE AND POSITIVE VOLUME AVERAGE///// // This component is necessary because the volume are changing by the time, and this variation distorce de indicator. // The volume are meas and calculate the average from last periods, to minimize the impact by desviations. // The average volume is calculating from positive and negative prices variation to capture their peculiarities. comprimento = 7 // Define the number of past candles from average fonte = volume var volp = array.new_float(comprimento,fonte) if close[0]>=close[1] array.push(volp, fonte) array.shift(volp) volpmedio = array.avg(volp) var voln = array.new_float(comprimento, fonte) if close[0]<close[1] array.push(voln,fonte) array.shift(voln) volnmedio = array.avg(voln) volmed = (close[0]>=close[1])? volpmedio*1000000 :volnmedio*1000000 ////// THE FIRST INDICATOR: Volume Price Force Belini [VPFB] ///////// FV =((close[0]-close[1])/(close[1])) FV2 = vol <50 ? 0 : math.pow(FV,2)/vol FVC = FV<0 ?FV2*-1 : FV2 cor = FV>0 ? color.green : color.red plot(FVC*volmed, color=cor, style=plot.style_columns, title = "T1")
RSI Profile
https://www.tradingview.com/script/hqxJC0QA-RSI-Profile/
AtifRizwan
https://www.tradingview.com/u/AtifRizwan/
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/ // © AtifRizwan //@version=5 indicator("RSI Profile") profileType = input.string("RSI Values","Profile Type",options=["RSI Values","RSI Pivots High","RSI Pivots Low"]) rsilen = input.int(14,"RSI Length") rsisrc = input.source(close,"RSI Source") leftLenH = input.int(14,"Pivot High ",group="Pivot Length Left/Right",inline="ph") rightLenH = input.int(14,"/",group="Pivot Length Left/Right",inline="ph") showPivotH = input.bool(false,"Show?",group="Pivot Length Left/Right",inline="ph") leftLenL = input.int(14,"Pivot Low",group="Pivot Length Left/Right",inline="pl") rightLenL = input.int(14,"/",group="Pivot Length Left/Right",inline="pl") showPivotL = input.bool(false,"Show?",group="Pivot Length Left/Right",inline="pl") lineColor = input.color(color.purple,"Histogram",group="Visuals",inline="line") lineWidth = input.int(1,"Width",group="Visuals",inline="line") maxLineColor= input.color(color.red,"POC Line",group="Visuals",inline="maxline") maxlineWidth= input.int(1,"Width",group="Visuals",inline="maxline") maxlineEx = input.bool(true,"Extend POC Line",group="Visuals",inline="maxline") showMax = input.bool(true,"Show POC Values?",group="Visuals",inline="showmax") _offset = input.int(5,"Histogram Offset",group="Visuals") maxWidth = input.int(55,"Width of Histogram",group="Visuals") maxRSI = input.int(70,"Max RSI",group="Visuals") minRSI = input.int(30,"Min RSI",group="Visuals") rsi = ta.rsi(rsisrc,rsilen) ph = ta.pivothigh(rsi,leftLenH,rightLenH) pl = ta.pivotlow(rsi,leftLenL,rightLenL) plot(rsi,color=color.purple,linewidth=2,title="RSI") rsilow=hline(30,title="RSI Low Band") rsihigh=hline(70,title="RSI High Band") fill(rsilow,rsihigh,color=color.new(color.purple,90),title = "RSI Band Background") var rsi_array = array.new_int(100) var li = array.new_line(0) var line li1 = na var label la = na float pivotH = na float pivotL = na if bar_index==1 for i = 0 to 99 array.set(rsi_array,i,0) if bar_index > 1 and profileType=="RSI Values" array.set(rsi_array,math.floor(rsi),array.get(rsi_array,math.floor(rsi))+1) if bar_index > 1 and profileType=="RSI Pivots High" and not na(ph) array.set(rsi_array,math.floor(ph),array.get(rsi_array,math.floor(ph))+1) if bar_index > 1 and profileType=="RSI Pivots Low" and not na(pl) array.set(rsi_array,math.floor(pl),array.get(rsi_array,math.floor(pl))+1) if showPivotH and not na(ph) pivotH:=ph if showPivotL and not na(pl) pivotL:=pl plotshape(pivotH,"Pivot High",offset=-rightLenH,location=location.absolute,style=shape.diamond,color=color.new(color.red,30),size=size.small) plotshape(pivotL,"Pivot Low",offset=-rightLenL,location=location.absolute,style=shape.diamond,color=color.new(color.green,30),size=size.small) if barstate.islast if array.size(li) > 0 for i = 0 to array.size(li)-1 line.delete(array.get(li,i)) array.clear(li) label.delete(la) line.delete(li1) color c=na int w=1 bool isMax=na max=array.max(rsi_array) li1:=line.new(bar_index+_offset,minRSI,bar_index+_offset,maxRSI,color=color.gray) for i = minRSI to maxRSI thisWidth=math.ceil((array.get(rsi_array,i))/max*maxWidth) isMax:=thisWidth==maxWidth w:=isMax?maxlineWidth:lineWidth c:=isMax?maxLineColor:lineColor array.push(li,line.new(bar_index+_offset,i,bar_index+_offset+thisWidth,i,width=w,color=c,extend=isMax?extend.left:extend.none)) if isMax and showMax la:=label.new(bar_index+_offset+maxWidth+5,i,str.tostring(i),style=label.style_label_left,color=color.red,textcolor=color.white)
Relative Market Status by @WilliamBelini
https://www.tradingview.com/script/qZbWtvMm-Relative-Market-Status-by-WilliamBelini/
wbelini
https://www.tradingview.com/u/wbelini/
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/ // © wbelini // Volume Price Course Belini - VPCB // This indicator is a part of a pack of indicators created by William Belini, that suppose the market move based from volume effects at prices. // !! My theory arguments are these: !! // >> The oscillation at prices compared with the volume that make it happen, can describe the market comportment. // >> Small oscillation with big volume denotes a stable market, and big oscillation with small volume denote a market course variation. // - The first indicator is the Relative Volume Prices Index Belini - RVPI, that denote how volume are impacting prices. Meas the sensibility of prices by volume; // - The second indicator is The Relative Market Status Belini - RMS, what denote the market feeling cicles; // - The third indicator its elaborated to traders, named Trade Trigger RVPI Belini - TTR, // that show the best moment to start a position trading. Do this based from a normal distribution analysis, // from previous values designed by the Relative Prices Index Belini indicator and its historical impact at the future prices. //Ps. These indicators are made based from commodities contracts environment and have adaptative mechanisms from their peculiarities. // To use for other markets could be necessary modifications. //@version=5 indicator(title="Relative Market Status by @WilliamBelini", shorttitle="RMS-B", format=format.price, precision=0, timeframe="", timeframe_gaps=true, overlay = false) vol = volume <= 0 ? 1 : math.pow(volume,1) /////NEGATIVE AND POSITIVE VOLUME AVERAGE///// // This component is necessary because the volume are changing by the time, and this variation distorce de indicator. // The volume are meas and calculate the average from last periods, to minimize the impact by desviations. // The average volume is calculating from positive and negative prices variation to capture their peculiarities. comprimento = 7 // Define the number of past candles from average fonte = volume var volp = array.new_float(comprimento,fonte) if close[0]>=close[1] array.push(volp, fonte) array.shift(volp) volpmedio = array.avg(volp) var voln = array.new_float(comprimento, fonte) if close[0]<close[1] array.push(voln,fonte) array.shift(voln) volnmedio = array.avg(voln) volmed = (close[0]>=close[1])? volpmedio*1000000 :volnmedio*1000000 ////// THE FIRST INDICATOR: Volume Price Force Belini [VPFB] ///////// FV =((close[0]-close[1])/(close[1])) FV2 = vol <50 ? 0 : math.pow(FV,2)/vol FVC = FV<0 ?FV2*-1 : FV2 cor = FV>0 ? color.green : color.red //plot(FVC*volmed, color=cor, style=plot.style_columns, title = "T1") ///// THE SECOND INDICATOR: Relative Market Status Belini [RMS] /////// ///// FV ACU ///// / FVAcu= ta.cum(FVC) ////// FV CROSS MED ////// periodK = input.int(1, title="Short Average", minval=1) periodD = input.int(15, title="Long Average", minval=1) FVAcuMed = ta.sma(FVAcu,periodK) FVAcuMedM = ta.sma(FVAcu, periodD) DifMedia = (FVAcuMed - FVAcuMedM)*volmed cor1 = DifMedia < 0 ? color.gray : color.orange plot(DifMedia, title="Cross averages RVFI", color=cor1, style = plot.style_area) hline(0,color= color.gray)
Round Number Levels
https://www.tradingview.com/script/oE813Qz0-Round-Number-Levels/
melodicfish
https://www.tradingview.com/u/melodicfish/
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/ // © melodicfish //@version=5 indicator("Round Number Levels",overlay = true,max_labels_count = 101,max_lines_count = 101) incrementVal=input.float(defval=500, title="Unit Place Rounding Value", tooltip = "The Unit Place that a number will be rounded and distance between rounded levels. Example Value setting of 100 and a price of 225.00 would result in a line level value of 200.00; Where a price of 265.00 would result in a line level value of 300 with the same value setting of 100") lQty=input.int(defval=2,minval=1,maxval=50, title="Line Amount",tooltip = "Each Line Amount increase will add a line level above and below baseline level; Baseline = line nearest to price) ") offset=input.int(defval=50,minval=0, maxval=490,step=10, title="Line Price Horizontal Offset",inline = "a") textCol=input.color(defval = color.white,title="Price Label Text Color",tooltip = "Use Horizontal Offset to adjust the X position of the price labels. To hide price labels disable Labels on the style tab",inline = "a") belowColor=input.color(defval = color.blue,title="Line Color Below price",inline="b") aboveColor=input.color(defval = color.orange,title="Line Color Above price",inline="b") ext=input.string(defval = "To Right",options = ["To Right","Both"],title="Extend Line: ") float iv= incrementVal lQty:=lQty+1 var lines=array.new_line(lQty*2) var labels=array.new_label(lQty*2) var line baseLine=na RoundValue(value) => math.round(value / iv) * iv baseVal=RoundValue(close) if barstate.isconfirmed and baseVal!= baseVal[1] for i = 0 to (lQty*2) - 1 line.delete(array.get(lines,i)) label.delete(array.get(labels,i)) lines:=array.new_line(lQty*2) labels:=array.new_label(lQty*2) for j = 0 to lQty - 1 newLine=line.new(bar_index,baseVal+(j*iv),bar_index+1,baseVal+(j*iv),extend=ext=="Both"?extend.both:extend.right,color=close>baseVal+(j*iv)?belowColor:aboveColor) newLabel=label.new(bar_index+1+offset,baseVal+(j*iv),text=str.tostring(baseVal+(j*iv)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines,j,newLine) array.insert(labels,j,newLabel) for k = 1 to lQty - 1 newLine=line.new(bar_index,baseVal-(k*iv),bar_index+1,baseVal-(k*iv),extend=ext=="Both"?extend.both:extend.right,color=belowColor) newLabel=label.new(bar_index+1+offset,baseVal-(k*iv),text=str.tostring(baseVal-(k*iv)),style= label.style_none,textcolor = textCol, textalign=text.align_right) array.insert(lines,k+lQty,newLine) array.insert(labels,k+lQty,newLabel) else if barstate.isconfirmed and baseVal== baseVal[1] line.set_color(array.get(lines,0),color=close>baseVal?belowColor:aboveColor) for l = 0 to (lQty*2)-1 label.set_x(array.get(labels,l),bar_index+1+offset)
AmitN STDEV V5
https://www.tradingview.com/script/mDYlR901-AmitN-STDEV-V5/
amitni82
https://www.tradingview.com/u/amitni82/
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/ // © amitni82 //@version=5 indicator("AmitN STDEV V5", max_bars_back = 365,overlay = true) lookbackPeriod = input.int(365, "Lookback period for STDEV") numberOfDays = input.int(7, "Number of candles to find the range") extendRange = input.bool(true, "Extend the range lines") // Daily log returns logClose = math.log(close / close[1]) // Average/Mean smalogClose = ta.sma(logClose, lookbackPeriod) // Daily Volatility SD dailyVolatility = ta.stdev(logClose, lookbackPeriod) // Spot CMP - Close of current candle spotCmp = close // request.security(syminfo.tickerid, "D", close, barmerge.gaps_on , barmerge.lookahead_off) // Custom deviations averageMean = numberOfDays * smalogClose volatilitySD = dailyVolatility * math.sqrt(numberOfDays) // Price range calculations minPriceX1SD = spotCmp * math.exp(averageMean - (1 * volatilitySD)) maxPriceX1SD = spotCmp * math.exp(averageMean + 1 * volatilitySD) minPriceX2SD = spotCmp * math.exp(averageMean - (2 * volatilitySD)) maxPriceX2SD = spotCmp * math.exp(averageMean + (2 * volatilitySD)) var tbl = table.new(position.top_right, 5, 7, border_color = color.white, border_width = 1, frame_color = color.gray, frame_width = 2) if barstate.islast line.new(bar_index, maxPriceX1SD, bar_index + (extendRange ? numberOfDays : 7), maxPriceX1SD, color= color.aqua, style = line.style_solid, width = 4) label.new(bar_index + 7, maxPriceX1SD, str.tostring(math.round_to_mintick(maxPriceX1SD)) + " (" + str.tostring(math.round_to_mintick(maxPriceX1SD-close)) + " ~ " + str.tostring(math.round(((maxPriceX1SD /close) - 1) * 100, 2))+ "%)", textcolor = color.white, size = size.large) line.new(bar_index, minPriceX1SD, bar_index + (extendRange ? numberOfDays : 7), minPriceX1SD, color= color.aqua, style = line.style_solid, width = 4) label.new(bar_index + 7, minPriceX1SD, str.tostring(math.round_to_mintick(minPriceX1SD)) + " (" + str.tostring(math.round_to_mintick(minPriceX1SD-close)) + " ~ " + str.tostring(math.round(((minPriceX1SD /close) - 1) * 100, 2))+ "%)", textcolor = color.white, size = size.large) line.new(bar_index, maxPriceX2SD, bar_index + (extendRange ? numberOfDays : 7), maxPriceX2SD, color= color.maroon, style = line.style_solid, width = 5) label.new(bar_index + 7, maxPriceX2SD, str.tostring(math.round_to_mintick(maxPriceX2SD)) + " (" + str.tostring(math.round_to_mintick(maxPriceX2SD-close)) + " ~ " + str.tostring(math.round(((maxPriceX2SD /close) - 1) * 100, 2))+ "%)", textcolor = color.white, size = size.large) line.new(bar_index, minPriceX2SD, bar_index + (extendRange ? numberOfDays : 7), minPriceX2SD, color= color.maroon, style = line.style_solid, width = 5) label.new(bar_index + 7, minPriceX2SD, str.tostring(math.round_to_mintick(minPriceX2SD)) + " (" + str.tostring(math.round_to_mintick(minPriceX2SD-close)) + " ~ " + str.tostring(math.round(((minPriceX2SD /close) - 1) * 100, 2))+ "%)", textcolor = color.white, size = size.large) table.cell(tbl, 0, 0, "Range for", text_color = color.white, bgcolor = color.rgb(91, 92, 95), width = 12, height = 4, text_size = size.large) table.cell(tbl, 0, 1, str.tostring(numberOfDays) + " candles", text_color = color.white, bgcolor = color.rgb(91, 92, 95), width = 7, height = 4, text_size = size.large) table.cell(tbl, 0, 2, str.tostring(numberOfDays) + " candles", text_color = color.white, bgcolor = color.rgb(91, 92, 95), width = 7, height = 4, text_size = size.large) table.cell(tbl, 1, 0, "StdDev", text_color = color.white, bgcolor = color.rgb(91, 92, 95), width = 7, height = 4, text_size = size.large) table.cell(tbl, 1, 1, "1", text_color = color.white, bgcolor = color.gray, width = 7, height = 4, text_size = size.auto) table.cell(tbl, 1, 2, "2", text_color = color.white, bgcolor = color.gray, width = 7, height = 4, text_size = size.auto) table.cell(tbl, 2, 0, "Min", text_color = color.white, bgcolor = color.rgb(91, 92, 95), width = 7, height = 4, text_size = size.large) table.cell(tbl, 2, 1, str.tostring(math.round_to_mintick(minPriceX1SD)), text_color = color.white, bgcolor = color.gray, width = 7, height = 4, text_size = size.auto) table.cell(tbl, 2, 2, str.tostring(math.round_to_mintick(minPriceX2SD)), text_color = color.white, bgcolor = color.gray, width = 7, height = 4, text_size = size.auto) table.cell(tbl, 3, 0, "Max", text_color = color.white, bgcolor = color.rgb(91, 92, 95), width = 7, height = 4, text_size = size.large) table.cell(tbl, 3, 1, str.tostring(math.round_to_mintick(maxPriceX1SD)), text_color = color.white, bgcolor = color.gray, width = 7, height = 4, text_size = size.auto) table.cell(tbl, 3, 2, str.tostring(math.round_to_mintick(maxPriceX2SD)), text_color = color.white, bgcolor = color.gray, width = 7, height = 4, text_size = size.auto)
PatronsitoP
https://www.tradingview.com/script/EzuGkU7m/
theinfamouspaul
https://www.tradingview.com/u/theinfamouspaul/
49
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/ // © theinfamouspaul //@version=5 indicator(title="PatronsitoP by Sr.Sombrero", shorttitle="PatronsitoP", overlay=true) // ---- Inputs & Plotting plotEma = input.bool(true, "EMA", group="Display in chart") plotBB = input.bool(true, "Bollinger bands", group="Display in chart") plotRSI = input.bool(true, "RSI", group="Display in chart") plotOI = input.bool(true, "Open Interest", group="Display in chart") plotRSIHeaderColor = input.color(defval=color.orange, title="RSI Header color", group = "Display in chart") plotRSIValueColor = input.color(defval=color.white, title="RSI Value color", group = "Display in chart") bbSource = input.source(close, "Source", group="Bollinger Bands") bbLength = input.int(20, "Length", group="Bollinger Bands") bbStdDev = input.int(2, "Dev", group="Bollinger Bands") rsiSource = input.source(close, "Source", group="RSI") rsiLength = input.int(14, "Length", 1, group="RSI") rsiExtra1Timeframe = input.timeframe(defval = "60", title="Extra1 Timeframe", group="RSI") rsiExtra2Timeframe = input.timeframe(defval = "240", title="Extra2 Timeframe", group="RSI") rsiLongValue = input.int(20, "Long if RSI below", 1, 100, group="Alert signals") rsiShortValue = input.int(80, "Short if RSI above", 1, 100, group="Alert signals") emaSource = input.source(close, "Source", group="EMA") emaLength = input.int(13, "Length", group="EMA") // ---- Main // EMA emaLine = ta.ema(emaSource, emaLength) // Bollinger Bands data [bbMiddle, bbUpper, bbLower] = ta.bb(bbSource, bbLength, bbStdDev) // Long condition rsiValue = ta.rsi(rsiSource, rsiLength) rsiLongCondition = ta.rsi(rsiSource, rsiLength) < rsiLongValue bbLongCondition = close < bbLower // Short condition rsiShortCondition = ta.rsi(rsiSource, rsiLength) > rsiShortValue bbShortCondition = close > bbUpper // Long and short signals bool longSignal = rsiLongCondition and bbLongCondition bool shortSignal = rsiShortCondition and bbShortCondition plotchar(longSignal, "Long", "▲", location.belowbar, color.lime, size = size.tiny) plotchar(shortSignal, "Short", "▼", location.abovebar, color.red, size = size.tiny) // ---- Alerts // Specific direction alerts alertcondition(longSignal, "Long signal", "Long signal") alertcondition(shortSignal, "Short signal", "Short signal") // These ones to be used if you want alerts in any direction if longSignal alert("Long signal") if shortSignal alert("Short signal") // ---- Plotting // Bollinger Bands plot(plotBB ? bbUpper: na,"BB upper", color=color.gray) plot(plotBB ? bbMiddle: na, "BB middle", color=color.teal) plot(plotBB ? bbLower: na, "BB lower", color=color.gray) plot(plotEma ? emaLine: na, "EMA", color=color.orange) // Request 2 extra rsi info for higher timeframes rsiExtra1Value = request.security(syminfo.ticker, rsiExtra1Timeframe, rsiValue[1], barmerge.gaps_off, barmerge.lookahead_on) rsiExtra2Value = request.security(syminfo.ticker, rsiExtra2Timeframe, rsiValue[1], barmerge.gaps_off, barmerge.lookahead_on) [oiOpen,oiClose] = request.security(syminfo.ticker + "_OI", timeframe.period, [open, close], ignore_invalid_symbol = true) bool oiLong = oiClose > oiOpen bool oiShort = oiOpen > oiClose //plotchar(oiLong, "OI Long", "▲", location.belowbar, color.lime, size = size.tiny) plotshape(plotOI ? oiLong: na, style=shape.circle, title="OI positive", location=location.abovebar, color=color.new(color.green,60), textcolor=color.new(color.black, 0)) plotshape(plotOI ? oiShort: na, style=shape.circle, title="OI negative", location=location.abovebar, color=color.new(color.red,60), textcolor=color.new(color.black, 0)) if plotRSI var rsiTable = table.new(position=position.bottom_left, columns=3, rows=2, border_color = color.blue, border_width = 1, frame_width = 1, bgcolor = plotRSIHeaderColor) table.cell(table_id = rsiTable, column = 0, row = 0, text = timeframe.period) table.cell(table_id = rsiTable, column = 1, row = 0, text = rsiExtra1Timeframe) table.cell(table_id = rsiTable, column = 2, row = 0, text = rsiExtra2Timeframe) table.cell(table_id = rsiTable, column = 0, row = 1, text = str.tostring(math.round(rsiValue, 2)), bgcolor=plotRSIValueColor) table.cell(table_id = rsiTable, column = 1, row = 1, text= str.tostring(math.round(rsiExtra1Value, 2)), bgcolor=plotRSIValueColor) table.cell(table_id = rsiTable, column = 2, row = 1, text= str.tostring(math.round(rsiExtra2Value, 2)), bgcolor=plotRSIValueColor)
Pivots
https://www.tradingview.com/script/hVEw5qxv-Pivots/
syntaxgeek
https://www.tradingview.com/u/syntaxgeek/
86
study
5
MPL-2.0
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © syntaxgeek //@version=5 indicator("Pivots", overlay=true) // <inputs> i_pivotLength = input.int(title='Pivot Length', defval = 8, tooltip='Length of historical data to reference when searching for pivot highs and lows.') i_timeframe = input.timeframe(title='Timeframe', defval='') i_timeframeGapsOn = input.bool(title='Timeframe Gaps?', defval=false) // </inputs> // <funcs> f_renderGaps() => i_timeframeGapsOn ? barmerge.gaps_on : barmerge.gaps_off f_regSec(f) => request.security(syminfo.tickerid, i_timeframe, f, f_renderGaps()) // </funcs> // <vars> v_barsLow = i_pivotLength v_barsHigh = i_pivotLength v_pivotHigh = f_regSec(fixnan(ta.pivothigh(v_barsLow, v_barsHigh)[1])) v_pivotLow = f_regSec(fixnan(ta.pivotlow(v_barsLow, v_barsHigh)[1])) // </vars> // <plots> plot(v_pivotHigh, "Resistance", ta.change(v_pivotHigh) ? na : color.red, 2, offset=-(i_pivotLength + 1), style=plot.style_linebr) plot(v_pivotLow, "Support", ta.change(v_pivotLow) ? na : color.green, 2, offset=-(i_pivotLength + 1), style=plot.style_linebr) var v_highLabel = label.new(bar_index, v_pivotHigh, style=label.style_label_lower_left, text=i_timeframe + ' ' + str.tostring(i_pivotLength) + ' High', color=ta.change(v_pivotHigh) ? na : color.red, textcolor=color.black) label.set_xy(v_highLabel, bar_index , v_pivotHigh) label.set_color(v_highLabel, ta.change(v_pivotHigh) ? na : color.red) var v_lowLabel = label.new(bar_index, v_pivotLow, style=label.style_label_lower_left, text=i_timeframe + ' ' + str.tostring(i_pivotLength) + ' Low', color=ta.change(v_pivotLow) ? na : color.green, textcolor=color.black) label.set_xy(v_lowLabel, bar_index , v_pivotLow) label.set_color(v_lowLabel, ta.change(v_pivotLow) ? na : color.green) // </plots>
Position Tool
https://www.tradingview.com/script/WGf6XZ6K-Position-Tool/
TradingView
https://www.tradingview.com/u/TradingView/
1,020
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/ // © TradingView //@version=5 indicator("Position Tool", overlay = true) // Position Tool // v2, 2023.06.25 // This code was written using the recommendations from the Pine Script™ User Manual's Style Guide: // https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html import TradingView/ta/6 as ta //#region ———————————————————— Constants and Inputs color VENETIAN = #C90707 color WHITE = #ffffff color STORM_GREY = #787b86 color GRAY_LT = #9598a1 color GREEN_MD = color.new(#009688, 70) color RED_MD = color.new(#f44336, 70) color GREEN_LT = color.new(#009688, 90) color RED_LT = color.new(#f44336, 90) string CI1 = "Default" string EI1 = "Open Position" string EI2 = "Always" string EI3 = "Never" string EP_TT = "Click at the point in time where an order is placed, using the order's entry level. The trade will be entered when this level is reached." string TP_TT = "Set the profit level where the position will be exited. It must be above the entry level for longs, and below for shorts." string SL_TT = "Set the stop loss level where the position will be exited. It must be below the entry level for longs, and above for shorts." string GRP1 = "Trade Sizing" float sizeInput = input.float(1000.0, "Account Size", group = GRP1, inline = "11", minval = 0.0) float riskValueInput = input.float(10, "Risk    ", group = GRP1, inline = "12", minval = 0) string currencyInput = input.string(CI1, "", group = GRP1, inline = "11", options = [CI1, "USD", "EUR", "CAD", "JPY", "GBP", "HKD", "CNY", "NZD", "RUB", "AUD", "CHF", "NOK", "SEK", "SGD", "TRY", "ZAR", "MYR", "KRW", "USDT", "INR"]) string riskUnitInput = input.string("%", "", group = GRP1, inline = "12", options = ["%", "Account Currency"]) int lotSizeInput = input.int(1, "Lot Size    ", group = GRP1, inline = "13", minval = 1) string GRP2 = "Trade Levels" float entryPriceInput = input.price(0, "Entry Point", group = GRP2, confirm = true, inline = "21") int entryTime = input.time(0, "", group = GRP2, confirm = true, tooltip = EP_TT, inline = "21") float inputTpPrice = input.price(0, "Take Profit", group = GRP2, confirm = true, tooltip = TP_TT, inline = "22") float inputSlPrice = input.price(0, "Stop Loss", group = GRP2, confirm = true, tooltip = SL_TT, inline = "23") string GRP3 = "Style" color entryColorInput = input.color(STORM_GREY, "Lines", group = GRP3, inline = "31") color tpColorInput = input.color(GREEN_LT, " TP and SL Zones   ",group = GRP3, inline = "31") color slColorInput = input.color(RED_LT, "", group = GRP3, inline = "31") color txtColorInput = input.color(GRAY_LT, "Text ", group = GRP3, inline = "32") color txtBgTpColorInput = input.color(GREEN_MD, " Text backgrounds", group = GRP3, inline = "32") color txtBgSlColorInput = input.color(RED_MD, "", group = GRP3, inline = "32") bool showCurrencyUnits = input.bool(true, "Show currency", group = GRP3, inline = "33") string extendInput = input.string(EI1, "  Extend Right", group = GRP3, inline = "33", options = [EI1, EI2, EI3]) string GRP4 = "Target and Stop Labels" bool showPriceInput = input.bool(true, "Price", group = GRP4, inline = "41") bool showStopInput = input.bool(true, "Value", group = GRP4, inline = "41") bool showPercInput = input.bool(true, "Percent", group = GRP4, inline = "41") bool showTicksInput = input.bool(true, "Tick", group = GRP4, inline = "41") bool showAmountInput = input.bool(true, "Amount", group = GRP4, inline = "41") string GRP5 = "Order Label" bool showTPriceInput = input.bool(true, "Entry price", group = GRP5, inline = "51") bool showTPlInput = input.bool(true, "P & L", group = GRP5, inline = "51") bool showTQtyInput = input.bool(true, "Quantity", group = GRP5, inline = "51") bool showTRRInput = input.bool(true, "RR", group = GRP5, inline = "51") bool showTPipInput = input.bool(true, "Per Tick/Pip", group = GRP5, inline = "51") bool showTCagrInput = input.bool(true, "CAGR", group = GRP5, inline = "51") //#endregion //#region ———————————————————— Global variables // Round trade values to chart precision. float entryPrice = math.round_to_mintick(entryPriceInput) float tpPrice = math.round_to_mintick(inputTpPrice) float slPrice = math.round_to_mintick(inputSlPrice) var bool isOrderClosedByBracket = na var int realEntryTime = na string extend = extendInput == EI3 ? extend.none : extend.right // Declare line objects for display. Locations to be set during trade. var line entryPriceLine = line.new(entryTime, entryPrice, na, na, xloc = xloc.bar_time, color = entryColorInput, extend = extend) var line pointerOrderPriceLine = line.new(entryTime, entryPrice, na, na, xloc = xloc.bar_time, color = entryColorInput, style = line.style_dashed) // Declare box objects for trade zones. Locations to be set during trade. var box tpZone = box.new(entryTime, tpPrice, na, entryPrice, xloc = xloc.bar_time, extend = extend, bgcolor = tpColorInput, border_width = 0) var box slZone = box.new(entryTime, slPrice, na, entryPrice, xloc = xloc.bar_time, extend = extend, bgcolor = slColorInput, border_width = 0) var box orderZone = box.new(na, na, na, entryPrice, xloc = xloc.bar_time, bgcolor = na, border_width = 0) // Declare label objects for order information display. Locations to be set during trade. var label profit = label.new(na, tpPrice, "", style = label.style_label_center, color = txtBgTpColorInput, textcolor = txtColorInput, xloc = xloc.bar_time) var label loss = label.new(na, slPrice, "", style = label.style_label_center, color = txtBgSlColorInput, textcolor = txtColorInput, xloc = xloc.bar_time) var label mainInfo = label.new(na, entryPrice, "", style = label.style_label_center, color = na, textcolor = txtColorInput, xloc = xloc.bar_time) //#endregion //#region ———————————————————— Functions // @function Determines the currency based on the input value selected by the user/ // @returns (float) Returns a string with short currency name. defineCurrency() => string currency = currencyInput == CI1 ? "" : currencyInput // @function Converts a price to a user defined currency using `request.security()`. // @param price (series float) The price to convert. // @param currency (simple string) The currency to convert // @returns (float) Returns a value in the user-chosen currency converted from `price`. convertCurrency(series float price, simple string currency) => if syminfo.basecurrency == currency and not na(syminfo.basecurrency) string errorString = "Invalid operation: Conversion currency ({0}) cannot be the same as the base currency ({1}). Please select a different conversion currency." runtime.error(str.format(errorString, currency, syminfo.basecurrency)) float convertedClose = request.security(syminfo.tickerid, timeframe.period, close, currency = currency, ignore_invalid_symbol = true) float ratio = convertedClose / close float result = math.round_to_mintick(price * ratio) // @function Determines profit or loss given the entry price calculated against another price. // @param price (series float) Price to calculate profit from. // @param entryPrice (series float) The price of entry for the position. // @param qty (series float) Number of contracts in an open position // @param isLongPosition (series bool) The condition determining whether the trade is a "long" or a "short" position. // @returns (float) The profit or loss of the trade based on the `price` relative to the `entryPrice` taking into account whether or not the trade `isLongPosition`. calcPL(series float price, series float entryPrice, series float qty, series bool isLongPosition) => float pl = math.round_to_mintick((price - entryPrice) * qty) float result = isLongPosition ? pl : pl * -1 // @function Calculates the risk amount for a given position size. The risk amount can be specified either as a percentage or a fixed amount through `riskUnitInput` in the settings.. // @param size (series float) The size of the position for which the risk amount is calculated. // @returns (float) The calculated risk amount. If the risk unit input is "%", it returns the risk amount as a percentage of the size. If the risk unit input is not "%", it returns the risk amount as it is. calcRiskAmount(series float size) => float currecyValueRiskAmount = riskUnitInput == "%" ? size * riskValueInput * 0.01 : riskValueInput // @function Calculates a position size and a quantity per lot of the account size to risk based on the user-chosen "risk percent". // @param riskAmount (series float) The account size to use in the risk calculation. // @param lossSize (series float) The value of loss based on the user defined risk. // @returns ([float, float]) A tuple of the trade quantity and a ratio of the quantity per lot. calcQty(series float riskAmount, series float lossSize) => var bool floatContracts = syminfo.type == "crypto" or syminfo.type == "futures" var float qty = floatContracts ? riskAmount / math.abs(lossSize) : math.floor(riskAmount / math.abs(lossSize)) var float qtyPerLot = floatContracts ? qty / lotSizeInput : math.floor(qty / lotSizeInput) [qty, qtyPerLot] // @function Calculates a difference between a `price` and the `entryPrice` in absolute terms. // @param price (series float) The price to calculate the difference from. // @param entryPrice (series float) The price of entry for the position. // @returns (float) The absolute price displacement of a price from an entry price. calcProfitLossSize(series float price, series float entryPrice, series bool isLongPosition) => float priceDiff = price - entryPrice float result = isLongPosition ? priceDiff : priceDiff * -1 // @function Calculates the absolute size of a profit or loss given the `price` relative to the `entryPrice`, as well as the `price` as a percent of the `entry price`. // @param price (series float) The price to calculate the difference from. // @param entryPrice (series float) The price of entry for the position. // @returns ([float, float]) A tuple of the PnL size in absolute terms and in a percent rounded to two decimal places. calcOrderProfitLossParam(series float price, series float entryPrice, series bool isLongPosition) => float orderProfitLossSize = calcProfitLossSize(price, entryPrice, isLongPosition) float orderProfitLossPercent = math.round(orderProfitLossSize / entryPrice * 100, 2) [orderProfitLossSize, orderProfitLossPercent] // @function Calculates the chart symbol's base unit of change in asset prices. // @returns (float) A ticks or pips value of base units of change. calcBaseUnit() => bool isForexSymbol = syminfo.type == "forex" bool isYenQuote = syminfo.currency == "JPY" bool isYenBase = syminfo.basecurrency == "JPY" float result = isForexSymbol ? isYenQuote ? 0.01 : isYenBase ? 0.00001 : 0.0001 : syminfo.mintick // @function Converts the `orderSize` to ticks. // @param orderSize (series float) The order size to convert to ticks. // @param unit (simple float) The basic units of change in asset prices. // @returns (int) A tick value based on a given order size. calcOrderPipsOrTicks(series float orderSize, simple float unit) => int result = math.abs(math.round(orderSize / unit)) // @function Calculates the money value of the PnL. // @param qty (series float) The quantity of contracts to use in the PnL calculation. // @param orderProfitLossSize (series float) The size of the PnL in absolute terms. // @returns (float) A cash value of the PnL in the symbol's currency. calcProfitLossRiskSize(series float qty, series float orderProfitLossSize) => float result = qty * orderProfitLossSize * syminfo.pointvalue // @function Calculates an end equity value given the initial account equity and the open PnL. // @param size (series float) The initial equity value before trades. // @param riskSize (series float) The size of the profit or loss in absolute terms. // @returns (float) The account equity after PnL. calcOrderProfitLossAmount(series float size, series float riskSize) => float result = size + riskSize // @function Calculates a risk to reward ratio given the size of profit and loss. // @param profitSize (series float) The size of the profit in absolute terms. // @param lossSize (series float) The size of the loss in absolute terms. // @returns (float) The ratio between the `profitSize` to the `lossSize` calcRiskRewardRatio(series float profitSize, series float lossSize) => float result = math.abs(math.round(profitSize / lossSize, 2)) // @function Calculates a ratio of the profit or loss per pip. // @param riskSize (series float) The profit or loss for the position in absolute terms. // @param units (series float) Amount of the basic units of change in asset prices. // @returns (float) A ratio of the PnL on a per pip basis. calcProfitlossPerPipOrTick(series float riskSize, series float units) => float result = riskSize / units // @function Determine a color by the profit or loss value. // @param price (series float) The profit or loss value for the color defenition. // @returns (color) A color of for the current profit or loss value. getColorByPositionReturn(series float price) => color result = price >= 0 ? txtBgTpColorInput : txtBgSlColorInput // @function Calculates an exit price considering the `sl` and `tp` price and returns a color for the exit zone. // @param isLongPosition (series bool) Condition that determines whether the position is long or short. // @param tp (series float) The take profit price for the position. // @param sl (series float) The stop loss price for the position. // @returns ([float, color]) A tuple of the exit price and a color that is dependant on whether that price is the `tp` or the `sl`. getExitParams(series bool isLongPosition, series float tp, series float sl) => float takeProfit = tp float stopLoss = sl if not isLongPosition takeProfit := sl stopLoss := tp float exitPrice = high >= takeProfit ? takeProfit : low <= stopLoss ? stopLoss : close color exitZoneColor = isLongPosition and exitPrice > entryPrice or not isLongPosition and exitPrice < entryPrice ? tpColorInput : slColorInput [exitPrice, exitZoneColor] // @function Sets the text and the position of a label on the x axis. If the `txt` argument is blank, the label will be deleted. // @param labelId (label) The id of the label to be modified. // @param x (series int) The position of the label on the x axis in a timestamp. // @param txt (series string) The text to set in the label. // @returns (void) Updates a label identified by `labelId` with a position on the `x` axis with `text`. If no text is defined, the label is deleted. labelSetInfo(label labelId, series int x, series string txt, series color col) => if txt == "" label.delete(labelId) else label.set_x(labelId, x) label.set_text(labelId, txt) label.set_color(labelId, col) // @function Concatenates trade metrics into a string suitable for display in a label at the take profit or stop loss level. // @param price (series float) The price of the level. // @param size (series float) The contract quantity of the trade. // @param percent (series float) The distance from the entry price to the level in percent. // @param ticks (series int) The distance from the entry price to the level in ticks. // @param amount (series float) The money value of the account considering the size of the profit or loss. // @param isTarget (series bool) A condition to determine if the level is the target level or not. // @returns (void) A string for display within a label at the stop or limit level. Includes the distance in money value to the stop or target, // the `percent` change to the level, the distance in `ticks`, the money value of the account if the level were reached, and a ratio of the amount `perPipOrTick`. getLevelInfo(series float price, series float size, series float percent, series int ticks, series float amount, simple string currency, series bool isTarget) => string resultInfo = "" string level = isTarget ? "Target: " : "Stop: " string unit = syminfo.type == "forex" ? "Pip" : "Tick" string cur = showCurrencyUnits ? " " + currency : "" string targetStopPriceString = showPriceInput ? str.format("@{0,number},", price) : "" string targetStopString = showStopInput ? str.format(" {0,number,###,###,###.######}{1}", size, cur) : "" string targetStopPercentString = showPercInput ? str.format(" ({0,number,#.###}%)", percent) : "" string targetStopTicksString = showTicksInput ? str.format(" {0,number,#} {1}s", ticks, unit) : "" string targetStopAmountString = showAmountInput ? str.format("\nAmount: {0,number,###,###,###.##}{1}", amount, cur) : "" resultInfo := targetStopPriceString + targetStopString + targetStopPercentString + targetStopTicksString + targetStopAmountString resultInfo := resultInfo != "" and (showStopInput or showPercInput or showTicksInput) ? level + resultInfo : resultInfo // @function Creates a string for display of order metrics in a label. // @param price (series float) The entry price of the position. // @param pl (series float) The PnL value of the position. // @param qty (series float) The quantity of contracts in the position. // @param perPipOrTick (series float) The ratio of the profit or loss on a per-pip basis. // @param riskReward (series float) The risk to reward ratio. // @param cagr (series float) The value of the compound annual growth rate. // @param isOrderOpen (series bool) Condition determining if the order is currently open. // @param isOrderClosedByBracket (series bool) Condition determining if the order is currently closed. // @returns (string) A string concatenating the order position, PnL, quantity, risk to reward ratio, and the CAGR. getOrderInfo(series float price, series float pl, series float qty, series float perPipOrTick, series float riskReward, series float cagr, series bool isOrderOpen, series bool isOrderClosedByBracket, simple string currency) => string orderPosition = switch isOrderClosedByBracket => "Closed" isOrderOpen => "Open" => "Position isn't open yet" string cur = showCurrencyUnits ? str.format(" {0}", currency) : "" string unit = syminfo.type == "forex" ? "Pip" : "Tick" bool hasPositionStatus = orderPosition != "Position isn't open yet" string priceString = showTPriceInput ? str.format("@{0,number}, ", price) : "" string plString = showTPlInput and hasPositionStatus ? str.format(" P&L: {0,number,###,###,###.##}{1}", pl, cur) : "" string qtyString = showTQtyInput ? str.format(", Qty: {0,number}", qty) : "" string riskRewardString = showTRRInput ? str.format("\nRR: {0,number,#.##}:1", riskReward) : "" string cagrString = showTCagrInput and not na(cagr) ? str.format("\nCAGR: {0,number,###,###.#}%", cagr) : "" string perPipString = showTPipInput ? str.format(", Per {0}: {1,number}{2}", unit, math.round_to_mintick(perPipOrTick), cur) : "" string result = priceString + orderPosition + plString + qtyString + riskRewardString + perPipString + cagrString // @function Updates location, color, and text for order information labels. // @param lblProfitText (series string) Text for the profit label. // @param profitColor (series color) Color for the profit label. // @param lblLossText (series string) Text for the loss label. // @param lossColor (series color) Color for the loss label. // @param lblOrderInfo (series string) Text for the main order label. // @param plColor (series color) Color for the main order label. // @returns (void) Sets text and location attributes for the profit, loss, and main order labels. drawOrderInfo(series string lblProfitText, series color profitColor, series string lblLossText, series color lossColor, series string lblOrderInfo, series color plColor) => int drawingCenter = math.round(time - (time - entryTime)/2) labelSetInfo(profit, drawingCenter, lblProfitText, profitColor) labelSetInfo(loss, drawingCenter, lblLossText, lossColor) labelSetInfo(mainInfo, drawingCenter, lblOrderInfo, plColor) // @function Sets location and color for trade zone and order pointer line. // @param exitPrice (series float) The exit price of the position. // @param realEntryPrice (series float) The entry price of the position. // @param realEntryTime (series int) The entry time of the position. // @param orderZoneColor (series color) The color for the order zone. // @returns (void) Sets box attributes to update the order zone dimensions and color as the trade progresses, and sets start and end locations for the trade pointer line. redrawOrderZone(series float exitPrice, series float realEntryPrice, series int realEntryTime, series color orderZoneColor) => line.set_xy1(pointerOrderPriceLine, realEntryTime, realEntryPrice) line.set_xy2(pointerOrderPriceLine, time, exitPrice) box.set_lefttop(orderZone, realEntryTime, exitPrice) box.set_right(orderZone, time) box.set_bgcolor(orderZone, orderZoneColor) //#endregion //#region ———————————————————— Calculations // Create an error if the target and stop are not on either side of the entry price. if (slPrice > entryPrice and tpPrice > entryPrice) or (slPrice < entryPrice and tpPrice < entryPrice) runtime.error("The 'Target' and 'Stop' levels are misplaced. One must be set above the 'Entry Price', the other below.") // Calculate trade parameters in user-selected currency. string currency = defineCurrency() float exitPrice = close float convertedPrice = convertCurrency(exitPrice, currency) float convertedEntryPrice = convertCurrency(entryPrice, currency) float convertedTpPrice = convertCurrency(tpPrice, currency) float convertedSlPrice = convertCurrency(slPrice, currency) float convertedAccountSize = convertCurrency(sizeInput, currency) // Check that the entry time has been exceeded by the chart series to begin calcs and display. Stop when the order has been calculated as closed . [p, l] = if time >= entryTime and not isOrderClosedByBracket // Set trade parameters and locations of boxes and lines used for order display. var color exitZoneColor = entryColorInput bool isLongPosition = tpPrice > slPrice realEntryTime := na(realEntryTime[1]) and (low <= entryPrice and high >= entryPrice) ? time : realEntryTime[1] line.set_xy2(entryPriceLine, time, entryPrice) box.set_right(tpZone, time) box.set_right(slZone, time) isOrderOpen = not na(realEntryTime) // Check if an order is open. if isOrderOpen // Get an exit price and zone color based on the trade bias, tp, and sl price. [currentExitPrice, currentExitZoneColor] = getExitParams(isLongPosition, tpPrice, slPrice) exitZoneColor := currentExitZoneColor // Check if the order has been closed. isOrderClosedByBracket := currentExitPrice != exitPrice if isOrderClosedByBracket convertedPrice := convertCurrency(currentExitPrice, currency) // Update order zone and pointer line locations/ color. redrawOrderZone(currentExitPrice, entryPrice, realEntryTime, exitZoneColor) var float fixedEntryPrice = convertedEntryPrice convertedEntryPrice := fixedEntryPrice // Check if a position was opened, if so send an alert. if not isOrderOpen[1] alert(str.format("The position was entered at the price {0, number}", entryPrice), alert.freq_once_per_bar) // Check if the stop or take profit price has been hit and send an alert. if isOrderClosedByBracket if currentExitPrice == tpPrice alert(str.format("The position was closed by Take Profit at the price {0, number}", currentExitPrice), alert.freq_once_per_bar) if currentExitPrice == slPrice alert(str.format("The position was closed by Stop Loss at the price {0, number}", currentExitPrice), alert.freq_once_per_bar) // Calculate trade metrics for position. [profitSize, profitPercent] = calcOrderProfitLossParam(convertedTpPrice, convertedEntryPrice, isLongPosition) [lossSize, lossPercent] = calcOrderProfitLossParam(convertedSlPrice, convertedEntryPrice, isLongPosition) float riskAmount = calcRiskAmount(sizeInput) [qty, qtyPerLot] = calcQty(riskAmount, lossSize) // Calculate PnL. float PL = calcPL(convertedPrice, convertedEntryPrice, qty, isLongPosition) // Calculate the profit and loss in ticks or pips. var float unit = calcBaseUnit() var int profitPipsOrTicks = calcOrderPipsOrTicks(profitSize, unit) var int lossPipsOrTicks = calcOrderPipsOrTicks(lossSize, unit) // Calculate the trade size based on the user-defined account size and risk profile. float profitRiskSize = calcProfitLossRiskSize(qtyPerLot * lotSizeInput, profitSize) float lossRiskSize = calcProfitLossRiskSize(qtyPerLot * lotSizeInput, lossSize) // Calculate the money value of the profit and loss amount in the user-chosen currency. float profitAmount = calcOrderProfitLossAmount(sizeInput, profitRiskSize) float lossAmount = calcOrderProfitLossAmount(sizeInput, lossRiskSize) // Calculate the ratio of profit or loss on a per-pip basis. float profitPerPipOrTick = calcProfitlossPerPipOrTick(profitRiskSize, profitPipsOrTicks) float lossPerPipOrTick = calcProfitlossPerPipOrTick(lossRiskSize, lossPipsOrTicks) // Calculate the risk to reward ratio given the size of the potential profit and loss. Calculate the CAGR. float riskRewardRatio = calcRiskRewardRatio(profitSize, lossSize) float cagr = ta.cagr(realEntryTime, convertedEntryPrice, time, convertedPrice) // Get the trade metrics for the stop loss and take profit level. string currencyDisplayName = currency == "" ? syminfo.currency : currency string lblProfitText = getLevelInfo(tpPrice, profitSize, profitPercent, profitPipsOrTicks, profitAmount, currencyDisplayName, true) string lblLossText = getLevelInfo(slPrice, lossSize, lossPercent, lossPipsOrTicks, lossAmount, currencyDisplayName, false) string lblOrderInfo = getOrderInfo(entryPrice, PL, qtyPerLot, profitPerPipOrTick, riskRewardRatio, cagr, isOrderOpen, isOrderClosedByBracket, currencyDisplayName) // Set the text, color, and location of the order information labels. color profitColor = getColorByPositionReturn(profitSize) color lossColor = getColorByPositionReturn(lossSize) color plColor = getColorByPositionReturn(PL) drawOrderInfo(lblProfitText, profitColor, lblLossText, lossColor, lblOrderInfo, plColor) // Check if the order is closed and if the user-defined box extension input is enabled. // If the trade is closed, remove extend right from the exit zones. if isOrderClosedByBracket and extendInput == EI1 box.set_extend(tpZone, extend.none) box.set_extend(slZone, extend.none) line.set_extend(entryPriceLine, extend.none) [profitSize, lossSize] //#endregion plot(p, "p", display = display.data_window) plot(l, "l", display = display.data_window)
Ohana_Wick_Entry
https://www.tradingview.com/script/vLDlXBsd-Ohana-Wick-Entry/
OhanaJ
https://www.tradingview.com/u/OhanaJ/
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/ // © OhanaJ //@version=5 indicator("Ohana Wick Entry") a = math.abs (open - close) b = high - low wick = 100 * ( (b-a) / b ) bodyColor = if wick <= 35 color.green else color.red plot (a, style=plot.style_columns, color=bodyColor)