turn this pine script into nexuscript. indicator("...
Erstellt am: 5. Dezember 2026
Beantwortet mit GPT-6.2 Thinking von Chat01
Erstellt am: 5. Dezember 2026
Beantwortet mit GPT-6.2 Thinking von Chat01
turn this pine script into nexuscript. indicator("watermark", overlay=true)
showTF = input.bool(true, "show time frame", inline = "24")
showpf = input.bool(true, "show prefix", inline = "24")
showchange = input.bool(false, "show change %", inline = "24")
string i_tableYpos = input.string("bottom", "Position", inline = "12", options = ["top", "middle", "bottom"])
string i_tableXpos = input.string("left", "", inline = "12", options = ["left", "center", "right"])
size1 = input.string("huge", "title", inline = "14", options = ["tiny", "small", "normal", "large", "huge", "auto"])
size3 = input.string("large", "change", inline = "14", options = ["tiny", "small", "normal", "large", "huge", "auto"])
size2 = input.string("large", "signature", inline = "14", options = ["tiny", "small", "normal", "large", "huge", "auto"])
color = input.color(#ffffff77, "color")
string = input.string("by The HUN", "your signature")
seperator = input.string("/", "seperator")
cahngeClose = request.security(syminfo.tickerid, timeframe.period, close)
cur = syminfo.currency
base = syminfo.basecurrency
exchange = syminfo.prefix
getTimeFrame() =>
tf = timeframe.multiplier
tfstr = ""
if timeframe.isseconds
tfstr := "s"
if timeframe.isminutes
if tf >= 60
tf := tf / 60
tfstr := "h"
else
tfstr := "m"
if timeframe.isdaily
tfstr := "D"
if timeframe.isweekly
tfstr := "W"
if timeframe.ismonthly
tfstr := "M"
text[tfstr, str.tostring(tf)]
var table table1 = table.new(i_tableYpos + "_" + i_tableXpos , 4, 1)
if barstate.islast
textstr1 = base != "" ? base + seperator + cur : syminfo.ticker [tf, period] = getTimeFrame() change = math.round(((cahngeClose[0] / cahngeClose[1]) - 1) * 100, 2) changeStr = "" if change > 0 changeStr := "▲" + str.tostring(math.abs(change)) + "%" else changeStr := "▼" + str.tostring(math.abs(change)) + "%" table.cell(table1, 0, 0, showpf ? exchange : "", text_color = color, width=0, text_size=size2) table.cell(table1, 1, 0, str1 + (showTF ? (" " + period + tf) : ""), width=0, text_color = color, text_size=size1) table.cell(table1, 2, 0, showchange ? changeStr : "", width=0, text_color = change > 0 ? color.green : color.red, text_size=size3) table.cell(table1, 3, 0, string, text_color = color, width=0, text_size=size2)
I’ll check NexusScript’s syntax and chart-drawing functions so the conversion preserves your watermark settings as closely as possible.
NexuScript supports all nine watermark positions and per-cell colors, but it has only one font size per table. I’ll use the largest supported size by default and keep the other display options.
Here’s your Pine Script watermark converted to NexuScript 1.6, using the official Nexus scripting syntax.
I've preserved the exchange prefix, ticker, timeframe, percentage change, customizable signature, transparency, separator and all nine watermark positions.
julianexscript 1.6 indicator "Watermark", overlay = true # ─── Display settings ─── input showTF = true, title = "Show time frame", inline = "24" input showpf = true, title = "Show prefix", inline = "24" input showchange = false, title = "Show change %", inline = "24" # ─── Position settings ─── input ypos = "bottom", title = "Vertical position", options = ["top", "middle", "bottom"], inline = "12" input xpos = "left", title = "Horizontal position", options = ["left", "center", "right"], inline = "12" # ─── Appearance settings ─── input textSize = "large", title = "Text size", options = ["tiny", "small", "normal", "large"] input textColor = color.hex("#ffffff77"), title = "Color" input signature = "by The HUN", title = "Your signature" input separator = "/", title = "Separator" input baseOverride = "", title = "Base currency override" # ─── Main indicator ─── on bar let previousClose = close[1] if bar.last # Table position let tablePos = ypos * "_" * xpos # Symbol information let ticker = symbol.ticker let exchange = symbol.exchange let currency = symbol.currency let base = baseOverride # Detect base currency for perpetuals if base == "" && symbol.asset_class == "perps" base = symbol.root if currency != "" && endswith(base, currency) base = slice(base, 1, length(base) - length(currency)) if endswith(base, "-") || endswith(base, "/") || endswith(base, "_") base = slice(base, 1, length(base) - 1) end end end let symbolText = ticker if base != "" && currency != "" symbolText = base * separator * currency end # Format timeframe let seconds = timeframe.seconds let tfText = timeframe.name if tfText == "D" || tfText == "W" || tfText == "M" tfText = "1" * tfText elseif !ismissing(seconds) && seconds > 0 && seconds < 86400 if seconds < 60 tfText = string(seconds) * "s" elseif seconds < 3600 tfText = string(seconds / 60) * "m" else tfText = string(seconds / 3600) * "h" end end # Build watermark title let titleText = symbolText if showTF && tfText != "" titleText = symbolText * " " * tfText end # Percentage change let changeText = "" let changeColor = textColor if showchange && !ismissing(previousClose) && previousClose != 0 let changePct = round(((close / previousClose) - 1) * 100, digits = 2) if changePct > 0 changeText = "▲" * string(abs(changePct)) * "%" changeColor = color.green else changeText = "▼" * string(abs(changePct)) * "%" changeColor = color.red end end # Exchange prefix let prefixText = showpf ? exchange : "" # Draw watermark table( [[ cell(prefixText, color = textColor), cell(titleText, color = textColor), cell(changeText, color = changeColor), cell(signature, color = textColor) ]], position = tablePos, color = textColor, background = color.hex("#00000000"), size = textSize ) end end
Illustrative preview with percentage change enabled.
large being the maximum. Individual cell sizes and huge are not supported.syminfo.basecurrency, so I've added automatic detection for perpetuals and an optional manual override.#ffffff77 color is preserved.Paste the code into the Nexus Scripts editor, press Run, then Save.
I've checked the syntax against the official NexuScript documentation, but I haven't compiled it inside the Nexus platform itself.
turn this pine script into nexuscript. study("SuperFuckingGoodIndicator", overlay = true, max_bars_back = 1000, max_lines_count = 400, max_labels_count = 400)
prd = input(defval = 5, title = "Pivot Period", minval = 1, maxval = 50)
source = input(defval = "Close", title = "Source for Pivot Points", options = ["Close", "High/Low"])
searchdiv = input(defval = "Regular", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"])
showindis = input(defval = "Full", title = "Show Indicator Names", options = ["Full", "First Letter", "Don't Show"])
showlimit = input(1, title="Minimum Number of Divergence", minval = 1, maxval = 11)
maxpp = input(defval = 10, title = "Maximum Pivot Points to Check", minval = 1, maxval = 20)
maxbars = input(defval = 100, title = "Maximum Bars to Check", minval = 30, maxval = 200)
shownum = input(defval = true, title = "Show Divergence Number")
showlast = input(defval = false, title = "Show Only Last Divergence")
dontconfirm = input(defval = false, title = "Don't Wait for Confirmation")
showlines = input(defval = true, title = "Show Divergence Lines")
showpivot = input(defval = false, title = "Show Pivot Points")
calcmacd = input(defval = true, title = "MACD")
calcmacda = input(defval = true, title = "MACD Histogram")
calcrsi = input(defval = true, title = "RSI")
calcstoc = input(defval = true, title = "Stochastic")
calccci = input(defval = true, title = "CCI")
calcmom = input(defval = true, title = "Momentum")
calcobv = input(defval = true, title = "OBV")
calcvwmacd = input(true, title = "VWmacd")
calccmf = input(true, title = "Chaikin Money Flow")
calcmfi = input(true, title = "Money Flow Index")
calcext = input(false, title = "Check External Indicator")
externalindi = input(defval = close, title = "External Indicator")
pos_reg_div_col = input(defval = color.rgb(255, 235, 59, 53), title = "Positive Regular Divergence")
neg_reg_div_col = input(defval = color.rgb(49, 27, 146, 43), title = "Negative Regular Divergence")
pos_hid_div_col = input(defval = color.lime, title = "Positive Hidden Divergence")
neg_hid_div_col = input(defval = color.red, title = "Negative Hidden Divergence")
pos_div_text_col = input(defval = color.black, title = "Positive Divergence Text Color")
neg_div_text_col = input(defval = color.white, title = "Negative Divergence Text Color")
reg_div_l_style_ = input(defval = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"])
hid_div_l_style_ = input(defval = "Dashed", title = "Hdden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"])
reg_div_l_width = input(defval = 2, title = "Regular Divergence Line Width", minval = 1, maxval = 5)
hid_div_l_width = input(defval = 1, title = "Hidden Divergence Line Width", minval = 1, maxval = 5)
showmas = input(defval = false, title = "Show MAs 50 & 200", inline = "ma12")
cma1col = input(defval = color.lime, title = "", inline = "ma12")
cma2col = input(defval = color.red, title = "", inline = "ma12")
plot(showmas ? sma(close, 50) : na, color = showmas ? cma1col : na)
plot(showmas ? sma(close, 200) : na, color = showmas ? cma2col: na)
// 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
rsi = rsi(close, 14) // RSI
[macd, signal, deltamacd] = macd(close, 12, 26, 9) // MACD
moment = mom(close, 10) // Momentum
cci = cci(close, 10) // CCI
Obv = obv // OBV
stk = sma(stoch(close, high, low, 14), 3) // Stoch
maFast = vwma(close, 12), maSlow = vwma(close, 26), vwmacd = maFast - maSlow // volume weighted macd
Cmfm = ((close-low) - (high-close)) / (high - low), Cmfv = Cmfm * volume, cmf = sma(Cmfv, 21) / sma(volume,21) // Chaikin money flow
Mfi = mfi(close, 14) // Moneyt Flow Index
// keep indicators names and colors in arrays
var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
// names
array.set(indicators_name, 0, showindis == "Full" ? "." : "M")
array.set(indicators_name, 1, showindis == "Full" ? "." : "H")
array.set(indicators_name, 2, showindis == "Full" ? "." : "E")
array.set(indicators_name, 3, showindis == "Full" ? "." : "S")
array.set(indicators_name, 4, showindis == "Full" ? "." : "C")
array.set(indicators_name, 5, showindis == "Full" ? "." : "M")
array.set(indicators_name, 6, showindis == "Full" ? "." : "O")
array.set(indicators_name, 7, showindis == "Full" ? "." : "V")
array.set(indicators_name, 8, showindis == "Full" ? "." : "C")
array.set(indicators_name, 9, showindis == "Full" ? "." : "M")
array.set(indicators_name,10, showindis == "Full" ? "." : "X")
//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 = pivothigh((source == "Close" ? close : high), prd, prd)
float pl = pivotlow((source == "Close" ? close : low), prd, prd)
plotshape(ph and showpivot, text = "H", style = shape.labeldown, color = color.new(color.white, 100), textcolor = color.red, location = location.abovebar, offset = -prd)
plotshape(pl and showpivot, text = "L", style = shape.labelup, color = color.new(color.white, 100), textcolor = color.lime, location = location.belowbar, offset = -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 = source == "Close" ? close : low
// 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
textif 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 = source == "Close" ? close : high
// 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
textif 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(44) // 11 indicators * 4 divergence = 44 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(calcmacd, macd), 0)
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
array_set_divs(calculate_divs(calcrsi, rsi), 2)
array_set_divs(calculate_divs(calcstoc, stk), 3)
array_set_divs(calculate_divs(calccci, cci), 4)
array_set_divs(calculate_divs(calcmom, moment), 5)
array_set_divs(calculate_divs(calcobv, Obv), 6)
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
array_set_divs(calculate_divs(calccmf, cmf), 8)
array_set_divs(calculate_divs(calcmfi, Mfi), 9)
array_set_divs(calculate_divs(calcext, externalindi), 10)
// check minimum number of divergence, if less than showlimit then delete all divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1
total_div := total_div + round(sign(array.get(all_divergences, x)))
if total_div < showlimit
array.fill(all_divergences, 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 10
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 ? line.new(x1 = bar_index - array.get(all_divergences, x * 4 + y),
y1 = (source == "Close" ? close[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" ? close[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
textif (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 // get text for labels if div_type >= 0 divergence_text_top := divergence_text_top + ((div_type % 2) == 1 ? (showindis != "Don't Show" ? array.get(indicators_name, x) + "\n" : "") : "") divergence_text_bottom := divergence_text_bottom + ((div_type % 2) == 0 ? (showindis != "Don't Show" ? array.get(indicators_name, x) + "\n" : "") : "")
// draw labels
if showindis != "Don't Show" or shownum
if shownum and dnumdiv_top > 0
divergence_text_top := divergence_text_top + tostring(dnumdiv_top)
if shownum and dnumdiv_bottom > 0
divergence_text_bottom := divergence_text_bottom + tostring(dnumdiv_bottom)
if divergence_text_top != ""
if showlast
delete_old_neg_div_labels()
array.push(neg_div_labels,
label.new( x = bar_index,
y = max(high, high[1]),
text = divergence_text_top,
color = top_label_col,
textcolor = neg_div_text_col,
style = label.style_label_down
))
textif divergence_text_bottom != "" if showlast delete_old_pos_div_labels() array.push(pos_div_labels, label.new( x = bar_index, y = min(low, low[1]), text = divergence_text_bottom, color = bottom_label_col, textcolor = pos_div_text_col, style = label.style_label_up ))
alertcondition(pos_reg_div_detected, title='Positive Regular Divergence Detected', message='Positive Regular Divergence Detected')
alertcondition(neg_reg_div_detected, title='Negative Regular Divergence Detected', message='Negative Regular Divergence Detected')
alertcondition(pos_hid_div_detected, title='Positive Hidden Divergence Detected', message='Positive Hidden Divergence Detected')
alertcondition(neg_hid_div_detected, title='Negative Hidden Divergence Detected', message='Negative Hidden Divergence Detected')
alertcondition(pos_reg_div_detected or pos_hid_div_detected, title='Positive Divergence Detected', message='Positive Divergence Detected')
alertcondition(neg_reg_div_detected or neg_hid_div_detected, title='Negative Divergence Detected', message='Negative Divergence Detected')
I’ll port the divergence logic, including the pivot search, regular and hidden signals, indicator filters, and chart labels. I’ll also check which drawing and alert features NexuScript supports.
The reference confirms that NexuScript has divergence-ready pivot functions, historical lookbacks, line and label drawing, and alerts. It doesn’t expose Pine’s line and label deletion methods, so I’ll emulate that behavior by retaining drawing records and redrawing only the ones that should still be visible.
I've converted your multi-indicator divergence script for Nexus Trader / Onyx.
This version retains the core functionality of your TradingView indicator:
"." indicator labels.I've also retained your original virtual trendline validation, rather than replacing it with a simpler pivot comparison.
NexuScript handles drawing objects and historical data differently from Pine Script, so this conversion uses stored drawing records to reproduce the original behavior. (www.nexusprop.com www.nexusprop.com www.nexusprop.com)
Copy the entire script below into your Nexus Scripts editor.
julianexscript 1.6 indicator "SuperFuckingGoodIndicator", overlay = true, short = "SFGI" # ================================================== # SETTINGS # ================================================== input prd = 5, title = "Pivot Period", min = 1, max = 50, group = "Divergence Settings" input source = "Close", title = "Source for Pivot Points", options = ["Close", "High/Low"], group = "Divergence Settings" input searchdiv = "Regular", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group = "Divergence Settings" input showindis = "Full", title = "Show Indicator Names", options = ["Full", "First Letter", "Don't Show"], group = "Divergence Settings" input showlimit = 1, title = "Minimum Number of Divergence", min = 1, max = 11, group = "Divergence Settings" input maxpp = 10, title = "Maximum Pivot Points to Check", min = 1, max = 20, group = "Divergence Settings" input maxbars = 100, title = "Maximum Bars to Check", min = 30, max = 200, group = "Divergence Settings" input shownum = true, title = "Show Divergence Number", group = "Display" input showlast = false, title = "Show Only Last Divergence", group = "Display" input dontconfirm = false, title = "Don't Wait for Confirmation", group = "Display" input showlines = true, title = "Show Divergence Lines", group = "Display" input showpivot = false, title = "Show Pivot Points", group = "Display" # ================================================== # INDICATOR SELECTION # ================================================== input calcmacd = true, title = "MACD", group = "Indicators" input calcmacda = true, title = "MACD Histogram", group = "Indicators" input calcrsi = true, title = "RSI", group = "Indicators" input calcstoc = true, title = "Stochastic", group = "Indicators" input calccci = true, title = "CCI", group = "Indicators" input calcmom = true, title = "Momentum", group = "Indicators" input calcobv = true, title = "OBV", group = "Indicators" input calcvwmacd = true, title = "VWmacd", group = "Indicators" input calccmf = true, title = "Chaikin Money Flow", group = "Indicators" input calcmfi = true, title = "Money Flow Index", group = "Indicators" input calcext = false, title = "Check External Indicator", group = "Indicators" input externalindi = close, title = "External Source", group = "Indicators" # ================================================== # COLORS AND LINE STYLES # ================================================== input pos_reg_div_col = color.rgb(255, 235, 59, 0.47), title = "Positive Regular Divergence", group = "Colors" input neg_reg_div_col = color.rgb(49, 27, 146, 0.57), title = "Negative Regular Divergence", group = "Colors" input pos_hid_div_col = color.hex("#00E676"), title = "Positive Hidden Divergence", group = "Colors" input neg_hid_div_col = color.hex("#FF5252"), title = "Negative Hidden Divergence", group = "Colors" input pos_div_text_col = color.black, title = "Positive Divergence Text Color", group = "Colors" input neg_div_text_col = color.white, title = "Negative Divergence Text Color", group = "Colors" input reg_div_l_style = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group = "Lines" input hid_div_l_style = "Dashed", title = "Hidden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group = "Lines" input reg_div_l_width = 2, title = "Regular Divergence Line Width", min = 1, max = 5, group = "Lines" input hid_div_l_width = 1, title = "Hidden Divergence Line Width", min = 1, max = 5, group = "Lines" # ================================================== # MOVING AVERAGES # ================================================== input showmas = false, title = "Show MAs 50 & 200", group = "Moving Averages" input cma1col = color.hex("#00E676"), title = "MA 50 Color", group = "Moving Averages" input cma2col = color.hex("#FF5252"), title = "MA 200 Color", group = "Moving Averages" # ================================================== # CONSTANTS # ================================================== const divColors = [ pos_reg_div_col, neg_reg_div_col, pos_hid_div_col, neg_hid_div_col ] const indicatorNames = [ ".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "." ] const indicatorLetters = [ "M", "H", "E", "S", "C", "M", "O", "V", "C", "M", "X" ] const enabledIndicators = [ calcmacd, calcmacda, calcrsi, calcstoc, calccci, calcmom, calcobv, calcvwmacd, calccmf, calcmfi, calcext ] const regularDash = lowercase(reg_div_l_style) const hiddenDash = lowercase(hid_div_l_style) # ================================================== # PERSISTENT STATE # ================================================== state phPositions::Array{Number} = [] state plPositions::Array{Number} = [] state phValues::Array{Number} = [] state plValues::Array{Number} = [] state obvTotal = 0.0 # Circular history buffer: # 201 bars x 12 values # 11 indicators plus closing price state oscHistory::Array{Number} = fill(0, 2412) # Each divergence line uses five values: # start time, start price, end time, end price, type state bullLines::Array{Number} = [] state bearLines::Array{Number} = [] # Each label uses three numeric values: # time, price, divergence type state bullLabels::Array{Number} = [] state bearLabels::Array{Number} = [] state bullTexts::Array{String} = [] state bearTexts::Array{String} = [] state lastBullSize = 0 state lastBearSize = 0 # ================================================== # DIVERGENCE DETECTION FUNCTION # ================================================== # # Type 1 = Positive Regular # Type 2 = Negative Regular # Type 3 = Positive Hidden # Type 4 = Negative Hidden # # ================================================== function find_divergence(ind, kind, startpoint, idx, endPrice, pivotPositions, pivotValues) let bullish = kind % 2 == 1 let regular = kind <= 2 if idx < 1 || isempty(pivotPositions) return 0 end let currentSlot = (idx % 201) * 12 let previousSlot = ((idx - 1) % 201) * 12 let currentOsc = oscHistory[currentSlot + ind] let previousOsc = oscHistory[previousSlot + ind] let currentClose = oscHistory[currentSlot + 12] let previousClose = oscHistory[previousSlot + 12] # Original confirmation condition if !dontconfirm if bullish if !(currentOsc > previousOsc || currentClose > previousClose) return 0 end else if !(currentOsc < previousOsc || currentClose < previousClose) return 0 end end end let startSlot = ((idx - startpoint) % 201) * 12 let startOsc = oscHistory[startSlot + ind] let startClose = oscHistory[startSlot + 12] if ismissing(startOsc) || ismissing(startClose) || ismissing(endPrice) return 0 end let pivotsToCheck = min(maxpp, length(pivotPositions)) for x in 1:pivotsToCheck let distance = idx - pivotPositions[x] if distance > maxbars break end if distance <= 5 continue end let oldSlot = ((idx - distance) % 201) * 12 let oldOsc = oscHistory[oldSlot + ind] let oldClose = oscHistory[oldSlot + 12] let oldPrice = pivotValues[x] if ismissing(oldOsc) || ismissing(oldClose) || ismissing(oldPrice) continue end let valid = false # Positive regular: # Price lower low, oscillator higher low if bullish && regular valid = startOsc > oldOsc && endPrice < oldPrice # Negative regular: # Price higher high, oscillator lower high elseif !bullish && regular valid = startOsc < oldOsc && endPrice > oldPrice # Positive hidden: # Price higher low, oscillator lower low elseif bullish && !regular valid = startOsc < oldOsc && endPrice > oldPrice # Negative hidden: # Price lower high, oscillator higher high else valid = startOsc > oldOsc && endPrice < oldPrice end if !valid continue end # Original virtual trendline validation let span = distance - startpoint let slope1 = (startOsc - oldOsc) / span let slope2 = (startClose - oldClose) / span let virtualLine1 = startOsc - slope1 let virtualLine2 = startClose - slope2 let arrived = true for y in (startpoint + 1):(distance - 1) let checkSlot = ((idx - y) % 201) * 12 let checkOsc = oscHistory[checkSlot + ind] let checkClose = oscHistory[checkSlot + 12] if ismissing(checkOsc) || ismissing(checkClose) arrived = false break end if bullish if checkOsc < virtualLine1 || checkClose < virtualLine2 arrived = false break end else if checkOsc > virtualLine1 || checkClose > virtualLine2 arrived = false break end end virtualLine1 -= slope1 virtualLine2 -= slope2 end if arrived return distance end end return 0 end # ================================================== # SAVE AND REPLACE DIVERGENCE DRAWINGS # ================================================== function save_side(bullish, newLines, labelText, labelTime, labelPrice, labelKind) let keptLines = bullish ? bullLines : bearLines let keptLabels = bullish ? bullLabels : bearLabels let keptTexts = bullish ? bullTexts : bearTexts let previousSize = bullish ? lastBullSize : lastBearSize if !isempty(newLines) if showlast keptLines = fill(0, 0) elseif previousSize > 0 && length(keptLines) >= previousSize # Replace previous divergence within same pivot cycle for j in 1:previousSize pop!(keptLines) end if length(keptLabels) >= 3 && !isempty(keptTexts) for j in 1:3 pop!(keptLabels) end pop!(keptTexts) end end for value in newLines push!(keptLines, value) end previousSize = length(newLines) end if labelText != "" if showlast keptLabels = fill(0, 0) keptTexts = fill("", 0) end push!(keptLabels, labelTime) push!(keptLabels, labelPrice) push!(keptLabels, labelKind) push!(keptTexts, labelText) end if bullish bullLines = keptLines bullLabels = keptLabels bullTexts = keptTexts lastBullSize = previousSize else bearLines = keptLines bearLabels = keptLabels bearTexts = keptTexts lastBearSize = previousSize end return 0 end # ================================================== # DRAW STORED DIVERGENCES # ================================================== function draw_side(bullish, records, labels, texts) if showlines && length(records) >= 5 for j in 1:5:length(records) let kind = records[j + 4] let drawingColor = divColors[kind] let drawingWidth = kind <= 2 ? reg_div_l_width : hid_div_l_width let drawingDash = kind <= 2 ? regularDash : hiddenDash line( records[j], records[j + 1], records[j + 2], records[j + 3], color = drawingColor, width = drawingWidth, dash = drawingDash ) end end if !isempty(texts) for j in 1:length(texts) let offset = (j - 1) * 3 let labelTime = labels[offset + 1] let labelPrice = labels[offset + 2] let labelKind = labels[offset + 3] let labelColor = divColors[labelKind] let textColor = bullish ? pos_div_text_col : neg_div_text_col let labelPosition = bullish ? "below" : "above" marker( texts[j], time = labelTime, price = labelPrice, position = labelPosition, place = labelPosition, shape = "label", color = labelColor, text_color = textColor, size = "small" ) end end return 0 end # ================================================== # MAIN INDICATOR # ================================================== on bar # ---------------------------------------------- # Calculate all indicators on every bar # ---------------------------------------------- let rsiValue = ta.rsi(close, 14) let macdResult = ta.macd(close, 12, 26, 9) let macdValue = macdResult.macd let macdHistogram = macdResult.hist let momentum = close - close[10] let cciValue = ta.cci(close, 10) let stochasticRaw = ta.stoch(close, high, low, 14) let stochasticValue = ta.sma(stochasticRaw, 3) # OBV if close > close[1] obvTotal += coalesce(volume, 0) elseif close < close[1] obvTotal -= coalesce(volume, 0) end let obvValue = obvTotal # Volume Weighted MACD let vwmaFast = ta.vwma(close, 12) let vwmaSlow = ta.vwma(close, 26) let vwmacdValue = vwmaFast - vwmaSlow # Chaikin Money Flow let candleRange = high - low let cmfMultiplier = candleRange != 0 ? ((close - low) - (high - close)) / candleRange : 0 let cmfVolume = cmfMultiplier * volume let cmfNumerator = ta.sma(cmfVolume, 21) let cmfDenominator = ta.sma(volume, 21) let cmfValue = cmfDenominator != 0 ? cmfNumerator / cmfDenominator : missing # Money Flow Index let mfiValue = ta.mfi(close, 14) # Moving averages let ma50 = ta.sma(close, 50) let ma200 = ta.sma(close, 200) plot("MA 50", showmas ? ma50 : missing, color = cma1col) plot("MA 200", showmas ? ma200 : missing, color = cma2col) # ---------------------------------------------- # Store indicator history # ---------------------------------------------- let values = [ macdValue, macdHistogram, rsiValue, stochasticValue, cciValue, momentum, obvValue, vwmacdValue, cmfValue, mfiValue, externalindi, close ] let historySlot = (bar.index % 201) * 12 for i in 1:12 oscHistory[historySlot + i] = values[i] end # ---------------------------------------------- # Calculate pivot points # ---------------------------------------------- let highSource = source == "Close" ? close : high let lowSource = source == "Close" ? close : low let ph = ta.pivot_high(highSource, prd, prd) let pl = ta.pivot_low(lowSource, prd, prd) if !ismissing(ph) pushfirst!(phPositions, bar.index - prd) pushfirst!(phValues, ph) if length(phPositions) > 20 pop!(phPositions) pop!(phValues) end lastBearSize = 0 if showpivot marker( "H", time = time[prd], price = high[prd], position = "above", place = "above", shape = "text", color = color.red, text_color = color.red ) end end if !ismissing(pl) pushfirst!(plPositions, bar.index - prd) pushfirst!(plValues, pl) if length(plPositions) > 20 pop!(plPositions) pop!(plValues) end lastBullSize = 0 if showpivot marker( "L", time = time[prd], price = low[prd], position = "below", place = "below", shape = "text", color = color.hex("#00E676"), text_color = color.hex("#00E676") ) end end # ---------------------------------------------- # Calculate all 44 divergence combinations # ---------------------------------------------- let startpoint = dontconfirm ? 0 : 1 let lowEnd = lowSource[startpoint] let highEnd = highSource[startpoint] let allDivergences = fill(0, 44) let totalDiv = 0 for i in 1:11 if !enabledIndicators[i] continue end for kind in 1:4 let regular = kind <= 2 if regular && searchdiv == "Hidden" continue end if !regular && searchdiv == "Regular" continue end let distance = 0 if kind % 2 == 1 distance = find_divergence( i, kind, startpoint, bar.index, lowEnd, plPositions, plValues ) else distance = find_divergence( i, kind, startpoint, bar.index, highEnd, phPositions, phValues ) end allDivergences[(i - 1) * 4 + kind] = distance if distance > 0 totalDiv += 1 end end end # ---------------------------------------------- # Minimum divergence filter # ---------------------------------------------- let detected = fill(false, 4) let topText = "" let bottomText = "" let topCount = 0 let bottomCount = 0 let topKind = 2 let bottomKind = 1 let newBullLines::Array{Number} = [] let newBearLines::Array{Number} = [] let usedDistances = fill(false, maxbars + 1) if totalDiv >= showlimit for i in 1:11 let lastKind = 0 for kind in 1:4 let distance = allDivergences[(i - 1) * 4 + kind] if distance <= 0 continue end lastKind = kind detected[kind] = true let bullish = kind % 2 == 1 if bullish bottomCount += 1 bottomKind = kind else topCount += 1 topKind = kind end # Prevent duplicate lines if !usedDistances[distance + 1] usedDistances[distance + 1] = true let price1 = bullish ? lowSource[distance] : highSource[distance] let price2 = bullish ? lowSource[startpoint] : highSource[startpoint] let record = [ time[distance], price1, time[startpoint], price2, kind ] if bullish for value in record push!(newBullLines, value) end else for value in record push!(newBearLines, value) end end end end # Original label naming behavior if lastKind > 0 && showindis != "Don't Show" let indicatorName = showindis == "Full" ? indicatorNames[i] : indicatorLetters[i] if lastKind % 2 == 1 bottomText = bottomText * indicatorName * "\n" else topText = topText * indicatorName * "\n" end end end # Append divergence counts if shownum && topCount > 0 topText = topText * string(topCount) end if shownum && bottomCount > 0 bottomText = bottomText * string(bottomCount) end # ------------------------------------------ # Save positive divergence drawings # ------------------------------------------ if !isempty(newBullLines) || bottomText != "" let labelLow = min(low, coalesce(low[1], low)) save_side( true, newBullLines, bottomText, time, labelLow, bottomKind ) end # ------------------------------------------ # Save negative divergence drawings # ------------------------------------------ if !isempty(newBearLines) || topText != "" let labelHigh = max(high, coalesce(high[1], high)) save_side( false, newBearLines, topText, time, labelHigh, topKind ) end end # ---------------------------------------------- # Limit divergence lines to 400 # ---------------------------------------------- let excessLines = (length(bullLines) + length(bearLines)) / 5 - 400 if excessLines > 0 for j in 1:excessLines let removeBull = isempty(bearLines) || (!isempty(bullLines) && bullLines[3] <= bearLines[3]) if removeBull for k in 1:5 popfirst!(bullLines) end else for k in 1:5 popfirst!(bearLines) end end end end # ---------------------------------------------- # Limit divergence labels to 400 # ---------------------------------------------- let excessLabels = length(bullTexts) + length(bearTexts) - 400 if excessLabels > 0 for j in 1:excessLabels let removeBull = isempty(bearLabels) || (!isempty(bullLabels) && bullLabels[1] <= bearLabels[1]) if removeBull for k in 1:3 popfirst!(bullLabels) end popfirst!(bullTexts) else for k in 1:3 popfirst!(bearLabels) end popfirst!(bearTexts) end end end # ---------------------------------------------- # Render retained divergence drawings # ---------------------------------------------- if bar.last draw_side( true, bullLines, bullLabels, bullTexts ) draw_side( false, bearLines, bearLabels, bearTexts ) end # ---------------------------------------------- # ALERTS # ---------------------------------------------- if detected[1] alert( "Positive Regular Divergence Detected", title = "Positive Regular Divergence Detected" ) end if detected[2] alert( "Negative Regular Divergence Detected", title = "Negative Regular Divergence Detected" ) end if detected[3] alert( "Positive Hidden Divergence Detected", title = "Positive Hidden Divergence Detected" ) end if detected[4] alert( "Negative Hidden Divergence Detected", title = "Negative Hidden Divergence Detected" ) end if detected[1] || detected[3] alert( "Positive Divergence Detected", title = "Positive Divergence Detected" ) end if detected[2] || detected[4] alert( "Negative Divergence Detected", title = "Negative Divergence Detected" ) end end
The following illustrates the four divergence types using your original color scheme.
Positive Regular
svg<svg viewBox="0 0 160 100" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="M5 15 L20 28 L37 51 L57 20 L79 30 L102 68 L123 40 L150 16" fill="none" stroke="currentColor" stroke-width="1.5" opacity=".65" /><path d="M37 51 L102 68" stroke="#FFEB3B" stroke-width="3" /><rect x="91" y="71" width="23" height="18" rx="3" fill="#FFEB3B" opacity=".7" /><text x="102.5" y="84" font-size="11" text-anchor="middle" fill="#000">3</text></svg>
Price: lower low
Oscillator: higher low
Negative Regular
svg<svg viewBox="0 0 160 100" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="M5 83 L20 70 L37 39 L57 70 L79 59 L102 22 L123 57 L150 84" fill="none" stroke="currentColor" stroke-width="1.5" opacity=".65" /><path d="M37 39 L102 22" stroke="#6552bd" stroke-width="3" /><rect x="91" y="1" width="23" height="18" rx="3" fill="#311B92" /><text x="102.5" y="14" font-size="11" text-anchor="middle" fill="#fff">3</text></svg>
Price: higher high
Oscillator: lower high
Positive Hidden
svg<svg viewBox="0 0 160 100" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="M5 28 L20 49 L37 75 L57 38 L79 20 L102 50 L123 26 L150 8" fill="none" stroke="currentColor" stroke-width="1.5" opacity=".65" /><path d="M37 75 L102 50" stroke="#00E676" stroke-width="2" stroke-dasharray="5 3" /><rect x="91" y="54" width="23" height="18" rx="3" fill="#00E676" /><text x="102.5" y="67" font-size="11" text-anchor="middle" fill="#000">3</text></svg>
Price: higher low
Oscillator: lower low
Negative Hidden
svg<svg viewBox="0 0 160 100" width="100%" xmlns="http://www.w3.org/2000/svg"><path d="M5 75 L20 49 L37 19 L57 65 L79 78 L102 44 L123 69 L150 91" fill="none" stroke="currentColor" stroke-width="1.5" opacity=".65" /><path d="M37 19 L102 44" stroke="#FF5252" stroke-width="2" stroke-dasharray="5 3" /><rect x="91" y="23" width="23" height="18" rx="3" fill="#FF5252" /><text x="102.5" y="36" font-size="11" text-anchor="middle" fill="#fff">3</text></svg>
Price: lower high
Oscillator: higher high
| Feature | Implementation |
|---|---|
| 44 divergence combinations | Preserved |
| Virtual trendline validation | Preserved |
| 20 stored pivot highs and lows | Preserved |
| 400 divergence lines and labels each | Preserved through stored records |
| Original transparency settings | Converted |
| Previous divergence removal | Emulated |
| External indicator | Price source input; other indicator outputs require a use declaration |
| Six alert conditions | Converted to alert() calls |
| Moving averages | Preserved |
Important: I've written this against the official NexuScript 1.6 documentation, but I haven't compiled or tested it inside Nexus itself.
There may also be minor signal differences because of pivot tie handling, missing indicator values and zero-range candles. Large lookback settings may increase execution time, and alerts fire on live bars rather than historical bars. (www.nexusprop.com www.nexusprop.com www.nexusprop.com www.nexusprop.com)
I've intentionally kept your original dot labels and default settings rather than redesigning the indicator.
turn this into nexuscript. nexscript 1.6
indicator "SuperFuckingGoodIndicator", overlay = true, short = "SFGI"
input prd = 5, title = "Pivot Period", min = 1, max = 50, group = "Divergence Settings"
input source = "Close", title = "Source for Pivot Points", options = ["Close", "High/Low"], group = "Divergence Settings"
input searchdiv = "Regular", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"], group = "Divergence Settings"
input showindis = "Full", title = "Show Indicator Names", options = ["Full", "First Letter", "Don't Show"], group = "Divergence Settings"
input showlimit = 1, title = "Minimum Number of Divergence", min = 1, max = 11, group = "Divergence Settings"
input maxpp = 10, title = "Maximum Pivot Points to Check", min = 1, max = 20, group = "Divergence Settings"
input maxbars = 100, title = "Maximum Bars to Check", min = 30, max = 200, group = "Divergence Settings"
input shownum = true, title = "Show Divergence Number", group = "Display"
input showlast = false, title = "Show Only Last Divergence", group = "Display"
input dontconfirm = false, title = "Don't Wait for Confirmation", group = "Display"
input showlines = true, title = "Show Divergence Lines", group = "Display"
input showpivot = false, title = "Show Pivot Points", group = "Display"
input calcmacd = true, title = "MACD", group = "Indicators"
input calcmacda = true, title = "MACD Histogram", group = "Indicators"
input calcrsi = true, title = "RSI", group = "Indicators"
input calcstoc = true, title = "Stochastic", group = "Indicators"
input calccci = true, title = "CCI", group = "Indicators"
input calcmom = true, title = "Momentum", group = "Indicators"
input calcobv = true, title = "OBV", group = "Indicators"
input calcvwmacd = true, title = "VWmacd", group = "Indicators"
input calccmf = true, title = "Chaikin Money Flow", group = "Indicators"
input calcmfi = true, title = "Money Flow Index", group = "Indicators"
input calcext = false, title = "Check External Indicator", group = "Indicators"
input externalindi = close, title = "External Source", group = "Indicators"
input pos_reg_div_col = color.rgb(255, 235, 59, 0.47), title = "Positive Regular Divergence", group = "Colors"
input neg_reg_div_col = color.rgb(49, 27, 146, 0.57), title = "Negative Regular Divergence", group = "Colors"
input pos_hid_div_col = color.hex("#00E676"), title = "Positive Hidden Divergence", group = "Colors"
input neg_hid_div_col = color.hex("#FF5252"), title = "Negative Hidden Divergence", group = "Colors"
input pos_div_text_col = color.black, title = "Positive Divergence Text Color", group = "Colors"
input neg_div_text_col = color.white, title = "Negative Divergence Text Color", group = "Colors"
input reg_div_l_style = "Solid", title = "Regular Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group = "Lines"
input hid_div_l_style = "Dashed", title = "Hidden Divergence Line Style", options = ["Solid", "Dashed", "Dotted"], group = "Lines"
input reg_div_l_width = 2, title = "Regular Divergence Line Width", min = 1, max = 5, group = "Lines"
input hid_div_l_width = 1, title = "Hidden Divergence Line Width", min = 1, max = 5, group = "Lines"
input showmas = false, title = "Show MAs 50 & 200", group = "Moving Averages"
input cma1col = color.hex("#00E676"), title = "MA 50 Color", group = "Moving Averages"
input cma2col = color.hex("#FF5252"), title = "MA 200 Color", group = "Moving Averages"
const divColors = [
pos_reg_div_col,
neg_reg_div_col,
pos_hid_div_col,
neg_hid_div_col
]
const indicatorNames = [
".", ".", ".", ".", ".", ".",
".", ".", ".", ".", "."
]
const indicatorLetters = [
"M", "H", "E", "S", "C", "M",
"O", "V", "C", "M", "X"
]
const enabledIndicators = [
calcmacd,
calcmacda,
calcrsi,
calcstoc,
calccci,
calcmom,
calcobv,
calcvwmacd,
calccmf,
calcmfi,
calcext
]
const regularDash = lowercase(reg_div_l_style)
const hiddenDash = lowercase(hid_div_l_style)
state phPositions::Array{Number} = []
state plPositions::Array{Number} = []
state phValues::Array{Number} = []
state plValues::Array{Number} = []
state obvTotal = 0.0
state oscHistory::Array{Number} = fill(0, 2412)
state bullLines::Array{Number} = []
state bearLines::Array{Number} = []
state bullLabels::Array{Number} = []
state bearLabels::Array{Number} = []
state bullTexts::Array{String} = []
state bearTexts::Array{String} = []
state lastBullSize = 0
state lastBearSize = 0
function find_divergence(ind, kind, startpoint, idx, endPrice, pivotPositions, pivotValues)
textlet bullish = kind % 2 == 1 let regular = kind <= 2 if idx < 1 || isempty(pivotPositions) return 0 end let currentSlot = (idx % 201) * 12 let previousSlot = ((idx - 1) % 201) * 12 let currentOsc = oscHistory[currentSlot + ind] let previousOsc = oscHistory[previousSlot + ind] let currentClose = oscHistory[currentSlot + 12] let previousClose = oscHistory[previousSlot + 12] # Original confirmation condition if !dontconfirm if bullish if !(currentOsc > previousOsc || currentClose > previousClose) return 0 end else if !(currentOsc < previousOsc || currentClose < previousClose) return 0 end end end let startSlot = ((idx - startpoint) % 201) * 12 let startOsc = oscHistory[startSlot + ind] let startClose = oscHistory[startSlot + 12] if ismissing(startOsc) || ismissing(startClose) || ismissing(endPrice) return 0 end let pivotsToCheck = min(maxpp, length(pivotPositions)) for x in 1:pivotsToCheck let distance = idx - pivotPositions[x] if distance > maxbars break end if distance <= 5 continue end let oldSlot = ((idx - distance) % 201) * 12 let oldOsc = oscHistory[oldSlot + ind] let oldClose = oscHistory[oldSlot + 12] let oldPrice = pivotValues[x] if ismissing(oldOsc) || ismissing(oldClose) || ismissing(oldPrice) continue end let valid = false # Positive regular: # Price lower low, oscillator higher low if bullish && regular valid = startOsc > oldOsc && endPrice < oldPrice # Negative regular: # Price higher high, oscillator lower high elseif !bullish && regular valid = startOsc < oldOsc && endPrice > oldPrice # Positive hidden: # Price higher low, oscillator lower low elseif bullish && !regular valid = startOsc < oldOsc && endPrice > oldPrice # Negative hidden: # Price lower high, oscillator higher high else valid = startOsc > oldOsc && endPrice < oldPrice end if !valid continue end # Original virtual trendline validation let span = distance - startpoint let slope1 = (startOsc - oldOsc) / span let slope2 = (startClose - oldClose) / span let virtualLine1 = startOsc - slope1 let virtualLine2 = startClose - slope2 let arrived = true for y in (startpoint + 1):(distance - 1) let checkSlot = ((idx - y) % 201) * 12 let checkOsc = oscHistory[checkSlot + ind] let checkClose = oscHistory[checkSlot + 12] if ismissing(checkOsc) || ismissing(checkClose) arrived = false break end if bullish if checkOsc < virtualLine1 || checkClose < virtualLine2 arrived = false break end else if checkOsc > virtualLine1 || checkClose > virtualLine2 arrived = false break end end virtualLine1 -= slope1 virtualLine2 -= slope2 end if arrived return distance end end return 0
end
function save_side(bullish, newLines, labelText, labelTime, labelPrice, labelKind)
textlet keptLines = bullish ? bullLines : bearLines let keptLabels = bullish ? bullLabels : bearLabels let keptTexts = bullish ? bullTexts : bearTexts let previousSize = bullish ? lastBullSize : lastBearSize if !isempty(newLines) if showlast keptLines = fill(0, 0) elseif previousSize > 0 && length(keptLines) >= previousSize # Replace previous divergence within same pivot cycle for j in 1:previousSize pop!(keptLines) end if length(keptLabels) >= 3 && !isempty(keptTexts) for j in 1:3 pop!(keptLabels) end pop!(keptTexts) end end for value in newLines push!(keptLines, value) end previousSize = length(newLines) end if labelText != "" if showlast keptLabels = fill(0, 0) keptTexts = fill("", 0) end push!(keptLabels, labelTime) push!(keptLabels, labelPrice) push!(keptLabels, labelKind) push!(keptTexts, labelText) end if bullish bullLines = keptLines bullLabels = keptLabels bullTexts = keptTexts lastBullSize = previousSize else bearLines = keptLines bearLabels = keptLabels bearTexts = keptTexts lastBearSize = previousSize end return 0
end
function draw_side(bullish, records, labels, texts)
textif showlines && length(records) >= 5 for j in 1:5:length(records) let kind = records[j + 4] let drawingColor = divColors[kind] let drawingWidth = kind <= 2 ? reg_div_l_width : hid_div_l_width let drawingDash = kind <= 2 ? regularDash : hiddenDash line( records[j], records[j + 1], records[j + 2], records[j + 3], color = drawingColor, width = drawingWidth, dash = drawingDash ) end end if !isempty(texts) for j in 1:length(texts) let offset = (j - 1) * 3 let labelTime = labels[offset + 1] let labelPrice = labels[offset + 2] let labelKind = labels[offset + 3] let labelColor = divColors[labelKind] let textColor = bullish ? pos_div_text_col : neg_div_text_col let labelPosition = bullish ? "below" : "above" marker( texts[j], time = labelTime, price = labelPrice, position = labelPosition, place = labelPosition, shape = "label", color = labelColor, text_color = textColor, size = "small" ) end end return 0
end
on bar
text# ---------------------------------------------- # Calculate all indicators on every bar # ---------------------------------------------- let rsiValue = ta.rsi(close, 14) let macdResult = ta.macd(close, 12, 26, 9) let macdValue = macdResult.macd let macdHistogram = macdResult.hist let momentum = close - close[10] let cciValue = ta.cci(close, 10) let stochasticRaw = ta.stoch(close, high, low, 14) let stochasticValue = ta.sma(stochasticRaw, 3) # OBV if close > close[1] obvTotal += coalesce(volume, 0) elseif close < close[1] obvTotal -= coalesce(volume, 0) end let obvValue = obvTotal # Volume Weighted MACD let vwmaFast = ta.vwma(close, 12) let vwmaSlow = ta.vwma(close, 26) let vwmacdValue = vwmaFast - vwmaSlow # Chaikin Money Flow let candleRange = high - low let cmfMultiplier = candleRange != 0 ? ((close - low) - (high - close)) / candleRange : 0 let cmfVolume = cmfMultiplier * volume let cmfNumerator = ta.sma(cmfVolume, 21) let cmfDenominator = ta.sma(volume, 21) let cmfValue = cmfDenominator != 0 ? cmfNumerator / cmfDenominator : missing # Money Flow Index let mfiValue = ta.mfi(close, 14) # Moving averages let ma50 = ta.sma(close, 50) let ma200 = ta.sma(close, 200) plot("MA 50", showmas ? ma50 : missing, color = cma1col) plot("MA 200", showmas ? ma200 : missing, color = cma2col) # ---------------------------------------------- # Store indicator history # ---------------------------------------------- let values = [ macdValue, macdHistogram, rsiValue, stochasticValue, cciValue, momentum, obvValue, vwmacdValue, cmfValue, mfiValue, externalindi, close ] let historySlot = (bar.index % 201) * 12 for i in 1:12 oscHistory[historySlot + i] = values[i] end # ---------------------------------------------- # Calculate pivot points # ---------------------------------------------- let highSource = source == "Close" ? close : high let lowSource = source == "Close" ? close : low let ph = ta.pivot_high(highSource, prd, prd) let pl = ta.pivot_low(lowSource, prd, prd) if !ismissing(ph) pushfirst!(phPositions, bar.index - prd) pushfirst!(phValues, ph) if length(phPositions) > 20 pop!(phPositions) pop!(phValues) end lastBearSize = 0 if showpivot marker( "H", time = time[prd], price = high[prd], position = "above", place = "above", shape = "text", color = color.red, text_color = color.red ) end end if !ismissing(pl) pushfirst!(plPositions, bar.index - prd) pushfirst!(plValues, pl) if length(plPositions) > 20 pop!(plPositions) pop!(plValues) end lastBullSize = 0 if showpivot marker( "L", time = time[prd], price = low[prd], position = "below", place = "below", shape = "text", color = color.hex("#00E676"), text_color = color.hex("#00E676") ) end end # ---------------------------------------------- # Calculate all 44 divergence combinations # ---------------------------------------------- let startpoint = dontconfirm ? 0 : 1 let lowEnd = lowSource[startpoint] let highEnd = highSource[startpoint] let allDivergences = fill(0, 44) let totalDiv = 0 for i in 1:11 if !enabledIndicators[i] continue end for kind in 1:4 let regular = kind <= 2 if regular && searchdiv == "Hidden" continue end if !regular && searchdiv == "Regular" continue end let distance = 0 if kind % 2 == 1 distance = find_divergence( i, kind, startpoint, bar.index, lowEnd, plPositions, plValues ) else distance = find_divergence( i, kind, startpoint, bar.index, highEnd, phPositions, phValues ) end allDivergences[(i - 1) * 4 + kind] = distance if distance > 0 totalDiv += 1 end end end # ---------------------------------------------- # Minimum divergence filter # ---------------------------------------------- let detected = fill(false, 4) let topText = "" let bottomText = "" let topCount = 0 let bottomCount = 0 let topKind = 2 let bottomKind = 1 let newBullLines::Array{Number} = [] let newBearLines::Array{Number} = [] let usedDistances = fill(false, maxbars + 1) if totalDiv >= showlimit for i in 1:11 let lastKind = 0 for kind in 1:4 let distance = allDivergences[(i - 1) * 4 + kind] if distance <= 0 continue end lastKind = kind detected[kind] = true let bullish = kind % 2 == 1 if bullish bottomCount += 1 bottomKind = kind else topCount += 1 topKind = kind end # Prevent duplicate lines if !usedDistances[distance + 1] usedDistances[distance + 1] = true let price1 = bullish ? lowSource[distance] : highSource[distance] let price2 = bullish ? lowSource[startpoint] : highSource[startpoint] let record = [ time[distance], price1, time[startpoint], price2, kind ] if bullish for value in record push!(newBullLines, value) end else for value in record push!(newBearLines, value) end end end end # Original label naming behavior if lastKind > 0 && showindis != "Don't Show" let indicatorName = showindis == "Full" ? indicatorNames[i] : indicatorLetters[i] if lastKind % 2 == 1 bottomText = bottomText * indicatorName * "\n" else topText = topText * indicatorName * "\n" end end end # Append divergence counts if shownum && topCount > 0 topText = topText * string(topCount) end if shownum && bottomCount > 0 bottomText = bottomText * string(bottomCount) end # ------------------------------------------ # Save positive divergence drawings # ------------------------------------------ if !isempty(newBullLines) || bottomText != "" let labelLow = min(low, coalesce(low[1], low)) save_side( true, newBullLines, bottomText, time, labelLow, bottomKind ) end # ------------------------------------------ # Save negative divergence drawings # ------------------------------------------ if !isempty(newBearLines) || topText != "" let labelHigh = max(high, coalesce(high[1], high)) save_side( false, newBearLines, topText, time, labelHigh, topKind ) end end # ---------------------------------------------- # Limit divergence lines to 400 # ---------------------------------------------- let excessLines = (length(bullLines) + length(bearLines)) / 5 - 400 if excessLines > 0 for j in 1:excessLines let removeBull = isempty(bearLines) || (!isempty(bullLines) && bullLines[3] <= bearLines[3]) if removeBull for k in 1:5 popfirst!(bullLines) end else for k in 1:5 popfirst!(bearLines) end end end end # ---------------------------------------------- # Limit divergence labels to 400 # ---------------------------------------------- let excessLabels = length(bullTexts) + length(bearTexts) - 400 if excessLabels > 0 for j in 1:excessLabels let removeBull = isempty(bearLabels) || (!isempty(bullLabels) && bullLabels[1] <= bearLabels[1]) if removeBull for k in 1:3 popfirst!(bullLabels) end popfirst!(bullTexts) else for k in 1:3 popfirst!(bearLabels) end popfirst!(bearTexts) end end end # ---------------------------------------------- # Render retained divergence drawings # ---------------------------------------------- if bar.last draw_side( true, bullLines, bullLabels, bullTexts ) draw_side( false, bearLines, bearLabels, bearTexts ) end # ---------------------------------------------- # ALERTS # ---------------------------------------------- if detected[1] alert( "Positive Regular Divergence Detected", title = "Positive Regular Divergence Detected" ) end if detected[2] alert( "Negative Regular Divergence Detected", title = "Negative Regular Divergence Detected" ) end if detected[3] alert( "Positive Hidden Divergence Detected", title = "Positive Hidden Divergence Detected" ) end if detected[4] alert( "Negative Hidden Divergence Detected", title = "Negative Hidden Divergence Detected" ) end if detected[1] || detected[3] alert( "Positive Divergence Detected", title = "Positive Divergence Detected" ) end if detected[2] || detected[4] alert( "Negative Divergence Detected", title = "Negative Divergence Detected" ) end
end
The code you pasted is already written in NexuScript-style syntax. I’ll check it against the actual language reference for compatibility issues, rather than simply returning the same script.
Your pasted code is already in NexuScript 1.6, but I've reviewed it again and rewritten it to simplify the divergence calculations and drawing management.
This revised version keeps all 11 indicator sources, all four divergence types, your original colors, dot labels, divergence counts, confirmation settings, moving averages and alerts.
One limitation is that NexuScript does not support deleting previously drawn objects the same way Pine Script does. The script therefore stores drawing information and renders the retained divergences. (www.nexusprop.com www.nexusprop.com www.nexusprop.com)
Copy everything inside this code block into the Nexus or Onyx Scripts editor.
julianexscript 1.6 indicator "SuperFuckingGoodIndicator", overlay = true, short = "SFGI" # SETTINGS input prd = 5, title = "Pivot Period", min = 1, max = 50 input source = "Close", title = "Source for Pivot Points", options = ["Close", "High/Low"] input searchdiv = "Regular", title = "Divergence Type", options = ["Regular", "Hidden", "Regular/Hidden"] input showindis = "Full", title = "Show Indicator Names", options = ["Full", "First Letter", "Don't Show"] input showlimit = 1, title = "Minimum Number of Divergence", min = 1, max = 11 input maxpp = 10, title = "Maximum Pivot Points to Check", min = 1, max = 20 input maxbars = 100, title = "Maximum Bars to Check", min = 30, max = 200 input shownum = true, title = "Show Divergence Number" input showlast = false, title = "Show Only Last Divergence" input dontconfirm = false, title = "Don't Wait for Confirmation" input showlines = true, title = "Show Divergence Lines" input showpivot = false, title = "Show Pivot Points" # INDICATORS input calcmacd = true, title = "MACD", group = "Indicators" input calcmacda = true, title = "MACD Histogram", group = "Indicators" input calcrsi = true, title = "RSI", group = "Indicators" input calcstoc = true, title = "Stochastic", group = "Indicators" input calccci = true, title = "CCI", group = "Indicators" input calcmom = true, title = "Momentum", group = "Indicators" input calcobv = true, title = "OBV", group = "Indicators" input calcvwmacd = true, title = "VWmacd", group = "Indicators" input calccmf = true, title = "Chaikin Money Flow", group = "Indicators" input calcmfi = true, title = "Money Flow Index", group = "Indicators" input calcext = false, title = "Check External Indicator", group = "Indicators" input externalindi = close, title = "External Source", group = "Indicators" # COLORS input pos_reg_div_col = color.rgb(255, 235, 59, 0.47), title = "Positive Regular Divergence", group = "Colors" input neg_reg_div_col = color.rgb(49, 27, 146, 0.57), title = "Negative Regular Divergence", group = "Colors" input pos_hid_div_col = color.hex("#00E676"), title = "Positive Hidden Divergence", group = "Colors" input neg_hid_div_col = color.hex("#FF5252"), title = "Negative Hidden Divergence", group = "Colors" input pos_div_text_col = color.black, title = "Positive Text Color", group = "Colors" input neg_div_text_col = color.white, title = "Negative Text Color", group = "Colors" # LINE SETTINGS input reg_div_l_style = "Solid", title = "Regular Line Style", options = ["Solid", "Dashed", "Dotted"] input hid_div_l_style = "Dashed", title = "Hidden Line Style", options = ["Solid", "Dashed", "Dotted"] input reg_div_l_width = 2, title = "Regular Line Width", min = 1, max = 5 input hid_div_l_width = 1, title = "Hidden Line Width", min = 1, max = 5 # MOVING AVERAGES input showmas = false, title = "Show MAs 50 & 200" input cma1col = color.hex("#00E676"), title = "MA 50 Color" input cma2col = color.hex("#FF5252"), title = "MA 200 Color" # CONSTANTS const divColors = [pos_reg_div_col, neg_reg_div_col, pos_hid_div_col, neg_hid_div_col] const names = [".", ".", ".", ".", ".", ".", ".", ".", ".", ".", "."] const letters = ["M", "H", "E", "S", "C", "M", "O", "V", "C", "M", "X"] const enabled = [calcmacd, calcmacda, calcrsi, calcstoc, calccci, calcmom, calcobv, calcvwmacd, calccmf, calcmfi, calcext] const regularStyle = lowercase(reg_div_l_style) const hiddenStyle = lowercase(hid_div_l_style) # PERSISTENT STATE state phPositions::Array{Number} = [] state plPositions::Array{Number} = [] state phValues::Array{Number} = [] state plValues::Array{Number} = [] state history::Array{Number} = fill(missing, 2412) state obvValue = 0.0 state bullLines::Array{Number} = [] state bearLines::Array{Number} = [] state bullLabels::Array{Number} = [] state bearLabels::Array{Number} = [] state bullTexts::Array{String} = [] state bearTexts::Array{String} = [] state activeBull = 0 state activeBear = 0 # HISTORY ACCESS function hist_value(idx, channel) return history[(idx % 201) * 12 + channel] end # DIVERGENCE SEARCH # # 1 = Regular Bullish # 2 = Regular Bearish # 3 = Hidden Bullish # 4 = Hidden Bearish function find_div(ind, kind, idx, startpoint, endPrice, positions, prices) if idx < 6 || isempty(positions) return 0 end let bullish = kind % 2 == 1 let regular = kind <= 2 let currentOsc = hist_value(idx, ind) let previousOsc = hist_value(idx - 1, ind) let currentClose = hist_value(idx, 12) let previousClose = hist_value(idx - 1, 12) if !dontconfirm if bullish if !(currentOsc > previousOsc || currentClose > previousClose) return 0 end else if !(currentOsc < previousOsc || currentClose < previousClose) return 0 end end end let startOsc = hist_value(idx - startpoint, ind) let startClose = hist_value(idx - startpoint, 12) if !isfinite(startOsc) || !isfinite(startClose) || !isfinite(endPrice) return 0 end let pivotCount = min(maxpp, length(positions)) for x in 1:pivotCount let distance = idx - positions[x] if distance > maxbars break end if distance <= 5 continue end let oldOsc = hist_value(idx - distance, ind) let oldClose = hist_value(idx - distance, 12) let oldPrice = prices[x] if !isfinite(oldOsc) || !isfinite(oldClose) || !isfinite(oldPrice) continue end let valid = false if kind == 1 valid = startOsc > oldOsc && endPrice < oldPrice elseif kind == 2 valid = startOsc < oldOsc && endPrice > oldPrice elseif kind == 3 valid = startOsc < oldOsc && endPrice > oldPrice else valid = startOsc > oldOsc && endPrice < oldPrice end if !valid continue end # Virtual trendline validation let span = distance - startpoint let slopeOsc = (startOsc - oldOsc) / span let slopeClose = (startClose - oldClose) / span let virtualOsc = startOsc - slopeOsc let virtualClose = startClose - slopeClose let arrived = true for y in (startpoint + 1):(distance - 1) let testOsc = hist_value(idx - y, ind) let testClose = hist_value(idx - y, 12) if !isfinite(testOsc) || !isfinite(testClose) arrived = false break end if bullish if testOsc < virtualOsc || testClose < virtualClose arrived = false break end else if testOsc > virtualOsc || testClose > virtualClose arrived = false break end end virtualOsc -= slopeOsc virtualClose -= slopeClose end if arrived return distance end end return 0 end # STORE DIVERGENCE DRAWINGS function store_side(bullish, newLines, labelText, labelTime, labelPrice, labelKind) let lines = bullish ? bullLines : bearLines let labels = bullish ? bullLabels : bearLabels let texts = bullish ? bullTexts : bearTexts let active = bullish ? activeBull : activeBear if !isempty(newLines) if showlast lines = fill(0, 0) elseif active > 0 && length(lines) >= active for j in 1:active pop!(lines) end if !isempty(texts) && length(labels) >= 3 pop!(labels) pop!(labels) pop!(labels) pop!(texts) end end for value in newLines push!(lines, value) end active = length(newLines) end if labelText != "" if showlast labels = fill(0, 0) texts = fill("", 0) end push!(labels, labelTime) push!(labels, labelPrice) push!(labels, labelKind) push!(texts, labelText) end if bullish bullLines = lines bullLabels = labels bullTexts = texts activeBull = active else bearLines = lines bearLabels = labels bearTexts = texts activeBear = active end return 0 end # DRAW LINES AND LABELS function draw_side(bullish, lines, labels, texts) if showlines && !isempty(lines) for j in 1:5:length(lines) let kind = lines[j + 4] let lineColor = divColors[kind] let lineWidth = kind <= 2 ? reg_div_l_width : hid_div_l_width let lineStyle = kind <= 2 ? regularStyle : hiddenStyle if isfinite(lines[j]) && isfinite(lines[j + 1]) && isfinite(lines[j + 2]) && isfinite(lines[j + 3]) line( lines[j], lines[j + 1], lines[j + 2], lines[j + 3], color = lineColor, width = lineWidth, dash = lineStyle ) end end end if !isempty(texts) let labelPosition = bullish ? "below" : "above" let labelTextColor = bullish ? pos_div_text_col : neg_div_text_col for j in 1:length(texts) let offset = (j - 1) * 3 let kind = labels[offset + 3] marker( texts[j], time = labels[offset + 1], price = labels[offset + 2], position = labelPosition, place = labelPosition, shape = "label", color = divColors[kind], text_color = labelTextColor, size = "small" ) end end return 0 end # MAIN SCRIPT on bar # INDICATOR CALCULATIONS let macd = ta.macd(close, 12, 26, 9) let rsiValue = ta.rsi(close, 14) let momentum = close - close[10] let cciValue = ta.cci(close, 10) let stochasticRaw = ta.stoch(close, high, low, 14) let stochastic = ta.sma(stochasticRaw, 3) # OBV if close > close[1] obvValue += coalesce(volume, 0) elseif close < close[1] obvValue -= coalesce(volume, 0) end # VW MACD let vwFast = ta.vwma(close, 12) let vwSlow = ta.vwma(close, 26) let vwmacd = vwFast - vwSlow # CHAIKIN MONEY FLOW let candleRange = high - low let multiplier = candleRange != 0 ? (2 * close - low - high) / candleRange : 0 let moneyVolume = multiplier * volume let cmfNumerator = ta.sma(moneyVolume, 21) let cmfDenominator = ta.sma(volume, 21) let cmf = cmfDenominator > 0 ? cmfNumerator / cmfDenominator : missing # MONEY FLOW INDEX let mfi = ta.mfi(close, 14) # MOVING AVERAGES let ma50 = ta.sma(close, 50) let ma200 = ta.sma(close, 200) plot("MA 50", showmas ? ma50 : missing, color = cma1col) plot("MA 200", showmas ? ma200 : missing, color = cma2col) # STORE HISTORY let values = [ macd.macd, macd.hist, rsiValue, stochastic, cciValue, momentum, obvValue, vwmacd, cmf, mfi, externalindi, close ] let slot = (bar.index % 201) * 12 for i in 1:12 history[slot + i] = values[i] end # PIVOT CALCULATIONS let highSource = source == "Close" ? close : high let lowSource = source == "Close" ? close : low let ph = ta.pivot_high(highSource, prd, prd) let pl = ta.pivot_low(lowSource, prd, prd) if !ismissing(ph) pushfirst!(phPositions, bar.index - prd) pushfirst!(phValues, ph) if length(phPositions) > 20 pop!(phPositions) pop!(phValues) end activeBear = 0 if showpivot marker( "H", time = time[prd], price = high[prd], position = "above", place = "above", shape = "text", color = color.red, text_color = color.red ) end end if !ismissing(pl) pushfirst!(plPositions, bar.index - prd) pushfirst!(plValues, pl) if length(plPositions) > 20 pop!(plPositions) pop!(plValues) end activeBull = 0 if showpivot marker( "L", time = time[prd], price = low[prd], position = "below", place = "below", shape = "text", color = color.hex("#00E676"), text_color = color.hex("#00E676") ) end end # SEARCH ALL DIVERGENCES let startpoint = dontconfirm ? 0 : 1 let lowEnd = lowSource[startpoint] let highEnd = highSource[startpoint] let divergences = fill(0, 44) let total = 0 for i in 1:11 if !enabled[i] continue end for kind in 1:4 if kind <= 2 && searchdiv == "Hidden" continue end if kind > 2 && searchdiv == "Regular" continue end let distance = 0 if kind % 2 == 1 distance = find_div( i, kind, bar.index, startpoint, lowEnd, plPositions, plValues ) else distance = find_div( i, kind, bar.index, startpoint, highEnd, phPositions, phValues ) end divergences[(i - 1) * 4 + kind] = distance if distance > 0 total += 1 end end end # DIVERGENCE LABELS let bullishText = "" let bearishText = "" let bullishCount = 0 let bearishCount = 0 let bullishKind = 1 let bearishKind = 2 let detected = fill(false, 4) let usedDistances = fill(false, maxbars + 1) let newBullLines::Array{Number} = [] let newBearLines::Array{Number} = [] if total >= showlimit for i in 1:11 let lastKind = 0 for kind in 1:4 let distance = divergences[(i - 1) * 4 + kind] if distance <= 0 continue end lastKind = kind detected[kind] = true let bullish = kind % 2 == 1 if bullish bullishCount += 1 bullishKind = kind else bearishCount += 1 bearishKind = kind end # Avoid duplicate lines if !usedDistances[distance + 1] usedDistances[distance + 1] = true let price1 = bullish ? lowSource[distance] : highSource[distance] let price2 = bullish ? lowSource[startpoint] : highSource[startpoint] let record = [ time[distance], price1, time[startpoint], price2, kind ] if bullish for value in record push!(newBullLines, value) end else for value in record push!(newBearLines, value) end end end end # Original dot / letter labels if lastKind > 0 && showindis != "Don't Show" let name = showindis == "Full" ? names[i] : letters[i] if lastKind % 2 == 1 bullishText = bullishText * name * "\n" else bearishText = bearishText * name * "\n" end end end # Add divergence numbers if shownum && bullishCount > 0 bullishText = bullishText * string(bullishCount) end if shownum && bearishCount > 0 bearishText = bearishText * string(bearishCount) end # Store bullish drawings if !isempty(newBullLines) || bullishText != "" store_side( true, newBullLines, bullishText, time, min(low, coalesce(low[1], low)), bullishKind ) end # Store bearish drawings if !isempty(newBearLines) || bearishText != "" store_side( false, newBearLines, bearishText, time, max(high, coalesce(high[1], high)), bearishKind ) end end # LIMIT TOTAL STORED LINES let excessLines = (length(bullLines) + length(bearLines)) / 5 - 400 if excessLines > 0 for i in 1:excessLines let removeBull = isempty(bearLines) || (!isempty(bullLines) && bullLines[3] <= bearLines[3]) if removeBull for j in 1:5 popfirst!(bullLines) end activeBull = min(activeBull, length(bullLines)) else for j in 1:5 popfirst!(bearLines) end activeBear = min(activeBear, length(bearLines)) end end end # LIMIT TOTAL STORED LABELS let excessLabels = length(bullTexts) + length(bearTexts) - 400 if excessLabels > 0 for i in 1:excessLabels let removeBull = isempty(bearLabels) || (!isempty(bullLabels) && bullLabels[1] <= bearLabels[1]) if removeBull popfirst!(bullLabels) popfirst!(bullLabels) popfirst!(bullLabels) popfirst!(bullTexts) else popfirst!(bearLabels) popfirst!(bearLabels) popfirst!(bearLabels) popfirst!(bearTexts) end end end # RENDER DIVERGENCES if bar.last draw_side( true, bullLines, bullLabels, bullTexts ) draw_side( false, bearLines, bearLabels, bearTexts ) end # ALERTS if detected[1] alert( "Positive Regular Divergence Detected", title = "Positive Regular Divergence Detected" ) end if detected[2] alert( "Negative Regular Divergence Detected", title = "Negative Regular Divergence Detected" ) end if detected[3] alert( "Positive Hidden Divergence Detected", title = "Positive Hidden Divergence Detected" ) end if detected[4] alert( "Negative Hidden Divergence Detected", title = "Negative Hidden Divergence Detected" ) end if detected[1] || detected[3] alert( "Positive Divergence Detected", title = "Positive Divergence Detected" ) end if detected[2] || detected[4] alert( "Negative Divergence Detected", title = "Negative Divergence Detected" ) end end
Compatibility note: This version has been checked against the official NexuScript 1.6 reference, but I cannot compile it inside the trading platform here. The external source is limited to the source dropdown, and the historical drawing replacement behavior may differ from TradingView, especially when new live candles form.
If the editor displays a compilation error, send me the error code and line number so I can correct the specific incompatibility.
turn this into a nexuscript. indicator(" Gabors Other Shit ", overlay = true, max_lines_count = 500, max_labels_count = 500,max_boxes_count = 500)
//INPUTS
var GRP1 = "== Gabors Fucking Magic Band Setting =="
HalfLength = input.int(56, "Centered TMA Half Period", group = GRP1)
string PriceType = input.string("Weighted", "Price to use", options = ["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average"], group = GRP1)
AtrPeriod = input.int(110, "Average true range period", group = GRP1)
AtrMultiplier = input.float(2.5, "Average true range multiplier", group = GRP1)
TMAangle = input.int(4, "Centered TMA angle caution", group = GRP1)
tmawidth = input.int(defval = 1, title = 'Band LineWidth', minval = 1, maxval = 4, group = GRP1)
//Gold Gabors Fucking Magic Setting : 56 , 110 , 2.5 , 4
//VARIABLES
float tmac = na
float tmau = na
float tmad = na
var float pastTmac = na //from the previous candle
var float pastTmau = na
var float pastTmad = na
float tmau_temp = na //before looping
float tmac_temp = na
float tmad_temp = na
float point = syminfo.pointvalue //NEEDS MORE TESTS
bool last = false //checks if a loop is needed
var string alertSignal = "EMPTY" //needed for alarms to avoid repetition
//COLORS
var GRP2 = "== Midnight Colors =="
var color colorBuffer = na
color colorDOWN = input.color(color.new(color.red, 0), "Bear Color", inline = "5", group = GRP1)
color colorUP = input.color(color.new(color.green, 0), "Bull Color", inline = "5", group = GRP1)
color colorBands = input.color(color.new(#b2b5be, 0), "3 Bands Color", inline = "5", group = GRP1)
bool cautionInput = input.bool(false, "Caution Label", inline = "6", group = GRP1)
//ALERTS
var GRP3 = "Alerts (Needs to create alert manually after every change)"
bool crossUpInput = input.bool(false, "Crossing up", inline = "7", group = GRP3)
bool crossDownInput = input.bool(false, "Crossing down", inline = "7", group = GRP3)
bool comingBackInput = input.bool(false, "Coming back", inline = "7", group = GRP3)
bool onArrowDownInput = input.bool(false, "On arrow down", inline = "8", group = GRP3)
bool onArrowUpInput = input.bool(false, "On arrow up", inline = "8", group = GRP3)
//CLEAR LINES
a_allLines = line.all
if array.size(a_allLines) > 0
for p = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, p))
//GET PRICE
Price(x) =>
float price = switch PriceType
"Close" => close[x]
"Open" => open[x]
"High" => high[x]
"Low" => low[x]
"Median" => (high[x] + low[x]) / 2
"Typical" => (high[x] + low[x] + close[x]) / 3
"Weighted" => (high[x] + low[x] + close[x] + close[x]) / 4
"Average" => (high[x] + low[x] + close[x] + open[x])/ 4
price
//MAIN
for i = HalfLength to 0
text//ATR atr = 0.0 for j = 0 to AtrPeriod - 1 atr += math.max(high[i + j + 10], close[i + j + 11]) - math.min(low[i + j + 10], close[i + j + 11]) atr /= AtrPeriod //BANDS sum = (HalfLength + 1) * Price(i) sumw = (HalfLength + 1) k = HalfLength for j = 1 to HalfLength sum += k * Price(i + j) sumw += k if (j <= i) sum += k * Price(i - j) sumw += k k -= 1 tmac := sum/sumw tmau := tmac+AtrMultiplier*atr tmad := tmac-AtrMultiplier*atr //ALERTS if i == 0 //Only on a real candle if (high > tmau and alertSignal != "UP") //crossing up band if crossUpInput == true //checks if activated alert("Crossing up Band") //calling alert alertSignal := "UP" //to avoid repeating else if (low < tmad and alertSignal != "DOWN") //crossing down band if crossDownInput == true alert("Crossing down Band") alertSignal := "DOWN" else if (alertSignal == "DOWN" and high >= tmad and alertSignal != "EMPTY") //back from the down band if comingBackInput == true alert("Coming back") alertSignal := "EMPTY" else if (alertSignal == "UP" and low <= tmau and alertSignal != "EMPTY") //back from the up band if comingBackInput == true alert("Coming back") alertSignal := "EMPTY" //CHANGE TREND COLOR if pastTmac != 0.0 if tmac > pastTmac colorBuffer := colorUP if tmac < pastTmac colorBuffer := colorDOWN //SIGNALS reboundD = 0.0 reboundU = 0.0 caution = 0.0 if pastTmac != 0.0 if (high[i + 1] > pastTmau and close[i + 1] > open[i + 1] and close[i] < open[i]) reboundD := high[i] + AtrMultiplier * atr / 2 if (tmac - pastTmac > TMAangle * point) caution := reboundD + 10 * point if (low[i + 1] < pastTmad and close[i + 1] < open[i + 1] and close[i] > open[i]) reboundU := low[i] - AtrMultiplier * atr / 2 if (pastTmac - tmac > TMAangle * point) caution := reboundU - 10 * point //LAST REAL if barstate.islast and i == HalfLength last := true tmau_temp := tmau tmac_temp := tmac tmad_temp := tmad //DRAW HANDICAPPED BANDS if barstate.islast and i < HalfLength line.new(bar_index - (i + 1), pastTmau, bar_index - (i), tmau, width = 2, style = line.style_dotted, color = colorBands) line.new(bar_index - (i + 1), pastTmac, bar_index - (i), tmac, width = 2, style = line.style_dotted, color = colorBuffer) line.new(bar_index - (i + 1), pastTmad, bar_index - (i), tmad, width = 2, style = line.style_dotted, color = colorBands) //DRAW SIGNALS if reboundD != 0 //label.new(bar_index - (i), reboundD, color = colorDOWN, style = label.style_triangledown, size = size.tiny, textcolor = na) label.new(bar_index - (i), reboundD, '▼', color = na, textcolor = colorDOWN, textalign= text.align_center) if i == 0 and onArrowDownInput == true //alert alert("Down arrow") if caution != 0 and cautionInput == true label.new(bar_index - (i), reboundD, color = colorUP, style = label.style_xcross, size = size.tiny, textcolor = na) if reboundU != 0 //label.new(bar_index - (i), reboundU, color = colorUP, style = label.style_triangleup, size = size.tiny, textcolor = na) label.new(bar_index - (i), reboundU, '▲', color = na, textcolor = colorUP, textalign = text.align_center) if i == 0 and onArrowUpInput == true //alert alert("UP arrow") if caution != 0 and cautionInput == true label.new(bar_index - (i), reboundU, color = colorDOWN, style = label.style_xcross, size = size.tiny, textcolor = na) //SAVE HISTORY pastTmac := tmac pastTmau := tmau pastTmad := tmad //LOOP IS ONLY FOR HANDICAPPED if barstate.islast != true break
//DRAW REAL BANDS
plot(last ? tmau_temp : tmau, title = "TMA Up", color = colorBands, linewidth=tmawidth, style = plot.style_line, offset = -HalfLength)
plot(last ? tmac_temp : tmac, title = "TMA Mid", color = colorBuffer, linewidth=tmawidth, style = plot.style_line, offset = -HalfLength)
plot(last ? tmad_temp : tmad, title = "TMA Down", color = colorBands, linewidth=tmawidth, style = plot.style_line, offset = -HalfLength)
threeengulfing_mode = input.bool(title="3 Candle Engulfing Signal", defval=true, group="== ENGULFING SIGNAL ==", inline = '9')
engulfing_mode = input.bool(title="Normal Engulfing Signal", defval=false, group="== ENGULFING SIGNAL ==", inline = '9')
// bullish engulfing (Bueng)
Bueng = open[3] > close[3] and open[2] > close[2] and open[1] > close[1] and close > open and (close >= open[1] or close[1] >= open) and close - open > open[1] - close[1]
plotshape(threeengulfing_mode ? Bueng : na, style=shape.diamond, location=location.belowbar, color=color.new(#00e926,0), size=size.small, text = "Bull", textcolor = color.new(#4eff64,0))
// bearish engulfing (Beeng)
Beeng = open[3] < close[3] and open[2] < close[2] and close[1] > open[1] and open > close and (open >= close[1] or open[1] >= close) and open - close > close[1] - open[1]
plotshape(threeengulfing_mode ? Beeng : na, style=shape.diamond, location=location.abovebar, color=color.new(#ff571b,0), size=size.small, text = "Bear", textcolor = color.new(#ff5a9b,0))
// bullish engulfing (Bueng)
Bueng2 = open[3] > close[3] ? open[2] > close[2] ? open[1] > close[1] ? close > open ? close >= open[1] ? close[1] >= open ? close - open > open[1] - close[1] ? color.blue : na : na : na : na : na : na : na
barcolor(threeengulfing_mode ? Bueng2 : na)
// bearish engulfing (Beeng)
Beeng2 = open[3] < close[3] ? open[2] < close[2] ? close[1] > open[1] ? open > close ? open >= close[1] ? open[1] >= close ? open - close > close[1] - open[1] ? color.white : na : na : na : na : na : na : na
barcolor(threeengulfing_mode ? Beeng2 : na)
////////////////////////////////////////////////////////////////////////////////////
/////////// Normal Setting ////////////////
srcstrategy = input(close, title='Source Multi MA', group = '= Multi MA SETTING =', tooltip = 'Normal Line = Close \nSmooth Line = ohlc4')
///////////// EMA/SMA SETTING /////////////
pricestrategy = request.security(syminfo.tickerid, timeframe.period, srcstrategy)
fastSW = input.bool(title='Show Fast MA Line', defval=false, group = '= Multi MA SETTING =', inline = '11')
fastcolor = input.color(color.new(color.red,0), group = '= Multi MA SETTING =', inline = '110', title = 'Fast MA Color')
slowSW = input.bool(title='Show Slow MA Line', defval=false, group = '= Multi MA SETTING =', inline = '11')
slowcolor = input.color(color.new(color.yellow,0), group = '= Multi MA SETTING =', inline = '110', title = 'Slow MA Color')
ma1strategy = input(18, title='Fast MA Length', group = '= Multi MA SETTING =', inline = '12')
type1strategy = input.string('EMA', 'Fast MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '= Multi MA SETTING =', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA', inline = '12')
ma3strategy = input(34, title='Slow MA Length', group = '= Multi MA SETTING =', inline = '13')
type3strategy = input.string('EMA', 'Slow MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '= Multi MA SETTING =', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA', inline = '13')
price1strategy = switch type1strategy
"EMA" => ta.ema(pricestrategy, ma1strategy)
"SMA" => ta.sma(pricestrategy, ma1strategy)
"WMA" => ta.wma(pricestrategy, ma1strategy)
"HMA" => ta.hma(pricestrategy, ma1strategy)
"RMA" => ta.rma(pricestrategy, ma1strategy)
"VWMA" => ta.vwma(pricestrategy, ma1strategy)
price3strategy = switch type3strategy
"EMA" => ta.ema(pricestrategy, ma3strategy)
"SMA" => ta.sma(pricestrategy, ma3strategy)
"WMA" => ta.wma(pricestrategy, ma3strategy)
"HMA" => ta.hma(pricestrategy, ma3strategy)
"RMA" => ta.rma(pricestrategy, ma3strategy)
"VWMA" => ta.vwma(pricestrategy, ma3strategy)
FastL = plot(fastSW ? price1strategy : na, 'Fast MA', color=fastcolor, style = plot.style_line, linewidth=2)
SlowL = plot(slowSW ? price3strategy : na, 'Slow MA', color=slowcolor, style= plot.style_line, linewidth=1)
///////////////////////////////////////////////////////////////////////////////////
stobg_mode = input.bool(title="Stochastic RSI Background Paint", defval=true, group="== STO BACKGROUND ==")
stobg_plot = input.bool(title="STO-TEXT", defval=false, group="== STO BACKGROUND ==", inline = 'STOT1')
stobull_text = input.color(title = 'BULL', defval = color.white, group = '== STO BACKGROUND ==', inline = 'STOT1')
stobear_text = input.color(title = 'BEAR', defval = color.orange, group = '== STO BACKGROUND ==', inline = 'STOT1')
lengthMACD = input(title='Length', defval=21, group = '== STO BACKGROUND ==', inline = '15')
offsetMACD = input(title='Offset', defval=0, group = '== STO BACKGROUND ==', inline = '15')
srcMACD = input(close, title='Source', group = '== STO BACKGROUND ==', inline = '16')
length2MACD = input(title='Trigger Length', defval=6, group = '== STO BACKGROUND ==', inline = '16')
bullstobg = input.color(title = 'Bull BG Color', defval = color.green, group = '== STO BACKGROUND ==', inline = 'STOBG1')
bearstobg = input.color(title = 'Bear BG Color', defval = color.red, group = '== STO BACKGROUND ==', inline = 'STOBG1')
transstobg = input.int(defval = 75, title = 'Trans', minval = 0, maxval = 100, group = '== STO BACKGROUND ==', inline = 'STOBG1')
lsma = ta.linreg(srcMACD, lengthMACD, offsetMACD)
lsma2 = ta.linreg(lsma, lengthMACD, offsetMACD)
b = lsma - lsma2
zlsma2 = lsma + b
trig2 = ta.sma(zlsma2, length2MACD)
c1 = zlsma2 > trig2 ? bullstobg : bearstobg
stobull = ta.crossover(zlsma2,trig2)
stobear = ta.crossunder(zlsma2, trig2)
plotshape(stobg_plot ? stobull : na, title = 'STO-BULL', text = 'STO-BULL', location = location.belowbar, textcolor = stobull_text, size = size.tiny)
plotshape(stobg_plot ? stobear : na, title = 'STO-BULL', text = 'STO-BEAR', location = location.abovebar, textcolor = stobear_text, size = size.tiny)
p1 = plot(stobg_mode ? zlsma2 : na, color=c1, linewidth=0)
p2 = plot(stobg_mode ? trig2 : na, color=c1, linewidth=0)
fill(p1, p2, color=color.new(c1,transp = transstobg))
// bullish engulfing
bullishEngulfing = open[1] > close[1] ? close > open ? close >= open[1] ? close[1] >= open ? close - open > open[1] - close[1] ? color.purple : na : na : na : na : na
barcolor(engulfing_mode ? bullishEngulfing : na)
// bearish engulfing
bearishEngulfing = close[1] > open[1] ? open > close ? open >= close[1] ? open[1] >= close ? open - close > close[1] - open[1] ? color.yellow : na : na : na : na : na
barcolor(engulfing_mode ? bearishEngulfing : na)
bullishEngulfing2 = (open[1] > close[1] and close > open and close >= open[1] and close[1] >= open and close - open > open[1] - close[1]) and (zlsma2 > trig2)
bearishEngulfing2 = (close[1] > open[1] and open > close and open >= close[1] and open[1] >= close and open - close > close[1] - open[1]) and (zlsma2 < trig2)
plotshape(engulfing_mode ? bullishEngulfing2 : na, style=shape.labelup, location=location.belowbar, color=color.yellow, size=size.auto, text = '↗️')
plotshape(engulfing_mode ? bearishEngulfing2 : na, style=shape.labeldown, location=location.abovebar, color=color.white, size=size.auto, text = '↘️')
//Termline = ta.sma(close,200)
//plot(Termline, "TermLine", color = color.white, linewidth = 2, style = plot.style_line)
ma_trend_mode = input.bool(title="Show MA LINE For Big Trend", defval=false, group="== BIG TREND ==")
srcstrategy_trend = input(close, title='SOURCE OF BIG TREND', group = '== BIG TREND ==', tooltip = 'Normal Line = Close \nSmooth Line = ohlc4')
type4strategy = input.string('SMA', 'BIG TREND Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '== BIG TREND ==', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA', inline = '19')
ma_trend = input(defval = 200, title = "BIG TREND VALUE", group = '== BIG TREND ==', inline = '19')
death_mode = input.bool(title="Show SHORT-TERM MA LINE For DEATH CROSS and GOLDEN CROSS", defval=false, group="== BIG TREND ==")
deathstrategy = input.string('SMA', 'CROSS MA Type', options=['SMA', 'EMA', 'WMA', 'HMA', 'RMA', 'VWMA'], group = '== BIG TREND ==', tooltip = 'SMA / EMA / WMA / HMA / RMA / VWMA', inline = '21')
death_trend = input(defval = 50, title = "CROSS MA VALUE", group = '== BIG TREND ==', inline = '21')
matrend = switch type4strategy
"EMA" => ta.ema(srcstrategy_trend, ma_trend)
"SMA" => ta.sma(srcstrategy_trend, ma_trend)
"WMA" => ta.wma(srcstrategy_trend, ma_trend)
"HMA" => ta.hma(srcstrategy_trend, ma_trend)
"RMA" => ta.rma(srcstrategy_trend, ma_trend)
"VWMA" => ta.vwma(srcstrategy_trend, ma_trend)
deathtrend = switch deathstrategy
"EMA" => ta.ema(srcstrategy_trend, death_trend)
"SMA" => ta.sma(srcstrategy_trend, death_trend)
"WMA" => ta.wma(srcstrategy_trend, death_trend)
"HMA" => ta.hma(srcstrategy_trend, death_trend)
"RMA" => ta.rma(srcstrategy_trend, death_trend)
"VWMA" => ta.vwma(srcstrategy_trend, death_trend)
mycol = matrend > close ? color.white : color.blue
deathcol = deathtrend > matrend ? color.new(color.green,50) : color.new(color.red,50)
plot(ma_trend_mode ? matrend : na, "SMA-TREND",color=mycol,linewidth = 2)
plot(death_mode ? deathtrend : na, "DEATH-TREND",color=deathcol,linewidth = 1, style = plot.style_stepline_diamond)
// Swing Plot
//Swing_MODE = input.bool(title="PLOT SWING MODE", defval=true, group = '= SWING SETTING =', tooltip = 'If Mode On = Plot Swing High and Swing Low')
Swing_STOP = input.bool(title="SWING MODE", defval=true, group = '== SWING SETTING ==', tooltip = 'If Mode On = Use Stop Loss By Last Swing')
pvtLenL = input.int(6, minval=1, title='Length Left', group = '== SWING SETTING ==', inline = '23')
pvtLenR = input.int(6, minval=1, title='Length Right', group = '== SWING SETTING ==', inline = '23')
swhcolor = input.color(defval = color.maroon, title = 'HH Color', inline = 'SWC1', group = '== SWING SETTING ==')
swlcolor = input.color(defval = color.green, title = 'LL Color', inline = 'SWC1', group = '== SWING SETTING ==')
swhwidth = input.int(defval = 1, title = 'Width', minval = 0, maxval = 4, inline = 'SWC1', group = '== SWING SETTING ==')
// Get High and Low Pivot Points
pvthi_ = ta.pivothigh(high, pvtLenL, pvtLenR)
pvtlo_ = ta.pivotlow(low, pvtLenL, pvtLenR)
// Force Pivot completion before plotting.
Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0 //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]
// Count How many candles for current Pivot Level, If new reset.
counthi = ta.barssince(not na(pvthi))
countlo = ta.barssince(not na(pvtlo))
pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = ta.change(pvthis) != 0 ? na : swhcolor
lopc = ta.change(pvtlos) != 0 ? na : swlcolor
// Display Pivot lines
plot(Swing_STOP ? maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na : na, color=hipc, linewidth=swhwidth, offset=-pvtLenR - Shunt, title='Top Levels')
plot(Swing_STOP ? maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na : na, color=lopc, linewidth=swhwidth, offset=-pvtLenR - Shunt, title='Bottom Levels')
plot(Swing_STOP ? maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na : na, color=hipc, linewidth=swhwidth, offset=0, title='Top Levels 2')
plot(Swing_STOP ? maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na : na, color=lopc, linewidth=swhwidth, offset=0, title='Bottom Levels 2')
//////////////////////////////
// Standard practice declared input variables with i_ easier to identify
fvg_mode = input.bool(false, "Endable/Disable FVG MODE",group = "== FVG IMBALANCE SETTING ==")
i_tf = input.timeframe("D", "MTF Timeframe", group = "== FVG IMBALANCE SETTING ==", inline = 'FVGTF')
i_mtf = input.string(defval = "Current TF",group = "== FVG IMBALANCE SETTING ==", title = "MTF Options", options = ["Current TF", "Current + HTF", "HTF"], inline = 'FVGTF')
i_tfos = input.int(defval = 10,title = "Offset", minval = 0, maxval = 500 ,group = "== FVG IMBALANCE SETTING ==", inline = "OS")
i_mtfos = input.int(defval = 20,title = "MTF Offset", minval = 0, maxval = 500 ,group = "== FVG IMBALANCE SETTING ==", inline = "OS")
i_fillByMid = input.bool(false, "MidPoint Fill",group = "== FVG IMBALANCE SETTING ==", tooltip = "When enabled FVG is filled when midpoint is tested")
i_deleteonfill = input.bool(true, "Delete Old On Fill",group = "== FVG IMBALANCE SETTING ==")
i_labeltf = input.bool(false,"Label FVG Timeframe",group = "== FVG IMBALANCE SETTING ==")
i_bullishfvgcolor = input.color(color.new(color.green,70), "Bullish FVG", group = "== FVG IMBALANCE SETTING ==", inline = "BLFVG")
i_mtfbullishfvgcolor = input.color(color.new(color.lime,70), "MTF Bullish FVG", group = "== FVG IMBALANCE SETTING ==", inline = "BLFVG")
i_bearishfvgcolor = input.color(color.new(color.red,70), "Bearish FVG", group = "== FVG IMBALANCE SETTING ==", inline = "BRFVG")
i_mtfbearishfvgcolor = input.color(color.new(color.maroon,70), "MTF Bearish FVG", group = "== FVG IMBALANCE SETTING ==", inline = "BRFVG")
i_midPointColor = input.color(color.new(color.white,70), "MidPoint Color", group = "== FVG IMBALANCE SETTING ==")
i_textColor = input.color(color.white, "Text Color", group = "== FVG IMBALANCE SETTING ==")
// }
// ———————————————————— Global data {
//Using current bar data for HTF highs and lows instead of security to prevent future leaking
var htfH = open
var htfL = open
if close > htfH
htfH:= close
if close < htfL
htfL := close
//Security Data, used for HTF Bar Data reference
sClose = request.security(syminfo.tickerid, i_tf, close[1], barmerge.gaps_off, barmerge.lookahead_on)
sHighP2 = request.security(syminfo.tickerid, i_tf, high[2], barmerge.gaps_off, barmerge.lookahead_on)
sLowP2 = request.security(syminfo.tickerid, i_tf, low[2], barmerge.gaps_off, barmerge.lookahead_on)
sOpen = request.security(syminfo.tickerid, i_tf, open[1], barmerge.gaps_off, barmerge.lookahead_on)
sBar = request.security(syminfo.tickerid, i_tf, bar_index, barmerge.gaps_off, barmerge.lookahead_on)
// }
//var keyword can be used to hold data in memory, with pinescript all data is lost including variables unless the var keyword is used to preserve this data
var bullishgapholder = array.new_box(0)
var bearishgapholder = array.new_box(0)
var bullishmidholder = array.new_line(0)
var bearishmidholder = array.new_line(0)
var bullishlabelholder = array.new_label(0)
var bearishlabelholder = array.new_label(0)
var transparentcolor = color.new(color.white,100)
// ———————————————————— Functions {
//function paramaters best declared with '_' this helps defer from variables in the function scope declaration and elsewhere e.g. close => _close
f_gapCreation(_upperlimit,_lowerlimit,_midlimit,_bar,_boxholder,_midholder,_labelholder,_boxcolor,_mtfboxcolor, _htf)=>
timeholder = str.tostring(i_tf)
offset = i_mtfos
boxbgcolor = _mtfboxcolor
if _htf == false
timeholder := str.tostring(timeframe.period)
offset := i_tfos
boxbgcolor := _boxcolor
if fvg_mode
array.push(_boxholder,box.new(_bar,_upperlimit,_bar+1,_lowerlimit,border_color=transparentcolor,bgcolor = boxbgcolor, extend = extend.right))
if i_fillByMid
array.push(_midholder,line.new(_bar,_midlimit,_bar+1,_midlimit,color = i_midPointColor, extend = extend.right))
if i_labeltf
textarray.push(_labelholder,label.new(_bar+ offset,_midlimit * 0.999, text = timeholder + " FVG", style =label.style_none, size = size.normal, textcolor = i_textColor))
//checks for gap between current candle and 2 previous candle e.g. low of current candle and high of the candle before last, this is the fair value gap.
f_gapLogic(_close,_high,_highp2,_low,_lowp2,_open,_bar,_htf)=>
textif _open > _close if _high - _lowp2 < 0 upperlimit = _close - (_close - _lowp2 ) lowerlimit = _close - (_close-_high) midlimit = (upperlimit + lowerlimit) / 2 f_gapCreation(upperlimit,lowerlimit,midlimit,_bar,bullishgapholder,bullishmidholder,bullishlabelholder,i_bullishfvgcolor,i_mtfbullishfvgcolor,_htf) else if _low - _highp2 > 0 upperlimit = _close - (_close-_low) lowerlimit = _close- (_close - _highp2), midlimit = (upperlimit + lowerlimit) / 2 f_gapCreation(upperlimit,lowerlimit,midlimit,_bar,bearishgapholder,bearishmidholder,bearishlabelholder,i_bearishfvgcolor,i_mtfbearishfvgcolor,_htf)
//Used to remove the gap from its relevant array as a result of it being filled.
f_gapDeletion(_currentgap,_i,_boxholder,_midholder,_labelholder)=>
textarray.remove(_boxholder,_i) if i_fillByMid currentmid=array.get(_midholder,_i) array.remove(_midholder,_i) if i_deleteonfill line.delete(currentmid) else line.set_extend(currentmid, extend.none) line.set_x2(currentmid,bar_index) if i_deleteonfill box.delete(_currentgap) else box.set_extend(_currentgap,extend.none) box.set_right(_currentgap,bar_index) if i_labeltf currentlabel=array.get(_labelholder,_i) array.remove(_labelholder,_i) if i_deleteonfill label.delete(currentlabel)
//checks if gap has been filled either by 0.5 fill (i_fillByMid) or SHRINKS the gap to reflect the true value gap left.
f_gapCheck(_high,_low)=>
textif array.size(bullishgapholder) > 0 for i = array.size(bullishgapholder)-1 to 0 currentgap = array.get(bullishgapholder,i) currenttop = box.get_top(currentgap) if i_fillByMid currentmid = array.get(bullishmidholder,i) currenttop := line.get_y1(currentmid) if _high >= currenttop f_gapDeletion(currentgap,i,bullishgapholder,bullishmidholder,bullishlabelholder) if _high > box.get_bottom(currentgap) and _high < box.get_top(currentgap) box.set_bottom(fvg_mode ? currentgap : na,_high) if array.size(bearishgapholder) > 0 for i = array.size(bearishgapholder)-1 to 0 currentgap = array.get(bearishgapholder,i) currentbottom = box.get_bottom(currentgap) if i_fillByMid currentmid = array.get(bearishmidholder,i) currentbottom := line.get_y1(currentmid) if _low <= currentbottom f_gapDeletion(currentgap,i,bearishgapholder,bearishmidholder,bearishlabelholder) if _low < box.get_top(currentgap) and _low > box.get_bottom(currentgap) box.set_top(fvg_mode ? currentgap : na,_low)
// pine provided function to determine a new bar
is_newbar(res) =>
t = time(res)
not na(t) and (na(t[1]) or t > t[1])
if is_newbar(i_tf)
htfH := open
htfL := open
// }
// User Input, allow MTF data calculations
if is_newbar(i_tf) and (i_mtf == "Current + HTF" or i_mtf == "HTF")
f_gapLogic(sClose, htfH, sHighP2, htfL, sLowP2, sOpen,bar_index,true)
// Use current Timeframe data to provide gap logic
if (i_mtf == "Current + HTF" or i_mtf == "Current TF")
f_gapLogic(close[1],high,high[2],low,low[2],open[1],bar_index,false)
f_gapCheck(high,low)
//Dashboard_mode = input.bool(title="Show Dashboard", defval=true, group="= DASH BOARD =")
//Start dashboard
import jdehorty/EconomicCalendar/1 as calendar
// ---- Table Settings Start ----//
max = 160 //Maximum Length
min = 10 //Minimum Length
var GRP5 = "== DASH BOARD SETTING =="
var GRP6 = "== DASH BOARD INDICATOR SETTING =="
var GRP7 = "== DASH BOARD TABLE SETTING =="
// Input setting page start
dash_loc = input.session("Bottom Left","Dashboard Posision" ,["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"], group = GRP5, inline = 'DB1')
text_size = input.session('Tiny',"Dashboard Size" ,options=["Tiny","Small","Normal","Large"] ,group=GRP5, inline = 'DB1')
cell_up = input.color(color.green,'Up Cell Color' ,group=GRP5, inline = 'DB2')
cell_dn = input.color(color.red,'Down Cell Color' ,group=GRP5, inline = 'DB2')
cell_Neut = input.color(color.gray,'Nochange Cell Color' ,group=GRP5, inline = 'DB2')
row_col = color.blue
col_col = color.white
txt_col = color.white
cell_transp = input.int(60,'Cell Transparency' ,minval=0 ,maxval=100 ,group=GRP5)
Header_col = color.rgb(35, 94, 255)
//MACDV color
cell_MACDV1 = color.teal
cell_MACDV2 = color.green
cell_MACDV3 = color.red
cell_MACDV4 = color.rgb(194, 179, 47)
cell_MACDV5 = color.green
cell_MACDV6 = color.red
cell_MACDV7 = color.rgb(204, 8, 24)
//Momentum color
cell_phase1 = color.green
cell_phase2 = color.teal
cell_phase3 = color.red
cell_phase4 = color.red
cell_phase5 = color.orange
cell_phase6 = color.green
// ---- Table Settings End ----}//
// ---- Indicators Show/Hide Settings Start ----//
showCls = input.bool(defval=false, title="Price Close", group=GRP7, inline = 'DBSHOW1')
showMA01 = input.bool(defval=false, title="MA01", group=GRP7, inline = 'DBSHOW2')
showMA02 = input.bool(defval=false, title="MA02", group=GRP7, inline = 'DBSHOW2')
showMACross = input.bool(defval=true, title="Trend", group=GRP7, inline = 'DBSHOW2')
showRSI = input.bool(defval=true, title="RSI ", group=GRP7, inline = 'DBSHOW2')
showMACDV = input.bool(defval=true, title="MACDV", group=GRP7, inline = 'DBSHOW2')
showSignalV = input.bool(defval=false, title="SignalV", group=GRP7, inline = 'DBSHOW4')
showMACDV_Status = input.bool(defval=true, title="Condition", group=GRP7, inline = 'DBSHOW4')
showmomentum = input.bool(defval=false, title="Momentum", group=GRP7, inline = 'DBSHOW4')
//---- MACD-V code start ----//
MACD_fast_length = input(title="MACD-V Fast", defval=14, group=GRP6, inline = 'DBMACD1')
MACD_slow_length = input(title="MACD-V Slow", defval=26, group=GRP6, inline = 'DBMACD1')
MACD_signal_length = input.int(title="MACD-V Signal ", minval = 1, maxval = 50, defval = 9, group=GRP6, inline = 'DBMACD2')
MACD_atr_length = input(title="ATR", defval=26, group=GRP6, inline = 'DBMACD2')
// ---- Indicators Show/Hide Settings end ----}//
// ==================
// ==== Settings ====
// ==================
//------Seting Color Calender Economi------
color1 = color.red
color2 = color.orange
color3 = color.yellow
color4 = color.lime
color5 = color.aqua
color6 = color.fuchsia
color7 = color.silver
show_fomc_meetings = input.bool(defval = false, title = "📅 FOMC", inline = "FOMC", group="⚙️ Settings", tooltip="The FOMC meets eight times a year to determine the course of monetary policy. The FOMC's decisions are announced in a press release at 2:15 p.m. ET on the day of the meeting. The press release is followed by a press conference at 2:30 p.m. ET. The FOMC's decisions are based on a review of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
c_fomcMeeting = input.color(color.new(color1, 50), title = "Color", group="⚙️ Settings", inline = "FOMC")
show_fomc_minutes = input.bool(defval = false, title = "📅 FOMC Minutes", inline = "FOMCMinutes", group="⚙️ Settings", tooltip="The FOMC minutes are released three weeks after each FOMC meeting. The minutes provide a detailed account of the FOMC's discussion of economic and financial developments and its assessment of the likely effects of these developments on the economic outlook.")
c_fomcMinutes = input.color(color.new(color2, 50), title = "Color", group="⚙️ Settings", inline = "FOMCMinutes")
show_ppi = input.bool(defval = false, title = "📅 Producer Price Index (PPI)", inline = "PPI", group="⚙️ Settings", tooltip="The Producer Price Index (PPI) measures changes in the price level of goods and services sold by domestic producers. The PPI is a weighted average of prices of a basket of goods and services, such as transportation, food, and medical care. The PPI is a leading indicator of CPI.")
c_ppi = input.color(color.new(color3, 50), title = "Color", group="⚙️ Settings", inline = "PPI")
show_cpi = input.bool(defval = false, title = "📅 Consumer Price Index (CPI)", inline = "CPI", group="⚙️ Settings", tooltip="The Consumer Price Index (CPI) measures changes in the price level of goods and services purchased by households. The CPI is a weighted average of prices of a basket of consumer goods and services, such as transportation, food, and medical care. The CPI-U is the most widely used measure of inflation. The CPI-U is based on a sample of about 87,000 households and measures the change in the cost of a fixed market basket of goods and services purchased by urban consumers.")
c_cpi = input.color(color.new(color4, 50), title = "Color", group="⚙️ Settings", inline = "CPI")
show_csi = input.bool(defval = false, title = "📅 Consumer Sentiment Index (CSI)", inline = "CSI", group="⚙️ Settings", tooltip="The University of Michigan's Consumer Sentiment Index (CSI) is a measure of consumer attitudes about the economy. The CSI is based on a monthly survey of 500 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CSI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_csi = input.color(color.new(color5, 50), title = "Color", group="⚙️ Settings", inline = "CSI")
show_cci = input.bool(defval = false, title = "📅 Consumer Confidence Index (CCI)", inline = "CCI", group="⚙️ Settings", tooltip="The Conference Board's Consumer Confidence Index (CCI) is a measure of consumer attitudes about the economy. The CCI is based on a monthly survey of 5,000 U.S. households. The index is based on consumers' assessment of present and future economic conditions. The CCI is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_cci = input.color(color.new(color6, 50), title = "Color", group="⚙️ Settings", inline = "CCI")
show_nfp = input.bool(defval = false, title = "📅 Non-Farm Payroll (NFP)", inline = "NFP", group="⚙️ Settings", tooltip="The Non-Farm Payroll (NFP) is a measure of the change in the number of employed persons, excluding farm workers and government employees. The NFP is a leading indicator of consumer spending, which accounts for about two-thirds of U.S. economic activity.")
c_nfp = input.color(color.new(color7, 50), title = "Color", group="⚙️ Settings", inline = "NFP")
show_legend = input.bool(false, "Show Legend", group="⚙️ Settings", inline = "Legend", tooltip="Show the color legend for the economic calendar events.")
// =======================
// ==== Dates & Times ====
// =======================
getUnixTime(_eventArr, _index) =>
switch
timeframe.isdaily => array.get(_eventArr, _index) - timeframe.multiplier86400000 // -n day(s)
timeframe.isweekly => array.get(_eventArr, _index) - timeframe.multiplier604800000 // -n week(s)
timeframe.ismonthly => array.get(_eventArr, _index) - timeframe.multiplier2592000000 // -n month(s)
timeframe.isminutes and timeframe.multiplier > 59 => array.get(_eventArr, _index) - timeframe.multiplier60000 // -n minute(s)
=> array.get(_eventArr, _index)
if barstate.islastconfirmedhistory
text// Note: An offset of -n units is needed to realign events with the timeframe in which they occurred if show_fomc_meetings fomcMeetingsArr = calendar.fomcMeetings() for i = 0 to array.size(fomcMeetingsArr) - 1 unixTime = getUnixTime(fomcMeetingsArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMeeting, width=2, xloc=xloc.bar_time) if show_fomc_minutes fomcMinutesArr = calendar.fomcMinutes() for i = 0 to array.size(fomcMinutesArr) - 1 unixTime = getUnixTime(fomcMinutesArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_fomcMinutes, width=2, xloc=xloc.bar_time) if show_ppi ppiArr = calendar.ppiReleases() for i = 0 to array.size(ppiArr) - 1 unixTime = getUnixTime(ppiArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_ppi, width=2, xloc=xloc.bar_time) if show_cpi cpiArr = calendar.cpiReleases() for i = 0 to array.size(cpiArr) - 1 unixTime = getUnixTime(cpiArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cpi, width=2, xloc=xloc.bar_time) if show_csi csiArr = calendar.csiReleases() for i = 0 to array.size(csiArr) - 1 unixTime = getUnixTime(csiArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_csi, width=2, xloc=xloc.bar_time) if show_cci cciArr = calendar.cciReleases() for i = 0 to array.size(cciArr) - 1 unixTime = getUnixTime(cciArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_cci, width=2, xloc=xloc.bar_time) if show_nfp nfpArr = calendar.nfpReleases() for i = 0 to array.size(nfpArr) - 1 unixTime = getUnixTime(nfpArr, i) line.new(x1=unixTime, y1=high, x2=unixTime, y2=low, extend=extend.both,color=c_nfp, width=2, xloc=xloc.bar_time)
// ================
// ==== Legend ====
// ================
if show_legend
var tbl = table.new(position.top_right, columns=8, rows=8, frame_color=#151715, frame_width=1, border_width=2, border_color=color.new(color.black, 100))
units = timeframe.isminutes ? "m" : ""
table.cell(tbl, 1, 0, syminfo.ticker + ' => ' + str.tostring(timeframe.period)+ units, text_halign=text.align_center, text_color=color.gray, text_size=size.small)
table.cell(tbl, 2, 0, 'FOMC Meeting', text_halign=text.align_center, bgcolor=color.black, text_color=color1, text_size=size.small)
table.cell(tbl, 3, 0, 'FOMC Minutes', text_halign=text.align_center, bgcolor=color.black, text_color=color2, text_size=size.small)
table.cell(tbl, 4, 0, 'Producer Price Index (PPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color3, text_size=size.small)
table.cell(tbl, 1, 1, 'Consumer Price Index (CPI)', text_halign=text.align_center, bgcolor=color.black, text_color=color4, text_size=size.small)
table.cell(tbl, 2, 1, 'Consumer Sentiment Index (CSI)', text_halign=text.align_center, bgcolor=color.black, text_color=color5, text_size=size.small)
table.cell(tbl, 3, 1, 'Consumer Confidence Index (CCI)', text_halign=text.align_center, bgcolor=color.black, text_color=color6, text_size=size.small)
table.cell(tbl, 4, 1, 'Non-Farm Payrolls (NFP)', text_halign=text.align_center, bgcolor=color.black, text_color=color7, text_size=size.small)
// =======================
// ==== CE And ===========
// =======================
// ---- Timeframe Row Show/Hide Settings Start ----//
showTF1 = input.bool(defval=true, title="Show TF MN", inline='indicator1',group="Rows Settings")
f_MACDV(_close) =>
text//---- Indicators code Start ----// CLS= _close[1] //---- RSI code start ----// rsiPeriod = 14 RSI = ta.rsi(_close, rsiPeriod) //---- RSI code end ----// //---- EMA 1 code start----// length_MA1 = input.int(title="MA1",defval=50, minval=1, inline = 'TFROW1') MA1 = ta.ema(_close, length_MA1) //plot(MA01, color=color.red, title="MA1") //---- EMA 1 code end ----// //---- EMA 2 code start---// length_MA2 = input.int(title="MA2",defval=200, minval=1, inline = 'TFROW1') MA2 = ta.ema(_close, length_MA2) //plot(MA02, color=color.blue, title="MA2") //---- EMA 2 code end ----// // Input seeting page end // Calculating fast_ma = ta.ema(_close, MACD_fast_length) slow_ma = ta.ema(_close, MACD_slow_length) atr = ta.atr(MACD_atr_length) MACDV = (((fast_ma - slow_ma)/atr)*100)//[( 12 bar EMA - 26 bar EMA) / ATR(26) ] * 100 SignalV = ta.ema(MACDV, MACD_signal_length) //---- MACD-V code end ----// //---- Indicators code end ----// //-----Condition start stringmacdv =(MACDV>150) ? "Wait Continue/Reversal" :(MACDV>50 and MACDV<150 and MACDV>SignalV ) ? "Buy G0" :(MACDV>50 and MACDV<150 and MACDV<SignalV ) ? "Buy Retest":(MACDV<50) and (MACDV>-50) ? "Sideway" :(MACDV<-50 and MACDV>-150 and MACDV>SignalV ) ? "Short go":(MACDV<-50 and MACDV>-150 and MACDV<SignalV ) ? "Short Retest":(MACDV<150) ? "Wait Continue/Reversal" :na //momentum stringmomentum =(CLS>MA1 and CLS>MA2 and MA1<MA2) ? "Accumulation:Stop Sell - Setup Buy" :(CLS>MA1 and CLS>MA2 and MA1>MA2) ? "Runing Up: Buy Runing":(CLS<MA1 and CLS>MA2 and MA1>MA2) ? "Re-Acumulasi: Continue Up":(CLS<MA1 and CLS<MA2 and MA1>MA2) ? "Distribution: Stop Buy-Setup Short":(CLS<MA1 and CLS<MA2 and MA1<MA2) ? "Re-Distribusi: Continue Down":(CLS>MA1 and CLS<MA2 and MA1<MA2) ? "Accumulation-Distribusi: Don't Trade Wait Break":na //-----Condition end // Return values [CLS, MA1, MA2, RSI, MACDV, SignalV, stringmacdv, stringmomentum]
// ] -------- Alerts ----------------- [
//---- Table Position & Size code start {----//
var table_position = dash_loc == 'Bottom Right' ? position.bottom_right :
dash_loc == 'Bottom Left' ? position.bottom_left :
dash_loc == 'Middle Right' ? position.middle_right :
dash_loc == 'Bottom Center' ? position.bottom_center :
dash_loc == 'Top Left' ? position.top_right : position.bottom_right
var table_text_size = text_size == 'Normal' ? size.normal :
text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small :
text_size == 'Normal' ? size.normal : size.large
var t = table.new(table_position,15,math.abs(max-min)+2,
frame_color =color.new(#f1ff2a, 0),
frame_width =1,
border_color =color.new(#f1ff2a,0),
border_width =1)
//---- Table Position & Size code end ----//
// get values for table
[CLS_chart, MA1_chart, MA2_chart, RSI_chart, MACDV_chart, SignalV_chart, stringmacdv_chart, stringmomentum_chart] = f_MACDV(close)
[CLS_5_min, MA1_5_min, MA2_5_min, RSI_5_min, MACDV_5_min, SignalV_5_min, stringmacdv_5_min, stringmomentum_5_min] = request.security(syminfo.tickerid, "5", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_15_min, MA1_15_min, MA2_15_min, RSI_15_min, MACDV_15_min, SignalV_15_min, stringmacdv_15_min, stringmomentum_15_min] = request.security(syminfo.tickerid, "15", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_1_hour, MA1_1_hour, MA2_1_hour, RSI_1_hour, MACDV_1_hour, SignalV_1_hour, stringmacdv_1_hour, stringmomentum_1_hour] = request.security(syminfo.tickerid, "60", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_4_hour, MA1_4_hour, MA2_4_hour, RSI_4_hour, MACDV_4_hour, SignalV_4_hour, stringmacdv_4_hour, stringmomentum_4_hour] = request.security(syminfo.tickerid, "240", f_MACDV(close), lookahead=barmerge.lookahead_on)
[CLS_1_day, MA1_1_day, MA2_1_day, RSI_1_day, MACDV_1_day, SignalV_1_day, stringmacdv_1_day, stringmomentum_1_day] = request.security(syminfo.tickerid, "D", f_MACDV(close), lookahead=barmerge.lookahead_on)
//---- Table Column & Rows code start ----//
if (barstate.islast)
//---- Table Main Column Headers code start ----//
table.cell(t,1,1, 'TimeFrame',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showCls
table.cell(t,2,1,'L.Close',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMA01
table.cell(t,3,1,'MA01',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMA02
table.cell(t,4,1,'MA02',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMACross
table.cell(t,5,1,'Trend',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showRSI
table.cell(t,6,1,'RSI',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMACDV
table.cell(t,7,1,'MACDV',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showSignalV
table.cell(t,8,1,'SignalV',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showMACDV_Status
table.cell(t,9,1,'Condition',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
if showmomentum
table.cell(t,10,1,'Phase Market',text_color=col_col,text_size=table_text_size,bgcolor=Header_col)
text//---- Table Main Column Headers code end ----// //---- Display data code start ----// //---------------------- Chart period ---------------------------------- table.cell(t, 1, 2, "Chart",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255)) if showCls table.cell(t,2,2, str.tostring(CLS_chart, '#.###'),text_color=color.new(CLS_chart >CLS_chart[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_chart >CLS_chart[2] ? cell_up : cell_dn ,cell_transp)) if showMA01 table.cell(t,3,2, str.tostring(MA1_chart, '#.###'),text_color=color.new(MA1_chart >MA1_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_chart >MA1_chart[1] ? cell_up : cell_dn ,cell_transp)) if showMA02 table.cell(t,4,2, str.tostring(MA2_chart, '#.###'),text_color=color.new(MA2_chart >MA2_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_chart >MA2_chart[1] ? cell_up : cell_dn ,cell_transp)) if showMACross table.cell(t,5,2, MA1_chart > MA2_chart ? "Bullish" : "Bearish",text_color=color.new(MA1_chart > MA2_chart ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_chart > MA2_chart ? cell_up : cell_dn ,cell_transp)) if showRSI table.cell(t,6,2, str.tostring(RSI_chart, '#.###'),text_color=color.new(RSI_chart > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_chart > 50 ? cell_up : cell_dn ,cell_transp)) if showMACDV table.cell(t,7,2,str.tostring(MACDV_chart, '#.###'),text_color=color.new(MACDV_chart > MACDV_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_chart > MACDV_chart[1] ? cell_up : cell_dn ,cell_transp)) if showSignalV table.cell(t,8,2,str.tostring(SignalV_chart, '#.###'),text_color=color.new(SignalV_chart > SignalV_chart[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_chart> SignalV_chart[1] ? cell_up : cell_dn ,cell_transp)) if showMACDV_Status table.cell(t,9,2,stringmacdv_chart,text_color=color.rgb(0, 0, 0),text_size=table_text_size, bgcolor=color.new(MACDV_chart>50 ? cell_up :MACDV_chart<-50 ? cell_dn:cell_MACDV4 ,cell_transp)) if showmomentum table.cell(t,10,2,stringmomentum_chart,text_color=color.rgb(2, 2, 2),text_size=table_text_size, bgcolor=color.new(CLS_chart>MA1_chart and CLS_chart>MA2_chart and MA1_chart<MA2_chart ? cell_phase1 : (CLS_chart>MA1_chart and CLS_chart>MA2_chart and MA1_chart>MA2_chart) ? cell_phase2 : (CLS_chart<MA1_chart and CLS_chart>MA2_chart and MA1_chart>MA2_chart) ?cell_phase3 :(CLS_chart<MA1_chart and CLS_chart<MA2_chart and MA1_chart>MA2_chart) ? cell_phase4:(CLS_chart<MA1_chart and CLS_chart<MA2_chart and MA1_chart<MA2_chart) ? cell_phase5:(CLS_chart>MA1_chart and CLS_chart<MA2_chart and MA1_chart<MA2_chart) ? cell_phase6:col_col,cell_transp))
// alert("\nRSI =(" + str.tostring(CLS_chart, '#.###') + ")\n Momentum = (" + str.tostring(stringmomentum_chart) + ")\n Trend =("+ str.tostring(MA1_chart > MA2_chart ? "Bullish" : "Bearish")+").", alert.freq_once_per_bar_close)
//---------------------- 5 minute chart ----------------------------------
texttable.cell(t,1,3, "5 minute",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255)) if showCls table.cell(t,2,3, str.tostring(CLS_5_min, '#.###'),text_color=color.new(CLS_5_min >CLS_5_min[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_5_min >CLS_5_min[2] ? cell_up : cell_dn ,cell_transp)) if showMA01 table.cell(t,3,3, str.tostring(MA1_5_min, '#.###'),text_color=color.new(MA1_5_min >MA1_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_5_min >MA1_5_min[1] ? cell_up : cell_dn ,cell_transp)) if showMA02 table.cell(t,4,3, str.tostring(MA2_5_min, '#.###'),text_color=color.new(MA2_5_min >MA2_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_5_min >MA2_5_min[1] ? cell_up : cell_dn ,cell_transp)) if showMACross table.cell(t,5,3, MA1_5_min > MA2_5_min ? "Bullish" : "Bearish",text_color=color.new(MA1_5_min > MA2_5_min ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_5_min > MA2_5_min ? cell_up : cell_dn ,cell_transp)) if showRSI table.cell(t,6,3, str.tostring(RSI_5_min, '#.###'),text_color=color.new(RSI_5_min > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_5_min > 50 ? cell_up : cell_dn ,cell_transp)) if showMACDV table.cell(t,7,3,str.tostring(MACDV_5_min, '#.###'),text_color=color.new(MACDV_5_min > MACDV_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_5_min > MACDV_5_min[1] ? cell_up : cell_dn ,cell_transp)) if showSignalV table.cell(t,8,3,str.tostring(SignalV_5_min, '#.###'),text_color=color.new(SignalV_5_min > SignalV_5_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_5_min> SignalV_5_min[1] ? cell_up : cell_dn ,cell_transp)) if showMACDV_Status table.cell(t,9,3,stringmacdv_5_min,text_color=color.rgb(5, 5, 5),text_size=table_text_size, bgcolor=color.new(MACDV_5_min>50 ? cell_up :MACDV_5_min<-50 ? cell_dn:cell_MACDV4 ,cell_transp)) if showmomentum table.cell(t,10,3,stringmomentum_5_min,text_color=color.rgb(5, 5, 5),text_size=table_text_size, bgcolor=color.new(CLS_5_min>MA1_5_min and CLS_5_min>MA2_5_min and MA1_5_min<MA2_5_min ? cell_phase1 : (CLS_5_min>MA1_5_min and CLS_5_min>MA2_5_min and MA1_5_min>MA2_5_min) ? cell_phase2 : (CLS_5_min<MA1_5_min and CLS_5_min>MA2_5_min and MA1_5_min>MA2_5_min) ?cell_phase3 :(CLS_5_min<MA1_5_min and CLS_5_min<MA2_5_min and MA1_5_min>MA2_5_min) ? cell_phase4:(CLS_5_min<MA1_5_min and CLS_5_min<MA2_5_min and MA1_5_min<MA2_5_min) ? cell_phase5:(CLS_5_min>MA1_5_min and CLS_5_min<MA2_5_min and MA1_5_min<MA2_5_min) ? cell_phase6:col_col,cell_transp))
//---------------------- 15 minute chart ----------------------------------
texttable.cell(t,1,4, "15 minute",text_color=color.rgb(245, 243, 243),text_size=table_text_size, bgcolor=color.rgb(0, 68, 255)) if showCls table.cell(t,2,4, str.tostring(CLS_15_min, '#.###'),text_color=color.new(CLS_15_min >CLS_15_min[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_15_min >CLS_15_min[2] ? cell_up : cell_dn ,cell_transp)) if showMA01 table.cell(t,3,4, str.tostring(MA1_15_min, '#.###'),text_color=color.new(MA1_15_min >MA1_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_15_min >MA1_15_min[1] ? cell_up : cell_dn ,cell_transp)) if showMA02 table.cell(t,4,4, str.tostring(MA2_15_min, '#.###'),text_color=color.new(MA2_15_min >MA2_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_15_min >MA2_15_min[1] ? cell_up : cell_dn ,cell_transp)) if showMACross table.cell(t,5,4, MA1_15_min > MA2_15_min ? "Bullish" : "Bearish",text_color=color.new(MA1_15_min > MA2_15_min ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_15_min > MA2_15_min ? cell_up : cell_dn ,cell_transp)) if showRSI table.cell(t,6,4, str.tostring(RSI_15_min, '#.###'),text_color=color.new(RSI_15_min > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_15_min > 50 ? cell_up : cell_dn ,cell_transp)) if showMACDV table.cell(t,7,4,str.tostring(MACDV_15_min, '#.###'),text_color=color.new(MACDV_15_min > MACDV_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_15_min > MACDV_15_min[1] ? cell_up : cell_dn ,cell_transp)) if showSignalV table.cell(t,8,4,str.tostring(SignalV_15_min, '#.###'),text_color=color.new(SignalV_15_min > SignalV_15_min[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_15_min> SignalV_15_min[1] ? cell_up : cell_dn ,cell_transp)) if showMACDV_Status table.cell(t,9,4,stringmacdv_15_min,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(MACDV_15_min>50 ? cell_up :MACDV_15_min<-50 ? cell_dn:cell_MACDV4 ,cell_transp)) if showmomentum table.cell(t,10,4,stringmomentum_15_min,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(CLS_15_min>MA1_15_min and CLS_15_min>MA2_15_min and MA1_15_min<MA2_15_min ? cell_phase1 : (CLS_15_min>MA1_15_min and CLS_15_min>MA2_15_min and MA1_15_min>MA2_15_min) ? cell_phase2 : (CLS_15_min<MA1_15_min and CLS_15_min>MA2_15_min and MA1_15_min>MA2_15_min) ?cell_phase3 :(CLS_15_min<MA1_15_min and CLS_15_min<MA2_15_min and MA1_15_min>MA2_15_min) ? cell_phase4:(CLS_15_min<MA1_15_min and CLS_15_min<MA2_15_min and MA1_15_min<MA2_15_min) ? cell_phase5:(CLS_15_min>MA1_15_min and CLS_15_min<MA2_15_min and MA1_15_min<MA2_15_min) ? cell_phase6:col_col,cell_transp))
//---------------------- 1 Hour chart ----------------------------------
texttable.cell(t,1,6, "1 Hour",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255)) if showCls table.cell(t,2,6, str.tostring(CLS_1_hour, '#.###'),text_color=color.new(CLS_1_hour >CLS_1_hour[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_1_hour >CLS_1_hour[2] ? cell_up : cell_dn ,cell_transp)) if showMA01 table.cell(t,3,6, str.tostring(MA1_1_hour, '#.###'),text_color=color.new(MA1_1_hour >MA1_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_hour >MA1_1_hour[1] ? cell_up : cell_dn ,cell_transp)) if showMA02 table.cell(t,4,6, str.tostring(MA2_1_hour, '#.###'),text_color=color.new(MA2_1_hour >MA2_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_1_hour >MA2_1_hour[1] ? cell_up : cell_dn ,cell_transp)) if showMACross table.cell(t,5,6, MA1_1_hour > MA2_1_hour ? "Bullish" : "Bearish",text_color=color.new(MA1_1_hour > MA2_1_hour ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_hour > MA2_1_hour ? cell_up : cell_dn ,cell_transp)) if showRSI table.cell(t,6,6, str.tostring(RSI_1_hour, '#.###'),text_color=color.new(RSI_1_hour > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_1_hour > 50 ? cell_up : cell_dn ,cell_transp)) if showMACDV table.cell(t,7,6,str.tostring(MACDV_1_hour, '#.###'),text_color=color.new(MACDV_1_hour > MACDV_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_1_hour > MACDV_1_hour[1] ? cell_up : cell_dn ,cell_transp)) if showSignalV table.cell(t,8,6,str.tostring(SignalV_1_hour, '#.###'),text_color=color.new(SignalV_1_hour > SignalV_1_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_1_hour> SignalV_1_hour[1] ? cell_up : cell_dn ,cell_transp)) if showMACDV_Status table.cell(t,9,6,stringmacdv_1_hour,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(MACDV_1_hour>50 ? cell_up :MACDV_1_hour<-50 ? cell_dn:cell_MACDV4 ,cell_transp)) if showmomentum table.cell(t,10,6,stringmomentum_1_hour,text_color=color.rgb(8, 8, 8),text_size=table_text_size, bgcolor=color.new(CLS_1_hour>MA1_1_hour and CLS_1_hour>MA2_1_hour and MA1_1_hour<MA2_1_hour ? cell_phase1 : (CLS_1_hour>MA1_1_hour and CLS_1_hour>MA2_1_hour and MA1_1_hour>MA2_1_hour) ? cell_phase2 : (CLS_1_hour<MA1_1_hour and CLS_1_hour>MA2_1_hour and MA1_1_hour>MA2_1_hour) ?cell_phase3 :(CLS_1_hour<MA1_1_hour and CLS_1_hour<MA2_1_hour and MA1_1_hour>MA2_1_hour) ? cell_phase4:(CLS_1_hour<MA1_1_hour and CLS_1_hour<MA2_1_hour and MA1_1_hour<MA2_1_hour) ? cell_phase5:(CLS_1_hour>MA1_1_hour and CLS_1_hour<MA2_1_hour and MA1_1_hour<MA2_1_hour) ? cell_phase6:col_col,cell_transp))
//---------------------- 4 Hour chart ----------------------------------
texttable.cell(t,1,7, "4 Hour",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 255)) if showCls table.cell(t,2,7, str.tostring(CLS_4_hour, '#.###'),text_color=color.new(CLS_4_hour >CLS_4_hour[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_4_hour >CLS_4_hour[2] ? cell_up : cell_dn ,cell_transp)) if showMA01 table.cell(t,3,7, str.tostring(MA1_4_hour, '#.###'),text_color=color.new(MA1_4_hour >MA1_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_4_hour >MA1_4_hour[1] ? cell_up : cell_dn ,cell_transp)) if showMA02 table.cell(t,4,7, str.tostring(MA2_4_hour, '#.###'),text_color=color.new(MA2_4_hour >MA2_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_4_hour >MA2_4_hour[1] ? cell_up : cell_dn ,cell_transp)) if showMACross table.cell(t,5,7, MA1_4_hour > MA2_4_hour ? "Bullish" : "Bearish",text_color=color.new(MA1_4_hour > MA2_4_hour ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_4_hour > MA2_4_hour ? cell_up : cell_dn ,cell_transp)) if showRSI table.cell(t,6,7, str.tostring(RSI_4_hour, '#.###'),text_color=color.new(RSI_4_hour > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_4_hour > 50 ? cell_up : cell_dn ,cell_transp)) if showMACDV table.cell(t,7,7,str.tostring(MACDV_4_hour, '#.###'),text_color=color.new(MACDV_4_hour > MACDV_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_4_hour > MACDV_4_hour[1] ? cell_up : cell_dn ,cell_transp)) if showSignalV table.cell(t,8,7,str.tostring(SignalV_4_hour, '#.###'),text_color=color.new(SignalV_4_hour > SignalV_4_hour[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_4_hour> SignalV_4_hour[1] ? cell_up : cell_dn ,cell_transp)) if showMACDV_Status table.cell(t,9,7,stringmacdv_4_hour,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(MACDV_4_hour>50 ? cell_up :MACDV_4_hour<-50 ? cell_dn:cell_MACDV4 ,cell_transp)) if showmomentum table.cell(t,10,7,stringmomentum_4_hour,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(CLS_4_hour>MA1_4_hour and CLS_4_hour>MA2_4_hour and MA1_4_hour<MA2_4_hour ? cell_phase1 : (CLS_4_hour>MA1_4_hour and CLS_4_hour>MA2_4_hour and MA1_4_hour>MA2_4_hour) ? cell_phase2 : (CLS_4_hour<MA1_4_hour and CLS_4_hour>MA2_4_hour and MA1_4_hour>MA2_4_hour) ?cell_phase3 :(CLS_4_hour<MA1_4_hour and CLS_4_hour<MA2_4_hour and MA1_4_hour>MA2_4_hour) ? cell_phase4:(CLS_4_hour<MA1_4_hour and CLS_4_hour<MA2_4_hour and MA1_4_hour<MA2_4_hour) ? cell_phase5:(CLS_4_hour>MA1_4_hour and CLS_4_hour<MA2_4_hour and MA1_4_hour<MA2_4_hour) ? cell_phase6:col_col,cell_transp))
//---------------------- 1 Day chart ----------------------------------
texttable.cell(t,1,9, "1 Day",text_color=color.white,text_size=table_text_size, bgcolor=color.rgb(0, 68, 253)) if showCls table.cell(t,2,9, str.tostring(CLS_1_day, '#.###'),text_color=color.new(CLS_1_day >CLS_1_day[2] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(CLS_1_day >CLS_1_day[2] ? cell_up : cell_dn ,cell_transp)) if showMA01 table.cell(t,3,9, str.tostring(MA1_1_day, '#.###'),text_color=color.new(MA1_1_day >MA1_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_day >MA1_1_day[1] ? cell_up : cell_dn ,cell_transp)) if showMA02 table.cell(t,4,9, str.tostring(MA2_1_day, '#.###'),text_color=color.new(MA2_1_day >MA2_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA2_1_day >MA2_1_day[1] ? cell_up : cell_dn ,cell_transp)) if showMACross table.cell(t,5,9, MA1_1_day > MA2_1_day ? "Bullish" : "Bearish",text_color=color.new(MA1_1_day > MA2_1_day ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MA1_1_day > MA2_1_day ? cell_up : cell_dn ,cell_transp)) if showRSI table.cell(t,6,9, str.tostring(RSI_1_day, '#.###'),text_color=color.new(RSI_1_day > 50 ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(RSI_1_day > 50 ? cell_up : cell_dn ,cell_transp)) if showMACDV table.cell(t,7,9,str.tostring(MACDV_1_day, '#.###'),text_color=color.new(MACDV_1_day > MACDV_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(MACDV_1_day > MACDV_1_day[1] ? cell_up : cell_dn ,cell_transp)) if showSignalV table.cell(t,8,9,str.tostring(SignalV_1_day, '#.###'),text_color=color.new(SignalV_1_day > SignalV_1_day[1] ? cell_up : cell_dn ,0),text_size=table_text_size, bgcolor=color.new(SignalV_1_day> SignalV_1_day[1] ? cell_up : cell_dn ,cell_transp)) if showMACDV_Status table.cell(t,9,9,stringmacdv_1_day,text_color=color.rgb(5, 5, 5),text_size=table_text_size, bgcolor=color.new(MACDV_1_day>50 ? cell_up :MACDV_1_day<-50 ? cell_dn:cell_MACDV4 ,cell_transp)) if showmomentum table.cell(t,10,9,stringmomentum_1_day,text_color=color.rgb(7, 7, 7),text_size=table_text_size, bgcolor=color.new(CLS_1_day>MA1_1_day and CLS_1_day>MA2_1_day and MA1_1_day<MA2_1_day ? cell_phase1 : (CLS_1_day>MA1_1_day and CLS_1_day>MA2_1_day and MA1_1_day>MA2_1_day) ? cell_phase2 : (CLS_1_day<MA1_1_day and CLS_1_day>MA2_1_day and MA1_1_day>MA2_1_day) ?cell_phase3 :(CLS_1_day<MA1_1_day and CLS_1_day<MA2_1_day and MA1_1_day>MA2_1_day) ? cell_phase4:(CLS_1_day<MA1_1_day and CLS_1_day<MA2_1_day and MA1_1_day<MA2_1_day) ? cell_phase5:(CLS_1_day>MA1_1_day and CLS_1_day<MA2_1_day and MA1_1_day<MA2_1_day) ? cell_phase6:col_col,cell_transp))
//---- Display data code end ----//
//End dahs board
// **********************************************
Ichi_Mode = input.bool(title="Ichimoku CLOUD MODE", defval=false, group = '== ICHIMOKU SETTING ==')
tenkan_len = input(9,'Tenkan ',inline='tenkan', group = '== ICHIMOKU SETTING ==', tooltip = 'TENKAN = FAST SIGNAL')
tenkan_mult = input(2.,'',inline='tenkan', group = '== ICHIMOKU SETTING ==')
kijun_len = input(26,'Kijun ',inline='kijun', group = '== ICHIMOKU SETTING ==', tooltip = 'KIJUN = SLOW SIGNAL')
kijun_mult = input(4.,'',inline='kijun', group = '== ICHIMOKU SETTING ==')
spanB_len = input(52,'Senkou Span A/B ',inline='span', group = '== ICHIMOKU SETTING ==', tooltip = 'SENKOU = CLOUD SIGNAL')
spanB_mult = input(6.,'',inline='span', group = '== ICHIMOKU SETTING ==')
cloudacolor = input.color(defval = color.new(color.orange,20), title = 'CLOUD-A', inline='span1', group = '== ICHIMOKU SETTING ==')
cloudbcolor = input.color(defval = color.new(color.purple,20), title = 'CLOUD-B', inline='span1', group = '== ICHIMOKU SETTING ==')
chi_color = input.color(defval = color.new(#73ecff,0), title = "Chikou-Color", group = '== ICHIMOKU SETTING ==', inline = 'CHIKOU')
offset = input(26,'Chikou', group = '== ICHIMOKU SETTING ==', tooltip = 'CHIKOU = CANDLE LOOK BACK DEFAULT = 26', inline = 'CHIKOU')
//------------------------------------------------------------------------------
avg(src,length,mult)=>
atr = ta.atr(length)*mult
up = hl2 + atr
dn = hl2 - atr
upper = 0.,lower = 0.
upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
textos = 0,max = 0.,min = 0. os := src > upper ? 1 : src < lower ? 0 : os[1] spt = os == 1 ? lower : upper max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ? math.max(src,max[1]) : spt min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ? math.min(src,min[1]) : spt math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)
senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
tenkan_css = color.white
kijun_css = #ff5d00
cloud_a = cloudacolor
cloud_b = cloudbcolor
chikou_css = color.new(#73ecff,20)
plot(Ichi_Mode ? tenkan : na,'Tenkan-Sen',tenkan_css,style = plot.style_stepline, linewidth = 2)
plot(Ichi_Mode ? kijun : na,'Kijun-Sen',kijun_css, style = plot.style_stepline, linewidth = 2)
plot(Ichi_Mode ? ta.crossover(tenkan,kijun) ? kijun : na : na,'Crossover',#2157f3,3,plot.style_circles)
plot(Ichi_Mode ? ta.crossunder(tenkan,kijun) ? kijun : na : na,'Crossunder',#ff5d00,3,plot.style_circles)
A = plot(Ichi_Mode ? senkouA : na,'Senkou Span A',na,offset=offset-1)
B = plot(Ichi_Mode ? senkouB : na,'Senkou Span B',na,offset=offset-1)
fill(A,B,senkouA > senkouB ? cloud_a : cloud_b)
plot(Ichi_Mode ? close : na,'Chikou',chi_color,offset=-offset+1, linewidth = 2)
////////////////////////////////////////////////////////////////////////////////////////
RSI_MODE = input.bool(title="RSI MODE", defval=false, group = '== RSI SETTING >> COMFIRM RSI BEFORE OPEN POSITION ==', tooltip = 'If Mode On = Use RSI Strategy With Long and Short\n >> RSI Confirm Before Open Position')
//if RSI_MODE == true
RSILength = input(14, title='RSI Length', group = '== RSI SETTING >> PLOT RSI SIGNAL OB OS ==')
OverBought = input(70, title='RSI OB', group = '== RSI SETTING >> PLOT RSI SIGNAL OB OS ==', inline = 'RSI1')
OverSold = input(30, title='RSI OS', group = '== RSI SETTING >> PLOT RSI SIGNAL OB OS ==', inline = 'RSI1')
vrsi = ta.rsi(srcstrategy, RSILength)
RSIUP = ta.crossover(vrsi, OverBought)
RSIDOWN = ta.crossunder(vrsi, OverSold)
plotshape(RSI_MODE ? RSIUP : na, title='RSIUP', text = 'OB', color=color.new(color.yellow, 100), style=shape.circle, location=location.belowbar, size=size.auto) //plot for buy icon
plotshape(RSI_MODE ? RSIDOWN : na, title='RSIDOWN', text = 'OS', color=color.new(color.red, 100), style=shape.circle, location=location.abovebar, size=size.auto) //plot for buy icon
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MACD_MODE_SIG= input.bool(title="MACD MODE = MACD Cross Signal", defval=false, group = '== MACD SETTING ==', tooltip = 'If Mode On = Use MACD Strategy for Signal When Cross Up and Cross Down')
//if MACD_MODE_SIG == true
MACDfastLength = input(12, title='MACD Fast', group = '== MACD SETTING ==', inline = 'MACDSIG1')
MACDslowlength = input(26, title='MACD Slow', group = '== MACD SETTING ==', inline = 'MACDSIG1')
MACDLength = input(18, title='MACD Length', group = '== MACD SETTING ==')
macdupcolor = input.color(defval = color.new(color.green,0), title = 'CROSS-UP', inline = 'MACDCO', group = '== MACD SETTING ==')
macddowncolor = input.color(defval = color.new(color.red,0), title = 'CROSS-DOWN', inline = 'MACDCO', group = '== MACD SETTING ==')
MACD = ta.ema(close, MACDfastLength) - ta.ema(close, MACDslowlength)
aMACD = ta.ema(MACD, MACDLength)
delta = MACD - aMACD
macdTPl = (ta.crossover(delta, 0))
macdTPs = (ta.crossunder(delta, 0))
plotshape(MACD_MODE_SIG ? macdTPl : na, title='macdTPl', text = '0', color=macdupcolor, style=shape.circle, location=location.belowbar, size=size.auto) //plot for buy icon
plotshape(MACD_MODE_SIG ? macdTPs : na, title='macdTPs', text = '0', color=macddowncolor, style=shape.circle, location=location.abovebar, size=size.auto) //plot for buy icon
I’ll convert this into a single NexuScript indicator, keeping your original settings and separating the TMA bands, signals, moving averages, FVGs, dashboard, and Ichimoku logic. I’ll check the language reference for features that need a different implementation.
I’ve confirmed two important differences: Nexus can’t import the TradingView economic-calendar library, and it can only request timeframes higher than the current chart. I’ll keep the chart indicators, rebuild the FVG boxes, and make the dashboard skip unsupported lower-timeframe rows rather than invent their values.
The script now includes the centered TMA and its dotted live edge, the custom ATR-based Ichimoku, both engulfing modes, swing levels, and the MACD-V dashboard. I’ve also added manual economic-event timestamps as a substitute for the unavailable calendar import. I’m checking the generated file for structural and compatibility issues.
I've converted Gabors Other Shit into a single NexuScript 1.6 indicator for Nexus / Onyx Trader.
The converted script is 922 lines long, so I've packaged the entire code into a text file for easy copying into the script editor.
Gabors Other Shit — NexuScript 1.6
Complete source code · 922 lines · 125 configurable settings
[Download NexuScript code]
| Original indicator feature | Status |
|---|---|
| Centered TMA Magic Bands | Converted |
| Dotted live TMA bands | Converted |
| Rebound arrows and caution labels | Converted |
| Band crossing alerts | Converted |
| Three-candle engulfing | Converted |
| Normal engulfing | Converted |
| Candle coloring | Converted |
| SMA, EMA, WMA, HMA, RMA, VWMA | Converted |
| ZLSMA trend shading | Converted |
| Big Trend moving averages | Converted |
| Swing high and low levels | Converted |
| Fair Value Gap boxes | Adapted |
| Higher-timeframe FVG | Adapted |
| Multi-timeframe MACD-V dashboard | Adapted |
| Custom ATR-based Ichimoku Cloud | Converted |
| RSI overbought/oversold signals | Converted |
| MACD crossing signals | Converted |
| Automatic economic calendar | Manual replacement |
I've retained your original default parameters.
Centered TMA Half Period
ATR Period
ATR Multiplier
TMA Angle Caution
Price source
Weighted
Band line width
1
jdehorty/EconomicCalendar library. I've substituted manually configurable FOMC, CPI, PPI, NFP and other economic-event markers.These changes reflect the capabilities documented in the official NexuScript 1.6 reference. (www.nexusprop.com www.nexusprop.com www.nexusprop.com)
Testing status: The script passed structural checks, and I verified the centered TMA and linear regression mathematics independently. However, I haven't compiled it inside the Nexus editor, so platform-specific compilation or rendering issues remain possible.
turn this into nexuscript. indicator("Gabors Stochastic without Alerts", shorttitle="Gabors Stoch", overlay=false)
// Inputs
period = input.int(8, minval=1, title="Period")
slowKPeriod = input.int(8, minval=1, title="Slow %K SMA Period")
smoothPeriod = input.int(4, minval=2, title="%D SMA Period")
hh = ta.highest(high, period)
ll = ta.lowest(low, period)
rawK = hh - ll == 0 ? 0 : 100 * (close - ll) / (hh - ll)
slowK = ta.sma(rawK, slowKPeriod)
slowD = ta.sma(slowK, smoothPeriod)
plot(slowK, title="Slow %K", color=color.rgb(204, 51, 255), linewidth=2)
plot(slowD, title="Slow %D", color=color.rgb(204, 102, 0), linewidth=2)
hline(87, "Overbought", color=color.red)
hline(13, "Oversold", color=color.green)
bullCross = ta.crossover(slowK, slowD)
bearCross = ta.crossunder(slowK, slowD)
Here's your Gabors Stochastic without Alerts converted to NexuScript 1.6 for Nexus / Onyx Trader.
I've preserved your exact calculations, default settings, line colors, overbought and oversold levels, and crossover logic without adding any alerts.
julianexscript 1.6 indicator "Gabors Stochastic without Alerts", overlay = false, short = "Gabors Stoch" # Inputs input period = 8, min = 1, title = "Period" input slowKPeriod = 8, min = 1, title = "Slow %K SMA Period" input smoothPeriod = 4, min = 2, title = "%D SMA Period" # Horizontal levels level "Overbought", 87, color = color.red, style = "solid" level "Oversold", 13, color = color.green, style = "solid" on bar # Highest high and lowest low let hh = ta.highest(high, period) let ll = ta.lowest(low, period) # Raw Stochastic %K let rawK = (hh - ll) == 0 ? 0 : 100 * (close - ll) / (hh - ll) # Smoothed Stochastic let slowK = ta.sma(rawK, slowKPeriod) let slowD = ta.sma(slowK, smoothPeriod) # Plot oscillator lines plot("Slow %K", slowK, color = color.hex("#CC33FF"), width = 2) plot("Slow %D", slowD, color = color.hex("#CC6600"), width = 2) # Crossover calculations without alerts let bullCross = ta.crossover(slowK, slowD) let bearCross = ta.crossunder(slowK, slowD) end
| Setting | Value |
|---|---|
| Stochastic period | 8 |
| Slow %K smoothing | 8 |
| Slow %D smoothing | 4 |
| ● Slow %K | Purple |
| ● Slow %D | Dark orange |
| ● Overbought | 87 |
| ● Oversold | 13 |
| Alerts | Disabled |
| Chart placement | Separate indicator pane |
The main syntax difference is using NexuScript's level declaration instead of Pine Script's hline() for fixed horizontal levels.
The code follows the official NexuScript reference. All required functions are supported, although I haven't compiled it inside Nexus itself. You can copy the entire code directly into your Scripts editor.
turn this into nexuscript. indicator("GaborsAdaptive Trend Finder)", overlay=true, max_bars_back=200)
confidence(pearsonR) =>
switch
pearsonR < 0.2 => "Extremely Weak"
pearsonR < 0.3 => "Very Weak"
pearsonR < 0.4 => "Weak"
pearsonR < 0.5 => "Mostly Weak"
pearsonR < 0.6 => "Somewhat Weak"
pearsonR < 0.7 => "Moderately Weak"
pearsonR < 0.8 => "Moderate"
pearsonR < 0.9 => "Moderately Strong"
pearsonR < 0.92 => "Mostly Strong"
pearsonR < 0.94 => "Strong"
pearsonR < 0.96 => "Very Strong"
pearsonR < 0.98 => "Exceptionally Strong"
=> "Ultra Strong"
getTablePosition(string pos) =>
switch pos
"Bottom Right" => position.bottom_right
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
"Top Right" => position.top_right
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Right" => position.middle_right
=> position.middle_left // "Middle Left" - default
// Calculate deviations for given length
calcDev(float source, int length) =>
float logSource = math.log(source)
var int period_1 = length - 1
if barstate.islast
float sumX = 0.0
float sumXX = 0.0
float sumYX = 0.0
float sumY = 0.0
for int i=1 to length
float lSrc = logSource[i-1]
sumX += i
sumXX += i * i
sumYX += i * lSrc
sumY += lSrc
float slope = nz((length * sumYX - sumX * sumY) / (length * sumXX - sumX * sumX))
float average = sumY / length
float intercept = average - (slope * sumX / length) + slope
float sumDev = 0.0
float sumDxx = 0.0
float sumDyy = 0.0
float sumDyx = 0.0
float regres = intercept + slope * period_1 * 1.7
float sumSlp = intercept
for int i=0 to period_1
float lSrc = logSource[i]
float dxt = lSrc - average
float dyt = sumSlp - regres
lSrc -= sumSlp
sumSlp += slope
sumDxx += dxt * dxt
sumDyy += dyt * dyt
sumDyx += dxt * dyt
sumDev += lSrc * lSrc
float unStdDev = math.sqrt(sumDev / period_1) // unbiased
float divisor = sumDxx * sumDyy
float pearsonR = nz(sumDyx / math.sqrt(divisor))
[unStdDev, pearsonR, slope, intercept]
else
[na, na, na, na]
string t1 = "In Long-Term Channel mode, if the channel is not visible, scroll back on the chart for additional historical data."
string t2 = "Pearson's R, a statistical measure in Adaptive Trend Finder, gauges the linear relationship between price and trend projection. A value closer to 1 indicates a strong positive correlation, reinforcing confidence in the trend direction based on historical price movements."
sourceInput = input.source(close, title="Source")
string group0 = "CHANNEL SETTINGS"
bool periodMode = input.bool ( false, "Use Long-Term Channel", group=group0, tooltip=t1)
float devMultiplier = input.float ( 2.0, "Deviation Multiplier:", group=group0, step=0.1)
color colorInput = input.color ( color.rgb(240, 206, 16), "", group=group0, inline=group0)
string lineStyle1 = input.string( "Solid", "", group=group0, inline=group0, options=["Solid", "Dotted", "Dashed"])
string extendStyle = input.string("Extend None", "", group=group0, inline=group0, options=["Extend Right", "Extend Both", "Extend None", "Extend Left"])
int fillTransparency = input.int ( 99, "Fill Transp:", group=group0, inline="mid", minval=0, maxval=100, step=1)
int channelTransparency = input.int ( 10, "Line Transp:", group=group0, inline="mid", minval=0, maxval=100, step=1)
string group1 = "MIDLINE SETTINGS"
int transpInput = input.int ( 100, "Transp:", group=group1, inline=group1, minval=0, maxval=100, step=10)
int lineWidth = input.int ( 1, "Line Width:", group=group1, inline=group1)
string midLineStyle = input.string("Solid", "", group=group1, inline=group1, options=["Dotted", "Solid", "Dashed"])
string group2 = "TABLE SETTINGS"
string tablePositionInput = input.string("Bottom Right", "Table Position", options=["Bottom Right", "Bottom Left", "Middle Right", "Middle Left", "Top Right", "Top Left", "Top Center", "Bottom Center"], group=group2)
bool showPearsonInput = input.bool ( false, "Show Pearson's R instead of Projection Confidence Level", group=group2, tooltip=t2)
string textSizeInput = input.string( "Normal", "Text Size", options=["Normal", "Large"], group=group2)
var string EXTEND_STYLE = switch extendStyle
"Extend Right" => extend.right
"Extend Both" => extend.both
"Extend None" => extend.none
=> extend.left
// Length Inputs
var array<int> Periods = periodMode ? array.from(na,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100) : array.from(na,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200)
// Calculate deviations, correlation, slope, and intercepts for different lengths
[stdDev01, pearsonR01, slope01, intercept01] = calcDev(sourceInput, Periods.get( 1))
[stdDev02, pearsonR02, slope02, intercept02] = calcDev(sourceInput, Periods.get( 2))
[stdDev03, pearsonR03, slope03, intercept03] = calcDev(sourceInput, Periods.get( 3))
[stdDev04, pearsonR04, slope04, intercept04] = calcDev(sourceInput, Periods.get( 4))
[stdDev05, pearsonR05, slope05, intercept05] = calcDev(sourceInput, Periods.get( 5))
[stdDev06, pearsonR06, slope06, intercept06] = calcDev(sourceInput, Periods.get( 6))
[stdDev07, pearsonR07, slope07, intercept07] = calcDev(sourceInput, Periods.get( 7))
[stdDev08, pearsonR08, slope08, intercept08] = calcDev(sourceInput, Periods.get( 8))
[stdDev09, pearsonR09, slope09, intercept09] = calcDev(sourceInput, Periods.get( 9))
[stdDev10, pearsonR10, slope10, intercept10] = calcDev(sourceInput, Periods.get(10))
[stdDev11, pearsonR11, slope11, intercept11] = calcDev(sourceInput, Periods.get(11))
[stdDev12, pearsonR12, slope12, intercept12] = calcDev(sourceInput, Periods.get(12))
[stdDev13, pearsonR13, slope13, intercept13] = calcDev(sourceInput, Periods.get(13))
[stdDev14, pearsonR14, slope14, intercept14] = calcDev(sourceInput, Periods.get(14))
[stdDev15, pearsonR15, slope15, intercept15] = calcDev(sourceInput, Periods.get(15))
[stdDev16, pearsonR16, slope16, intercept16] = calcDev(sourceInput, Periods.get(16))
[stdDev17, pearsonR17, slope17, intercept17] = calcDev(sourceInput, Periods.get(17))
[stdDev18, pearsonR18, slope18, intercept18] = calcDev(sourceInput, Periods.get(18))
[stdDev19, pearsonR19, slope19, intercept19] = calcDev(sourceInput, Periods.get(19))
if barstate.islast
// Find the highest Pearson's R
float highestPearsonR = math.max(pearsonR01, pearsonR02, pearsonR03, pearsonR04, pearsonR05, pearsonR06, pearsonR07, pearsonR08, pearsonR09, pearsonR10, pearsonR11, pearsonR12, pearsonR13, pearsonR14, pearsonR15, pearsonR16, pearsonR17, pearsonR18, pearsonR19)
text// Determine selected length, slope, intercept, and deviations int detectedPeriod = na float detectedSlope = na float detectedIntrcpt = na float detectedStdDev = na switch highestPearsonR pearsonR01 => detectedPeriod := Periods.get(1) detectedSlope := slope01 detectedIntrcpt := intercept01 detectedStdDev := stdDev01 pearsonR02 => detectedPeriod := Periods.get(2) detectedSlope := slope02 detectedIntrcpt := intercept02 detectedStdDev := stdDev02 pearsonR03 => detectedPeriod := Periods.get(3) detectedSlope := slope03 detectedIntrcpt := intercept03 detectedStdDev := stdDev03 pearsonR04 => detectedPeriod := Periods.get(4) detectedSlope := slope04 detectedIntrcpt := intercept04 detectedStdDev := stdDev04 pearsonR05 => detectedPeriod := Periods.get(5) detectedSlope := slope05 detectedIntrcpt := intercept05 detectedStdDev := stdDev05 pearsonR06 => detectedPeriod := Periods.get(6) detectedSlope := slope06 detectedIntrcpt := intercept06 detectedStdDev := stdDev06 pearsonR07 => detectedPeriod := Periods.get(7) detectedSlope := slope07 detectedIntrcpt := intercept07 detectedStdDev := stdDev07 pearsonR08 => detectedPeriod := Periods.get(8) detectedSlope := slope08 detectedIntrcpt := intercept08 detectedStdDev := stdDev08 pearsonR09 => detectedPeriod := Periods.get(9) detectedSlope := slope09 detectedIntrcpt := intercept09 detectedStdDev := stdDev09 pearsonR10 => detectedPeriod := Periods.get(10) detectedSlope := slope10 detectedIntrcpt := intercept10 detectedStdDev := stdDev10 pearsonR11 => detectedPeriod := Periods.get(11) detectedSlope := slope11 detectedIntrcpt := intercept11 detectedStdDev := stdDev11 pearsonR12 => detectedPeriod := Periods.get(12) detectedSlope := slope12 detectedIntrcpt := intercept12 detectedStdDev := stdDev12 pearsonR13 => detectedPeriod := Periods.get(13) detectedSlope := slope13 detectedIntrcpt := intercept13 detectedStdDev := stdDev13 pearsonR14 => detectedPeriod := Periods.get(14) detectedSlope := slope14 detectedIntrcpt := intercept14 detectedStdDev := stdDev14 pearsonR15 => detectedPeriod := Periods.get(15) detectedSlope := slope15 detectedIntrcpt := intercept15 detectedStdDev := stdDev15 pearsonR16 => detectedPeriod := Periods.get(16) detectedSlope := slope16 detectedIntrcpt := intercept16 detectedStdDev := stdDev16 pearsonR17 => detectedPeriod := Periods.get(17) detectedSlope := slope17 detectedIntrcpt := intercept17 detectedStdDev := stdDev17 pearsonR18 => detectedPeriod := Periods.get(18) detectedSlope := slope18 detectedIntrcpt := intercept18 detectedStdDev := stdDev18 pearsonR19 => detectedPeriod := Periods.get(19) detectedSlope := slope19 detectedIntrcpt := intercept19 detectedStdDev := stdDev19 var line upperLine = na, var linefill upperFill = na var line baseLine = na var line lowerLine = na, var linefill lowerFill = na // Calculate start and end price based on detected slope and intercept float startPrice = math.exp(detectedIntrcpt + detectedSlope * (detectedPeriod - 1)) float endPrice = math.exp(detectedIntrcpt) int startAtBar = bar_index - detectedPeriod + 1 var color ChannelColor = color.new(colorInput, channelTransparency) if na(baseLine) baseLine := line.new(startAtBar, startPrice, bar_index, endPrice, width=lineWidth, extend=EXTEND_STYLE, color=color.new(colorInput, transpInput), style=midLineStyle == "Dotted" ? line.style_dotted : midLineStyle == "Dashed" ? line.style_dashed : line.style_solid) else line.set_xy1(baseLine, startAtBar, startPrice) line.set_xy2(baseLine, bar_index, endPrice) float upperStartPrice = startPrice * math.exp(devMultiplier * detectedStdDev) float upperEndPrice = endPrice * math.exp(devMultiplier * detectedStdDev) if na(upperLine) upperLine := line.new(startAtBar, upperStartPrice, bar_index, upperEndPrice, width=1, extend=EXTEND_STYLE, color=ChannelColor, style=lineStyle1 == "Dotted" ? line.style_dotted : lineStyle1 == "Dashed" ? line.style_dashed : line.style_solid) else line.set_xy1 (upperLine, startAtBar, upperStartPrice) line.set_xy2 (upperLine, bar_index, upperEndPrice) line.set_color(upperLine, colorInput) float lowerStartPrice = startPrice / math.exp(devMultiplier * detectedStdDev) float lowerEndPrice = endPrice / math.exp(devMultiplier * detectedStdDev) if na(lowerLine) lowerLine := line.new(startAtBar, lowerStartPrice, bar_index, lowerEndPrice, width=1, extend=EXTEND_STYLE, color=ChannelColor, style=lineStyle1 == "Dotted" ? line.style_dotted : lineStyle1 == "Dashed" ? line.style_dashed : line.style_solid) else line.set_xy1 (lowerLine, startAtBar, lowerStartPrice) line.set_xy2 (lowerLine, bar_index, lowerEndPrice) line.set_color(lowerLine, colorInput) if na(upperFill) upperFill := linefill.new(upperLine, baseLine, color=color.new(colorInput, fillTransparency)) if na(lowerFill) lowerFill := linefill.new(baseLine, lowerLine, color=color.new(colorInput, fillTransparency)) var table t = table.new(getTablePosition(tablePositionInput), 3, 2) string text1 = periodMode ? "Auto-Selected Period (Long Term): " + str.tostring(detectedPeriod) : "Auto-Selected Period: " + str.tostring(detectedPeriod) var colorInputLight = color.new(colorInput, 40) table.cell(t, 0, 0, text1, text_color=colorInputLight, text_size=textSizeInput == "Large" ? size.large : size.normal) if showPearsonInput table.cell(t, 1, 0, "Pearson's R: " + str.tostring(detectedSlope > 0.0 ? -highestPearsonR : highestPearsonR, "#.###"), text_color=colorInput, text_size=textSizeInput == "Large" ? size.large : size.normal) else table.cell(t, 1, 0, "Projection Confidence: " + confidence(highestPearsonR), text_color=colorInput, text_size=textSizeInput == "Large" ? size.large : size.normal)
I’ll preserve the adaptive period selection and your custom regression formula, including the 1.7 factor, while checking NexuScript’s channel-drawing options.
Here's your Gabors Adaptive Trend Finder converted to NexuScript 1.6 for Nexus / Onyx Trader.
I've preserved your logarithmic regression calculations, automatic period selection, custom 1.7 regression factor, Pearson's R calculations, channel shading, line extensions, transparency settings and confidence dashboard.
julianexscript 1.6 indicator "Gabors Adaptive Trend Finder", overlay = true, short = "Gabors ATF" # ================================================== # SOURCE # ================================================== input sourceInput = close, title = "Source" # ================================================== # CHANNEL SETTINGS # ================================================== input periodMode = false, title = "Use Long-Term Channel", group = "CHANNEL SETTINGS" input devMultiplier = 2.0, title = "Deviation Multiplier", step = 0.1, group = "CHANNEL SETTINGS" input colorInput = color.rgb(240, 206, 16), title = "Channel Color", group = "CHANNEL SETTINGS" input lineStyle1 = "Solid", title = "Channel Line Style", options = ["Solid", "Dotted", "Dashed"], group = "CHANNEL SETTINGS" input extendStyle = "Extend None", title = "Extend Style", options = ["Extend Right", "Extend Both", "Extend None", "Extend Left"], group = "CHANNEL SETTINGS" input fillTransparency = 99, title = "Fill Transparency", min = 0, max = 100, group = "CHANNEL SETTINGS" input channelTransparency = 10, title = "Line Transparency", min = 0, max = 100, group = "CHANNEL SETTINGS" # ================================================== # MIDLINE SETTINGS # ================================================== input transpInput = 100, title = "Transparency", min = 0, max = 100, step = 10, group = "MIDLINE SETTINGS" input lineWidth = 1, title = "Line Width", min = 1, max = 10, group = "MIDLINE SETTINGS" input midLineStyle = "Solid", title = "Midline Style", options = ["Dotted", "Solid", "Dashed"], group = "MIDLINE SETTINGS" # ================================================== # TABLE SETTINGS # ================================================== input tablePositionInput = "Bottom Right", title = "Table Position", options = ["Bottom Right", "Bottom Left", "Middle Right", "Middle Left", "Top Right", "Top Left", "Top Center", "Bottom Center"], group = "TABLE SETTINGS" input showPearsonInput = false, title = "Show Pearson's R instead of Projection Confidence Level", group = "TABLE SETTINGS" input textSizeInput = "Normal", title = "Text Size", options = ["Normal", "Large"], group = "TABLE SETTINGS" # ================================================== # CONFIDENCE FUNCTION # ================================================== function confidence(pearsonR) if pearsonR < 0.2 return "Extremely Weak" elseif pearsonR < 0.3 return "Very Weak" elseif pearsonR < 0.4 return "Weak" elseif pearsonR < 0.5 return "Mostly Weak" elseif pearsonR < 0.6 return "Somewhat Weak" elseif pearsonR < 0.7 return "Moderately Weak" elseif pearsonR < 0.8 return "Moderate" elseif pearsonR < 0.9 return "Moderately Strong" elseif pearsonR < 0.92 return "Mostly Strong" elseif pearsonR < 0.94 return "Strong" elseif pearsonR < 0.96 return "Very Strong" elseif pearsonR < 0.98 return "Exceptionally Strong" else return "Ultra Strong" end end # ================================================== # TABLE POSITION # ================================================== function get_table_position(pos) if pos == "Bottom Right" return "bottom_right" elseif pos == "Bottom Center" return "bottom_center" elseif pos == "Bottom Left" return "bottom_left" elseif pos == "Top Right" return "top_right" elseif pos == "Top Left" return "top_left" elseif pos == "Top Center" return "top_center" elseif pos == "Middle Right" return "middle_right" else return "middle_left" end end # ================================================== # LINE EXTENSION # ================================================== function get_extend_style(style) if style == "Extend Right" return "right" elseif style == "Extend Both" return "both" elseif style == "Extend Left" return "left" else return "none" end end # ================================================== # MAIN INDICATOR # ================================================== on bar # Calculate logarithmic price on every bar let logSource = sourceInput > 0 ? log(sourceInput) : missing # Calculate adaptive channel only on newest bar if bar.last let highestPearsonR = -1.0 let detectedPeriod = 0 let detectedSlope = 0.0 let detectedIntercept = 0.0 let detectedStdDev = 0.0 # ========================================== # SEARCH ALL 19 PERIODS # ========================================== # # Original Long-Term mode: # 10, 15, 20 ... 100 # # Original Normal mode: # 20, 30, 40 ... 200 # # ========================================== for candidate in 0:18 let n = periodMode ? 10 + candidate * 5 : 20 + candidate * 10 # Skip periods without enough history if bar.index + 1 < n continue end let period1 = n - 1 let sumX = 0.0 let sumXX = 0.0 let sumYX = 0.0 let sumY = 0.0 let validData = true # ====================================== # LINEAR REGRESSION # ====================================== for i in 1:n let lSrc = logSource[i - 1] if !isfinite(lSrc) validData = false break end sumX += i sumXX += i * i sumYX += i * lSrc sumY += lSrc end if !validData continue end let denominator = n * sumXX - sumX * sumX let slope = denominator != 0 ? (n * sumYX - sumX * sumY) / denominator : 0.0 let average = sumY / n let intercept = average - slope * sumX / n + slope # ====================================== # STANDARD DEVIATION AND PEARSON R # ====================================== let sumDev = 0.0 let sumDxx = 0.0 let sumDyy = 0.0 let sumDyx = 0.0 # Preserve original 1.7 regression factor let regres = intercept + slope * period1 * 1.7 let sumSlp = intercept for i in 0:period1 let lSrc = logSource[i] let dxt = lSrc - average let dyt = sumSlp - regres let residual = lSrc - sumSlp sumSlp += slope sumDxx += dxt * dxt sumDyy += dyt * dyt sumDyx += dxt * dyt sumDev += residual * residual end # Unbiased standard deviation let unStdDev = sqrt(sumDev / period1) let divisor = sumDxx * sumDyy let pearsonR = divisor > 0 ? sumDyx / sqrt(divisor) : 0.0 # ====================================== # SELECT STRONGEST PERIOD # ====================================== if isfinite(pearsonR) && isfinite(unStdDev) if pearsonR > highestPearsonR highestPearsonR = pearsonR detectedPeriod = n detectedSlope = slope detectedIntercept = intercept detectedStdDev = unStdDev end end end # ========================================== # CHANNEL APPEARANCE # ========================================== let tablePosition = get_table_position(tablePositionInput) let tableSize = lowercase(textSizeInput) if detectedPeriod > 0 let startPrice = exp(detectedIntercept + detectedSlope * (detectedPeriod - 1)) let endPrice = exp(detectedIntercept) let startTime = time[detectedPeriod - 1] let endTime = time let deviation = exp(devMultiplier * detectedStdDev) # Upper channel let upperStartPrice = startPrice * deviation let upperEndPrice = endPrice * deviation # Lower channel let lowerStartPrice = startPrice / deviation let lowerEndPrice = endPrice / deviation # Colors and styles let channelColor = color.fade(colorInput, channelTransparency) let middleColor = color.fade(colorInput, transpInput) let fillColor = color.fade(colorInput, fillTransparency) let transparentColor = color.fade(colorInput, 100) let channelDash = lowercase(lineStyle1) let middleDash = lowercase(midLineStyle) let extension = get_extend_style(extendStyle) # ====================================== # CHANNEL FILL # ====================================== if fillTransparency < 100 polyline( "Adaptive Channel Fill", [ startTime, endTime, endTime, startTime ], [ upperStartPrice, upperEndPrice, lowerEndPrice, lowerStartPrice ], color = transparentColor, closed = true, fill = fillColor, z = -10 ) end # ====================================== # UPPER CHANNEL LINE # ====================================== if channelTransparency < 100 line( startTime, upperStartPrice, endTime, upperEndPrice, color = channelColor, width = 1, dash = channelDash, extend = extension ) # LOWER CHANNEL LINE line( startTime, lowerStartPrice, endTime, lowerEndPrice, color = channelColor, width = 1, dash = channelDash, extend = extension ) end # ====================================== # MIDDLE REGRESSION LINE # ====================================== if transpInput < 100 line( startTime, startPrice, endTime, endPrice, color = middleColor, width = lineWidth, dash = middleDash, extend = extension ) end # ====================================== # CONFIDENCE DASHBOARD # ====================================== let periodText = periodMode ? "Auto-Selected Period (Long Term): $(detectedPeriod)" : "Auto-Selected Period: $(detectedPeriod)" # Preserve original Pearson sign let signedPearson = detectedSlope > 0.0 ? -highestPearsonR : highestPearsonR let confidenceText = confidence(highestPearsonR) let infoText = "" if showPearsonInput infoText = "Pearson's R: $(round(signedPearson, digits = 3))" else infoText = "Projection Confidence: $(confidenceText)" end table( [[ cell( periodText, color = color.fade(colorInput, 40) ), cell( infoText, color = colorInput ) ]], position = tablePosition, background = color.hex("#00000000"), size = tableSize ) else # Insufficient historical data table( [["Waiting for historical data"]], position = tablePosition, color = colorInput, background = color.hex("#00000000"), size = tableSize ) end end end
| Setting | Default |
|---|---|
| Source | Close |
| Long-Term Channel | Off |
| Deviation multiplier | 2.0 |
| ● Channel color | Gold |
| Channel line style | Solid |
| Line extension | None |
| Fill transparency | 99% |
| Channel transparency | 10% |
| Midline transparency | 100% |
| Midline width | 1 |
| Dashboard position | Bottom Right |
| Dashboard text size | Normal |
| Show Pearson's R | Off |
| Candidate periods | 19 |
line() and closed polyline() functions instead of Pine's mutable lines and linefill objects. All four line extension modes are supported, although the shaded fill remains within the detected channel endpoints.The drawing functions, historical indexing and dashboard syntax follow the official NexuScript 1.6 reference. (www.nexusprop.com www.nexusprop.com)
Testing status: The conversion has been checked against the language documentation but has not been compiled inside Nexus itself. Copy the entire code into your Scripts editor and press Run.