//@version=6
indicator('Market Magnet Algo - Indicator ', overlay = true, max_bars_back = 5000,
max_labels_count = 500, max_lines_count = 500)
const bool DEBUG = false
const float epsilon = 0.02 / 100.0
const int showLastXPivots = 50
// Auto Trendline
var int TYPE_UP = 1
var int TYPE_DOWN = -1
var string LINE_WIDTH1_STR = 'Width 1'
var string LINE_WIDTH2_STR = 'Width 2'
_get_width(string str_input) =>
switch str_input
LINE_WIDTH1_STR => 1
LINE_WIDTH2_STR => 2
var string GROUP_FRACT = 'Fractals'
var color col_hl = input.color(color.blue, title = 'Plot:', inline = 'plot_low',
group = GROUP_FRACT)
var bool show_hl = input.bool(true, title = 'HL', inline = 'plot_low', group =
GROUP_FRACT)
var color col_ll = input.color(color.gray, title = ', Plot:', inline = 'plot_low',
group = GROUP_FRACT)
var bool show_ll = input.bool(false, title = 'LL', inline = 'plot_low', group =
GROUP_FRACT)
var color col_lh = input.color(color.red, title = 'Plot:', inline = 'plot_high',
group = GROUP_FRACT)
var bool show_lh = input.bool(false, title = 'LH', inline = 'plot_high', group =
GROUP_FRACT)
var color col_hh = input.color(color.gray, title = ', Plot:', inline = 'plot_high',
group = GROUP_FRACT)
var bool show_hh = input.bool(false, title = 'HH', inline = 'plot_high', group =
GROUP_FRACT)
var string GROUP_ATL = 'Auto trendlines'
var string subgroup1 = 'recent line'
var color ln_col_recent = input.color(color.new(color.purple, 0), title = 'Latest
Trendline', group = GROUP_ATL, inline = subgroup1)
var int lnwidth_recent = _get_width(input.string(LINE_WIDTH1_STR, options =
[LINE_WIDTH1_STR, LINE_WIDTH2_STR], title = '', inline = subgroup1, group =
GROUP_ATL))
var string subgroup2 = 'historical line'
var color ln_col_prev = input.color(color.new(color.gray, 50), title = 'Historical
Trendline', group = GROUP_ATL, inline = subgroup2)
var int lnwidth_prev = _get_width(input.string(LINE_WIDTH1_STR, options =
[LINE_WIDTH1_STR, LINE_WIDTH2_STR], title = '', inline = subgroup2, group =
GROUP_ATL))
var bool show_historical = input.bool(false, title = 'Show Historical Lines', group
= GROUP_ATL)
var int max_tl = input.int(1, title = 'Max pair of lines', maxval = 250, minval =
1, group = GROUP_ATL) * 2
var string _str_extend = input.string('Right', options = ['Right', 'Both ways'],
title = 'Which way to extend lines', group = GROUP_ATL)
var string str_extend = _str_extend == 'Both ways' ? extend.both : extend.right
var bool show_crosses = input.bool(false, title = 'Show crosses', tooltip =
'Instances when closing price of a bar has crossed lower/upper trendlines', group =
GROUP_ATL)
type fractal
int up_or_down = na
int xloc = na
float yloc = na
int xloc_parent = na
float yloc_parent = na
var array<fractal> arr_fract = array.new<fractal>()
var array<line> arr_ln_up = array.new_line()
var array<line> arr_ln_dn = array.new_line()
init_fractal(int fract_type, int xloc, float yloc, int xparent, float yparent) =>
f = fractal.new()
f.up_or_down := fract_type
f.xloc := xloc
f.yloc := yloc
f.xloc_parent := xparent
f.yloc_parent := yparent
ln = line.new(xloc, yloc, xparent, yparent, xloc.bar_index, str_extend, color =
ln_col_recent, style = line.style_dashed, width = lnwidth_recent)
if f.up_or_down == TYPE_UP
array.unshift(arr_ln_up, ln)
else if f.up_or_down == TYPE_DOWN
array.unshift(arr_ln_dn, ln)
array.unshift(arr_fract, f)
f
drop_and_roll(fractal f) =>
arr_ln = f.up_or_down == TYPE_UP ? arr_ln_up : f.up_or_down == TYPE_DOWN ?
arr_ln_dn : na
if array.size(arr_ln) > 1
if show_historical
line.set_color(array.get(arr_ln, 1), ln_col_prev)
line.set_width(array.get(arr_ln, 1), lnwidth_prev)
else
line.delete(array.get(arr_ln, 1))
while array.size(arr_ln) > math.floor(max_tl / 2)
line.delete(array.pop(arr_ln))
draw_trendline(fract_type, x2, y2, x1, y1) =>
f = init_fractal(fract_type, x2, y2, x1, y1)
drop_and_roll(f)
float ph = ta.pivothigh(10, 10)[1]
bool upfract = not na(ph)
float pl = ta.pivotlow(10, 10)[1]
bool downfract = not na(pl)
alertcondition(not na(ph) or not na(pl), title = 'New trendline formed', message =
'New trendline formed')
var float recent_dn1 = na
var int i_recent_dn1 = na
var float recent_up1 = na
var int i_recent_up1 = na
var float recent_dn2 = na
var int i_recent_dn2 = na
var float recent_up2 = na
var int i_recent_up2 = na
if downfract
recent_dn2 := recent_dn1
i_recent_dn2 := i_recent_dn1
recent_dn1 := low[11]
i_recent_dn1 := bar_index - 11
draw_trendline(TYPE_DOWN, i_recent_dn2, recent_dn2, i_recent_dn1, recent_dn1)
if upfract
recent_up2 := recent_up1
i_recent_up2 := i_recent_up1
recent_up1 := high[11]
i_recent_up1 := bar_index - 11
draw_trendline(TYPE_UP, i_recent_up2, recent_up2, i_recent_up1, recent_up1)
// ~~ Tooltips {
t1 = 'The \'Period\' setting in the indicator determines the number of bars used to
identify pivot highs and lows. Increasing this value leads to fewer but more
significant pivot points, as it considers a wider range of data. Decreasing it
results in more frequent pivot points but with potentially less significance,
suitable for short-term analysis.'
t2 = 'The \'Pivot Surrounding\' or \'candles\' setting defines the number of
candles analyzed around each pivot point to identify bullish or bearish patterns.
Increasing this value extends the analysis range, possibly capturing more patterns
but including less significant ones. Decreasing the value focuses on a narrower
range, potentially highlighting more significant trade setups but missing broader
patterns. This setting can be adjusted based on trading style: smaller numbers for
short-term trades and larger numbers for broader market analysis.'
//
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
//ProPivotTrader
text_R7 = 'Ultimate Target'
text_R6 = 'Secondary Target'
text_R5 = 'Primary Target'
text_R4 = 'Key Resistance'
text_R35 = 'Upper Reversal'
text_R3 = 'Lower Reversal'
text_R3R35 = 'Reversal Band'
text_S7 = 'Ultimate Target'
text_S6 = 'Secondary Target'
text_S5 = 'Primary Target'
text_S4 = 'Key Support'
text_S35 = 'Lower Reversal'
text_S3 = 'Upper Reversal'
text_S3S35 = 'Reversal Band'
t_d = 'D'
t_w = 'W'
t_m = 'M'
t_q = '3M'
t_y = '12M'
t_d_lt = '1440'
tooltip_enable_indicator = 'Toggle the display of pivot levels, including targets,
support/resistance, and reversal zones for your chosen timeframe.'
//***Start of local functions definition***
draw_line(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
dline = line.new(x1 = _x1, y1 = _y1, x2 = _x2, y2 = _y2, xloc = _xloc, extend =
_extend, color = _color, style = _style, width = _width)
line.delete(dline[1])
draw_box(_left, _top, _right, _bottom, _color, _width, _style, _extend, _xloc,
_bgcolor) =>
dbox = box.new(left = _left, top = _top, right = _right, bottom = _bottom,
border_color = _color, border_width = _width, border_style = _style, extend =
_extend, xloc = _xloc, bgcolor = _bgcolor)
box.delete(dbox[1])
draw_label(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size,
_textalign, _tooltip) =>
dlabel = label.new(x = _x, y = _y, text = _text, xloc = _xloc, yloc = _yloc,
color = _color, style = _style, textcolor = _textcolor, size = _size, textalign =
_textalign, tooltip = _tooltip)
label.delete(dlabel[1])
//If security is futures - replace the ticker with continuous contract
tickerid_func() =>
tickerid = syminfo.prefix + ':' + syminfo.tickerid
if syminfo.type == 'futures'
tickerid := syminfo.prefix + ':' + syminfo.root + '1!'
tickerid
//Workaround to disable color management on the standard tab Style for plots
transp_func() =>
transp_0 = 0
transp_0
//Timeframe to request data
t_func(t, use_last_traded) =>
t_temp = t
if use_last_traded
if t == t_d
t_temp := t_d_lt
t_temp
t_temp
//***End of local functions definition***
//***Start of Inputs***
var enable_indicator = input.bool(defval = true, title = 'Show Pivot Levels',
tooltip = tooltip_enable_indicator)
var labels_enabled = input.bool(defval = true, title = 'Display Labels')
var show_ema = input.bool(defval = false, title = 'Show 61 EMA', tooltip = 'Display
the 61-period EMA used for signal filtering')
var t = input.string(title = 'Pivot Timeframe', defval = t_d, options = [t_d, t_w,
t_m, t_q, t_y])
// Hard-coded defaults for removed inputs
var use_last_traded = false
var rolling_pivots = false
var emojis = false
var plot_history = false
var color_R7 = input.color(defval = color.new(color.green, 0), title = text_R7,
group = 'Colors')
var color_R6 = input.color(defval = color.new(color.green, 0), title = text_R6,
group = 'Colors')
var color_R5 = input.color(defval = color.new(color.green, 0), title = text_R5,
group = 'Colors')
var color_R4 = input.color(defval = color.new(color.green, 0), title = text_R4,
group = 'Colors')
var color_R35 = input.color(defval = color.new(color.red, 80), title = text_R3R35,
group = 'Colors')
var color_S7 = input.color(defval = color.new(color.red, 0), title = text_S7, group
= 'Colors')
var color_S6 = input.color(defval = color.new(color.red, 0), title = text_S6, group
= 'Colors')
var color_S5 = input.color(defval = color.new(color.red, 0), title = text_S5, group
= 'Colors')
var color_S4 = input.color(defval = color.new(color.red, 0), title = text_S4, group
= 'Colors')
var color_S35 = input.color(defval = color.new(color.green, 80), title =
text_S3S35, group = 'Colors')
var color_ema = input.color(defval = color.new(color.blue, 0), title = '61 EMA',
group = 'Colors')
//***End of Inputs***
//Get data
shigh = request.security(tickerid_func(), t_func(t, use_last_traded), high[1],
barmerge.gaps_off, barmerge.lookahead_on)
slow = request.security(tickerid_func(), t_func(t, use_last_traded), low[1],
barmerge.gaps_off, barmerge.lookahead_on)
sclose = request.security(tickerid_func(), rolling_pivots ? t_func(t_d,
use_last_traded) : t_func(t, use_last_traded), close[1], barmerge.gaps_off,
barmerge.lookahead_on)
start_time = request.security(tickerid_func(), t_func(t, use_last_traded),
time_close[1], barmerge.gaps_off, barmerge.lookahead_on)
r = shigh - slow
//Calculate pivots
R6 = shigh / slow * sclose //Bull Secondary Target
R4 = sclose + r * (1.1 / 2) //Bear Key Resistance
R3 = sclose + r * (1.1 / 4) //Bear Lower Reversal
R5 = R4 + 1.168 * (R4 - R3) //Bull Primary Target
R35 = R4 - (R4 - R3) / 2 //Bear Upper Reversal
R7 = R6 + 1.618 * (R4 - R3) //Bull Ultimate Target
S3 = sclose - r * (1.1 / 4) //Bull Upper Reversal
S4 = sclose - r * (1.1 / 2) //Bull Key Support
S6 = sclose - (R6 - sclose) //Bear Secondary Target
S35 = S3 - (S3 - S4) / 2 //Bull Lower Reversal
S5 = S4 - 1.168 * (S3 - S4) //Bear Primary Target
S7 = S6 - 1.618 * (S3 - S4) //Bear Ultimate Target
//*********************
//***Start of plotting***
//Decide if we can show the chart:
//Daily levels should be visible on intraday chart only,
//Weekly levels should be visible on daily chart and lower,
//And so on...
var show_chart = false
if timeframe.isintraday
show_chart := true
show_chart
else if timeframe.isdaily
show_chart := switch t
t_w => true
t_m => true
t_q => true
t_y => true
show_chart
else if timeframe.isweekly
show_chart := switch t
t_m => true
t_q => true
t_y => true
show_chart
else if timeframe.ismonthly
if timeframe.period == t_m
show_chart := switch t
t_q => true
t_y => true
show_chart
else if timeframe.period == t_q and t == t_y
show_chart := true
show_chart
if show_chart == false
runtime.error('Pivot timeframe is too low for this chart. Please lower the
chart\'s resolution or choose a higher timeframe for the pivots.')
//Plot current period only
if show_chart and enable_indicator
draw_line(start_time, R7, time, R7, xloc.bar_time, extend.none, color_R7,
line.style_solid, 2) //Bull Ultimate Target
draw_line(start_time, R6, time, R6, xloc.bar_time, extend.none, color_R6,
line.style_solid, 2) //Bull Secondary Target
draw_line(start_time, R5, time, R5, xloc.bar_time, extend.none, color_R5,
line.style_solid, 2) //Bull Primary Target
draw_line(start_time, R4, time, R4, xloc.bar_time, extend.none, color_R4,
line.style_solid, 2) //Bear Key Resistance
draw_line(start_time, R3, time, R3, xloc.bar_time, extend.none,
color.new(color_R35, transp_func()), line.style_solid, 2) //Bear Lower Reversal
draw_line(start_time, R35, time, R35, xloc.bar_time, extend.none,
color.new(color_R35, transp_func()), line.style_solid, 2) //Bear Upper Reversal
draw_box(start_time, R35, time, R3, color.new(color_R35, 100), 1,
line.style_solid, extend.none, xloc.bar_time, color_R35) //Bear Reversal Band
draw_line(start_time, S3, time, S3, xloc.bar_time, extend.none,
color.new(color_S35, transp_func()), line.style_solid, 2) //Bull Upper Reversal
draw_line(start_time, S35, time, S35, xloc.bar_time, extend.none,
color.new(color_S35, transp_func()), line.style_solid, 2) //Bull Lower Reversal
draw_box(start_time, S3, time, S35, color.new(color_S35, 100), 1,
line.style_solid, extend.none, xloc.bar_time, color_S35) //Bull Reversal Band
draw_line(start_time, S4, time, S4, xloc.bar_time, extend.none, color_S4,
line.style_solid, 2) //Bull Key Support
draw_line(start_time, S5, time, S5, xloc.bar_time, extend.none, color_S5,
line.style_solid, 2) //Bear Primary Target
draw_line(start_time, S6, time, S6, xloc.bar_time, extend.none, color_S6,
line.style_solid, 2) //Bear Secondary Target
draw_line(start_time, S7, time, S7, xloc.bar_time, extend.none, color_S7,
line.style_solid, 2) //Bear Ultimate Target
//***End of plotting***
//*********************
//*********************
//***Start of alerts***
bool triggerBullReversal = close < S3
bool triggerBearReversal = close > R3
bool triggerBullLastStand = close < S4
bool triggerBearLastStand = close > R4
alertcondition(condition = triggerBullReversal, title = 'Bull Reversal Band
Reached', message = 'Price reached Bullish Reversal Band')
alertcondition(condition = triggerBearReversal, title = 'Bear Reversal Band
Reached', message = 'Price reached Bearish Reversal Band')
alertcondition(condition = triggerBullLastStand, title = 'Bull Key Support
Breached', message = 'Price breached Bullish Key Support')
alertcondition(condition = triggerBearLastStand, title = 'Bear Key Resistance
Breached', message = 'Price breached Bearish Key Resistance')
//***End of alerts***
//*********************
//*********************
//***Start of Labels***
bull = 'Bull '
bear = 'Bear '
label_R7 = ''
label_R6 = ''
label_R5 = ''
label_R4 = ''
label_R3 = ''
label_R35 = ''
label_S7 = ''
label_S6 = ''
label_S5 = ''
label_S4 = ''
label_S3 = ''
label_S35 = ''
//Convert 3M/12M to Q/Y, 24H to D for labels
label_t = t + ' '
if t == t_q
label_t := 'Q '
label_t
else if t == t_y
label_t := 'Y '
label_t
else if t == t_d_lt
label_t := 'D '
label_t
if labels_enabled and enable_indicator and show_chart
label_R7 := str.tostring(math.round_to_mintick(R7))
label_R6 := str.tostring(math.round_to_mintick(R6))
label_R5 := str.tostring(math.round_to_mintick(R5))
label_R4 := str.tostring(math.round_to_mintick(R4))
label_R35 := str.tostring(math.round_to_mintick(R35))
label_R3 := str.tostring(math.round_to_mintick(R3))
label_S7 := str.tostring(math.round_to_mintick(S7))
label_S6 := str.tostring(math.round_to_mintick(S6))
label_S5 := str.tostring(math.round_to_mintick(S5))
label_S4 := str.tostring(math.round_to_mintick(S4))
label_S35 := str.tostring(math.round_to_mintick(S35))
label_S3 := str.tostring(math.round_to_mintick(S3))
label_S3
string_R7 = ' (' + label_R7 + ')'
string_R6 = ' (' + label_R6 + ')'
string_R5 = ' (' + label_R5 + ')'
string_R4 = ' (' + label_R4 + ')'
string_R3R35 = ' (' + label_R3 + ' - ' + label_R35 + ')'
string_S7 = ' (' + label_S7 + ')'
string_S6 = ' (' + label_S6 + ')'
string_S5 = ' (' + label_S5 + ')'
string_S4 = ' (' + label_S4 + ')'
string_S3S35 = ' (' + label_S3 + ' - ' + label_S35 + ')'
//This period labels
if show_chart and labels_enabled and enable_indicator
draw_label(bar_index, R7, label_t + bull + text_R7 + string_R7, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_R7, transp_func()), size.normal, text.align_left, '') //Bull
Ultimate Target
draw_label(bar_index, R6, label_t + bull + text_R6 + string_R6, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_R6, transp_func()), size.normal, text.align_left, '') //Bull
Secondary Target
draw_label(bar_index, R5, label_t + bull + text_R5 + string_R5, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_R5, transp_func()), size.normal, text.align_left, '') //Bull
Primary Target
draw_label(bar_index, R4, label_t + bear + text_R4 + string_R4, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_R4, transp_func()), size.normal, text.align_left, '') //Bear Key
Resistance
draw_label(bar_index, R3 + (R35 - R3) / 2, label_t + bear + text_R3R35 +
string_R3R35, xloc.bar_index, yloc.price, color.new(color.white, 100),
label.style_label_left, color.new(color_R35, transp_func()), size.normal,
text.align_left, '') //Bear Reversal Band
draw_label(bar_index, S3 - (S3 - S35) / 2, label_t + bull + text_S3S35 +
string_S3S35, xloc.bar_index, yloc.price, color.new(color.white, 100),
label.style_label_left, color.new(color_S35, transp_func()), size.normal,
text.align_left, '') //Bull Reversal Band
draw_label(bar_index, S4, label_t + bull + text_S4 + string_S4, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_S4, transp_func()), size.normal, text.align_left, '') //Bull Key
Support
draw_label(bar_index, S5, label_t + bear + text_S5 + string_S5, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_S5, transp_func()), size.normal, text.align_left, '') //Bear
Primary Target
draw_label(bar_index, S6, label_t + bear + text_S6 + string_S6, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_S6, transp_func()), size.normal, text.align_left, '') //Bear
Secondary Target
draw_label(bar_index, S7, label_t + bear + text_S7 + string_S7, xloc.bar_index,
yloc.price, color.new(color.white, 100), label.style_label_left,
color.new(color_S7, transp_func()), size.normal, text.align_left, '') //Bear
Ultimate Target
//---------------------------------------------------------------------------------
--------------------------------------------------------------------------------
// Volatility Range Functions
//---------------------------------------------------------------------------------
--------------------------------------------------------------------------------
vol_range(input_data, multiplier, period) =>
window_size = period * 2 - 1
vol_avg = ta.ema(math.abs(input_data - input_data[1]), period)
adjusted_vol = ta.ema(vol_avg, window_size) * multiplier
vol_range = adjusted_vol
vol_range
vol_filter(input_data, range_val, period) =>
v_range = range_val
var v_filtered = array.new_float(2, input_data)
array.set(v_filtered, 1, array.get(v_filtered, 0))
if input_data - v_range > array.get(v_filtered, 1)
array.set(v_filtered, 0, input_data - v_range)
if input_data + v_range < array.get(v_filtered, 1)
array.set(v_filtered, 0, input_data + v_range)
filtered_val = array.get(v_filtered, 0)
upper_band = filtered_val + v_range
lower_band = filtered_val - v_range
vol_filter = filtered_val
[upper_band, lower_band, vol_filter]
// Inputs
periodsInput = input.int(title = 'ATR Period', defval = 8, minval = 1)
multiplierInput = input.float(title = 'ATR Multiplier', step = 0.1, defval = 3.0)
src = input.source(hl2, title = 'Source')
changeATR = input.bool(title = 'Change ATR Calculation Method?', defval = false)
showsignals = input.bool(title = 'Show Buy/Sell Signals?', defval = true)
highlighting = input.bool(title = 'Highlighter On/Off?', defval = true)
autoTimeframe = input.bool(title = 'Automatically Adjust Indicator Timeframe?',
defval = true)
manualResolution = input.timeframe(title = 'Manual Indicator Timeframe', defval =
'60') // Default to 1-hour timeframe
// Determine ATR Period and Multiplier based on timeframe
Periods = timeframe.isintraday ? timeframe.multiplier == 1 ? 7 :
timeframe.multiplier == 3 ? 14 : timeframe.multiplier == 5 ? 14 :
timeframe.multiplier == 15 ? 14 : timeframe.multiplier == 60 ? 8 :
timeframe.multiplier == 240 ? 6 : timeframe.multiplier == 720 ? 8 : periodsInput :
periodsInput
Multiplier = timeframe.isintraday ? timeframe.multiplier == 1 ? 4 :
timeframe.multiplier == 3 ? 3.5 : timeframe.multiplier == 5 ? 4.0 :
timeframe.multiplier == 15 ? 4.0 : timeframe.multiplier == 60 ? 3.0 :
timeframe.multiplier == 60 ? 2 : timeframe.multiplier == 720 ? 3 :
multiplierInput : multiplierInput
// Determine the resolution to use
resolution = autoTimeframe ? timeframe.period : manualResolution
// Define the time frame for the Alpha Trend line
res = resolution == '60' ? '240' : '1440' //res = input("240", title="Time Frame")
// Technical calculations
tr = request.security(syminfo.tickerid, resolution, ta.tr)
atr2 = ta.sma(tr, Periods)
atr = changeATR ? request.security(syminfo.tickerid, resolution, ta.atr(Periods)) :
atr2
up = src - Multiplier * atr
up1 = na(up[1]) ? up : up[1]
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = na(dn[1]) ? dn : dn[1]
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
avgVolume = request.security(syminfo.tickerid, resolution, ta.sma(volume, Periods))
emaValue = request.security(syminfo.tickerid, resolution, ta.sma(close, 30))
// Calculate the 50-period EMA on 4-hour data
emaValue_4h = request.security(syminfo.tickerid, res, ta.ema(close, 50))
// Calculate the 30-period SMA on 4-hour data
smaValue_4h = request.security(syminfo.tickerid, res, ta.sma(close, 30))
// This part of the code ensures that the calculations are based on the 4-hour time
frame
alphaTrend_4h = (emaValue_4h + smaValue_4h) / 2
// Define buy and sell volumes
buyVolume = request.security(syminfo.tickerid, resolution, volume * (close > open ?
1 : 0))
sellVolume = request.security(syminfo.tickerid, resolution, volume * (close <
open ? 1 : 0))
// Calculate average buy and sell volumes
avgBuyVolume = request.security(syminfo.tickerid, resolution, ta.ema(buyVolume,
Periods))
avgSellVolume = request.security(syminfo.tickerid, resolution, ta.ema(sellVolume,
Periods))
// Trend determination
var trend = 1
trend := na(trend[1]) ? trend : trend[1]
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend
// Define trend color
trendColor = trend == 1 ? close > alphaTrend_4h ? #00dd99 : color.orange : close <
alphaTrend_4h ? #ff5252 : color.orange
// Define trend change condition
trendChange = trend != trend[1]
// Define standard and power signals
buySignal = ta.crossover(trend, -1)
sellSignal = ta.crossunder(trend, 1)
// RSI, MACD, and OBV calculations
rsiValue = request.security(syminfo.tickerid, resolution, ta.rsi(close, 14))
[macdLine, signalLine, hist] = request.security(syminfo.tickerid, resolution,
ta.macd(close, 12, 26, 9))
obvFunc(closeVal, vol) =>
var float obvVar = 0.0
obvVar := na(obvVar[1]) ? vol : closeVal > closeVal[1] ? obvVar[1] + vol :
closeVal < closeVal[1] ? obvVar[1] - vol : obvVar[1]
obvVar
obvValue = request.security(syminfo.tickerid, resolution, obvFunc(close, volume))
powerBuySignal = buyVolume > 1.95 * avgBuyVolume and close > close[1] * 1.02 and
close > ta.highest(high, 10)[1] and macdLine > signalLine and macdLine >
macdLine[1] * 1 and obvValue > obvValue[1] * 1.05 and ta.ema(close, 20) >
ta.ema(close, 50) and ta.ema(close, 50) > ta.ema(close, 200)
powerSellSignal = sellVolume > 2.25 * avgSellVolume and close < close[1] and close
< ta.lowest(low, 1) and high < high[1] and rsiValue < rsiValue[1] and rsiValue > 30
and macdLine < 0 and macdLine < macdLine[1] and macdLine < signalLine and macdLine
< signalLine[2] and obvValue < obvValue[1] and hist < 0
// Continuous trend line
continuousLine = plot(trend == 1 ? up : dn, title = 'Trend Line', color =
trendColor, linewidth = 1)
// Highlighting configuration with eye-catching contrast colors
bullColor = color.new(color.lime, 85) // Bright Green
bearColor = color.new(color.red, 85) // Bright Red
neutralColor = color.new(color.blue, 85) // Royal Blue
fillColor = trend == 1 ? close > alphaTrend_4h ? bullColor : neutralColor : close <
alphaTrend_4h ? bearColor : neutralColor
// Apply background highlight
fill(continuousLine, plot(close, color = na, display = display.none), title =
'Trend Highlight', color = fillColor)
// Inputs
len = input.int(25, 'Trend Period')
tgt = input.int(0, 'Adjust Targets')
ts_period = input.int(14, 'Trend Strength Period', minval = 1)
ts_threshold = input.int(20, 'Trend Strength Threshold', minval = 0, maxval = 100)
// Variables
var bool dir = false
float dir_val = na
// Colors
color bull_color = #b2ebf2 // Light cyan for targets
color bear_color = #f48fb1 // Light pink for SL
// ATR calculation
float atr_val = ta.sma(ta.atr(200), 200) * 0.75
// Moving averages
float ma_hi = ta.sma(high, len) + atr_val
float ma_lo = ta.sma(low, len) - atr_val
// Custom Trend Strength calculation (formerly ADX)
f_plusDM() =>
math.max(high - high[1], 0)
f_minusDM() =>
math.max(low[1] - low, 0)
float plusDM = f_plusDM()
float minusDM = f_minusDM()
float tr_val = ta.tr(true)
float ts_plusDI = 100 * ta.rma(plusDM, ts_period) / ta.rma(tr, ts_period)
float ts_minusDI = 100 * ta.rma(minusDM, ts_period) / ta.rma(tr, ts_period)
float ts_dx = 100 * math.abs(ts_plusDI - ts_minusDI) / (ts_plusDI + ts_minusDI)
float ts_value = ta.rma(ts_dx, ts_period)
bool strong_trend = ts_value >= ts_threshold
// UDT for lines and labels
type DirTargets
array<line> lns
array<label> lbls
// Initialize
var DirTargets bulls = DirTargets.new(array.new_line(), array.new_label())
var DirTargets bears = DirTargets.new(array.new_line(), array.new_label())
// Trend direction with Trend Strength only
bool crossover_condition = ta.crossover(close, ma_hi) and barstate.isconfirmed and
strong_trend
bool crossunder_condition = ta.crossunder(close, ma_lo) and barstate.isconfirmed
and strong_trend
if crossover_condition
dir := true
dir
if crossunder_condition
dir := false
dir
dir_val := switch
dir => ma_lo
not dir => ma_hi
dir_clr = dir ? bull_color : not dir ? bear_color : na
bool sig_bull = ta.change(dir) and not dir[1] and strong_trend
bool sig_bear = ta.change(dir) and dir[1] and strong_trend
pl0 = plot(hl2, display = display.none, editable = false)
// Buy/Sell signals
float bull_sig = sig_bull ? low - atr_val * 1.5 : na
float bear_sig = sig_bear ? high + atr_val * 1.5 : na
plotshape(bull_sig, title = 'Buy', style = shape.labelup, location =
location.absolute, color = color.new(color.green, 0), text = '🟢', textcolor =
color.white, size = size.tiny)
plotshape(bear_sig, title = 'Sell', style = shape.labeldown, location =
location.absolute, color = color.new(color.red, 0), text = '🔴', textcolor =
color.white, size = size.tiny)
// Alert conditions (still can include emojis if you like)
alertcondition(sig_bull, title = 'Buy Signal', message = '🟢🚀 BUY signal detected')
alertcondition(sig_bear, title = 'Sell Signal', message = '⚡SELL signal detected')
// Input Groups
var string atr_settings = '════════ ATR Settings ════════'
var string score_settings = '════════ Dynamic Score Settings ════════'
var string bar_coloring = '════════ Bar Coloring ════════'
// Descriptions for inputs (Tooltips)
tooltip_atr_length = 'Length of the Average True Range (ATR) used to calculate the
Supertrend bands. A higher length will make the Supertrend smoother.'
tooltip_atr_multiplier = 'Multiplier applied to the ATR value to calculate the
Supertrend bands. Increasing the multiplier will widen the bands, making trend
changes less frequent.'
tooltip_window_length = 'The length of the window over which the dynamic score is
calculated. A longer window will consider more data points, resulting in a slower
but more stable score.'
tooltip_uptrend_threshold = 'Threshold value above which an uptrend is detected.
Increase to make trend signals less sensitive.'
tooltip_downtrend_threshold = 'Threshold value below which a downtrend is detected.
Decrease to make trend signals less sensitive.'
tooltip_bar_coloring = 'Enable or disable bar coloring based on the detected trend
direction.'
tooltip_bg_coloring = 'Enable or disable background coloring based on trend
direction.'
// ATR Settings
atr_length = input.int(14, 'ATR Length', group = atr_settings, tooltip =
tooltip_atr_length)
atr_multiplier = input.float(2.0, 'ATR Multiplier', group = atr_settings, tooltip =
tooltip_atr_multiplier)
// Dynamic Score Settings
window_len = input.int(50, 'Window Length', group = score_settings, tooltip =
tooltip_window_length)
uptrend_threshold = input.int(40, 'Uptrend Threshold', group = score_settings,
tooltip = tooltip_uptrend_threshold)
downtrend_threshold = input.int(-10, 'Downtrend Threshold', group = score_settings,
tooltip = tooltip_downtrend_threshold)
// Bar Coloring Settings
bar = input.bool(true, 'Color Bars?', group = bar_coloring, tooltip =
tooltip_bar_coloring)
bg_coloring = input.bool(false, 'Background Coloring?', group = bar_coloring,
tooltip = tooltip_bg_coloring)
// ── Fixed parameters (no input boxes)
sensitivity = 4 // SuperTrend sensitivity
atrLenST = 11 // ATR length used inside SuperTrend
adxLen = 14 // ADX length
adxThresh = 20 // Require at least this ADX to allow signals
// ── SuperTrend (standard)
supertrend(_src, factor, atrLen) =>
atr = ta.atr(atrLen)
upperBand = _src + factor * atr
lowerBand = _src - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])
lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ?
lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ?
upperBand : prevUpperBand
int direction = na
float superTrend = na
prevSuperTrend = superTrend[1]
if na(atr[1])
direction := 1
direction
else if prevSuperTrend == prevUpperBand
direction := close > upperBand ? -1 : 1
direction
else
direction := close < lowerBand ? 1 : -1
direction
superTrend := direction == -1 ? lowerBand : upperBand
[superTrend, direction]
// ── MAs / PSAR
sma4 = ta.sma(close, 8)
sma5 = ta.sma(close, 9)
sma9 = ta.sma(close, 13)
psar = ta.sar(0.02, 0.02, 0.2)
// ── Get SuperTrend
[st, dirST] = supertrend(close, sensitivity, atrLenST)
// ── Manual Wilder ADX
calcAdx(_len) =>
upMove = high - high[1]
downMove = low[1] - low
plusDM = upMove > downMove and upMove > 0 ? upMove : 0.0
minusDM = downMove > upMove and downMove > 0 ? downMove : 0.0
trHL = high - low
trHC = math.abs(high - close[1])
trLC = math.abs(low - close[1])
tr = math.max(trHL, math.max(trHC, trLC))
smTR = ta.rma(tr, _len)
smPDM = ta.rma(plusDM, _len)
smMDM = ta.rma(minusDM, _len)
plusDI = 100.0 * smPDM / math.max(smTR, 1e-10)
minusDI = 100.0 * smMDM / math.max(smTR, 1e-10)
dx = 100.0 * math.abs(plusDI - minusDI) / math.max(plusDI + minusDI, 1e-10)
adxV = ta.rma(dx, _len)
adxV
adx = calcAdx(adxLen)
adxFilter = adx >= adxThresh
// ── Label Y positions
yBuy = low - ta.atr(30) * 2
ySell = high + ta.atr(30) * 2
// ── Signals (blocked when ADX < 20)
uptrend = ta.crossover(close, st) and close >= sma9 and adxFilter
Downtrend = ta.crossunder(close, st) and close <= sma9 and adxFilter
// ── Smart labels (Options style: CALL BUY / PUT BUY)
buy = uptrend ? label.new(bar_index, yBuy, sma4 >= sma5 ? 'CALL BUY' : ' BUY',
xloc.bar_index, yloc.price, #00CC00, label.style_label_up, #141923, size.normal) :
na
sell = Downtrend ? label.new(bar_index, ySell, sma4 <= sma5 ? 'PUT BUY' : 'SELL',
xloc.bar_index, yloc.price, #CC0000, label.style_label_down, color.white,
size.normal) : na
//TechnicalRatingsColoredCandles
res_val = input.timeframe('', title = 'Indicator Timeframe')
ratingSignal = input.string(defval = 'All', title = 'Rating is based on', options =
['MAs', 'Oscillators', 'All'])
// Awesome Oscillator
AO() =>
ta.sma(hl2, 5) - ta.sma(hl2, 34)
// Stochastic RSI
StochRSI() =>
rsi1 = ta.rsi(close, 14)
K = ta.sma(ta.stoch(rsi1, rsi1, rsi1, 14), 3)
D = ta.sma(K, 3)
[K, D]
// Ultimate Oscillator
tl() =>
close[1] < low ? close[1] : low
uo(ShortLen, MiddlLen, LongLen) =>
Value1 = math.sum(ta.tr, ShortLen)
Value2 = math.sum(ta.tr, MiddlLen)
Value3 = math.sum(ta.tr, LongLen)
Value4 = math.sum(close - tl(), ShortLen)
Value5 = math.sum(close - tl(), MiddlLen)
Value6 = math.sum(close - tl(), LongLen)
float UO = na
if Value1 != 0 and Value2 != 0 and Value3 != 0
var0 = LongLen / ShortLen
var1 = LongLen / MiddlLen
Value7 = Value4 / Value1 * var0
Value8 = Value5 / Value2 * var1
Value9 = Value6 / Value3
UO := (Value7 + Value8 + Value9) / (var0 + var1 + 1)
UO
UO
// Ichimoku Cloud
donchian(len) =>
math.avg(ta.lowest(len), ta.highest(len))
ichimoku_cloud() =>
conversionLine = donchian(9)
baseLine = donchian(26)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(52)
[conversionLine, baseLine, leadLine1, leadLine2]
calcRatingMA(ma, src) =>
na(ma) or na(src) ? na : ma == src ? 0 : ma < src ? 1 : -1
calcRating(buy, sell) =>
buy ? 1 : sell ? -1 : 0
calcRatingAll() =>
//============== MA =================
SMA10 = ta.sma(close, 10)
SMA20 = ta.sma(close, 20)
SMA30 = ta.sma(close, 30)
SMA50 = ta.sma(close, 50)
SMA100 = ta.sma(close, 100)
SMA200 = ta.sma(close, 200)
EMA10 = ta.ema(close, 10)
EMA20 = ta.ema(close, 20)
EMA30 = ta.ema(close, 30)
EMA50 = ta.ema(close, 50)
EMA100 = ta.ema(close, 100)
EMA200 = ta.ema(close, 200)
HullMA9 = ta.hma(close, 9)
// Volume Weighted Moving Average (VWMA)
VWMA = ta.vwma(close, 20)
[IC_CLine, IC_BLine, IC_Lead1, IC_Lead2] = ichimoku_cloud()
// ======= Other =============
// Relative Strength Index, RSI
RSI = ta.rsi(close, 14)
// Stochastic
lengthStoch = 14
smoothKStoch = 3
smoothDStoch = 3
kStoch = ta.sma(ta.stoch(close, high, low, lengthStoch), smoothKStoch)
dStoch = ta.sma(kStoch, smoothDStoch)
// Commodity Channel Index, CCI
CCI = ta.cci(close, 20)
// Average Directional Index
float adxValue = na
float adxPlus = na
float adxMinus = na
[P, M, V] = ta.dmi(14, 14)
adxValue := V
adxPlus := P
adxMinus := M
// Awesome Oscillator
ao = AO()
// Momentum
Mom = ta.mom(close, 10)
// Moving Average Convergence/Divergence, MACD
[macdMACD, signalMACD, _] = ta.macd(close, 12, 26, 9)
// Stochastic RSI
[Stoch_RSI_K, Stoch_RSI_D] = StochRSI()
// Williams Percent Range
WR = ta.wpr(14)
// Bull / Bear Power
BullPower = high - ta.ema(close, 13)
BearPower = low - ta.ema(close, 13)
// Ultimate Oscillator
UO = uo(7, 14, 28)
if not na(UO)
UO := UO * 100
UO
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////
PriceAvg = ta.ema(close, 50)
DownTrend = close < PriceAvg
UpTrend = close > PriceAvg
// calculate trading recommendation based on SMA/EMA
float ratingMA = 0
float ratingMAC = 0
if not na(SMA10)
ratingMA := ratingMA + calcRatingMA(SMA10, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(SMA20)
ratingMA := ratingMA + calcRatingMA(SMA20, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(SMA30)
ratingMA := ratingMA + calcRatingMA(SMA30, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(SMA50)
ratingMA := ratingMA + calcRatingMA(SMA50, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(SMA100)
ratingMA := ratingMA + calcRatingMA(SMA100, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(SMA200)
ratingMA := ratingMA + calcRatingMA(SMA200, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(EMA10)
ratingMA := ratingMA + calcRatingMA(EMA10, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(EMA20)
ratingMA := ratingMA + calcRatingMA(EMA20, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(EMA30)
ratingMA := ratingMA + calcRatingMA(EMA30, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(EMA50)
ratingMA := ratingMA + calcRatingMA(EMA50, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(EMA100)
ratingMA := ratingMA + calcRatingMA(EMA100, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(EMA200)
ratingMA := ratingMA + calcRatingMA(EMA200, close)
ratingMAC := ratingMAC + 1
ratingMAC
if not na(HullMA9)
ratingHullMA9 = calcRatingMA(HullMA9, close)
ratingMA := ratingMA + ratingHullMA9
ratingMAC := ratingMAC + 1
ratingMAC
if not na(VWMA)
ratingVWMA = calcRatingMA(VWMA, close)
ratingMA := ratingMA + ratingVWMA
ratingMAC := ratingMAC + 1
ratingMAC
float ratingIC = na
if not(na(IC_Lead1) or na(IC_Lead2) or na(close) or na(close[1]) or
na(IC_BLine) or na(IC_CLine))
ratingIC := calcRating(IC_Lead1 > IC_Lead2 and close > IC_Lead1 and close <
IC_BLine and close[1] < IC_CLine and close > IC_CLine, IC_Lead2 > IC_Lead1 and
close < IC_Lead2 and close > IC_BLine and close[1] > IC_CLine and close < IC_CLine)
ratingIC
if not na(ratingIC)
ratingMA := ratingMA + ratingIC
ratingMAC := ratingMAC + 1
ratingMAC
ratingMA := ratingMAC > 0 ? ratingMA / ratingMAC : na
float ratingOther = 0
float ratingOtherC = 0
ratingRSI = RSI
if not(na(ratingRSI) or na(ratingRSI[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ratingRSI < 30 and ratingRSI[1] <
ratingRSI, ratingRSI > 70 and ratingRSI[1] > ratingRSI)
ratingOther
if not(na(kStoch) or na(dStoch) or na(kStoch[1]) or na(dStoch[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(kStoch < 20 and dStoch < 20 and
kStoch > dStoch and kStoch[1] < dStoch[1], kStoch > 80 and dStoch > 80 and kStoch <
dStoch and kStoch[1] > dStoch[1])
ratingOther
ratingCCI = CCI
if not(na(ratingCCI) or na(ratingCCI[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ratingCCI < -100 and ratingCCI >
ratingCCI[1], ratingCCI > 100 and ratingCCI < ratingCCI[1])
ratingOther
if not(na(adxValue) or na(adxPlus[1]) or na(adxMinus[1]) or na(adxPlus) or
na(adxMinus))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(adxValue > 20 and adxPlus[1] <
adxMinus[1] and adxPlus > adxMinus, adxValue > 20 and adxPlus[1] > adxMinus[1] and
adxPlus < adxMinus)
ratingOther
if not(na(ao) or na(ao[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(ta.crossover(ao, 0) or ao > 0 and
ao[1] > 0 and ao > ao[1] and ao[2] > ao[1], ta.crossunder(ao, 0) or ao < 0 and
ao[1] < 0 and ao < ao[1] and ao[2] < ao[1])
ratingOther
if not(na(Mom) or na(Mom[1]))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(Mom > Mom[1], Mom < Mom[1])
ratingOther
if not(na(macdMACD) or na(signalMACD))
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + calcRating(macdMACD > signalMACD, macdMACD <
signalMACD)
ratingOther
float ratingWR = na
if not(na(WR) or na(WR[1]))
ratingWR := calcRating(WR < -80 and WR > WR[1], WR > -20 and WR < WR[1])
ratingWR
if not na(ratingWR)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingWR
ratingOther
float ratingUO = na
if not na(UO)
ratingUO := calcRating(UO > 70, UO < 30)
ratingUO
if not na(ratingUO)
ratingOtherC := ratingOtherC + 1
ratingOther := ratingOther + ratingUO
ratingOther
ratingOther := ratingOtherC > 0 ? ratingOther / ratingOtherC : na
float ratingTotal = 0
float ratingTotalC = 0
if not na(ratingMA)
ratingTotal := ratingTotal + ratingMA
ratingTotalC := ratingTotalC + 1
ratingTotalC
if not na(ratingOther)
ratingTotal := ratingTotal + ratingOther
ratingTotalC := ratingTotalC + 1
ratingTotalC
ratingTotal := ratingTotalC > 0 ? ratingTotal / ratingTotalC : na
[ratingTotal, ratingOther, ratingMA, ratingOtherC, ratingMAC]
[ratingTotal, ratingOther, ratingMA, ratingOtherC, ratingMAC] =
request.security(syminfo.tickerid, res, calcRatingAll())
StrongBound = 0.5
WeakBound = 0.1
getSignal(ratingTotal, ratingOther, ratingMA) =>
float _res = ratingTotal
if ratingSignal == 'MAs'
_res := ratingMA
_res
if ratingSignal == 'Oscillators'
_res := ratingOther
_res
_res
tradeSignal = getSignal(ratingTotal, ratingOther, ratingMA)
poscol = input(color.blue, 'Buy Color')
neutralcolor = input(color.white, 'Neutral Color')
negcol = input(color.red, 'Sell Color')
neutralcolor2 = input(color.gray, 'Table Neutral Color')
poscond = tradeSignal > WeakBound
negcond = tradeSignal < -WeakBound
posseries = poscond ? tradeSignal : 0
negseries = negcond ? tradeSignal : 0
count_rising(plot) =>
v_plot = plot > 0 ? plot : -plot
var count = 0
if v_plot == 0
count := 0
count
else if v_plot >= v_plot[1]
count := math.min(5, count + 1)
count
else if v_plot < v_plot[1]
count := math.max(1, count - 1)
count
count
poscount = count_rising(posseries)
negcount = count_rising(negseries)
_pc = poscond ? poscount : negcond ? negcount : 0
colorTransp(col, transp) =>
red = color.r(col)
green = color.g(col)
blue = color.b(col)
color.rgb(red, green, blue, transp)
getTimeOfNextBar() =>
currentTime = time(timeframe.period)
changeTime = ta.change(currentTime)
minChange = if not na(changeTime)
var float minChange = changeTime
minChange := math.min(minChange, changeTime)
minChange
int(currentTime + minChange)
drawInfo(txt, value) =>
var info = label.new(0, 0, '', yloc = yloc.price, xloc = xloc.bar_time,
textalign = text.align_left, textcolor = color.white)
label.set_x(info, getTimeOfNextBar())
label.set_text(info, txt)
label.set_color(info, poscond ? poscol : negcond ? negcol : color.gray)
label.set_style(info, label.style_label_left)
calcRatingStatus(value) =>
if -StrongBound > value
'Strong Sell'
else if value < -WeakBound
'Sell'
else if value > StrongBound
'Strong Buy'
else if value > WeakBound
'Buy'
else
'Neutral'
col_buy = color.from_gradient(tradeSignal, 0.0, 0.2, neutralcolor, poscol)
col_sell = color.from_gradient(tradeSignal, -0.2, 0.0, negcol, neutralcolor)
col_gradient = color.from_gradient(tradeSignal, -0.2, 0.2, col_sell, col_buy)
col_buy2 = color.from_gradient(tradeSignal, 0.0, 0.2, neutralcolor2, poscol)
col_sell2 = color.from_gradient(tradeSignal, -0.2, 0.0, negcol, neutralcolor2)
col_gradient2 = color.from_gradient(tradeSignal, -0.2, 0.2, col_sell2, col_buy2)
_cond1 = ta.crossunder(tradeSignal, -WeakBound)
alertcondition(_cond1, 'Sell', 'Ratings changed to Sell')
_cond2 = ta.crossover(tradeSignal, WeakBound)
alertcondition(_cond2, 'Buy', 'Ratings changed to Buy')
_cond3 = ta.crossunder(tradeSignal, -StrongBound)
alertcondition(_cond3, 'Strong Sell', 'Ratings changed to Strong Sell')
_cond4 = ta.crossover(tradeSignal, StrongBound)
alertcondition(_cond4, 'Strong Buy', 'Ratings changed to Strong Buy')
col_ma = color.from_gradient(ratingMA, -1, 1, negcol, poscol)
col_other = color.from_gradient(ratingOther, -1, 1, negcol, poscol)
TotaText = calcRatingStatus(ratingTotal)
// INPUTS
――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
――――――――――――――――――――――{
int amp = input.int(5, 'Amplitude', minval = 1) // Length for indicator
calculations
bool useHeikin = input.bool(false, 'Heikin Ashi') // Toggle Heikin Ashi mode
string signalSize = input.string('Large', 'Signals Size', ['Large', 'Small']) //
Size of signals
color up_col = input.color(#26e47b, 'Up', group = 'Trend Colors', inline = '1') //
Color for upward trend
color dn_col = input.color(#2c75c9, 'Down', group = 'Trend Colors', inline =
'1') // Color for downward trend
bool trend_candl = input.bool(false, 'Candles Color') // Toggle candles color based
on trend
// }
// 𝚄𝙳𝚃𝚜
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
――――――――――――――――――――――――――――{
type HeikinAshi
float open
float high
float low
float close
var HeikinAshi ha = HeikinAshi.new(na, na, na, na) // Initialize Heikin Ashi UDT
// }
// Variable Initialization
var bool up_signal = false // Signal Up
var bool dn_signal = false // Signal Down
var color trend_col = na // Trend color
var float hl_t = 0. // Half trend value
var float trend_st = 0. // Trend strength
var float oc2 = na // Midpoint for Heikin Ashi calculations
// CALCULATION
S――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
――――――――――――{
series float closeMA = ta.sma(close, amp) // Moving average of close prices
series float highestHigh = ta.highest(amp) // Highest high over the period
series float lowestLow = ta.lowest(amp) // Lowest low over the period
// Initialize half trend on the first bar
if barstate.isfirst
hl_t := close
hl_t
// Update half trend value based on conditions
switch
closeMA < hl_t and highestHigh < hl_t =>
hl_t := highestHigh
hl_t
closeMA > hl_t and lowestLow > hl_t =>
hl_t := lowestLow
hl_t
=>
hl_t := hl_t
hl_t
// Calculate Heikin Ashi values based on Half Trend
if useHeikin
ha.close := (nz(ha.open) + nz(ha.high) + nz(ha.low) + hl_t) / 4
field_0 = ha.open
field_1 = ha.open
field_2 = ha.close
ha.open := na(field_0[1]) ? (hl_t + hl_t[1]) / 2 : (nz(field_1[1]) +
nz(field_2[1])) / 2
ha.high := math.max(hl_t, math.max(ha.open, ha.close))
ha.low := math.min(hl_t, math.min(ha.open, ha.close))
oc2 := (ha.close + ha.open) / 2
oc2
// Calculate trend strength
trend_st := (ha.high - ha.low) / ta.stdev(ha.high - ha.low, 200)
trend_st := trend_st * 20 > 100 ? 100 : trend_st * 20
// Determine trend color
if ta.crossover(hl_t, hl_t[1])
trend_col := up_col
trend_col
if ta.crossunder(hl_t, hl_t[1])
trend_col := dn_col
trend_col
// Signal conditions for trend direction
float trend_change = (ha.close - ha.open) / ha.open
up_signal := (useHeikin ? ta.crossover(trend_change, 0) : ta.crossover(hl_t,
hl_t[1]) and ta.change(trend_col == up_col)) and barstate.isconfirmed
dn_signal := (useHeikin ? ta.crossunder(trend_change, 0) : ta.crossunder(hl_t,
hl_t[1]) and ta.change(trend_col == dn_col)) and barstate.isconfirmed
// }
// === Inputs ===
toggleBreaks = input(true, title = 'Show Breaks')
leftBars = input(15, title = 'Left Bars')
rightBars = input(15, title = 'Right Bars')
useVolumeFilter = input(true, title = 'Require Volume > Average')
volumeLength = input(20, title = 'Volume MA Length')
// === Higher TF RSI Risk (visual only) ===
useHTFRSI = input(true, title = 'Use H4 RSI Risk Warning')
rsiLenHTF = input(14, title = 'RSI Length (HTF)')
rsiTF = input('240', title = 'Higher TF (minutes) - H4=240')
rsiBuyMax = input(70, title = 'Risk if RSI(H4) > (Buy)')
rsiSellMin = input(30, title = 'Risk if RSI(H4) < (Sell)')
// === Pivots ===
highUsePivot = fixnan(ta.pivothigh(leftBars, rightBars)[1])
lowUsePivot = fixnan(ta.pivotlow(leftBars, rightBars)[1])
// === EMAs ===
ema34_high = ta.ema(high, 34)
ema34_low = ta.ema(low, 34)
ema34_close = ta.ema(close, 34)
ema89 = ta.ema(close, 89)
// === EMA Filters ===
aboveEMAs = close > ema34_high and close > ema34_low and close > ema34_close and
close > ema89
belowEMAs = close < ema34_high and close < ema34_low and close < ema34_close and
close < ema89
// === Volume Filter ===
volAverage = ta.sma(volume, volumeLength)
volCondition = not useVolumeFilter or volume > avgVolume
// === One-time trigger per pivot ===
var bool bullBreakTriggered = false
var bool bearBreakTriggered = false
if bool(ta.change(highUsePivot))
bullBreakTriggered := false
bullBreakTriggered
if bool(ta.change(lowUsePivot))
bearBreakTriggered := false
bearBreakTriggered
// === Wick Filter for entry: each side ≤ 50% of candle range ===
candleLength = high - low
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
maxWickRatio = 0.5
upperWickOK = candleLength > 0 ? upperWick / candleLength <= maxWickRatio : true
lowerWickOK = candleLength > 0 ? lowerWick / candleLength <= maxWickRatio : true
// === H4 RSI (risk color only; no blocking) ===
rsiHTF = request.security(syminfo.tickerid, rsiTF, ta.rsi(close, rsiLenHTF),
barmerge.gaps_off, barmerge.lookahead_off)
riskBull = useHTFRSI and rsiHTF > rsiBuyMax
riskBear = useHTFRSI and rsiHTF < rsiSellMin
// === Entry Conditions ===
bullBreakCond = toggleBreaks and ta.crossover(close, highUsePivot) and aboveEMAs
and not bullBreakTriggered and upperWickOK and volCondition
bearBreakCond = toggleBreaks and ta.crossunder(close, lowUsePivot) and belowEMAs
and not bearBreakTriggered and lowerWickOK and volCondition
if bullBreakCond
bullBreakTriggered := true
bullBreakTriggered
if bearBreakCond
bearBreakTriggered := true
bearBreakTriggered
// === Plot Signals (B/S) — gray if H4 RSI risk ===
bullLabelColor = riskBull ? color.gray : color.green
bearLabelColor = riskBear ? color.gray : color.red
plotshape(bullBreakCond, title = 'Bull Break', text = 'B', style = shape.labelup,
location = location.belowbar, color = bullLabelColor, textcolor =
color.new(color.white, 0), size = size.tiny)
plotshape(bearBreakCond, title = 'Bear Break', text = 'S', style = shape.labeldown,
location = location.abovebar, color = bearLabelColor, textcolor =
color.new(color.white, 0), size = size.tiny)
// === Unified alert ===
anyBreak = bullBreakCond or bearBreakCond
alertcondition(anyBreak, title = 'S/R Breakout (Unified)', message = 'S/R Breakout:
B=Buy, S=Sell. Gray label = H4 RSI risk. Filters: EMA (34 H/L/C & 89), wick≤50%,
volume>avg.')
// === Inputs ===
// Enable/disable EMAs
showEMA9 = input.bool(true, title="Show EMA 9")
showEMA21 = input.bool(true, title="Show EMA 21")
// Custom EMA lengths
ema9Length = input.int(9, "EMA 9 Length", minval=1)
ema21Length = input.int(21, "EMA 21 Length", minval=1)
// === Calculations ===
ema9 = ta.ema(src, ema9Length)
ema21 = ta.ema(src, ema21Length)
// === Plotting ===
plot(showEMA9 ? ema9 : na, color=color.rgb(0, 0, 0), linewidth=2, title="EMA 9")
plot(showEMA21 ? ema21 : na, color=color.rgb(0, 4, 255), linewidth=2, title="EMA
21")
// === Signals (optional background coloring) ===
// Only active if both EMAs are enabled
bullish = showEMA9 and showEMA21 and ta.crossover(ema9, ema21)
bearish = showEMA9 and showEMA21 and ta.crossunder(ema9, ema21)
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
//* BAR SETTINGS *//
paint_bars = input(false, title = "Paint bars?", group = 'Bars Settings')
catch_flat = input(false, title = "Try to catch flat?", group = 'Bars Settings')
uptrend_colour = input.color(defval = color.green, title = "Uptrend colour", group
= 'Bars Settings')
downtrend_colour = input.color(defval = color.red, title = "Downtrend colour",
group = 'Bars Settings')
neutraltrend_colour = input.color(defval = color.gray, title = "Downtrend colour",
tooltip = 'Note that this value is ignored if the setting to catch flat is switched
off.', group = 'Bars Settings')
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
//* TABLE SETTINGS *//
show_header = input.bool(false, title = "Show header?", group
= 'Table Settings')
show_ema_value = input.bool(false, title = "Show EMA value?", group
= 'Table Settings')
dashboard_position = input.session("Bottom left",
title = "Position",
options = ["Top right", "Bottom right", "Top left", "Bottom left", "Top
center", "Bottom center", "Middle right"],
group = 'Table Settings')
text_size = input.session("Normal", title = "Size", options =
["Tiny", "Small", "Normal", "Large"], group = 'Table Settings')
text_color = input.color(color.black, title = "Text colour", group
= 'Table Settings')
table_color = input.color(color.gray, title = "Border colour", group
= 'Table Settings')
uptrend_indicator = input.string("🟢", title = "Uptrend indicator",
group = 'Table Settings')
downtrend_indicator = input.string("🔴", title = "Downtrend indicator",
group = 'Table Settings')
neutraltrend_indicator = input.string("⚫️", title = "Neutraltrend indicator",
tooltip = 'Note that this value is ignored if the setting to catch flat is switched
off.', group = 'Table Settings')
header_bg_color = input.color(color.rgb(255, 0, 0 ), title = "Header
background colour", group = 'Table Settings')
uptrend_bg_color = input.color(color.rgb(40, 224, 46, 18), title = "Uptrend
background colour", group = 'Table Settings')
downtrend_bg_color = input.color(color.rgb(243, 48, 48, 9 ), title =
"Downtrend background colour", group = 'Table Settings')
neutraltrend_bg_color = input.color(color.rgb(120,123,134,43), title =
"Neutraltrend background colour", tooltip = 'Note that this value is ignored if
the setting to catch flat is switched off.', group = 'Table Settings')
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
//* EMA SETTINGS *//
trend_identification_approach = input.session("Direction of a single EMA", "Trend
identification approach", ["Direction of a single EMA", "Comparison of the two
EMAs"], group = 'EMA Settings')
ema1_length = input.int(title = "EMA length", defval = 50, minval = 1, maxval =
800, group = 'EMA Settings')
ema2_length = input.int(title = "Additional EMA length", defval = 200, minval = 1,
maxval = 800, tooltip = 'Note that the single EMA trend identification approach
ignores this value.', group = 'EMA Settings')
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
//* TIMEFRAME SETTINGS *//
show_1m = input(true, title = 'Show 1m', group = 'Timeframe Settings')
show_2m = input(false, title = 'Show 2m ', group = 'Timeframe Settings')
show_3m = input(true, title = 'Show 3m ', group = 'Timeframe Settings')
show_5m = input(true, title = 'Show 5m', group = 'Timeframe Settings')
show_10m = input(false, title = 'Show 10m', group = 'Timeframe Settings')
show_15m = input(true, title = 'Show 15m', group = 'Timeframe Settings')
show_30m = input(false, title = 'Show 30m', group = 'Timeframe Settings')
show_45m = input(false, title = 'Show 45m', group = 'Timeframe Settings')
show_1h = input(true, title = 'Show 1h', group = 'Timeframe Settings')
show_2h = input(false, title = 'Show 2h', group = 'Timeframe Settings')
show_3h = input(false, title = 'Show 3h', group = 'Timeframe Settings')
show_4h = input(true, title = 'Show 4h', group = 'Timeframe Settings')
show_6h = input(false, title = 'Show 6h', group = 'Timeframe Settings')
show_8h = input(false, title = 'Show 8h', group = 'Timeframe Settings')
show_12h = input(false, title = 'Show 12h', group = 'Timeframe Settings')
show_D = input(true, title = 'Show D', group = 'Timeframe Settings')
show_3D = input(false, title = 'Show 3D', group = 'Timeframe Settings')
show_W = input(false, title = 'Show W', group = 'Timeframe Settings')
show_M = input(false, title = 'Show M', group = 'Timeframe Settings')
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
//* CALCULATION *//
var table_position = dashboard_position == 'Top right' ? position.top_right :
dashboard_position == 'Top left' ? position.top_left :
dashboard_position == 'Top center' ? position.top_center :
dashboard_position == 'Bottom right' ? position.bottom_right :
dashboard_position == 'Bottom left' ? position.bottom_left :
dashboard_position == 'Bottom center' ? position.bottom_center :
dashboard_position == 'Middle right' ? position.middle_right :
dashboard_position == 'Middle left' ? position.middle_left :
position.middle_right
var table_text_size = text_size == 'Normal' ? size.normal :
text_size == 'Large' ? size.large :
text_size == 'Tiny' ? size.tiny :
text_size == 'Small' ? size.small : size.normal
var t3 = table.new(position = table_position,
columns = 3,
rows = 20,
frame_color = table_color,
frame_width = 2,
border_color = table_color,
border_width = 2)
calc_smma(src, len) =>
var float smma = na
sma_val = ta.sma(src, len)
smma := na(smma) ? sma_val : (smma[1] * (len - 1) + src) / len
smma
calc_zlema(src, len) =>
ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
d = ema1 - ema2
ema1 + d
check_impulse() =>
impulse_length = 34
impulse_strength = 9
hi = calc_smma(high, impulse_length)
lo = calc_smma(low, impulse_length)
mi = calc_zlema(hlc3, impulse_length)
md = (mi > hi) ? (mi - hi) : (mi < lo) ? (mi - lo) : 0
md_prev = (mi[1] > hi[1]) ? (mi[1] - hi[1]) : (mi[1] < lo[1]) ? (mi[1] - lo[1])
: 0
sb = ta.sma(md, impulse_strength)
sb_prev = ta.sma(md_prev, impulse_strength)
sh = md - sb
sh_prev = md_prev - sb_prev
is_impulse = sh != 0 and sh_prev != 0
is_impulse
get_trend_status() =>
impulse = catch_flat ? check_impulse() : true
ema1_current_candle = ta.ema(close, ema1_length)
ema1_previous_candle = ema1_current_candle[1]
round = ema1_current_candle > 1000 ? 0 : ema1_current_candle > 10 ? 1 :
ema1_current_candle > 0 ? 2 : ema1_current_candle > 0.1 ? 3 : 10
ema1_str = str.tostring(math.round(ema1_current_candle, round))
if (trend_identification_approach == "Direction of a single EMA")
ema1_previous_previous_candle = ema1_current_candle[2]
trend_bg_color = not impulse ? neutraltrend_bg_color : ema1_current_candle
> ema1_previous_candle ? uptrend_bg_color : ema1_current_candle <
ema1_previous_candle ? downtrend_bg_color : neutraltrend_bg_color
trend_current_candle = not impulse ? neutraltrend_indicator :
ema1_current_candle > ema1_previous_candle ? uptrend_indicator :
ema1_current_candle < ema1_previous_candle ? downtrend_indicator :
neutraltrend_indicator
trend_previous_candle = not impulse ? neutraltrend_indicator :
ema1_previous_candle > ema1_previous_previous_candle ? uptrend_indicator :
ema1_previous_candle < ema1_previous_previous_candle ? downtrend_indicator :
neutraltrend_indicator
[ema1_str, trend_bg_color, trend_current_candle, trend_previous_candle]
else
ema2_current_candle = ta.ema(close, ema2_length)
ema2_previous_candle = ema2_current_candle[1]
trend_bg_color = not impulse ? neutraltrend_bg_color : ema1_current_candle
> ema2_current_candle ? uptrend_bg_color : ema1_current_candle <
ema2_current_candle ? downtrend_bg_color : neutraltrend_bg_color
trend_current_candle = not impulse ? neutraltrend_indicator :
ema1_current_candle > ema2_current_candle ? uptrend_indicator : ema1_current_candle
< ema2_current_candle ? downtrend_indicator : neutraltrend_indicator
trend_previous_candle = not impulse ? neutraltrend_indicator :
ema1_previous_candle > ema2_previous_candle ? uptrend_indicator :
ema1_previous_candle < ema2_previous_candle ? downtrend_indicator :
neutraltrend_indicator
[ema1_str, trend_bg_color, trend_current_candle, trend_previous_candle]
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////
//* TABLE *//
[ema_1m, trend_bg_color_1m, trend_indicator_1m, _] = if (show_1m)
request.security(syminfo.tickerid, "1", get_trend_status())
else
[na, na, na, na]
[ema_2m, trend_bg_color_2m, trend_indicator_2m, _] = if (show_2m)
request.security(syminfo.tickerid, "2", get_trend_status())
else
[na, na, na, na]
[ema_3m, trend_bg_color_3m, trend_indicator_3m, _] = if (show_3m)
request.security(syminfo.tickerid, "3", get_trend_status())
else
[na, na, na, na]
[ema_5m, trend_bg_color_5m, trend_indicator_5m, _] = if (show_5m)
request.security(syminfo.tickerid, "5", get_trend_status())
else
[na, na, na, na]
[ema_10m, trend_bg_color_10m, trend_indicator_10m, _] = if (show_10m)
request.security(syminfo.tickerid, "10", get_trend_status())
else
[na, na, na, na]
[ema_15m, trend_bg_color_15m, trend_indicator_15m, _] = if (show_15m)
request.security(syminfo.tickerid, "15", get_trend_status())
else
[na, na, na, na]
[ema_30m, trend_bg_color_30m, trend_indicator_30m, _] = if (show_30m)
request.security(syminfo.tickerid, "30", get_trend_status())
else
[na, na, na, na]
[ema_45m, trend_bg_color_45m, trend_indicator_45m, _] = if (show_45m)
request.security(syminfo.tickerid, "45", get_trend_status())
else
[na, na, na, na]
[ema_1h, trend_bg_color_1h, trend_indicator_1h, _] = if (show_1h)
request.security(syminfo.tickerid, "60", get_trend_status())
else
[na, na, na, na]
[ema_2h, trend_bg_color_2h, trend_indicator_2h, _] = if (show_2h)
request.security(syminfo.tickerid, "120", get_trend_status())
else
[na, na, na, na]
[ema_3h, trend_bg_color_3h, trend_indicator_3h, _] = if (show_3h)
request.security(syminfo.tickerid, "180", get_trend_status())
else
[na, na, na, na]
[ema_4h, trend_bg_color_4h, trend_indicator_4h, _] = if (show_4h)
request.security(syminfo.tickerid, "240", get_trend_status())
else
[na, na, na, na]
[ema_6h, trend_bg_color_6h, trend_indicator_6h, _] = if (show_6h)
request.security(syminfo.tickerid, "360", get_trend_status())
else
[na, na, na, na]
[ema_8h, trend_bg_color_8h, trend_indicator_8h, _] = if (show_8h)
request.security(syminfo.tickerid, "480", get_trend_status())
else
[na, na, na, na]
[ema_12h, trend_bg_color_12h, trend_indicator_12h, _] = if (show_12h)
request.security(syminfo.tickerid, "720", get_trend_status())
else
[na, na, na, na]
[ema_D, trend_bg_color_D, trend_indicator_D, _] = if (show_D)
request.security(syminfo.tickerid, "D", get_trend_status())
else
[na, na, na, na]
[ema_3D, trend_bg_color_3D, trend_indicator_3D, _] = if (show_3D)
request.security(syminfo.tickerid, "3D", get_trend_status())
else
[na, na, na, na]
[ema_W, trend_bg_color_W, trend_indicator_W, _] = if (show_W)
request.security(syminfo.tickerid, "W", get_trend_status())
else
[na, na, na, na]
[ema_M, trend_bg_color_M, trend_indicator_M, _] = if (show_M)
request.security(syminfo.tickerid, "M", get_trend_status())
else
[na, na, na, na]
if (barstate.islast)
if (show_header)
table.cell(t3, 0, 0, "Timeframe", text_color = text_color, text_size =
table_text_size, bgcolor = header_bg_color)
table.cell(t3, 1, 0, "Trend", text_color = text_color, text_size =
table_text_size, bgcolor = header_bg_color)
if (show_ema_value)
table.cell(t3, 2, 0, str.tostring(ema1_length) + " EMA", text_color =
text_color, text_size = table_text_size, bgcolor = header_bg_color)
if (show_1m)
table.cell(t3, 0, 1, "1m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_1m)
table.cell(t3, 1, 1, trend_indicator_1m, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_1m)
if (show_ema_value)
table.cell(t3, 2, 1, ema_1m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_1m)
if (show_2m)
table.cell(t3, 0, 2, "2m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_2m)
table.cell(t3, 1, 2, trend_indicator_2m, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_2m)
if (show_ema_value)
table.cell(t3, 2, 2, ema_2m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_2m)
if (show_3m)
table.cell(t3, 0, 3, "3m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_3m)
table.cell(t3, 1, 3, trend_indicator_3m, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_3m)
if (show_ema_value)
table.cell(t3, 2, 3, ema_3m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_3m)
if (show_5m)
table.cell(t3, 0, 4, "5m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_5m)
table.cell(t3, 1, 4, trend_indicator_5m, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_5m)
if (show_ema_value)
table.cell(t3, 2, 4, ema_5m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_5m)
if (show_10m)
table.cell(t3, 0, 5, "10m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_10m)
table.cell(t3, 1, 5, trend_indicator_10m, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_10m)
if (show_ema_value)
table.cell(t3, 2, 5, ema_10m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_10m)
if (show_15m)
table.cell(t3, 0, 6, "15m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_15m)
table.cell(t3, 1, 6, trend_indicator_15m, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_15m)
if (show_ema_value)
table.cell(t3, 2, 6, ema_15m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_15m)
if (show_30m)
table.cell(t3, 0, 7, "30m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_30m)
table.cell(t3, 1, 7, trend_indicator_30m, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_30m)
if (show_ema_value)
table.cell(t3, 2, 7, ema_30m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_30m)
if (show_45m)
table.cell(t3, 0, 8, "45m", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_45m)
table.cell(t3, 1, 8, trend_indicator_45m, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_45m)
if (show_ema_value)
table.cell(t3, 2, 8, ema_45m, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_45m)
if (show_1h)
table.cell(t3, 0, 9, "1h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_1h)
table.cell(t3, 1, 9, trend_indicator_1h, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_1h)
if (show_ema_value)
table.cell(t3, 2, 9, ema_1h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_1h)
if (show_2h)
table.cell(t3, 0, 10, "2h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_2h)
table.cell(t3, 1, 10, trend_indicator_2h, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_2h)
if (show_ema_value)
table.cell(t3, 2, 10, ema_2h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_2h)
if (show_3h)
table.cell(t3, 0, 11, "3h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_3h)
table.cell(t3, 1, 11, trend_indicator_3h, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_3h)
if (show_ema_value)
table.cell(t3, 2, 11, ema_3h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_3h)
if (show_4h)
table.cell(t3, 0, 12, "4h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_4h)
table.cell(t3, 1, 12, trend_indicator_4h, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_4h)
if (show_ema_value)
table.cell(t3, 2, 12, ema_4h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_4h)
if (show_6h)
table.cell(t3, 0, 13, "6h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_6h)
table.cell(t3, 1, 13, trend_indicator_6h, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_6h)
if (show_ema_value)
table.cell(t3, 2, 13, ema_6h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_6h)
if (show_8h)
table.cell(t3, 0, 14, "8h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_8h)
table.cell(t3, 1, 14, trend_indicator_8h, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_8h)
if (show_ema_value)
table.cell(t3, 2, 14, ema_8h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_8h)
if (show_12h)
table.cell(t3, 0, 15, "12h", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_12h)
table.cell(t3, 1, 15, trend_indicator_12h, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_12h)
if (show_ema_value)
table.cell(t3, 2, 15, ema_12h, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_12h)
if (show_D)
table.cell(t3, 0, 16, "D", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_D)
table.cell(t3, 1, 16, trend_indicator_D, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_D)
if (show_ema_value)
table.cell(t3, 2, 16, ema_D, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_D)
if (show_3D)
table.cell(t3, 0, 17, "3D", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_3D)
table.cell(t3, 1, 17, trend_indicator_3D, text_color = text_color,
text_size = table_text_size, bgcolor = trend_bg_color_3D)
if (show_ema_value)
table.cell(t3, 2, 17, ema_3D, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_3D)
if (show_W)
table.cell(t3, 0, 18, "W", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_W)
table.cell(t3, 1, 18, trend_indicator_W, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_W)
if (show_ema_value)
table.cell(t3, 2, 18, ema_W, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_W)
if (show_M)
table.cell(t3, 0, 19, "M", text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_M)
table.cell(t3, 1, 19, trend_indicator_M, text_color = text_color, text_size
= table_text_size, bgcolor = trend_bg_color_M)
if (show_ema_value)
table.cell(t3, 2, 19, ema_M, text_color = text_color, text_size =
table_text_size, bgcolor = trend_bg_color_M)
////////////
// INPUTS //
// On/Off Toggle Button
indicator_enabled = input.bool(true, 'Enable Stock Table Indicator', group =
'Settings')
filter_enabled = input.bool(false, '', group = 'Filter', inline = 'Filter')
filter_column = input.string('Price', title = 'Column', options = ['Price', 'TSI',
'SuperTrend'], group = 'Filter', inline = 'Filter')
filter_from = input.float(-9999999, 'From', group = 'Filter', inline = 'Filter')
filter_to = input.float(9999999, 'To', group = 'Filter', inline = 'Filter')
// TSI
tsi_long_len = input.int(25, title = 'TSI Long Length', group = 'Indicators')
tsi_shrt_len = input.int(13, title = 'TSI Short Length', group = 'Indicators')
tsi_ob = input.float(30, title = 'TSI Overbought', group = 'Indicators')
tsi_os = input.float(-30, title = 'TSI Oversold', group = 'Indicators')
// ADX Params
adx_smooth = input.int(14, title = 'ADX Smoothing', group = 'Indicators')
adx_dilen = input.int(14, title = 'ADX DI Length', group = 'Indicators')
adx_level = input.float(20, title = 'ADX Level', group = 'Indicators')
// SuperTrend
sup_atr_len = input.int(10, 'Supertrend ATR Length', group = 'Indicators')
sup_factor = input.float(3.0, 'Supertrend Factor', group = 'Indicators')
/////////////
// SYMBOLS //
u01 = input.bool(true, title = '', group = 'Symbols', inline = 's01')
u02 = input.bool(true, title = '', group = 'Symbols', inline = 's02')
u03 = input.bool(true, title = '', group = 'Symbols', inline = 's03')
u04 = input.bool(true, title = '', group = 'Symbols', inline = 's04')
u05 = input.bool(true, title = '', group = 'Symbols', inline = 's05')
u06 = input.bool(true, title = '', group = 'Symbols', inline = 's06')
u07 = input.bool(true, title = '', group = 'Symbols', inline = 's07')
u08 = input.bool(true, title = '', group = 'Symbols', inline = 's08')
u09 = input.bool(true, title = '', group = 'Symbols', inline = 's09')
u10 = input.bool(true, title = '', group = 'Symbols', inline = 's10')
u11 = input.bool(true, title = '', group = 'Symbols', inline = 's11')
u12 = input.bool(true, title = '', group = 'Symbols', inline = 's12')
u13 = input.bool(true, title = '', group = 'Symbols', inline = 's13')
u14 = input.bool(true, title = '', group = 'Symbols', inline = 's14')
u15 = input.bool(true, title = '', group = 'Symbols', inline = 's15')
s01 = input.symbol('NSE:RELIANCE', group = 'Symbols', inline = 's01')
s02 = input.symbol('NSE:TCS', group = 'Symbols', inline = 's02')
s03 = input.symbol('NSE:INFY', group = 'Symbols', inline = 's03')
s04 = input.symbol('NSE:HDFCBANK', group = 'Symbols', inline = 's04')
s05 = input.symbol('NSE:ICICIBANK', group = 'Symbols', inline = 's05')
s06 = input.symbol('NSE:SBIN', group = 'Symbols', inline = 's06')
s07 = input.symbol('NSE:KOTAKBANK', group = 'Symbols', inline = 's07')
s08 = input.symbol('NSE:AXISBANK', group = 'Symbols', inline = 's08')
s09 = input.symbol('NSE:BAJFINANCE', group = 'Symbols', inline = 's09')
s10 = input.symbol('NSE:BAJAJFINSV', group = 'Symbols', inline = 's10')
s11 = input.symbol('NSE:HDFCLIFE', group = 'Symbols', inline = 's11')
s12 = input.symbol('NSE:SBILIFE', group = 'Symbols', inline = 's12')
s13 = input.symbol('NSE:ITC', group = 'Symbols', inline = 's13')
s14 = input.symbol('NSE:HINDUNILVR', group = 'Symbols', inline = 's14')
s15 = input.symbol('NSE:ASIANPAINT', group = 'Symbols', inline = 's15')
//////////////////
// CALCULATIONS //
filt_col_id = switch filter_column
'Price' => 1
'TSI' => 2
'SuperTrend' => 4
=> 0
if filter_column != 'Price' and filter_column != 'TSI' and filter_column !=
'SuperTrend'
log.warning('Invalid filter column selected. Please choose a valid option.')
// Get only symbol
only_symbol(s) =>
array.get(str.split(s, ':'), 1)
// Map symbol ID to symbol name
id_symbol(s) =>
switch s
1 => only_symbol(s01)
2 => only_symbol(s02)
3 => only_symbol(s03)
4 => only_symbol(s04)
5 => only_symbol(s05)
6 => only_symbol(s06)
7 => only_symbol(s07)
8 => only_symbol(s08)
9 => only_symbol(s09)
10 => only_symbol(s10)
11 => only_symbol(s11)
12 => only_symbol(s12)
13 => only_symbol(s13)
14 => only_symbol(s14)
15 => only_symbol(s15)
=> na
// for TSI
double_smooth(src, long, short) =>
fist_smooth = ta.ema(src, long)
ta.ema(fist_smooth, short)
// ADX
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : up > down and up > 0 ? up : 0
minusDM = na(down) ? na : down > up and down > 0 ? down : 0
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx_func(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
adx
screener_func() =>
// TSI
pc = ta.change(close)
double_smoothed_pc = double_smooth(pc, tsi_long_len, tsi_shrt_len)
double_smoothed_abs_pc = double_smooth(math.abs(pc), tsi_long_len,
tsi_shrt_len)
tsi = 100 * (double_smoothed_pc / double_smoothed_abs_pc)
// ADX
adx = adx_func(adx_dilen, adx_smooth)
// Supertrend
[sup_value, sup_dir] = ta.supertrend(sup_factor, sup_atr_len)
[math.round_to_mintick(close), tsi, adx, sup_dir]
// Set Up Matrix
screenerMtx = matrix.new<float>(0, 5, na)
screenerFun(numSym, sym, flg) =>
[cl, tsi, adx, sup] = request.security(sym, timeframe.period, screener_func())
// Only add to matrix if ADX > 20
if flg and adx > 20
arr = array.from(numSym, cl, tsi, adx, sup)
matrix.add_row(screenerMtx, matrix.rows(screenerMtx), arr)
// Only run calculations if indicator is enabled
if indicator_enabled
// Security call
screenerFun(01, s01, u01)
screenerFun(02, s02, u02)
screenerFun(03, s03, u03)
screenerFun(04, s04, u04)
screenerFun(05, s05, u05)
screenerFun(06, s06, u06)
screenerFun(07, s07, u07)
screenerFun(08, s08, u08)
screenerFun(09, s09, u09)
screenerFun(10, s10, u10)
screenerFun(11, s11, u11)
screenerFun(12, s12, u12)
screenerFun(13, s13, u13)
screenerFun(14, s14, u14)
screenerFun(15, s15, u15)
///////////
// PLOTS //
var tbl = table.new(position.top_right, 3, 16, frame_color = #2b2d2f, frame_width =
2, border_width = 1, border_color = #4a4d51)
alert_msg = ''
if barstate.islast and indicator_enabled
table.clear(tbl, 0, 0, 2, 15)
table.cell(tbl, 0, 0, 'Symbol', text_halign = text.align_center, bgcolor =
color.rgb(45, 85, 155), text_color = color.rgb(240, 240, 240), text_size =
size.normal)
table.cell(tbl, 1, 0, 'Price', text_halign = text.align_center, bgcolor =
color.rgb(85, 45, 155), text_color = color.rgb(240, 240, 240), text_size =
size.normal)
table.cell(tbl, 2, 0, 'Trend', text_halign = text.align_center, bgcolor =
color.rgb(35, 120, 85), text_color = color.rgb(240, 240, 240), text_size =
size.normal)
if matrix.rows(screenerMtx) > 0
for i = 0 to matrix.rows(screenerMtx) - 1 by 1
is_filt = not filter_enabled or (filt_col_id == 0 ? true :
matrix.get(screenerMtx, i, filt_col_id) >= filter_from and matrix.get(screenerMtx,
i, filt_col_id) <= filter_to)
if is_filt
if str.length(alert_msg) > 0
alert_msg := alert_msg + ','
alert_msg
alert_msg := alert_msg + id_symbol(matrix.get(screenerMtx, i, 0))
sup_text = matrix.get(screenerMtx, i, 4) > 0 ? 'Down' : 'Up'
sup_col = matrix.get(screenerMtx, i, 4) < 0 ? color.rgb(76, 175, 80) :
color.rgb(244, 67, 54)
row_bg = i % 2 == 0 ? color.rgb(43, 45, 47) : color.rgb(53, 55, 59)
table.cell(tbl, 0, i + 1, id_symbol(matrix.get(screenerMtx, i, 0)),
text_halign = text.align_left, bgcolor = row_bg, text_color = color.rgb(224, 224,
224), text_size = size.normal)
table.cell(tbl, 1, i + 1, str.tostring(matrix.get(screenerMtx, i, 1)),
text_halign = text.align_center, bgcolor = row_bg, text_color = color.rgb(255, 255,
255), text_size = size.normal)
table.cell(tbl, 2, i + 1, sup_text, text_halign = text.align_center,
bgcolor = sup_col, text_color = color.rgb(255, 255, 255), text_size = size.normal)
if str.length(alert_msg) > 0 and indicator_enabled
alert(alert_msg, freq = alert.freq_once_per_bar_close)
// Show message when indicator is disabled
if barstate.islast and not indicator_enabled
table.clear(tbl, 0, 0, 2, 15)
table.cell(tbl, 0, 0, 'Indicator Disabled', text_halign = text.align_center,
bgcolor = #3a3d41, text_color = #e0e0e0, text_size = size.normal)
// ATR Calculation
atrLength = input.int(14, title = 'ATR Length')
atrValue = ta.atr(atrLength)
// ADX/DMI Calculation
adxLength = input.int(14, title = 'ADX DI Length')
adxSmoothing = input.int(14, title = 'ADX Smoothing')
[plusDI, minusDI, adxValue] = ta.dmi(adxLength, adxSmoothing)
// RSI Calculation
rsiLength = input.int(14, title = 'RSI Length')
rsiSource = ta.rsi(close, rsiLength)
// --- Table Display ---
var table myTable = table.new(position.bottom_right, columns = 2, rows = 4,
border_width = 1, frame_color = color.black)
if barstate.islast
// --- Determine Conditional Colors ---
// ATR Color Logic
atrPercentage = atrValue / close * 100
atrColor = atrPercentage > 5 ? color.new(color.red, 0) : atrPercentage < 3 ?
color.new(color.green, 0) : color.new(color.orange, 0)
// ADX Color Logic
adxColor = adxValue > 25 ? color.new(color.green, 0) : adxValue < 20 ?
color.new(color.red, 0) : color.new(color.orange, 0)
// RSI Color Logic
rsiColor = rsiValue > 70 ? color.new(color.red, 0) : rsiValue < 40 ?
color.new(color.green, 0) : color.new(color.orange, 0)
// --- Populate Table ---
// Header Row
table.cell(myTable, 0, 0, 'Indicator', text_color = color.white, bgcolor =
#f37521, text_halign = text.align_center)
table.cell(myTable, 1, 0, 'Value', text_color = color.white, bgcolor =
color.rgb(243, 33, 138), text_halign = text.align_center)
// ATR Row
table.cell(myTable, 0, 1, 'ATR', text_color = color.white, bgcolor =
color.rgb(0, 0, 0))
table.cell(myTable, 1, 1, str.tostring(atrValue, format.mintick), text_color =
color.white, bgcolor = atrColor)
// ADX Row
table.cell(myTable, 0, 2, 'ADX', text_color = color.white, bgcolor =
color.rgb(0, 60, 255))
table.cell(myTable, 1, 2, str.tostring(adxValue, '#.##'), text_color =
color.rgb(255, 255, 255), bgcolor = adxColor)
// RSI Row
table.cell(myTable, 0, 3, 'RSI', text_color = color.white, bgcolor = #000000)
table.cell(myTable, 1, 3, str.tostring(rsiValue, '#.##'), text_color =
color.white, bgcolor = rsiColor)
// ==== VISIBLE INPUT ====
showTable = input.bool(true, 'Show SL Table (On/Off)') // The ONLY toggle visible
// ==== FIXED BACKEND SETTINGS ====
atrLen = 14
atrMultiplier = 2.5
// ATR Calculation
atrData = ta.atr(atrLen)
// Upper & Lower Bands
upperBand = close + atrMultiplier * atrValue // Sell side SL (red)
lowerBand = close - atrMultiplier * atrValue // Buy side SL (green)
// Live Market Price
livePrice = close
// ==== TABLE ====
var table slTable = table.new(position.bottom_center, 3, 2, border_width = 1,
frame_color = color.gray)
// Update table only if toggle is ON
if barstate.islast
if showTable
// Headers
table.cell(slTable, 0, 0, 'Live Price', text_color = color.black, bgcolor =
color.yellow)
table.cell(slTable, 1, 0, 'Buy Side SL', text_color = color.white, bgcolor
= color.green)
table.cell(slTable, 2, 0, 'Sell Side SL', text_color = color.white, bgcolor
= color.red)
// Values
table.cell(slTable, 0, 1, str.tostring(livePrice, '#.##'), text_color =
color.black)
table.cell(slTable, 1, 1, str.tostring(lowerBand, '#.##'), text_color =
color.green)
table.cell(slTable, 2, 1, str.tostring(upperBand, '#.##'), text_color =
color.red)
else // Clears the table when OFF
table.clear(slTable, 0, 0)