Re: Already Converted TradingView Indicators to MT4 Indicators

541
MeNiazi wrote: Sat Jan 25, 2025 2:15 am Hi Dear Coders......

Pls find below an indicator of TradingView "Adaptive EMA with ATR and Standard Deviation [QuantAlgo]"....I am sure this indicator is available here at Forex-Station.
Pls find it for me Thanks A Lot........

Reason: Useful in Lower TF's with good risk reward ratio

https://www.tradingview.com/script/W4SL ... QuantAlgo/
Here is a working version of the Adaptive EMA with ATR and StdDev indicator I converted from the pine script. I used the same display features as with the Adaptive Trend Flow indicator I posted previously. It doesn't show all the fancy visualizations as the original tradingview script shows but it does show the trend changes which is the main thing. Of course you can adjust the settings as you like to make the trend changes more sensitive. You can learn more about the original indicator from https://www.tradingview.com/v/W4SLAv9j/

This converted version shows the trend as a simple green and dark red EMA line with Standard Deviation bands that you can turn on or off in the settings. The colored candles are not part of the indicator but are drawn by a separate heiken ashi indicator.

To use this indicator with an EA just use an iCustom call to access the TrendState buffer number 5 with this call:
string indiAdEMA = "Adaptive EMA";
double AdaptiveEMATrend = iCustom(NULL,0,indiAdEMA,5,0);

If anyone can improve on this indicator then please do so for the benefit of all of us. I found that a StdDev Multiplier of 0.5 and an ATR Multiplier of 0.5 worked better than the original pine script indicator default values of StdDev Multiplier 2.0 and ATR Multiplier of 1.5, so I made 0.5 the default values for those two options. If you find settings that work better than the current default settings then please let us know. Thanks.

I found that with the current default settings, the trend changes of this indicator are almost identical to the trend changes of the Adaptive Trend Flow indicator I posted previously.


IMPORTANT Update: If you downloaded this indicator earlier today then you should redownload it because there was an error in the file I initially uploaded. The fixed file is below with the same name. The error was that part of the Trend Detection code was duplicated and that would have interfered with the line that followed. Anyway, it's now fixed so please redownload it. Thanks and sorry for the inconvenience.
These users thanked the author global for the post (total 4):
mrtools, kvak, MeNiazi, SijjiN


DownloadRe: Already Converted TradingView Indicators to MT4 Indicators

542
global wrote: Sat Jan 25, 2025 6:48 am Here is a working version of the Adaptive EMA with ATR and StdDev indicator I converted from the pine script. I used the same display features as with the Adaptive Trend Flow indicator I posted previously. It doesn't show all the fancy visualizations as the original tradingview script shows but it does show the trend changes which is the main thing. Of course you can adjust the settings as you like to make the trend changes more sensitive. You can learn more about the original indicator from https://www.tradingview.com/v/W4SLAv9j/

This converted version shows the trend as a simple green and dark red EMA line with Standard Deviation bands that you can turn on or off in the settings. The colored candles are not part of the indicator but are drawn by a separate heiken ashi indicator.

To use this indicator with an EA just use an iCustom call to access the TrendState buffer number 5 with this call:
string indiAdEMA = "Adaptive EMA";
double AdaptiveEMATrend = iCustom(NULL,0,indiAdEMA,5,0);

If anyone can improve on this indicator then please do so for the benefit of all of us. I found that a StdDev Multiplier of 0.5 and an ATR Multiplier of 0.5 worked better than the original pine script indicator default values of StdDev Multiplier 2.0 and ATR Multiplier of 1.5, so I made 0.5 the default values for those two options. If you find settings that work better than the current default settings then please let us know. Thanks.

I found that with the current default settings, the trend changes of this indicator are almost identical to the trend changes of the Adaptive Trend Flow indicator I posted previously.


Adaptive EMA.png


IMPORTANT Update: If you downloaded this indicator earlier today then you should redownload it because there was an error in the file I initially uploaded. The fixed file is below with the same name. The error was that part of the Trend Detection code was duplicated and that would have interfered with the line that followed. Anyway, it's now fixed so please redownload it. Thanks and sorry for the inconvenience.
Soo good to see your prompt response and I and many more students and newbies really appreciate your efforts....Its such a wonderful job.....

With alter some of setting its will definitely provide awesome results in scalping

DownloadRe: Already Converted TradingView Indicators to MT4 Indicators

543
global wrote: Sat Jan 25, 2025 6:48 am Here is a working version of the Adaptive EMA with ATR and StdDev indicator I converted from the pine script. I used the same display features as with the Adaptive Trend Flow indicator I posted previously. It doesn't show all the fancy visualizations as the original tradingview script shows but it does show the trend changes which is the main thing. Of course you can adjust the settings as you like to make the trend changes more sensitive. You can learn more about the original indicator from https://www.tradingview.com/v/W4SLAv9j/

This converted version shows the trend as a simple green and dark red EMA line with Standard Deviation bands that you can turn on or off in the settings. The colored candles are not part of the indicator but are drawn by a separate heiken ashi indicator.

To use this indicator with an EA just use an iCustom call to access the TrendState buffer number 5 with this call:
string indiAdEMA = "Adaptive EMA";
double AdaptiveEMATrend = iCustom(NULL,0,indiAdEMA,5,0);

If anyone can improve on this indicator then please do so for the benefit of all of us. I found that a StdDev Multiplier of 0.5 and an ATR Multiplier of 0.5 worked better than the original pine script indicator default values of StdDev Multiplier 2.0 and ATR Multiplier of 1.5, so I made 0.5 the default values for those two options. If you find settings that work better than the current default settings then please let us know. Thanks.

I found that with the current default settings, the trend changes of this indicator are almost identical to the trend changes of the Adaptive Trend Flow indicator I posted previously.


Adaptive EMA.png


IMPORTANT Update: If you downloaded this indicator earlier today then you should redownload it because there was an error in the file I initially uploaded. The fixed file is below with the same name. The error was that part of the Trend Detection code was duplicated and that would have interfered with the line that followed. Anyway, it's now fixed so please redownload it. Thanks and sorry for the inconvenience.

Pls spare some time and add arrows with alerts......Thanks

Re: Already Converted TradingView Indicators to MT4 Indicators

544
Please, can someone help me transfer this code to mt4, it is an RSI with divergences.

Thank you

Code: Select all

//@version=5
indicator(title="RSI Divergence Indicator", format=format.price, timeframe="", timeframe_gaps=true)
len = input.int(title="RSI Period", minval=1, defval=14)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=5, display = display.data_window)
lbL = input(title="Pivot Lookback Left", defval=5, display = display.data_window)
rangeUpper = input(title="Max of Lookback Range", defval=60, display = display.data_window)
rangeLower = input(title="Min of Lookback Range", defval=5, display = display.data_window)
plotBull = input(title="Plot Bullish", defval=true, display = display.data_window)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=false, display = display.data_window)
plotBear = input(title="Plot Bearish", defval=true, display = display.data_window)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false, display = display.data_window)
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
osc = ta.rsi(src, len)

plot(osc, title="RSI", linewidth=2, color=#2962FF)
hline(50, title="Middle Line", color=#787B86, linestyle=hline.style_dotted)
obLevel = hline(70, title="Overbought", color=#787B86, linestyle=hline.style_dotted)
osLevel = hline(30, title="Oversold", color=#787B86, linestyle=hline.style_dotted)
fill(obLevel, osLevel, title="Background", color=color.rgb(33, 150, 243, 90))

plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
	bars = ta.barssince(cond == true)
	rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low

oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Lower Low

priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCondAlert = priceLL and oscHL and plFound
bullCond = plotBull and bullCondAlert

plot(
     plFound ? osc[lbR] : na,
     offset=-lbR,
     title="Regular Bullish",
     linewidth=2,
     color=(bullCond ? bullColor : noneColor),
	 display = display.pane
     )

plotshape(
	 bullCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bullish Label",
	 text=" Bull ",
	 style=shape.labelup,
	 location=location.absolute,
	 color=bullColor,
	 textcolor=textColor
	 )

//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low

oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])

// Price: Higher Low

priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCondAlert = priceHL and oscLL and plFound
hiddenBullCond = plotHiddenBull and hiddenBullCondAlert

plot(
	 plFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bullish",
	 linewidth=2,
	 color=(hiddenBullCond ? hiddenBullColor : noneColor),
	 display = display.pane
	 )

plotshape(
	 hiddenBullCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bullish Label",
	 text=" H Bull ",
	 style=shape.labelup,
	 location=location.absolute,
	 color=bullColor,
	 textcolor=textColor
	 )

//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High

oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Higher High

priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)

bearCondAlert = priceHH and oscLH and phFound
bearCond = plotBear and bearCondAlert

plot(
	 phFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bearish",
	 linewidth=2,
	 color=(bearCond ? bearColor : noneColor),
	 display = display.pane
	 )

plotshape(
	 bearCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Regular Bearish Label",
	 text=" Bear ",
	 style=shape.labeldown,
	 location=location.absolute,
	 color=bearColor,
	 textcolor=textColor
	 )

//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High

oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])

// Price: Lower High

priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)

hiddenBearCondAlert = priceLH and oscHH and phFound
hiddenBearCond = plotHiddenBear and hiddenBearCondAlert

plot(
	 phFound ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bearish",
	 linewidth=2,
	 color=(hiddenBearCond ? hiddenBearColor : noneColor),
	 display = display.pane
	 )

plotshape(
	 hiddenBearCond ? osc[lbR] : na,
	 offset=-lbR,
	 title="Hidden Bearish Label",
	 text=" H Bear ",
	 style=shape.labeldown,
	 location=location.absolute,
	 color=bearColor,
	 textcolor=textColor
	 )

alertcondition(bullCondAlert, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar")
alertcondition(hiddenBullCondAlert, title='Hidden Bullish Divergence', message='Found a new Hidden Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')
alertcondition(bearCondAlert, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')
alertcondition(hiddenBearCondAlert, title='Hidden Bearish Divergence', message='Found a new Hidden Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar')


Re: Already Converted TradingView Indicators to MT4 Indicators

547
This Tradingview indicator will be of interest to Gann Square of Nine followers- would really appreciate conversion to MT4. It plots the reliable daily Gann based levels automatically :

Code: Select all

                             //@version=5
indicator("Gann Calculations", overlay=true, max_bars_back = 1000, max_labels_count = 500, max_lines_count = 500)

//---LINES

show_Buy = input.bool(true, "Buy", group = "Levels")
show_Sell = input.bool(true, "Sell", group = "Levels")
show_Sup = input.bool(true, "Support", group = "Levels")
show_Res = input.bool(true, "Resistance", group = "Levels")

//---LABELS

show_Buy_lb = input.bool(false, "Buy Label", group = "Labels")
show_Sell_lb = input.bool(false, "Sell Label", group = "Labels")
show_Sup_lb = input.bool(false, "Support Label", group = "Labels")
show_Res_lb = input.bool(false, "Resistance Label", group = "Labels")

//---SIGNALS

show_Signal_Buy = input.bool(false, "Signal Buy", group = "Signals")
show_Signal_Sell = input.bool(false, "Signal Sell", group = "Signals")

show_DO = input.bool(true, "Show Daily Open", group = "Daily Open")

//----

var line open_price_line = na
var line buyLine = na
var line sellLine = na
var label buyLabel = na
var label sellLabel = na

is_new_day = timeframe.change("D")

if (is_new_day)
    // Delete old lines
    line.delete(open_price_line)
    line.delete(buyLine)
    line.delete(sellLine)
    
    // Create new open price line
    open_price_line := line.new(na, na, na, na, color=color.white, style=line.style_dashed)
    line.set_xy1(open_price_line, bar_index, open)
    line.set_xy2(open_price_line, bar_index + 1, open)
else
    if show_DO
        line.set_x2(open_price_line, bar_index)

//----

num = line.get_y1(open_price_line)

root = math.sqrt(num)
minus_two = root - 2
rounded = math.round(minus_two)
result = math.pow(rounded, 2)

var float[] x = array.new_float(24)
var float[] sqr_x = array.new_float(24)
var float[] sqr_x_rounded = array.new_float(24)
var float[] sqr_x_rounded_root = array.new_float(24)

for i = 0 to 23
    array.set(x, i, rounded + 0.125 * (i + 1))
    array.set(sqr_x, i, array.get(x, i) * array.get(x, i))
    array.set(sqr_x_rounded, i, math.round(array.get(sqr_x, i) * 100) / 100)
    array.set(sqr_x_rounded_root, i, math.round((num - array.get(sqr_x_rounded, i)) * 100) / 100)

min_positive_index = -1
for i = 0 to 23
    if array.get(sqr_x_rounded_root, i) < 0
        min_positive_index := i
        break

var float buy_above = na
var float sell_below = na

if min_positive_index >= 0
    buy_above := array.get(sqr_x_rounded, min_positive_index)
    sell_below := array.get(sqr_x_rounded, min_positive_index - 1)

// Delete old lines
line.delete(buyLine)
line.delete(sellLine)

// Create new buy and sell lines
if min_positive_index >= 0 and show_Buy
    buyLine := line.new(na, na, na, na, color=color.aqua, width=1)

    line.set_xy1(buyLine, bar_index, buy_above)
    line.set_xy2(buyLine, line.get_x1(open_price_line), buy_above)

if min_positive_index >= 0 and show_Sell
    sellLine := line.new(na, na, na, na, color=color.yellow, width=1)
    line.set_xy1(sellLine, bar_index, sell_below)
    line.set_xy2(sellLine, line.get_x1(open_price_line), sell_below)

// Delete old labels
label.delete(buyLabel)
label.delete(sellLabel)

// Create new labels
buyLabel := label.new(na, na, "")
sellLabel := label.new(na, na, "")

// Print the values of buyLine and sellLine
buyLineValues = line.get_y1(buyLine)
sellLineValues = line.get_y1(sellLine)

if show_Buy_lb
    // Set label text and style
    label.set_text(buyLabel, "BUY: " + str.tostring(buyLineValues))
    label.set_textcolor(buyLabel, color.black)  // Text color
    label.set_color(buyLabel, color.new(color.aqua, 0))  // Background color
    label.set_xy(buyLabel, line.get_x1(open_price_line) - 1, line.get_y1(buyLine))  // At the beginning of the buy line 
    label.set_style(buyLabel, style=label.style_label_right) 

if show_Sell_lb
    label.set_text(sellLabel, "SELL: " + str.tostring(sellLineValues))
    label.set_textcolor(sellLabel, color.black)  // Text color
    label.set_color(sellLabel, color.new(color.yellow, 0))  // Background color
    label.set_xy(sellLabel, line.get_x1(open_price_line) - 1, line.get_y1(sellLine))  // At the beginning of the sell line
    label.set_style(sellLabel, style=label.style_label_right) 

// Create new labels for buy and sell signals
var label buySignalLabel = na
var label sellSignalLabel = na

//-----

show_startHour = input.bool(false, "Start Hour", group = "Signals Time Window")
show_endHour = input.bool(false, "End Hour", group = "Signals Time Window")

// Define the target hour and minute for the line
targetHour = input.int(15, title="Start Hour", minval=0, maxval=24, group = "START")
targetMinute =  input.int(0, title="Minute", minval=0, maxval=60, group = "START")

// Function to check if the current bar is at the target time using timestamp
isTargetTime() =>
    targetTimestamp = timestamp(year(time), month(time), dayofmonth(time), targetHour, targetMinute)
    time[1] < targetTimestamp and time >= targetTimestamp

plotshape( isTargetTime() ? show_startHour : na, style = shape.triangleup, location = location.bottom, color = color.new(color.gray,0), text = "in", textcolor = color.new(color.white,0), size = size.tiny)

// Define the target hour and minute for the line
targetHour1 = input.int(23, title="End Hour", minval=0, maxval=24, group = "END")
targetMinute1 =  input.int(00, title="Minute", minval=0, maxval=60, group = "END")

// Function to check if the current bar is at the target time using timestamp
isTargetTime1() =>
    targetTimestamp1 = timestamp(year(time), month(time), dayofmonth(time), targetHour1, targetMinute1)
    time[1] < targetTimestamp1 and time >= targetTimestamp1

plotshape( isTargetTime1() ? show_endHour : na, style = shape.triangledown, location = location.bottom, color = color.new(color.gray,0), text = "out", textcolor = color.new(color.white,0), size = size.tiny)

// Check if the current bar's time is within the specified range
isWithinTimeRange = hour >= targetHour and hour <= targetHour1

// // Plot xcross shape when price crosses the buy line
// plotshape(series=ta.crossover(close, buy_above), title="Buy Signal", color=color.aqua, style=shape.circle , size=size.tiny)

// Place label on the close of the candle that breaks above the buy line
if show_Signal_Buy and ta.crossover(close, buy_above) and (close > buy_above) and isWithinTimeRange
    buySignalLabel := label.new(x=bar_index, y=close, text="", color=color.aqua, style=label.style_label_down, textcolor=color.white, size=size.tiny)

// // Plot xcross shape when price crosses the sell line
// plotshape(series=ta.crossunder(close, sell_below), title="Sell Signal", color=color.yellow, style=shape.circle, size=size.tiny)

if show_Signal_Sell and ta.crossunder(close, sell_below)  and (close < sell_below) and isWithinTimeRange
    sellSignalLabel := label.new(x=bar_index, y=close, text="", color=color.yellow, style=label.style_label_up, textcolor=color.white, size=size.tiny)

//-------------

var line supportLine = na  // Declare supportLine outside the block
var line resistanceLine = na  // Declare resistanceLine outside the block

// Delete old lines
line.delete(supportLine)
line.delete(resistanceLine)

// Calculate and draw the 1st support and first resistance lines
if min_positive_index >= 0 and show_Sup

    firstSupport = array.get(sqr_x_rounded, min_positive_index - 2)

    // Draw the 1st support line
    // supportLine := line.new(bar_index, firstSupport, bar_index + 1, firstSupport, color=color.yellow, style=line.style_dashed)

    supportLine := line.new(na, na, na, na, color=color.yellow, width=1)
    line.set_xy1(supportLine, bar_index, firstSupport)
    line.set_xy2(supportLine, line.get_x1(open_price_line), firstSupport)

if min_positive_index >= 0 and show_Res

    firstResistance = array.get(sqr_x_rounded, min_positive_index + 1)

    // Draw the first resistance line
    // resistanceLine := line.new(bar_index, firstResistance, bar_index + 1, firstResistance, color=color.aqua, style=line.style_dashed)

    resistanceLine := line.new(na, na, na, na, color=color.aqua, width=1)
    line.set_xy1(resistanceLine, bar_index, firstResistance)
    line.set_xy2(resistanceLine, line.get_x1(open_price_line), firstResistance)

var label supportLabel = na
var label resistanceLabel = na

// Delete old labels for support and resistance
label.delete(supportLabel)
label.delete(resistanceLabel)

// Create new labels for support and resistance
supportLabel := label.new(na, na, "")
resistanceLabel := label.new(na, na, "")

// Print the values of supportLine and resistanceLine
supportLineValues = line.get_y1(supportLine)
resistanceLineValues = line.get_y1(resistanceLine)

if show_Sup_lb
    // Set label text and style for support
    label.set_text(supportLabel, "S: " + str.tostring(supportLineValues))
    label.set_textcolor(supportLabel, color.black)  // Text color
    label.set_color(supportLabel, color.new(color.yellow, 0))  // Background color
    label.set_xy(supportLabel, line.get_x1(open_price_line) - 1, line.get_y1(supportLine))  // At the beginning of the support line 
    label.set_style(supportLabel, style=label.style_label_right) 

if show_Res_lb
    // Set label text and style for resistance
    label.set_text(resistanceLabel, "R: " + str.tostring(resistanceLineValues))
    label.set_textcolor(resistanceLabel, color.black)  // Text color
    label.set_color(resistanceLabel, color.new(color.aqua, 0))  // Background color
    label.set_xy(resistanceLabel, line.get_x1(open_price_line) - 1, line.get_y1(resistanceLine))  // At the beginning of the resistance line
    label.set_style(resistanceLabel, style=label.style_label_right) 

//------------Gann

show_squares = input.bool(false, title = "Squares lines", group = "Gann Square Lines")

show_diagonals1 = input.bool(false, title = "Diagonals Type 1 lines", group = "Diagonals Lines")
show_diagonals2 = input.bool(false, title = "Diagonals Type 2 lines", group = "Diagonals Lines")

show_midlines_type1 = input.bool(false, title = "Mid Lines Type 1 lines", group = "Mid-Lines Lines")
show_midlines_type2 = input.bool(false, title = "Mid Lines Type 2 lines", group = "Mid-Lines Lines")

show_insquare_type1 = input.bool(false, title = "Inside Square Type 1 lines", group = "Inside Square Lines")
show_insquare_type2 = input.bool(false, title = "Inside Square Type 2 lines", group = "Inside Square Lines")

quarter = input.bool(false, title = "1/4 lines", group = "Lines")
sixth = input.bool(false, title = "1/6 lines", group = "Lines")
eighth = input.bool(false, title = "1/8 lines", group = "Lines")

outsiteLines = input.color(color.new(color.white,30), title = "Frame Lines Color", group = "Style", inline = "colors")
insideLines = input.color(color.new(color.white,50), title = "Inside Lines Color", group = "Style", inline = "colors")
widthLines =  input.int(1, title = "Width", group = "Style")


//----

show_startHour_S = input.bool(false, "Start Hour", group = "Gann Squares Time Window")
show_endHour_S = input.bool(false, "End Hour", group = "Gann Squares Time Window")

// Define the target hour and minute for the line
targetHour_S = input.int(0, title="Start Hour", minval=0, maxval=24, group = "Gann Squares Start")
targetMinute_S =  input.int(0, title="Minute", minval=0, maxval=60, group = "Gann Squares Start")

// Function to check if the current bar is at the target time using timestamp
isTargetTime_S() =>
    targetTimestamp = timestamp(year(time), month(time), dayofmonth(time), targetHour_S, targetMinute_S)
    time[1] < targetTimestamp and time >= targetTimestamp

plotshape( isTargetTime_S() ? show_startHour_S : na, style = shape.triangleup, location = location.bottom, color = color.new(color.gray,0), text = "in", textcolor = color.new(color.white,0), size = size.tiny)

// Define the target hour and minute for the line
targetHour_S1 = input.int(24, title="End Hour", minval=0, maxval=24, group = "Gann Squares End")
targetMinute_S1 =  input.int(00, title="Minute", minval=0, maxval=60, group = "Gann Squares End")

// Function to check if the current bar is at the target time using timestamp
isTargetTime_S1() =>
    targetTimestamp1 = timestamp(year(time), month(time), dayofmonth(time), targetHour_S1, targetMinute_S1)
    time[1] < targetTimestamp1 and time >= targetTimestamp1

plotshape( isTargetTime_S1() ? show_endHour_S : na, style = shape.triangledown, location = location.bottom, color = color.new(color.gray,0), text = "out", textcolor = color.new(color.white,0), size = size.tiny)

//----

calculations_day_back = input.int(1, title="Start Calculation in Days", minval=0, maxval = 3, group = "Gann Days Calculations")

//quarter - sixth - eighth
start = timestamp(year, month, dayofmonth - calculations_day_back, targetHour_S, targetMinute_S)
end = timestamp(year, month, dayofmonth - calculations_day_back, targetHour_S1, targetMinute_S1)

barsFromStart  = (time - start)/(time - time[1]) // From start to real time
barsFromEnd = (time - end)/(time - time[1]) // From end to real time
bars = barsFromStart - barsFromEnd
var lines = array.new_line()

getHighestValue(lookback, beginning) =>
    float higher = 0.0
    for i = 0 to lookback - 1
        value = nz(high[beginning - i], higher[1])
        if value > higher
            higher := value
    higher

getLowestValue(lookback, beginning) =>
    float lowest = 10000000000000
    for i = 0 to lookback - 1
        value = nz(low[beginning - i], lowest[1])
        if value < lowest
            lowest := value
    lowest


drawSquares(startTime, endTime, highValue, lowValue, midValue) =>

    //DRAW LINES
    if show_squares
        array.push(lines, line.new(startTime, highValue, endTime, highValue, xloc = xloc.bar_time, color = outsiteLines, width = widthLines))    
        array.push(lines, line.new(startTime, lowValue, endTime, lowValue, xloc = xloc.bar_time, color = outsiteLines, width = widthLines))
        array.push(lines, line.new(startTime, highValue, startTime, lowValue, xloc = xloc.bar_time, color = outsiteLines, width = widthLines))
        array.push(lines, line.new(endTime, highValue, endTime, lowValue, xloc = xloc.bar_time, color = outsiteLines, width = widthLines))

    if show_insquare_type1      
    //## X inside square ##
        array.push(lines, line.new(startTime, lowValue, endTime, highValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
    
    if show_insquare_type2    
        array.push(lines, line.new(startTime, highValue, endTime, lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))

    var float upperY = na
    var float lowerY = na

    var float upperY1 = na
    var float lowerY1 = na

    var int upperX = na
    var int lowerX = na

    var int upperX1 = na
    var int lowerX1 = na

    var line diagonal_line = na

    //##  Vertical mid start and end ##
    // Draw Diagonals and Place Labels on Price Cross
    if show_diagonals1
        upperDiagonalLine = line.new(startTime, midValue, endTime, highValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines)
        lowerDiagonalLine = line.new(startTime, midValue, endTime, lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines)

        // Retrieve y-coordinates
        upperY := line.get_y1(upperDiagonalLine)
        lowerY := line.get_y1(lowerDiagonalLine)
        // Retrieve y-coordinates
        upperY1 := line.get_y2(upperDiagonalLine)
        lowerY1 := line.get_x2(lowerDiagonalLine)

        // Retrieve y-coordinates
        upperX := line.get_x1(upperDiagonalLine)
        lowerX := line.get_x1(lowerDiagonalLine)
        // Retrieve y-coordinates
        upperX1 := line.get_x2(upperDiagonalLine)
        lowerX1 := line.get_x2(lowerDiagonalLine)

        // // Place label when price crosses above the upper diagonal line
        // if ta.cross(close, upperY)
        //     label.new(bar_index, close, text="Price Crossed Above Diagonal", color=color.green, style=label.style_label_up)
            
        // // Place label when price crosses below the lower diagonal line
        // if lowerY
        //     label.new(bar_index, lowerY, text="Price Crossed Below Diagonal", color=color.red, style=label.style_label_down)

    if show_diagonals2
        array.push(lines, line.new(endTime, midValue, startTime, highValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
        array.push(lines, line.new(endTime, midValue, startTime, lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))

    // ... (remaining code)

    //## Horizontal mid start and end ##
    if show_midlines_type1
        array.push(lines, line.new((startTime + ((endTime - startTime) / 2)), lowValue, endTime, highValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
        array.push(lines, line.new((startTime + ((endTime - startTime) / 2)), lowValue, startTime, highValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))

    if show_midlines_type2        
        array.push(lines, line.new((startTime + ((endTime - startTime) / 2)), highValue, endTime, lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
        array.push(lines, line.new((startTime + ((endTime - startTime) / 2)), highValue, startTime, lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
    //Quarter lines
    if quarter
        sectionPriceInterval = ((highValue - lowValue) / 4)
        sectionTimeInterval = ((endTime - startTime) / 4)
        for i = 1 to 3
            array.push(lines, line.new(startTime, (lowValue + (sectionPriceInterval * i)), endTime, (lowValue + (sectionPriceInterval * i)), xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
            array.push(lines, line.new((startTime + (sectionTimeInterval * i)), highValue, (startTime + (sectionTimeInterval * i)), lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
    //Sixth lines
    if sixth
        sectionPriceInterval = ((highValue - lowValue) / 6)
        sectionTimeInterval = ((endTime - startTime) / 6)
        for i = 1 to 5
            array.push(lines, line.new(startTime, (lowValue + (sectionPriceInterval * i)), endTime, (lowValue + (sectionPriceInterval * i)), xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
            array.push(lines, line.new((startTime + (sectionTimeInterval * i)), highValue, (startTime + (sectionTimeInterval * i)), lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
    //Eighth lines
    if eighth
        sectionPriceInterval = ((highValue - lowValue) / 8)
        sectionTimeInterval = ((endTime - startTime) / 8)
        for i = 1 to 7
            array.push(lines, line.new(startTime, (lowValue + (sectionPriceInterval * i)), endTime, (lowValue + (sectionPriceInterval * i)), xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))
            array.push(lines, line.new((startTime + (sectionTimeInterval * i)), highValue, (startTime + (sectionTimeInterval * i)), lowValue, xloc = xloc.bar_time, style = line.style_dashed, color = insideLines, width = widthLines))

if barstate.islast
    highestValuePrincipal = getHighestValue(bars, barsFromStart)
    lowestValuePrincipal = getLowestValue(bars, barsFromStart)
    midValuePrincipal = lowestValuePrincipal + ((highestValuePrincipal - lowestValuePrincipal) / 2)
    intervalTime = end - start

    //Draw principal square
    drawSquares(start, end, highestValuePrincipal, lowestValuePrincipal, midValuePrincipal)
    //Right Square
    drawSquares(end, (end + intervalTime), highestValuePrincipal, lowestValuePrincipal, midValuePrincipal)
    //Top Right Square
    drawSquares(end, (end + intervalTime), (highestValuePrincipal + (highestValuePrincipal - lowestValuePrincipal)), highestValuePrincipal, (midValuePrincipal + (highestValuePrincipal - lowestValuePrincipal)))
    //Bottom Right Square
    drawSquares(end, (end + intervalTime), lowestValuePrincipal, lowestValuePrincipal - (highestValuePrincipal - lowestValuePrincipal), (midValuePrincipal - (highestValuePrincipal - lowestValuePrincipal)))
    //Right Right Square
    drawSquares((end + intervalTime), (end + (intervalTime * 2)), highestValuePrincipal, lowestValuePrincipal, midValuePrincipal)
    //Top Right Right Square
    drawSquares((end + intervalTime), (end + (intervalTime * 2)), (highestValuePrincipal + (highestValuePrincipal - lowestValuePrincipal)), highestValuePrincipal, (midValuePrincipal + (highestValuePrincipal - lowestValuePrincipal)))
    //Bottom Right Right Square
    drawSquares((end + intervalTime), (end + (intervalTime * 2)), lowestValuePrincipal, lowestValuePrincipal - (highestValuePrincipal - lowestValuePrincipal), (midValuePrincipal - (highestValuePrincipal - lowestValuePrincipal)))

Re: Already Converted TradingView Indicators to MT4 Indicators

548
PeterChan wrote: Sat Jun 29, 2024 11:54 am Can someone help to port the Trending RSI from TradingView to MT4.?

https://tw.tradingview.com/script/qe0D9 ... hartPrime/

I think this indicator is really good. It takes a new approach to RSI intended to provide all of the missing information that traditional RSI lacks. Questions such as "why does the price continue to decline even during an oversold period?" can be aided using the Trending RSI.
Image
To make the porting easier, I have already removed those not that useful feature from the code, e.g. the glowing effect of the line.

Code: Select all

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime

//@version=5
indicator("Trending RSI [ChartPrime]", max_bars_back = 5000, timeframe = "", timeframe_gaps = true)

// Declarations {

convolve(float[] weights, float[] kernel, int iterations)=>
    var float[] convolution = weights.copy()

    if iterations > 0
        if barstate.isfirst
            for iteration = 0 to iterations - 1
                float[] temp = array.new<float>()

                for i = 0 to convolution.size() + kernel.size() - 2
                    float sum = 0.0

                    for j = 0 to kernel.size() - 1
                        int index = i - j

                        if index >= 0 and index < convolution.size()
                            sum += convolution.get(index) * kernel.get(j)
                        else
                            continue

                    temp.push(sum)

                convolution := temp.copy()

    convolution

method truncate_weights(float[] weights, bool enable = true)=>
    if enable
        int max_idx = weights.indexof(weights.max())

        if max_idx > 0
            for i = 0 to weights.indexof(weights.max()) - 1
                weights.shift()
        else
            weights

    weights

binomia_ma(float source, int length, bool enable)=>
    float pre_filter = ta.sma(source, 2)
    float[] h = array.from(0.5, 0.5)
    float[] weights = convolve(h, h, length * 10 - 1).truncate_weights()

    if enable and not na(source)
        float sum = 0
        float weight = 0

        for i = 0 to math.min(weights.size() - 1, bar_index)
            float w = weights.get(i)
            weight += w
            sum += nz(pre_filter[i], nz(source[i])) * w

        sum/weight

    else
        float(na)

precalculate_phi_coefficients(simple int length, simple float phase)=>
    var float[] coefficients = array.new<float>(length)
    var float E = 0.0

    const float SQRT_PIx2  = math.sqrt(2.0 * math.pi)
    const float MULTIPLIER = -0.5 / 0.93
    var int   length_1 = length - 1
    var float length_2 = length * 0.52353
    if barstate.isfirst
        for int i=0 to length_1
            float alpha = (i + phase - length_2) * MULTIPLIER
            float  beta = 1.0 / (0.2316419 * math.abs(alpha) + 1.0)
            float   phi = (math.exp(math.pow(alpha, 2) * -0.5)
                          *-0.398942280) * beta *
                          ( 0.319381530  + beta *
                          (-0.356563782  + beta *
                          ( 1.781477937  + beta *
                          (-1.821255978  + beta 
                          * 1.330274429)))) + 1.011
            if alpha < 0.0
                phi := 1.0 - phi
            float weight = phi / SQRT_PIx2
            E += weight
            coefficients.set(i, weight)
    [coefficients, E]

phi_smoother(series float source, series float[] coefficients, series float E, simple float hf_ratio = 0.5)=>
    float sma2 = source * math.min(math.max(0.5, hf_ratio), 1) + nz(source[1], source) * math.max(math.min(0.5, 1 - hf_ratio), 0)
    int length = coefficients.size()
    if length > 1
        float W = 0.0
        for int i=0 to length - 1
            float weight = coefficients.get(i)
            W  += weight * sma2[i]
        W / E
    else 
        source

rma(float source = close, float length = 9)=>
    float alpha = 1 / length
    var float smoothed = na
    smoothed := alpha * source + (1 - alpha) * nz(smoothed[1])

rsi(float source, int length)=> 
    float up = math.max(source - source[1], 0)
    float down = math.max(source[1] - source, 0)
    float rs = rma(up, length) / rma(down, length)
    float rsi = 100 - 100 / (1 + rs)
    rsi

reverse_rsi(series float source, simple int length, float value)=>
    float src = (source - ta.rma(source, length)) / (length / 2)
    float alpha = 1 / length
    float average_up_count = 0.0
    float average_down_count = 0.0

    average_up_count := src > src[1] 
                                     ? alpha * (src - src[1]) + (1 - alpha) * nz(average_up_count[1], 1) 
                                     : (1 - alpha) * nz(average_up_count[1], 1)

    average_down_count := src > src[1] 
                                     ? (1 - alpha) * nz(average_down_count[1], 1)
                                     : alpha * (src[1] - src) + (1 - alpha) * nz(average_down_count[1], 1)

    float reversed_value = (length - 1) * (average_down_count * value / (100 - value) - average_up_count)
    float reverse_rsi = reversed_value >= 0 ? src + reversed_value : src + reversed_value * (100 - value) / value

// }

// Inputs {

const string group_1 = "Settings"
const string top_value_tip = "Pick what RSI value you want the top range to represent."
const string bottom_value_tip = "Pick what RSI value you want the bottom range to represent"

float source = input.source(close, "Source", group = group_1)
int length = input.int(14, "Length", minval = 1, group = group_1)
float top_value = input.float(70, "Top Range", minval = 50, maxval = 99, tooltip = top_value_tip, group = group_1)
float bottom_value = input.float(30, "Bottom Range", minval = 1, maxval = 50, tooltip = bottom_value_tip, group = group_1) 
bool ma_enable = input.bool(false, "MA Length        ", inline = "MA", group = group_1)
int ma_length = input.int(30, "", minval = 0, maxval = 100, inline = "MA", group = group_1)

const string group_2 = "Smoothing"
const string smoothing_tip = "Adjusts the period of the filter."
const string speed_tip = "Adjusts the responsiveness of the filter."
const string hf_tip = "Adjusts the pre smoothing of the filter." + "\n" + "1 is no pre smoothing while 0.5 is maximum pre smoothing."

int left = input.int(15, "Look Left", minval = 1, tooltip = left_tip, group = group_3)
int right = input.int(15, "Look Right", minval = 1, tooltip = right_tip, group = group_3)
int lower_range = input.int(5, "Lower Range", minval = 1, tooltip = lower_range_tip, group = group_3)
int upper_range = input.int(60, "Upper Range", minval = 1, tooltip = upper_range_tip, group = group_3)
string divergence_label = input.string("Line", "Divergence Drawings", ["Line", "Label", "Line and Label"], group = group_3)
bool bullish_divergence = false // input.bool(false, "Enable Bullish Divergence", group = group_3)
bool bearish_divergence = false // input.bool(false, "Enable Bearish Divergence", group = group_3)

const string group_4 = "Color"
bool glow = false // input.bool(true, "Glow", group = group_4)
color rsi_color = input.color(#ffffff, "RSI", group = group_4)
color ma_color = input.color(#FFEE54, "MA Color", group = group_4)
color bg_color = input.color(#7E57C21A, "BG", group = group_4)
color top_color = input.color(#a222e283, "Upper Range", group = group_4)
color bottom_color = input.color(#e5b60c83, "Lower Range", group = group_4)
color center_bullish_up_color = input.color(#21a110, "Center", inline = "Center", group = group_4)
color center_bullish_down_color = input.color(#005e05, "", inline = "Center", group = group_4)
color center_bearish_up_color = input.color(#FCA0A9, "", inline = "Center", group = group_4)
color center_bearish_down_color = input.color(#FB3E38, "", inline = "Center", group = group_4)
color bullish_divergence_color = input.color(#00B374, "Bullish Divergence", group = group_4)
color bearish_divergence_color = input.color(#F03042, "Bearish Divergence", group = group_4)
color divergence_text_color = input.color(#FEFEFE, "Divergence Text", group = group_4)
color zero_line_color = input.color(#9E9E9E, "0 Line Color", group = group_4)

// }

// Calculations {

[smoothing_coefficients, smoothing_E] = precalculate_phi_coefficients(smoothing, smoothing_phase)
[boundary_coefficients, boundary_E] = precalculate_phi_coefficients(boundary_smoothing, boundary_smoothing_phase)

float top = phi_smoother(reverse_rsi(source, length, top_value), boundary_coefficients, boundary_E, boundary_hf)
float bottom = phi_smoother(reverse_rsi(source, length, bottom_value), boundary_coefficients, boundary_E, boundary_hf)
float center = phi_smoother(reverse_rsi(source, length, 50), smoothing_coefficients, smoothing_E, smoothing_hf)

float rsi = phi_smoother(reverse_rsi(source, length, rsi(source, length)), smoothing_coefficients, smoothing_E, smoothing_hf)
float ma = binomia_ma(rsi, ma_length, ma_enable)

float center_delta = center - center[1]

// }

// Color Calculations {

color center_color = center >= 0 
                                 ? (center_delta > 0 ? center_bullish_up_color : center_bullish_down_color) 
                                 : (center_delta > 0 ? center_bearish_up_color : center_bearish_down_color)

color top_glow_color_max = color.new(top_color, 80)
color bottom_glow_color_max = color.new(bottom_color, 80)
color top_glow_color_min = color.new(top_color, 100)
color bottom_glow_color_min = color.new(bottom_color, 100)

color zero_line_solid = color.new(zero_line_color, 80)
color zero_line_dashed = color.new(zero_line_color, 50)

// }

// Plotting {
plot(0, "0 Line", zero_line_solid, display = display.pane)
top_band = plot(top, "Upper Range", top_color)
bottom_band = plot(bottom, "Lower Range", bottom_color)
fill(top_band, bottom_band, bg_color, "RSI Background Fill")
plot(center, "Center", center_color,2)
plot(ma, "MA", ma_color, display = ma_enable ? display.all : display.pane)
plot(rsi, "RSI", rsi_color)
// }

This indicator looks really promising.
Is anyone able to convert it to MT4?

All the best to you all. :)


Who is online

Users browsing this forum: andrei-1, doolfrews, Google Images [Bot], LittleCaro, Musariri Ndlovu, thomdel, Tur005, Yandex [Bot] and 95 guests