name
stringlengths 1
64
| url
stringlengths 44
135
| author
stringlengths 3
30
| author_url
stringlengths 34
61
| likes_count
int64 0
33.2k
| kind
stringclasses 3
values | pine_version
int64 1
5
| license
stringclasses 3
values | source
stringlengths 177
279k
|
---|---|---|---|---|---|---|---|---|
Any Screener (Multiple) | https://www.tradingview.com/script/6pC1ZQdd-Any-Screener-Multiple/ | dg_factor | https://www.tradingview.com/u/dg_factor/ | 292 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ Author & Developer : ยฉ dg_factor [18.07.2023, Istanbul] โ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//@version=5
indicator("Any Screener (Multiple)", overlay=true)
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ SECTION 1 : INDICATORS โ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//{
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Inputs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
// Tooltips
string tt_per =
"When the percentage is 0.0,\n" +
"OTT is disabled and the signals are generated by the crossing of the closing price and the selected moving average."
string tt_osc =
"This option disables sequential signals in the same direction.\n" +
"ON : The Scanner shows how many bars have passed since the direction changed.\n" +
"OFF : The Scanner shows how many bars have passed since the last signal."
string tt_volt =
"BANDWIDTH and REGRESSION have been normalized. (For all time chart)"
//
string gr_ott = "โ โโโโโโโโโโโโโโโ OTT โโโโโโโโโโโโโโโโฃ"
mov_type = input.string(title="Type", defval="VAR", options=["SMA", "EMA", "EVWMA", "HULL", "VAR"], group=gr_ott)
ott_len = input.int(title="Length ", defval=50, group=gr_ott)
ott_per = input.float(title="Percent ", defval=2.5, group=gr_ott, tooltip=tt_per)
ott_sign = input.bool(title="Show Signals", defval=false, group=gr_ott)
string gr_sar = "โ โโโโโโโโโโโโโโ PSAR โโโโโโโโโโโโโโโโโฃ"
sar_start = input.float(title="Start ", defval=0.02, group=gr_sar)
sar_inc = input.float(title="Increment ", defval=0.02, group=gr_sar)
sar_max = input.float(title="Max", defval=0.2, group=gr_sar)
sar_sign = input.bool(title="Show Signals", defval=false, group=gr_sar)
string gr_osc = "โ โโโโโโโโโโโโ OSCILLATOR โโโโโโโโโโโโโฃ"
osc_type = input.string(title="Type", defval="MFI", options=["MFI", "RSI", "STOCH"], group=gr_osc)
osc_len = input.int(title="Length ", defval=14, group=gr_osc)
osc_os = input.int(title="Over Sold", defval=30, group=gr_osc)
osc_ob = input.int(title="Over Bought", defval=70, group=gr_osc)
osc_pyr = input.bool(title="Avoid Pyramiding", defval=true, group=gr_osc, tooltip=tt_osc)
osc_sign = input.bool(title="Show Signals", defval=false, group=gr_osc)
string gr_volt = "โ โโโโโโโโโโ VOLATILITY & TREND โโโโโโโโโโโฃ"
volt_type = input.string(title="Type", defval="REG-N", options=["ADX", "BBW-N", "REG-N"], group=gr_volt, tooltip=tt_volt)
volt_len = input.int(title="Length ", defval=14, group=gr_volt)
//
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Functions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
// Hull Moving Average [HULL]
f_hull(series float x, series int y) =>
a = y == 1 ? 1 : y / 2
b = 2 * ta.wma(x, a) - ta.wma(x, y)
r = ta.wma(b, math.round(math.sqrt(y)))
//
// Elastic Volume Weighted Moving Average [EVWMA]
f_evwma(series float x, series int y) =>
a = ta.sma(x, y)
b = math.sum(volume, y)
r = 0.0, r := na(r[1]) ? a : nz(r[1]) * (b - volume) / b + volume * x / b
//
// Variable Index Dynamic Adaptive Moving Average [VAR]
f_var(series float x, series int y) =>
a = ta.sma(x, y)
b = math.abs(ta.change(x, 9))
c = math.sum(math.abs(ta.change(x)), 9)
d = c != 0 ? b / c : 0
e = 2 / (y + 1)
r = 0.0, r := na(r[1]) ? a : d * e * (x - nz(r[1])) + nz(r[1])
//
// Moving Average
f_mov(simple string x, series float y, simple int z) =>
x == "SMA" ? ta.sma(y, z) :
x == "EMA" ? ta.ema(y, z) :
x == "EVWMA" ? f_evwma(y, z) :
x == "HULL" ? f_hull(y, z) :
x == "VAR" ? f_var(y, z) : na
//
// Optimized Trend Tracker
f_ott(series float x, series float y) =>
a = y / 100
b = x * a, c = x - b, d = x + b
c := c > nz(c[1]) or x < nz(c[1]) ? c : nz(c[1])
d := d < nz(d[1]) or x > nz(d[1]) ? d : nz(d[1])
e = 0.0, e := x > nz(e[1]) ? c : x < nz(e[1]) ? d : nz(e[1])
f = 1 + a / 2
g = 1 - a / 2
h = x > e ? e * f : e * g
r = nz(h[2])
//
// Oscillator
f_osc(simple string x, simple int y) =>
x == "MFI" ? ta.mfi(hlc3, y) :
x == "RSI" ? ta.rsi(close, y) :
x == "STOCH" ? ta.stoch(close, high, low, y) : na
//
// Volatility
f_volt(simple string x, simple int y) =>
[_, _, a] = ta.dmi(y, y)
b = ta.bbw(close, y, 2)
c = math.sqrt(ta.sma(math.pow(close - ta.linreg(close, y, 0), 2), y))
r =
x == "ADX" ? a :
x == "BBW-N" ? (b - ta.min(b)) / (ta.max(b) - ta.min(b)) * 100 :
x == "REG-N" ? (c - ta.min(c)) / (ta.max(c) - ta.min(c)) * 100 :
na
//
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Out โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
// Return
_sup = f_mov(mov_type, close, ott_len)
_ott = f_ott(_sup, ott_per)
_sar = ta.sar(sar_start, sar_inc, sar_max)
_osc = f_osc(osc_type, osc_len)
osc_l = ta.crossover(_osc, osc_os)
osc_s = ta.crossunder(_osc, osc_ob)
osc_bl = ta.barssince(osc_l) < ta.barssince(osc_s)
osc_bs = ta.barssince(osc_l) > ta.barssince(osc_s)
_volt = f_volt(volt_type, volt_len)
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ Data For Screener โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
// Long Conditions
long_1 = ott_per != 0.0 ? ta.crossover(_sup, _ott) : ta.crossover(close, _sup)
long_2 = ta.crossover(close, _sar)
long_3 = not osc_pyr ? osc_l : ta.cum(osc_l ? 1 : na) == 1 or osc_bl and (osc_bs[1] or not osc_bl[1])
// Short Conditions
short_1 = ott_per != 0.0 ? ta.crossunder(_sup, _ott) : ta.crossunder(close, _sup)
short_2 = ta.crossunder(close, _sar)
short_3 = not osc_pyr ? osc_s : ta.cum(osc_s ? 1 : na) == 1 or osc_bs and (osc_bl[1] or not osc_bs[1])
// Text Only
text_only = _volt
// Titles are required for the table
string title_1 = ott_per != 0.0 ? "OTT" : mov_type
string title_2 = "PSAR"
string title_3 = osc_type
string title_4 = volt_type
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Plot Signals โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
sl = shape.triangleup, ss = shape.triangledown,
ll = location.belowbar, ls = location.abovebar,
sz = size.tiny, cl = #00bb00, cs = #bb0000
plotshape(ott_sign ? ott_per != 0.0 and long_1 : na, "OTT Long", sl, ll, cl, text="OTT\nLong", textcolor=cl, size=sz)
plotshape(ott_sign ? ott_per != 0.0 and short_1 : na, "OTT Short", ss, ls, cs, text="OTT\nShort", textcolor=cs, size=sz)
plotshape(ott_sign ? ott_per == 0.0 and long_1 : na, "MA Long", sl, ll, cl, text="MA\nLong", textcolor=cl, size=sz)
plotshape(ott_sign ? ott_per == 0.0 and short_1 : na, "MA Short", ss, ls, cs, text="MA\nShort", textcolor=cs, size=sz)
plotshape(sar_sign ? long_2 : na, "PSAR Long", sl, ll, cl, text="PSAR\nLong", textcolor=cl, size=sz)
plotshape(sar_sign ? short_2 : na, "PSAR Short", ss, ls, cs, text="PSAR\nShort", textcolor=cs, size=sz)
plotshape(osc_sign ? long_3 : na, "OSC Long", sl, ll, cl, text="OSC\nLong", textcolor=cl, size=sz)
plotshape(osc_sign ? short_3 : na, "OSC Short", ss, ls, cs, text="OSC\nShort", textcolor=cs, size=sz)
//}
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โ SECTION 2 : SCREENER โ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//{
// The "SCREENER" section has been prepared in a way that can adapt to the variables defined above.
// Delete the Section 1 and code your own conditions and titles :
// (long_1, short_1, long_2, short_2, long_3, short_3, text_only) & (title_1, title_2, title_3, title_4)
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Inputs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
string gr_sc = "โ โโโโโโโโโโโโโ SCREENER โโโโโโโโโโโโโโฃ"
tb_sh = input.bool(title="Show Table", defval=true, group=gr_sc)
sh_pr = input.bool(title="Show Prefix", defval=false, group=gr_sc)
tb_ps = input.string(title="Positionย ย ย ", options=["Left", "Right", "Center"], defval="Right", group=gr_sc, inline="p")
tb_sz = input.string(title="Text Sizeย ", options=["Auto", "Small", "Normal", "Large"], defval="Normal", group=gr_sc, inline="s")
col_s = input.color(title="Coloursย ย ย ", defval=#00a5ba, group=gr_sc, inline="c") // Symbol
col_u = input.color(title="", defval=#00bb00, group=gr_sc, inline="c") // Up (Long)
col_d = input.color(title="", defval=#bb0000, group=gr_sc, inline="c") // Down (Short)
col_n = input.color(title="", defval=#686868, group=gr_sc, inline="c") // Neutral
string gr_sy = "โ โโโโโโโโโโโโโ SYMBOLS โโโโโโโโโโโโโโโฃ"
s01 = input.symbol(title="Symbol 01", inline="01", group=gr_sy, defval="BINANCE:BTCUSDT")
s02 = input.symbol(title="Symbol 02", inline='02', group=gr_sy, defval='BINANCE:ETHUSDT')
s03 = input.symbol(title="Symbol 03", inline="03", group=gr_sy, defval="BINANCE:BNBUSDT")
s04 = input.symbol(title="Symbol 04", inline="04", group=gr_sy, defval="BINANCE:ADAUSDT")
s05 = input.symbol(title="Symbol 05", inline="05", group=gr_sy, defval="BINANCE:AVAXUSDT")
s06 = input.symbol(title="Symbol 06", inline="06", group=gr_sy, defval="BINANCE:CHZUSDT")
s07 = input.symbol(title="Symbol 07", inline="07", group=gr_sy, defval="BINANCE:DOGEUSDT")
s08 = input.symbol(title="Symbol 08", inline="08", group=gr_sy, defval="BINANCE:SOLUSDT")
s09 = input.symbol(title="Symbol 09", inline="09", group=gr_sy, defval="BINANCE:TRXUSDT")
s10 = input.symbol(title="Symbol 10", inline="10", group=gr_sy, defval="BINANCE:XRPUSDT")
s11 = input.symbol(title="Symbol 11", inline='11', group=gr_sy, defval='NASDAQ:AAPL')
s12 = input.symbol(title="Symbol 12", inline='12', group=gr_sy, defval='NASDAQ:TSLA')
s13 = input.symbol(title="Symbol 13", inline='13', group=gr_sy, defval='NASDAQ:AMZN')
s14 = input.symbol(title="Symbol 14", inline='14', group=gr_sy, defval='NASDAQ:GOOGL')
s15 = input.symbol(title="Symbol 15", inline='15', group=gr_sy, defval='NASDAQ:NVDA')
// You can obtain various time frame results by defining inputs equal to the number of symbols to be used in the security function.
string x00 = timeframe.period
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Functions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
f_data(series bool x, series bool y) =>
r1 = 0, r1 := x ? 1 : y ? -1 : r1[1] // direction
r2 = ta.barssince(r1 != nz(r1[1])) // barssince
r3 = r1 == 1 ? col_u : r1 == -1 ? col_d : col_n // color
[r1, r2, r3]
//
f_screener() =>
[x1, y1, z1] = f_data(long_1, short_1)
[x2, y2, z2] = f_data(long_2, short_2)
[x3, y3, z3] = f_data(long_3, short_3)
t = text_only
[x1, x2, x3, y1, y2, y3, z1, z2, z3, t]
//
// Yรถn, Bar
f_text(int x, int y) =>
r1 = " "
r2 = str.tostring(y)
r3 = x == 1 ? r1 + "โฒ [" + r2 + "]" : x == -1 ? r1 + "โผ [" + r2 + "]" : r1 + "โ [" + r2 + "]"
//
f_prefix(simple string x) =>
r = sh_pr ? x : str.substring(x, str.pos(x, ':') + 1)
//
f_size(simple string x) =>
x == "Small" ? size.small :
x == "Normal" ? size.normal :
x == "Large" ? size.large : size.auto
//
f_position(simple string x) =>
x == "Left" ? position.top_left :
x == "Right" ? position.top_right : position.top_center
//
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Variables โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
[a01, b01, c01, d01, e01, f01, g01, h01, i01, j01] = request.security(s01, x00, f_screener())
[a02, b02, c02, d02, e02, f02, g02, h02, i02, j02] = request.security(s02, x00, f_screener())
[a03, b03, c03, d03, e03, f03, g03, h03, i03, j03] = request.security(s03, x00, f_screener())
[a04, b04, c04, d04, e04, f04, g04, h04, i04, j04] = request.security(s04, x00, f_screener())
[a05, b05, c05, d05, e05, f05, g05, h05, i05, j05] = request.security(s05, x00, f_screener())
[a06, b06, c06, d06, e06, f06, g06, h06, i06, j06] = request.security(s06, x00, f_screener())
[a07, b07, c07, d07, e07, f07, g07, h07, i07, j07] = request.security(s07, x00, f_screener())
[a08, b08, c08, d08, e08, f08, g08, h08, i08, j08] = request.security(s08, x00, f_screener())
[a09, b09, c09, d09, e09, f09, g09, h09, i09, j09] = request.security(s09, x00, f_screener())
[a10, b10, c10, d10, e10, f10, g10, h10, i10, j10] = request.security(s10, x00, f_screener())
[a11, b11, c11, d11, e11, f11, g11, h11, i11, j11] = request.security(s11, x00, f_screener())
[a12, b12, c12, d12, e12, f12, g12, h12, i12, j12] = request.security(s12, x00, f_screener())
[a13, b13, c13, d13, e13, f13, g13, h13, i13, j13] = request.security(s13, x00, f_screener())
[a14, b14, c14, d14, e14, f14, g14, h14, i14, j14] = request.security(s14, x00, f_screener())
[a15, b15, c15, d15, e15, f15, g15, h15, i15, j15] = request.security(s15, x00, f_screener())
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Return โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
i1_t01 = f_text(a01, d01), i2_t01 = f_text(b01, e01), i3_t01 = f_text(c01, f01), i4_t01 = str.tostring(j01, "#.##")
i1_t02 = f_text(a02, d02), i2_t02 = f_text(b02, e02), i3_t02 = f_text(c02, f02), i4_t02 = str.tostring(j02, "#.##")
i1_t03 = f_text(a03, d03), i2_t03 = f_text(b03, e03), i3_t03 = f_text(c03, f03), i4_t03 = str.tostring(j03, "#.##")
i1_t04 = f_text(a04, d04), i2_t04 = f_text(b04, e04), i3_t04 = f_text(c04, f04), i4_t04 = str.tostring(j04, "#.##")
i1_t05 = f_text(a05, d05), i2_t05 = f_text(b05, e05), i3_t05 = f_text(c05, f05), i4_t05 = str.tostring(j05, "#.##")
i1_t06 = f_text(a06, d06), i2_t06 = f_text(b06, e06), i3_t06 = f_text(c06, f06), i4_t06 = str.tostring(j06, "#.##")
i1_t07 = f_text(a07, d07), i2_t07 = f_text(b07, e07), i3_t07 = f_text(c07, f07), i4_t07 = str.tostring(j07, "#.##")
i1_t08 = f_text(a08, d08), i2_t08 = f_text(b08, e08), i3_t08 = f_text(c08, f08), i4_t08 = str.tostring(j08, "#.##")
i1_t09 = f_text(a09, d09), i2_t09 = f_text(b09, e09), i3_t09 = f_text(c09, f09), i4_t09 = str.tostring(j09, "#.##")
i1_t10 = f_text(a10, d10), i2_t10 = f_text(b10, e10), i3_t10 = f_text(c10, f10), i4_t10 = str.tostring(j10, "#.##")
i1_t11 = f_text(a11, d11), i2_t11 = f_text(b11, e11), i3_t11 = f_text(c11, f11), i4_t11 = str.tostring(j11, "#.##")
i1_t12 = f_text(a12, d12), i2_t12 = f_text(b12, e12), i3_t12 = f_text(c12, f12), i4_t12 = str.tostring(j12, "#.##")
i1_t13 = f_text(a13, d13), i2_t13 = f_text(b13, e13), i3_t13 = f_text(c13, f13), i4_t13 = str.tostring(j13, "#.##")
i1_t14 = f_text(a14, d14), i2_t14 = f_text(b14, e14), i3_t14 = f_text(c14, f14), i4_t14 = str.tostring(j14, "#.##")
i1_t15 = f_text(a15, d15), i2_t15 = f_text(b15, e15), i3_t15 = f_text(c15, f15), i4_t15 = str.tostring(j15, "#.##")
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Info Panel โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
string sp = " "
var table tb = table.new(position=f_position(tb_ps), columns=6, rows=20)
f_print(x, y, z, p, q) =>
table.cell(tb, x, y+1, q, text_color=z, text_halign=p == "" ? text.align_left : text.align_center, text_size=f_size(tb_sz))
if barstate.islast and tb_sh
f_print(0, -1, col_s, "", ""), f_print(0, 0, col_s, "", "")
f_print(1, -1, col_s, "", ""), f_print(1, 0, col_s, "c", sp + title_1)
f_print(2, -1, col_s, "", ""), f_print(2, 0, col_s, "c", sp + title_2)
f_print(3, -1, col_s, "", ""), f_print(3, 0, col_s, "c", sp + title_3)
f_print(4, -1, col_s, "", ""), f_print(4, 0, col_s, "c", sp + title_4)
f_print(0, 1, col_s, "", f_prefix(s01)), f_print(1, 1, g01, "", i1_t01)
f_print(0, 2, col_s, "", f_prefix(s02)), f_print(1, 2, g02, "", i1_t02)
f_print(0, 3, col_s, "", f_prefix(s03)), f_print(1, 3, g03, "", i1_t03)
f_print(0, 4, col_s, "", f_prefix(s04)), f_print(1, 4, g04, "", i1_t04)
f_print(0, 5, col_s, "", f_prefix(s05)), f_print(1, 5, g05, "", i1_t05)
f_print(0, 6, col_s, "", f_prefix(s06)), f_print(1, 6, g06, "", i1_t06)
f_print(0, 7, col_s, "", f_prefix(s07)), f_print(1, 7, g07, "", i1_t07)
f_print(0, 8, col_s, "", f_prefix(s08)), f_print(1, 8, g08, "", i1_t08)
f_print(0, 9, col_s, "", f_prefix(s09)), f_print(1, 9, g09, "", i1_t09)
f_print(0, 10, col_s, "", f_prefix(s10)), f_print(1, 10, g10, "", i1_t10)
f_print(0, 11, col_s, "", f_prefix(s11)), f_print(1, 11, g11, "", i1_t11)
f_print(0, 12, col_s, "", f_prefix(s12)), f_print(1, 12, g12, "", i1_t12)
f_print(0, 13, col_s, "", f_prefix(s13)), f_print(1, 13, g13, "", i1_t13)
f_print(0, 14, col_s, "", f_prefix(s14)), f_print(1, 14, g14, "", i1_t14)
f_print(0, 15, col_s, "", f_prefix(s15)), f_print(1, 15, g15, "", i1_t15)
f_print(2, 1, h01, "", i2_t01), f_print(3, 1, i01, "", i3_t01), f_print(4, 1, col_n, "", sp + i4_t01)
f_print(2, 2, h02, "", i2_t02), f_print(3, 2, i02, "", i3_t02), f_print(4, 2, col_n, "", sp + i4_t02)
f_print(2, 3, h03, "", i2_t03), f_print(3, 3, i03, "", i3_t03), f_print(4, 3, col_n, "", sp + i4_t03)
f_print(2, 4, h04, "", i2_t04), f_print(3, 4, i04, "", i3_t04), f_print(4, 4, col_n, "", sp + i4_t04)
f_print(2, 5, h05, "", i2_t05), f_print(3, 5, i05, "", i3_t05), f_print(4, 5, col_n, "", sp + i4_t05)
f_print(2, 6, h06, "", i2_t06), f_print(3, 6, i06, "", i3_t06), f_print(4, 6, col_n, "", sp + i4_t06)
f_print(2, 7, h07, "", i2_t07), f_print(3, 7, i07, "", i3_t07), f_print(4, 7, col_n, "", sp + i4_t07)
f_print(2, 8, h08, "", i2_t08), f_print(3, 8, i08, "", i3_t08), f_print(4, 8, col_n, "", sp + i4_t08)
f_print(2, 9, h09, "", i2_t09), f_print(3, 9, i09, "", i3_t09), f_print(4, 9, col_n, "", sp + i4_t09)
f_print(2, 10, h10, "", i2_t10), f_print(3, 10, i10, "", i3_t10), f_print(4, 10, col_n, "", sp + i4_t10)
f_print(2, 11, h11, "", i2_t11), f_print(3, 11, i11, "", i3_t11), f_print(4, 11, col_n, "", sp + i4_t11)
f_print(2, 12, h12, "", i2_t12), f_print(3, 12, i12, "", i3_t12), f_print(4, 12, col_n, "", sp + i4_t12)
f_print(2, 13, h13, "", i2_t13), f_print(3, 13, i13, "", i3_t13), f_print(4, 13, col_n, "", sp + i4_t13)
f_print(2, 14, h14, "", i2_t14), f_print(3, 14, i14, "", i3_t14), f_print(4, 14, col_n, "", sp + i4_t14)
f_print(2, 15, h15, "", i2_t15), f_print(3, 15, i15, "", i3_t15), f_print(4, 15, col_n, "", sp + i4_t15)
//}
// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Bitti โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฃ
plotshape(barstate.isfirst, "@ dg_factor", color=#13172200, editable=false) |
Previous OHLC Levels [TradeMaster Lite] | https://www.tradingview.com/script/lE5dbp3m-Previous-OHLC-Levels-TradeMaster-Lite/ | trademasterindicator | https://www.tradingview.com/u/trademasterindicator/ | 84 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Copyright (c) 2023 trademasterindicator. All rights reserved.
// The Pinescript source code ("Previous OHLC Levels [TradeMaster Lite]") is exclusively licensed to trademasterindicator TradingView account. No other use is permitted without written consent from trademasterindicator.
// By accessing or using the script, you agree to the following terms:
// Grant of License: You are granted a non-transferable license to use the script for personal, non-commercial purposes related to technical analysis and trading on TradingView.
// Ownership and Intellectual Property: trademasterindicator retains all ownership and intellectual property rights to the script. You may not modify, reverse engineer, or distribute the script.
// Disclaimer of Warranty: The source code is provided as-is, without warranties. trademasterindicator shall not be liable for any damages arising from its use.
// Termination: This license is valid until terminated.
//@version=5
indicator('Previous OHLC Levels [TradeMaster Lite]', 'Previous OHLC [TradeMaster Lite]', overlay = true)
i_showPlot = input.bool (true , 'Historical data' , group = 'calculation', inline = 'display', display = display.none)
i_showCurrent = input.bool (true , 'Current data' , group = 'calculation', inline = 'display', display = display.none)
i_pOHLC_tf = input.timeframe('W' , '' , group = 'calculation', inline = 'display', display = display.all , tooltip = "These levels can provide critical information about the previous trading period, whether it's a day, hour, week, or any other timeframe depending on your setting.\n\nโ Previous Open: shows the opening price of the previous period. It's the price at which the market first started trading in that period.\nโ Previous High: represents the highest price reached during the previous period. It can act as a resistance level for the current period.\nโ Previous Low: indicates the lowest price hit during the previous period. It can serve as a support level in the current period.\nโ Previous Close: the last price at which the asset traded during the previous period. It's often considered the most accurate reflection of the market sentiment at the end of that period.\n\nThese values provide a summary of the previous trading period's price action, giving you a baseline for comparing current price movements. They can help in understanding the market's direction and identifying potential support and resistance levels.")
i_offsetRight = input.int (20 , 'Offset drawings right' , group = 'style' , display = display.none, tooltip = 'This setting lets you align drawings slightly to the right of their original position. It can be useful to prevent overlapping with price action or other indicators on the chart.')
i_textSize = input.string (size.small , 'Text size on the Chart', group = 'style' , display = display.none, options = [size.tiny, size.small, size.normal, size.large, size.huge])
i_clrPOHLC = input.color (#3bd8ffb3, 'Color' , group = 'style')
get_pOHLC(tf) => request.security(syminfo.tickerid, tf, array.from(high[1], low[1], open[1], close[1]), barmerge.gaps_off, barmerge.lookahead_on)
convertTimeframe(string tf) =>
var tf_int = str.tonumber(tf)
tf_int % 60 == 0 ? str.format("{0}h", tf_int / 60) : str.format("{0}{1}", tf, na(tf_int) or str.endswith(tf, 'D') or str.endswith(tf, 'W') or str.endswith(tf, 'M') ? '' : 'm')
var pOHLCs = array.new<float>(4)
var lines = array.new<line>()
var labels = array.new<label>()
txts = array.from('high', 'low', 'open', 'close')
pOHLCs := timeframe.change(i_pOHLC_tf) or barstate.isfirst ? get_pOHLC(i_pOHLC_tf) : pOHLCs
if i_showCurrent
for [i,e] in pOHLCs
if barstate.isfirst
lines .push(line.new (na,na,na,na, xloc.bar_time, extend.none, i_clrPOHLC, i < 2 ? line.style_dotted : line.style_solid))
labels.push(label.new(na,na,na , xloc.bar_time, yloc.price , #ffffff00, label.style_label_left, i_clrPOHLC, i_textSize, text_font_family = font.family_monospace))
if barstate.islast
ln = lines .get(i)
lbl = labels.get(i)
ln.set_xy1 (time, e)
ln.set_xy2 (time + i_offsetRight * timeframe.in_seconds() * 1000, e)
lbl.set_xy (time + i_offsetRight * timeframe.in_seconds() * 1000, e)
lbl.set_text (str.format('prev.{0} {1}', i_pOHLC_tf, txts.get(i)))
lbl.set_tooltip(str.tostring(e))
plot_high = plot(i_showPlot ? pOHLCs.get(0) : na, 'prev. high' , na)
plot_low = plot(i_showPlot ? pOHLCs.get(1) : na, 'prev. low' , na)
plot_open = plot(i_showPlot ? pOHLCs.get(2) : na, 'prev. open' , na)
plot_close = plot(i_showPlot ? pOHLCs.get(3) : na, 'prev. close', na)
fill(plot_high, plot_low , pOHLCs.get(0) != pOHLCs.get(0)[1] ? na : color.new(i_clrPOHLC,90))
fill(plot_open, plot_close, pOHLCs.get(2) != pOHLCs.get(2)[1] ? na : color.new(i_clrPOHLC,80)) |
Ticker | https://www.tradingview.com/script/QiVEhv6R-Ticker/ | ozzy_livin | https://www.tradingview.com/u/ozzy_livin/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ BOtrades
//@version=5
indicator(title="Ticker", overlay=true)
// On the last historical bar, make a label that shows the
// instrument's symbol and exchange.
var textbox = table.new(position = position.top_left, columns = 2, rows = 3)
// Color Customization
textlight = input.color(color.new(#FFFFFF, 0), title="Text Color")
textdark = input.color(color.new(#333333, 0), title="Subtext Color")
cellbg = input.color(color.new(#ffbb3d, 0), title="Subtext Color")
// Ticker Customization
ticker = str.replace_all(syminfo.ticker, "USD", "")
// Symbol Customization
symbol = syminfo.description
arr = array.new_string(0)
array.push(arr, " / United States Dollar")
array.push(arr, " / U.S. Dollar")
array.push(arr, " / U. S. Dollar")
array.push(arr, " / U.S. dollar")
array.push(arr, " / US Dollar")
array.push(arr, " all time history index")
array.push(arr, " (calculated by TradingView)")
array.push(arr, " (CALCULATED BY TRADINGVIEW)")
array.push(arr, " (CONTINUOUS: CURRENT CONTRACT IN FRONT)")
array.push(arr, " INDUSTRIAL AVERAGE")
for i = 0 to array.size(arr) - 1
symbol := str.replace_all(symbol, str.tostring(array.get(arr, i)), "")
if barstate.islast
table.cell(table_id = textbox, column = 0, row = 0, text_size=size.tiny, width = 3, height = 5)
table.cell(table_id = textbox, column = 1, row = 1, text_size=size.huge, text = ticker, text_color = textlight)
table.cell(table_id = textbox, column = 1, row = 2, text_size=size.small, text = symbol, text_color = textdark, bgcolor = cellbg)
|
EMA-Deviation-Corrected T3 [Loxx] | https://www.tradingview.com/script/V2Sr2MNG-EMA-Deviation-Corrected-T3-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 85 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("EMA-Deviation-Corrected T3 [Loxx]",
overlay = true,
timeframe="",
timeframe_gaps = true)
var color greencolor = #2DD204
var color redcolor = #D2042D
import loxx/loxxexpandedsourcetypes/4
t3filter(float src, float per, float hot, string clean)=>
float a = hot
float _c1 = -a * a * a
float _c2 = 3 * a * a + 3 * a * a * a
float _c3 = -6 * a * a - 3 * a - 3 * a * a * a
float _c4 = 1 + 3 * a + a * a * a + 3 * a * a
float alpha = 0.
if (clean == "T3 New")
alpha := 2.0 / (2.0 + (per - 1.0) / 2.0)
else
alpha := 2.0 / (1.0 + per)
float _t30 = src, _t31 = src
float _t32 = src, _t33 = src
float _t34 = src, _t35 = src
_t30 := nz(_t30[1]) + alpha * (src - nz(_t30[1]))
_t31 := nz(_t31[1]) + alpha * (_t30 - nz(_t31[1]))
_t32 := nz(_t32[1]) + alpha * (_t31 - nz(_t32[1]))
_t33 := nz(_t33[1]) + alpha * (_t32 - nz(_t33[1]))
_t34 := nz(_t34[1]) + alpha * (_t33 - nz(_t34[1]))
_t35 := nz(_t35[1]) + alpha * (_t34 - nz(_t35[1]))
float out =
_c1 * _t35 + _c2 * _t34 +
_c3 * _t33 + _c4 * _t32
out
corrMaEmaDev(float price, float avg, simple int period)=>
float ema0 = 0.,float ema1 = 0., float corr = 0.
float alpha = 2.0 / (1.0 + period)
ema0 := ta.ema(price, period)
ema1 := ta.ema(price*price, period)
float _deviation = math.max(math.sqrt(period * (ema1 - ema0 * ema0) / math.max(period - 1, 1)), 0.0)
float v1 = math.pow(_deviation, 2)
float v2 = math.pow(nz(corr[1]) - avg, 2)
float c = (v2 < v1 or v2 == 0) ? 0 : 1 - v1 / v2
corr := nz(corr[1]) + c * (avg - nz(corr[1]))
corr
smthtype = input.string("Kaufman", "Heikin-Ashi Better Caculation Type", options = ["AMA", "T3", "Kaufman"], group = "Source Settings")
srcin = input.string("Close", "Source", group= "Source Settings",
options =
["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",
"HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",
"HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])
per = input.int(10, "T3 Period", group= "T3 Settings")
t3hot = input.float(.7, "T3 Hot", group= "T3 Settings")
t3swt = input.string("T3 New", "T3 Type", options = ["T3 New", "T3 Original"], group = "T3 Settings")
colorbars = input.bool(true, "Color bars?", group = "UI Options")
bool showSigs = input.bool(false, "Show signals?", group = "UI Options")
kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")
ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")
amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")
amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")
haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)
haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)
hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)
halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)
hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)
hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)
haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)
haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)
src = switch srcin
"Close" => loxxexpandedsourcetypes.rclose()
"Open" => loxxexpandedsourcetypes.ropen()
"High" => loxxexpandedsourcetypes.rhigh()
"Low" => loxxexpandedsourcetypes.rlow()
"Median" => loxxexpandedsourcetypes.rmedian()
"Typical" => loxxexpandedsourcetypes.rtypical()
"Weighted" => loxxexpandedsourcetypes.rweighted()
"Average" => loxxexpandedsourcetypes.raverage()
"Average Median Body" => loxxexpandedsourcetypes.ravemedbody()
"Trend Biased" => loxxexpandedsourcetypes.rtrendb()
"Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()
"HA Close" => loxxexpandedsourcetypes.haclose(haclose)
"HA Open" => loxxexpandedsourcetypes.haopen(haopen)
"HA High" => loxxexpandedsourcetypes.hahigh(hahigh)
"HA Low" => loxxexpandedsourcetypes.halow(halow)
"HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)
"HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)
"HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)
"HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)
"HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)
"HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)
"HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)
"HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)
"HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)
"HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)
"HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)
"HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)
"HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)
"HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)
"HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)
"HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)
"HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)
=> haclose
t3 = t3filter(src, per, t3hot, t3swt)
corrout = corrMaEmaDev(src, t3, per)
colorout = t3 > corrout ? greencolor : redcolor
barcolor(colorbars ? colorout : na)
plot(t3, color = colorout, linewidth = 2)
plot(corrout, color = color.yellow, linewidth = 1)
goLong = ta.crossover(t3, corrout)
goShort = ta.crossunder(t3, corrout)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.small)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.small)
alertcondition(goLong, title="Long", message="EMA-Deviation-Corrected T3 [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="EMA-Deviation-Corrected T3 [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
Extrapolated Previous Trend [LuxAlgo] | https://www.tradingview.com/script/oZ5v4fFM-Extrapolated-Previous-Trend-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 1,345 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ LuxAlgo
//@version=5
indicator("Extrapolated Previous Trend [LuxAlgo]", "LuxAlgo - Extrapolated Previous Trend", overlay = true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
tf = input.timeframe('D', 'Timeframe')
//Dashboard
showDash = input(false, 'Show Dashboard', group = 'Dashboard')
dashLoc = input.string('Top Right', 'Location', options = ['Top Right', 'Bottom Right', 'Bottom Left'], group = 'Dashboard')
textSize = input.string('Small', 'Size' , options = ['Tiny', 'Small', 'Normal'] , group = 'Dashboard')
//-----------------------------------------------------------------------------}
//Compute previous day trend
//-----------------------------------------------------------------------------{
//Hold variables
var y = array.new<float>(0)
var x = array.new<int>(0)
var float a = na
var float b = na
var color css = na
var up_per = 0
var up_den = 0
var dn_per = 0
var dn_den = 0
n = bar_index
dtf = timeframe.change(tf)
//Test for timeframe change
if dtf
if y.size() > 0
//Calculate regression coefficients
slope = x.covariance(y) / x.variance()
up_per += slope > 0 and a > 0 ? 1 : 0
up_den += a > 0 ? 1 : 0
dn_per += slope < 0 and a < 0 ? 1 : 0
dn_den += a < 0 ? 1 : 0
a := slope
b := y.avg() - a * x.avg()
css := a > 0 ? #00897B : #FF5252
//Clear arrays and push data
y.clear(), x.clear()
y.push(close), x.push(n)
else
y.push(close)
x.push(n)
//output
epdt = a * n + b
//-----------------------------------------------------------------------------}
//Dashboard
//-----------------------------------------------------------------------------{
var table_position = dashLoc == 'Bottom Left' ? position.bottom_left
: dashLoc == 'Top Right' ? position.top_right
: position.bottom_right
var table_size = textSize == 'Tiny' ? size.tiny
: textSize == 'Small' ? size.small
: size.normal
var tb = table.new(table_position, 2, 3
, bgcolor = #1e222d
, border_color = #373a46
, border_width = 1
, frame_color = #373a46
, frame_width = 1)
if showDash
if barstate.isfirst
tb.cell(0, 0, 'Trend Persistence', text_color = color.white, text_size = table_size)
tb.merge_cells(0,0,1,0)
tb.cell(0, 1, 'Uptrend', text_color = #089981, text_size = table_size)
tb.cell(1, 1, 'Downtrend', text_color = #f23645, text_size = table_size)
if barstate.islast
tb.cell(0, 2, str.tostring(up_per / up_den * 100, format.percent), text_color = #089981, text_size = table_size)
tb.cell(1, 2, str.tostring(dn_per / dn_den * 100, format.percent), text_color = #f23645, text_size = table_size)
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot(epdt, 'Extrapolated Previous Trend', dtf ? na : css)
barcolor(a > 0 ? #00897b80 : #ff525280)
bgcolor(dtf ? #787b8680 : na, title = 'Timeframe Change')
//-----------------------------------------------------------------------------} |
Gradient Money Flow Divergence Detector | https://www.tradingview.com/script/ZZSoZEf1-Gradient-Money-Flow-Divergence-Detector/ | JohannCoffee | https://www.tradingview.com/u/JohannCoffee/ | 180 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ JohannCoffee
// Credit HALDRO for the Divergence and Pivot - Detector For Any Indicator
//@version=5
indicator(title = "Gradient Money Flow Divergence Detector", shorttitle = "MF with Divs", overlay = false)
//Moneyflow
length = input.int(14, title="Length", minval=1, group = "---- Money Flow ----")
mfisrc = close
typical_price = hlc3
money_flow = typical_price * volume
positive_flow = math.sum(money_flow * (typical_price > typical_price[1] ? 1 : 0), length)
negative_flow = math.sum(money_flow * (typical_price < typical_price[1] ? 1 : 0), length)
money_flow_ratio = positive_flow / negative_flow
mfi = 100 - (100 / (1 + money_flow_ratio))
// Plot Gradient
red1 = 58, green1 = 80, blue1 = 107 // Color: 3a506b
red2 = 111, green2 = 255, blue2 = 233 // Color: 6fffe9
max_mfi = ta.highest(mfi, length) // max value in the last "length" periods
min_mfi = ta.lowest(mfi, length) // min value in the last "length" periods
mfi_range = max_mfi - min_mfi
mfi_normalized = (mfi - min_mfi) / mfi_range
red = red1 + mfi_normalized * (red2 - red1)
green = green1 + mfi_normalized * (green2 - green1)
blue = blue1 + mfi_normalized * (blue2 - blue1)
mfi_gradient_color = color.new(color.rgb(math.floor(red), math.floor(green), math.floor(blue)), transp=0)
plotchar(mfi, 'Money Flow Line', location = location.bottom, color=mfi_gradient_color, size = size.large, char = '-')
plot(mfi, 'Money Flow', color=mfi_gradient_color, linewidth=3)
// Plotting additional lines
hline(20, "Line 1", color=color.rgb(68,70,81), linewidth=1, linestyle=hline.style_dashed)
hline(50, "Line 2", color=color.rgb(68,70,81), linewidth=1, linestyle=hline.style_solid)
hline(80, "Line 3", color=color.rgb(68,70,81), linewidth=1, linestyle=hline.style_dashed)
// div detector 1 - Micro Div
// Inputs
groupdiv = '---- Micro Div Lookback ----'
pivR = 1
pivL = 21
lbR = 1
lbL = input.int (5, ' ' , group = groupdiv, inline = '1')
rangeUpper = 100
rangeLower = 6
plotBull = true
plotBear = true
//------------------------------------------------------------------------------
PHCond = ta.pivothigh(mfi, pivL, pivR), h3 = +1.1
PLCond = ta.pivotlow (mfi, pivL, pivR), l3 = -0.9
highestHighPoint = ta.highest(PHCond and mfi > 0 ? mfi : na, rangeUpper)
lowestLowPoint = ta.lowest(PLCond and mfi < 0 ? mfi : na, rangeLower)
// Divergence Detect:
osc = mfi
plFound = na(ta.pivotlow(mfi, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(mfi, lbL, lbR)) ? false : true
_inRange1(cond1) =>
bars = ta.barssince(cond1 == true)
rangeLower <= bars and bars <= rangeUpper
// Regular Bullish
// Osc: Higher Low
oscHL1 = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange1(plFound[1]) and mfi != close
// Price: Lower Low
priceLL1 = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL1 and oscHL1 and plFound
plot(plFound ? osc[lbR] : na, offset=-lbR, title='Micro Bullish Div', linewidth=1, color=bullCond ? color.rgb(0, 255, 8) : na)
// Regular Bearish
// Osc: Lower High
oscLH1 = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange1(phFound[1]) and mfi != close
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH1 and phFound
plot(phFound ? osc[lbR] : na, offset=-lbR, title='Micro Bearish Div', linewidth=1, color=bearCond ? color.rgb(255, 0, 0) : na)
//------------------------------------------------------------------------------
// div detector 2 - Sub Mid Div
// Inputs
groupdiv2 = '---- Sub-Mid Div Lookback ----'
pivR2 = 1
pivL2 = 21
lbR2 = 1
lbL2 = input.int (15, ' ' , group = groupdiv2, inline = '1')
rangeUpper2 = 100
rangeLower2 = 6
plotBull2 = true
plotBear2 = true
//------------------------------------------------------------------------------
PHCond2 = ta.pivothigh(mfi, pivL2, pivR2), h32 = +1.1
PLCond2 = ta.pivotlow (mfi, pivL2, pivR2), l32 = -0.9
highestHighPoint2 = ta.highest(PHCond2 and mfi > 0 ? mfi : na, rangeUpper2)
lowestLowPoint2 = ta.lowest(PLCond2 and mfi < 0 ? mfi : na, rangeLower2)
// Divergence Detect:
osc2 = mfi
plFound2 = na(ta.pivotlow(mfi, lbL2, lbR2)) ? false : true
phFound2 = na(ta.pivothigh(mfi, lbL2, lbR2)) ? false : true
_inRange2(cond2) =>
bars2 = ta.barssince(cond2 == true)
rangeLower2 <= bars2 and bars2 <= rangeUpper2
// Regular Bullish
// Osc: Higher Low
oscHL2 = osc2[lbR2] > ta.valuewhen(plFound2, osc2[lbR2], 1) and _inRange2(plFound2[1]) and mfi != close
// Price: Lower Low
priceLL2 = low[lbR] < ta.valuewhen(plFound2, low[lbR2], 1)
bullCond2 = plotBull2 and priceLL2 and oscHL2 and plFound2
plot(plFound2 ? osc[lbR2] : na, offset=-lbR, title='Sub-Mid Bullish Div', linewidth=1, color=bullCond2 ? color.rgb(0, 255, 8) : na)
// Regular Bearish
// Osc: Lower High
oscLH2 = osc2[lbR2] < ta.valuewhen(phFound2, osc2[lbR2], 1) and _inRange2(phFound2[1]) and mfi != close
// Price: Higher High
priceHH2 = high[lbR2] > ta.valuewhen(phFound2, high[lbR2], 1)
bearCond2 = plotBear2 and priceHH2 and oscLH2 and phFound2
plot(phFound2 ? osc2[lbR2] : na, offset=-lbR, title='Sub=Mid Bearish Div', linewidth=1, color=bearCond2 ? color.rgb(255, 0, 0) : na)
//------------------------------------------------------------------------------
// div detector 3 - Mid Div //
// Inputs
groupdiv3 = '---- Mid Div Lookback ----'
pivR3 = 1
pivL3 = 21
lbR3 = 1
lbL3 = input.int (55, ' ' , group = groupdiv3, inline = '1')
rangeUpper3 = 100
rangeLower3 = 6
plotBull3 = true
plotBear3 = true
//------------------------------------------------------------------------------
PHCond3 = ta.pivothigh(mfi, pivL3, pivR3), h33 = +1.1
PLCond3 = ta.pivotlow (mfi, pivL3, pivR3), l33 = -0.9
highestHighPoint3 = ta.highest(PHCond3 and mfi > 0 ? mfi : na, rangeUpper3)
lowestLowPoint3 = ta.lowest(PLCond3 and mfi < 0 ? mfi : na, rangeLower3)
// Divergence Detect:
osc3 = mfi
plFound3 = na(ta.pivotlow(mfi, lbL3, lbR3)) ? false : true
phFound3 = na(ta.pivothigh(mfi, lbL3, lbR3)) ? false : true
_inRange3(cond3) =>
bars3 = ta.barssince(cond3 == true)
rangeLower3 <= bars3 and bars3 <= rangeUpper3
// Regular Bullish
// Osc: Higher Low
oscHL3 = osc[lbR3] > ta.valuewhen(plFound3, osc3[lbR3], 1) and _inRange3(plFound3[1]) and mfi != close
// Price: Lower Low
priceLL3 = low[lbR3] < ta.valuewhen(plFound3, low[lbR3], 1)
bullCond3 = plotBull3 and priceLL3 and oscHL3 and plFound3
plot(plFound3 ? osc[lbR3] : na, offset=-lbR, title='Mid Bullish Div', linewidth=1, color=bullCond3 ? color.rgb(0, 255, 8) : na)
// Regular Bearish
// Osc: Lower High
oscLH3 = osc3[lbR3] < ta.valuewhen(phFound3, osc3[lbR3], 1) and _inRange3(phFound3[1]) and mfi != close
// Price: Higher High
priceHH3 = high[lbR3] > ta.valuewhen(phFound3, high[lbR3], 1)
bearCond3 = plotBear3 and priceHH3 and oscLH3 and phFound3
plot(phFound3 ? osc3[lbR3] : na, offset=-lbR, title='Mid Bearish Div', linewidth=1, color=bearCond3 ? color.rgb(255, 0, 0) : na)
//------------------------------------------------------------------------------
// div detector 4 - Macro Div
// Inputs
groupdiv4 = '---- Macro Div Lookback ----'
pivR4 = 1
pivL4 = 21
lbR4 = 1
lbL4 = input.int (70, ' ' , group = groupdiv4, inline = '2')
rangeUpper4 = 100
rangeLower4 = 6
plotBull4 = true
plotBear4 = true
//------------------------------------------------------------------------------
PHCond4 = ta.pivothigh(mfi, pivL4, pivR4), h44 = +1.1
PLCond4 = ta.pivotlow (mfi, pivL4, pivR4), l44 = -0.9
highestHighPoint4 = ta.highest(PHCond4 and mfi > 0 ? mfi : na, rangeUpper4)
lowestLowPoint4 = ta.lowest(PLCond4 and mfi < 0 ? mfi : na, rangeLower4)
// Divergence Detect:
osc4 = mfi
plFound4 = na(ta.pivotlow(mfi, lbL4, lbR4)) ? false : true
phFound4 = na(ta.pivothigh(mfi, lbL4, lbR4)) ? false : true
_inRange4(cond4) =>
bars4 = ta.barssince(cond4 == true)
rangeLower4 <= bars4 and bars4 <= rangeUpper4
// Regular Bullish
// Osc: Higher Low
oscHL4 = osc[lbR4] > ta.valuewhen(plFound4, osc4[lbR4], 1) and _inRange4(plFound4[1]) and mfi != close
// Price: Lower Low
priceLL4 = low[lbR4] < ta.valuewhen(plFound4, low[lbR4], 1)
bullCond4 = plotBull4 and priceLL4 and oscHL4 and plFound4
plot(plFound4 ? osc[lbR4] : na, offset=-lbR, title='Macro Bullish Div', linewidth=1, color=bullCond4 ? color.rgb(0, 255, 8) : na)
// Regular Bearish
// Osc: Lower High
oscLH4 = osc4[lbR4] < ta.valuewhen(phFound4, osc4[lbR4], 1) and _inRange4(phFound4[1]) and mfi != close
// Price: Higher High
priceHH4 = high[lbR4] > ta.valuewhen(phFound4, high[lbR4], 1)
bearCond4 = plotBear4 and priceHH4 and oscLH4 and phFound4
plot(phFound4 ? osc4[lbR4] : na, offset=-lbR, title='Macro Bearish Div', linewidth=1, color=bearCond4 ? color.rgb(255, 0, 0) : na)
//
Bearishdivalert = bearCond or bearCond2 or bearCond3 or bearCond4
Bullishdivalert = bullCond or bullCond2 or bullCond3 or bullCond4
alertcondition(Bearishdivalert, title = "Bearish Divergence Alert", message = "Bearish Divergence Detected")
alertcondition(Bullishdivalert, title = "Bullish Divergence Alert", message = "Bullish Divergence Detected")
|
RedK Relative Strength Ribbon: RS Ribbon and RS Charts | https://www.tradingview.com/script/89d1ZrHe-RedK-Relative-Strength-Ribbon-RS-Ribbon-and-RS-Charts/ | RedKTrader | https://www.tradingview.com/u/RedKTrader/ | 330 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ RedKTrader
//@version=5
indicator(title="RedK Relative Strength Ribbon v1.0", shorttitle="RedK RS_Ribbon v1.0", precision = 2,
timeframe = "", timeframe_gaps = false)
// to-do:s
// add alerts for ribbon swining green/red - or a generic swing
// add other MA types (done)
// Support MTF (done)
//==============================================================================
// updated this version of LazyLine() to reflect a regular WMA for length < 5
// newest version, avoids warning about wma() inside the if block, code cleaned-up
f_LazyLine(float _data, int _length) =>
LL1 = 0.0, LL2 = 0.0, _LL = 0.0
var float w = _length / 3
var int w2 = math.round(w)
var int w1 = math.round((_length - w2) / 2)
var int w3 = int((_length - w2) / 2)
L1 = ta.wma(_data, w1)
L2 = ta.wma(L1, w2)
L3 = ta.wma(L2, w3)
L4 = ta.wma(_data, _length)
_LL := _length > 4 ? L3 : L4
//==============================================================================
// =============================================================================
f_getMA(source, length, mtype) =>
mtype == "SMA" ? ta.sma(source, length) :
mtype == "EMA" ? ta.ema(source, length) :
mtype == "WMA" ? ta.wma(source, length) :
mtype == "HMA" ? ta.hma(source, length) :
mtype == "RMA" ? ta.rma(source, length) :
f_LazyLine(source, length)
// =============================================================================
MA1 = "MA1"
MA2 = "MA2"
grp_1 = "RS Ribbon"
grp_2 = "New x-Weeks Hi/Lo RS (only 1D & 1W TFs)"
base = input.symbol("SPY", "Base Symbol")
show_RSBars = input.bool(true, "Show RS Candles?โ
โ
โ
โ
โ
โ", inline = 'RScandles')
use_HA = input.bool(false, 'Use Heikin Ashi?', inline = 'RScandles')
show_Ribbon = input.bool(true, "Show RS Ribbon?", group = grp_1)
MA1_length = input.int(5, "MA1 Length", minval = 1, inline = MA1, group = grp_1)
MA1_type = input.string('WMA', title = 'Type', inline = MA1, group = grp_1,
options = ['RSS_WMA', 'WMA', 'EMA', 'SMA', 'HMA', 'RMA'] )
MA2_length = input.int(15, "MA2 Length", minval = 1, inline = MA2, group = grp_1)
MA2_type = input.string('RSS_WMA', title = 'Type', inline = MA2, group = grp_1,
options = ['RSS_WMA', 'WMA', 'EMA', 'SMA', 'HMA', 'RMA'])
var string Rel_sym = ticker.standard(syminfo.tickerid) + ' / ' + ticker.standard(base)
var string Current_TF = timeframe.period
// note: Current_TF is not the chart's TF, it's the TF selected in the TF dropdown in indicator settings
[o, h, l , rs] = request.security(Rel_sym, Current_TF, [100 * open, 100 * high, 100 * low, 100 * close])
// ====================================================================================================================
// Adding the option to show RS Candles - can be useful to do some TA on and check for patterns like VCP
// good tip hee is to use log scale too for these "RS charts"
// also added the ability to show the RS candles as HA Candles for any HA fans out there
// note that RS will continue to calc using normal close values
// ******
// HA bar construction from normal candles
// Open = (open of previous bar + close of previous bar) divided by 2
// Close = (open + close + high + low of current bar) divided by 4
// High = the maximum value from the high, open, or close of the current period
// Low = the minimum value from the low, open, or close of the current period
float ca_o = o
float ca_c = rs
float ca_h = h
float ca_l = l
var float HA_o = o
var float HA_c = rs
var float HA_h = h
var float HA_l = l
HA_o := math.avg(o[1], rs[1])
HA_c := math.avg(o, rs, h, l)
HA_h := math.max(h, o ,rs)
HA_l := math.min(l, o, rs)
if use_HA
ca_o := HA_o, ca_c := HA_c
ca_h := HA_h, ca_l := HA_l
up_bar = ca_c > ca_o
c_barup = color.new(#26a69a, 60)
c_bardn = color.new(#ef5350, 60)
c_barupb = color.new(#26a69a, 15)
c_bardnb = color.new(#ef5350, 15)
barcolor = up_bar ? c_barup : c_bardn
borcolor = up_bar ? c_barupb : c_bardnb
plotcandle(ca_o, ca_h, ca_l, ca_c, 'RS Candles', barcolor, borcolor, bordercolor = borcolor,
display = show_RSBars ? display.pane : display.none)
// ====================================================================================================================
RS_avg1 = f_getMA(rs, MA1_length, MA1_type)
RS_avg2 = f_getMA(rs, MA2_length, MA2_type)
green = #08440d80
red = #80192280
l_green = #1b5e20
l_red = #981919
c_avg1 = color.new(color.gray,50)
c_avg2 = RS_avg1 >= RS_avg2 ? l_green : l_red
c_ribbon = show_Ribbon ? (RS_avg1 > RS_avg2 ? green : red) : na
A1 = plot(RS_avg1, color = c_avg1, title="RS Avg1", linewidth = 2,
display = show_Ribbon ? display.pane + display.data_window : display.none)
A2 = plot(RS_avg2, color = c_avg2, title="RS Avg2", linewidth = 3,
display = show_Ribbon ? display.pane + display.data_window : display.none)
fill(A1, A2, color = c_ribbon)
// ====================================================================================================================
// New x Week Hi/Lo
// ====================================================================================================================
show_xwksHL = input.bool(true, 'Show New x_weeks Hi/Lo RS Markers?', group = grp_2)
num_wks = input.int (13, "Num Weeks", minval = 1, group = grp_2)
num_days = input.int (5, "Adjust days per week (if needed)", minval = 1, group = grp_2)
// ================================================================
// Get all-time Hi/Lo RS, will be used if there's less than x-weeks of data
athi = ta.max(rs)
atlo = ta.min(rs)
// =============================================================================
CalcRS_HiLo (string _TF, int _Length) =>
_hi_tf = request.security(Rel_sym, _TF, ta.highest(close, _Length)) * 100
_lo_tf = request.security(Rel_sym, _TF, ta.lowest(close, _Length)) * 100
[_hi_tf, _lo_tf]
// =============================================================================
var string RS_TF = "D"
var int RS_Length = 1
if Current_TF == "D"
RS_TF := "1D"
RS_Length := num_days * num_wks
else if Current_TF == "W"
RS_TF := "1W"
RS_Length := num_wks
// this call will still calculate Hi/Lo on the current chart timeframe - but will do a daily calc
// then we'll ignore the outcome later in the code - to avoid the issue with lower TF's missing points
// which is actually a "visual inconsistency" rather than a bug, due to the use of "closing price" in RS calculation vs high or low
[hi_tf, lo_tf] = CalcRS_HiLo(RS_TF, RS_Length)
// if the security call returns NA, use all-time hi/lo values
v_hi52WK = nz(hi_tf, athi)
v_lo52WK = nz(lo_tf, atlo)
plot(rs, title = "RS", color=#ffb74d)
plotchar(athi, "All-time Hi", char = "", color = color.aqua, editable = false, display = display.data_window)
plotchar(atlo, "All-time Lo", char = "", color = color.yellow, editable = false, display = display.data_window)
plotchar(hi_tf, "Num Weeks' Hi", char = "", color = color.aqua, editable = false, display = display.data_window)
plotchar(lo_tf, "Num Weeks' Lo", char = "", color = color.yellow, editable = false, display = display.data_window)
float MaxHi = na
float MaxLo = na
if (Current_TF == "D" or Current_TF == "W") and show_xwksHL
MaxHi := v_hi52WK
MaxLo := v_lo52WK
// if other TF's, we maintain na value for these variables. so do nothing here ....
plotchar(0.0, "**********", char = "", color = color.aqua, editable = false, display = display.data_window)
plotchar(MaxHi, "Final x_Wk Hi", char = "", color = color.aqua, editable = false, display = display.data_window)
plotchar(MaxLo, "Final x_Wk Lo", char = "", color = color.yellow, editable = false, display = display.data_window)
// set a flag if a new 52Wk Hi/Lo occurs
N52HL = rs == MaxHi ? 1 : rs == MaxLo ? -1 : 0
// plot
NewHL = N52HL == 0 ? na : rs
c_NewHL = N52HL == 1 ? color.aqua : color.orange
plot(NewHL, title = "New x_Wk Hi/Lo", color = c_NewHL, linewidth = 5, style = plot.style_circles,
display = display.pane + display.data_window)
|
ScalpTrader RSI | https://www.tradingview.com/script/CzRulXPp-ScalpTrader-RSI/ | scalptradr | https://www.tradingview.com/u/scalptradr/ | 183 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉScalpTradr
//@version=5
// Defining the main indicator with a short title
indicator(title='RSI [ScalpTradr]', shorttitle='ST RSI', overlay=false)
// User input for RSI length and whether to show bands
len = input(14)
bands = input(true)
// Function for calculating Hull Moving Average (HMA)
f_hma(_src, _length) =>
// Calculating the weighted moving average and assigning it to _return
_return = ta.wma(2 * ta.wma(_src, _length / 2) - ta.wma(_src, _length), math.round(math.sqrt(_length)))
// Returning the result
_return
// Source data for the RSI calculation is closing price
src = close
// Up is the relative moving average of the upward changes
up = ta.rma(math.max(ta.change(src), 0), len)
// Down is the relative moving average of the downward changes
down = ta.rma(-math.min(ta.change(src), 0), len)
// RSI calculation
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - 100 / (1 + up / down)
// Plots the middle line (zero line) with gray color
plotZero = plot(50, color=color.new(color.gray, 50), title='ZeroMiddle')
// Determines fill color based on RSI value
fillColor = rsi < 50 ? color.red : color.green
// Fills the area between RSI plot and zero line with determined color
fill(plot1=plot(rsi, color=color.new(color.black, 0), linewidth=2), plot2=plotZero, color=color.new(fillColor, 50))
// Bollinger Bands
var float upper = na
var float lower = na
if bands
basis = ta.sma(rsi, len)
dev = 2 * ta.stdev(rsi, len)
upper := basis + dev
lower := basis - dev
// Determines RSI color based on its value and its position relative to the Bollinger Bands
sma_color_rsi = rsi > upper ? color.red : rsi < lower ? color.red : color.black
// Plots RSI with determined color
plot(rsi, color=sma_color_rsi, title='RSI', linewidth=3)
plot(upper, color=color.blue, title='Bollinger Bands Top')
plot(lower, color=color.blue, title='Bollinger Bands Bottom')
|
[R]2 - Reversion | https://www.tradingview.com/script/chmJNFnv/ | zamansiz74 | https://www.tradingview.com/u/zamansiz74/ | 51 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ zamansiz74
//@version=5
indicator("[R]2 - Version 2", overlay=false)
// Input
o1 = input.bool(defval = true, title = "-------------[R]eversion--------------" )
periods = input.int(defval = 5, title="Periods")
length = input.int(defval = 10, title="Length")
threshold = input.float(5.0, step=1,title="Threshold")
multiplier = input.float(defval = 3.0, step=0.5, title="Multiplier")
median = input.bool(defval = true, title = "Calculate with median")
weighted = input.bool(defval = false, title = "Weighted average")
signal_by_changing_direction = input.bool(defval = false, title = "Signal when changing direction")
// PART 1
sum = 0.0
avg = 0.0
var float xyz = close
var float multi = 1
var bool buySignal = false
var float sumPrice = na
var int count = 0
var float avgPrice = na
var float distanceAvg = 0.0
var color clr = color.rgb(0,0,0,0)
// User-defined function to calculate the median
median(src, periods) =>
sorted = array.new_float(periods)
for i = 0 to periods - 1
array.push(sorted, src[i])
array.sort(sorted)
mid = int(periods / 2)
periods % 2 == 0 ? (array.get(sorted, mid) + array.get(sorted, mid - 1)) / 2 : array.get(sorted, mid)
// Loop for calculating the average...
sum := ta.ema(close, periods) * periods
//...or the meridian
if (median == false)
if(weighted==false)
avg := sum / periods
else
avg := ta.wma(close,periods)
else
if(weighted==false)
avg := median(ta.sma(close, periods), periods)
else
avg := median(ta.wma(close, periods), periods)
// Check if the current bar is a multiple of Periods
if bar_index % periods == 0
if na(xyz* multi) or math.abs(xyz - avg * multi) >= threshold
xyz := avg * multi
//
if (close > xyz and xyz == xyz[1] and buySignal == false)
buySignal := true
multi := (100-multiplier)/100
xyz := avg * multi
if (close < xyz and xyz == xyz[1] and buySignal == true)
buySignal := false
multi := (100+multiplier)/100
xyz := avg * multi
//
//---------------------------------------X
if barstate.isfirst
sumPrice := na
count := 0
if buySignal != buySignal[1]
// When the buySignal variable changes, save the average of the previous period.
if count > 0
avgPrice := sumPrice / count
// Reset the values to calculate the average for the new period
sumPrice := close
count := 1
else
// Add the prices between the state changes
sumPrice += close
count += 1
// Calculate distance between close and avgPrice
distance = ta.ema(close - avgPrice,length)
distance2 = ta.ema(distance,length)
if signal_by_changing_direction
clr := distance - distance2< 0 ? color.rgb(255,0,0,80) : color.rgb(0,255,0,80)
else
clr := distance < 0 ? color.rgb(255,0,0,80) : color.rgb(0,255,0,80)
// PLOT
// Draw continuous line at 0
hline(0, title="Nulllinie", color=color.gray, linestyle=hline.style_dotted, linewidth=3) // Hier setzen wir den Linienstil auf gepunktet (hline.style_dotted)
hli = plot(0, title="Nulllinie", color=color.black, linewidth = 0, display = display.none)
// Linie zeichnen, um den Abstand darzustellen
dis = plot(distance, title="", style=plot.style_histogram, color=clr, linewidth=1)
fill(hli, dis,clr)
// Alert!
alertcondition((nz(clr) != nz(clr[1])), title="[R]2", message="{{ticker}}, change of direction!")
|
Support and Resistance Backtester [SS] | https://www.tradingview.com/script/RwGN3iLX-Support-and-Resistance-Backtester-SS/ | Steversteves | https://www.tradingview.com/u/Steversteves/ | 212 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// /$$$$$$ /$$ /$$
// /$$__ $$ | $$ | $$
//| $$ \__//$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
//| $$$$$$|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$__ $$ /$$_____/|_ $$_/ /$$__ $$| $$ /$$//$$__ $$ /$$_____/
// \____ $$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$ \__/| $$$$$$ | $$ | $$$$$$$$ \ $$/$$/| $$$$$$$$| $$$$$$
// /$$ \ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/| $$ \____ $$ | $$ /$$| $$_____/ \ $$$/ | $$_____/ \____ $$
//| $$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$| $$ /$$$$$$$/ | $$$$/| $$$$$$$ \ $/ | $$$$$$$ /$$$$$$$/
// \______/ \___/ \_______/ \_/ \_______/|__/ |_______/ \___/ \_______/ \_/ \_______/|_______/
// ___________________
// / \
// / _____ _____ \
// / / \ / \ \
// __/__/ \____/ \__\_____
//| ___________ ____|
// \_________/ \_________/
// \ /////// /
// \/////////
// ยฉ Steversteves
//@version=5
indicator("Support and Resistance Backtester [SS]", shorttitle = "S/R Backtester [SS]", overlay=true, max_labels_count = 500)
// Groups //
g1 = "Settings"
g2 = "Support and Resistance Levels"
g3 = "Backtest Parameters"
// Tooltips //
t1 = "This will plot the price labels beside the support and resistance levels" // labels
t2 = "This will extend the support and resistance area to encompass the support and resistance zone +/- the threshold value inputted" // Threshold Plot
t3 = "This will extend the support and resistance to a general 'area' in which you are comfortable holding. Suggested value is the value in which you are willing to let the stock extend past your support or resistance level before stopping out."
t4 = "The number of candles you wish to lookback to test the support and resistance levels. Suggested values for optimization: \n Hourly: 300 \n Daily: 500"
t5 = "Will plot labels on each of the support and resistance passes."
t6 = "Will plot labels on each of the support and resistance fails."
t7 = "Determines the source you wish to look at. Suggested value is close."
// User inputs //
pltsr = input.bool(true, "Plot Support and Resistance Levels", group = g1)
pltlbl = input.bool(true, "Plot Labels", tooltip = t1, group=g1)
pltthresh = input.bool(false, "Plot Threshold Limits", tooltip = t2, group = g1)
chrt = input.bool(true, "Display Chart", group=g1)
sr1 = input.float(100, "Support/Resistance 1", group = g2)
sr2 = input.float(0, "Support/Resistance 2", group = g2)
sr3 = input.float(0, "Support/Resistance 3", group = g2)
sr4 = input.float(0, "Support/Resistance 4", group = g2)
sr5 = input.float(0, "Support/Resistance 5", group = g2)
src = input.source(close, "Source",tooltip = t7, group = g3)
len = input.int(500, "Lookback", tooltip = t4, group = g3)
margin = input.float(0.50, "Threshold parameter", tooltip = t3, group = g3)
pltpasses = input.bool(false, "Plot Passes", tooltip = t5)
pltfails = input.bool(false, "Plot Fails", tooltip = t6)
// Support and Resistance 1
bool sr1_support = src[3] > sr1 and src[2] >= sr1 - margin and src[2] <= sr1 + margin and src > sr1 + margin
bool sr1_resistance = src[3] < sr1 and src[2] >= sr1 - margin and src[2] <= sr1 + margin and src < sr1 - margin
bool sr1_resistance_fail = src[3] < sr1 and src[2] > sr1 and src[1] > sr1 and src > sr1 + margin
bool sr1_support_fail = src[3] > sr1 and src[2] < sr1 and src[1] < sr1 and src < sr1 - margin
bool sr1_touch = src >= sr1 - margin and src <= sr1 + margin
// Support and Resistance 2
bool sr2_support = src[3] > sr2 and src[2] >= sr2 - margin and src[2] <= sr2 + margin and src > sr2 + margin
bool sr2_resistance = src[3] < sr2 and src[2] >= sr2 - margin and src[2] <= sr2 + margin and src < sr2 - margin
bool sr2_resistance_fail = src[3] < sr2 and src[2] > sr2 and src[1] > sr2 and src > sr2 + margin
bool sr2_support_fail = src[3] > sr2 and src[2] < sr2 and src[1] < sr2 and src < sr2 - margin
bool sr2_touch = src >= sr2 - margin and src <= sr2 + margin
// Support and Resistance 3
bool sr3_support = src[3] > sr3 and src[2] >= sr3 - margin and src[2] <= sr3 + margin and src > sr3 + margin
bool sr3_resistance = src[3] < sr3 and src[2] >= sr3 - margin and src[2] <= sr3 + margin and src < sr3 - margin
bool sr3_resistance_fail = src[3] < sr3 and src[2] > sr3 and src[1] > sr3 and src > sr3 + margin
bool sr3_support_fail = src[3] > sr3 and src[2] < sr3 and src[1] < sr3 and src < sr3 - margin
bool sr3_touch = src >= sr3 - margin and src <= sr3 + margin
// Support and Resistance 4
bool sr4_support = src[3] > sr4 and src[2] >= sr4 - margin and src[2] <= sr4 + margin and src > sr4 + margin
bool sr4_resistance = src[3] < sr4 and src[2] >= sr4 - margin and src[2] <= sr4 + margin and src < sr4 - margin
bool sr4_resistance_fail = src[3] < sr4 and src[2] > sr4 and src[1] > sr4 and src > sr4 + margin
bool sr4_support_fail = src[3] > sr4 and src[2] < sr4 and src[1] < sr4 and src < sr4 - margin
bool sr4_touch = src >= sr4 - margin and src <= sr4 + margin
// Support and Resistance 5
bool sr5_support = src[3] > sr5 and src[2] >= sr5 - margin and src[2] <= sr5 + margin and src > sr5 + margin
bool sr5_resistance = src[3] < sr5 and src[2] >= sr5 - margin and src[2] <= sr5 + margin and src < sr5 - margin
bool sr5_resistance_fail = src[3] < sr5 and src[2] > sr5 and src[1] > sr5 and src > sr5 + margin
bool sr5_support_fail = src[3] > sr5 and src[2] < sr5 and src[1] < sr5 and src < sr5 - margin
bool sr5_touch = src >= sr5 - margin and src <= sr5 + margin
int sr1_support_count = 0
int sr1_resistance_count = 0
int sr1_resistance_fail_count = 0
int sr1_support_fail_count = 0
int sr1_touch_count = 0
int sr2_support_count = 0
int sr2_resistance_count = 0
int sr2_resistance_fail_count = 0
int sr2_support_fail_count = 0
int sr2_touch_count = 0
int sr3_support_count = 0
int sr3_resistance_count = 0
int sr3_resistance_fail_count = 0
int sr3_support_fail_count = 0
int sr3_touch_count = 0
int sr4_support_count = 0
int sr4_resistance_count = 0
int sr4_resistance_fail_count = 0
int sr4_support_fail_count = 0
int sr4_touch_count = 0
int sr5_support_count = 0
int sr5_resistance_count = 0
int sr5_resistance_fail_count = 0
int sr5_support_fail_count = 0
int sr5_touch_count = 0
for i = 0 to len
if sr1_support[i] and barstate.islast
sr1_support_count := sr1_support_count + 1
if sr1_resistance[i] and barstate.islast
sr1_resistance_count := sr1_resistance_count + 1
if sr1_resistance_fail[i] and barstate.islast
sr1_resistance_fail_count := sr1_resistance_fail_count + 1
if sr1_support_fail[i] and barstate.islast
sr1_support_fail_count := sr1_support_fail_count + 1
if sr1_touch[i] and barstate.islast
sr1_touch_count := sr1_touch_count + 1
if sr2_support[i] and barstate.islast
sr2_support_count := sr2_support_count + 1
if sr2_resistance[i] and barstate.islast
sr2_resistance_count := sr2_resistance_count + 1
if sr2_resistance_fail[i] and barstate.islast
sr2_resistance_fail_count := sr2_resistance_fail_count + 1
if sr2_support_fail[i] and barstate.islast
sr2_support_fail_count := sr2_support_fail_count + 1
if sr2_touch[i] and barstate.islast
sr2_touch_count := sr2_touch_count + 1
if sr3_support[i] and barstate.islast
sr3_support_count := sr3_support_count + 1
if sr3_resistance[i] and barstate.islast
sr3_resistance_count := sr3_resistance_count + 1
if sr3_resistance_fail[i] and barstate.islast
sr3_resistance_fail_count := sr3_resistance_fail_count + 1
if sr3_support_fail[i] and barstate.islast
sr3_support_fail_count := sr3_support_fail_count + 1
if sr3_touch[i] and barstate.islast
sr3_touch_count := sr3_touch_count + 1
if sr4_support[i] and barstate.islast
sr4_support_count := sr4_support_count + 1
if sr4_resistance[i] and barstate.islast
sr4_resistance_count := sr4_resistance_count + 1
if sr4_resistance_fail[i] and barstate.islast
sr4_resistance_fail_count := sr4_resistance_fail_count + 1
if sr4_support_fail[i] and barstate.islast
sr4_support_fail_count := sr4_support_fail_count + 1
if sr4_touch[i] and barstate.islast
sr4_touch_count := sr4_touch_count + 1
if sr5_support[i] and barstate.islast
sr5_support_count := sr5_support_count + 1
if sr5_resistance[i] and barstate.islast
sr5_resistance_count := sr5_resistance_count + 1
if sr5_resistance_fail[i] and barstate.islast
sr5_resistance_fail_count := sr5_resistance_fail_count + 1
if sr5_support_fail[i] and barstate.islast
sr5_support_fail_count := sr5_support_fail_count + 1
if sr5_touch[i] and barstate.islast
sr5_touch_count := sr5_touch_count + 1
f_perc(support_pass, resistance_pass, support_fail, resistance_fail) =>
a = support_pass + resistance_pass
b = support_fail + resistance_fail
c = a / (a + b) * 100
f_success(input1, input2) =>
input1 / (input1 + input2) * 100
sr1_perc = f_perc(sr1_support_count, sr1_resistance_count, sr1_support_fail_count, sr1_resistance_fail_count)
sr2_perc = f_perc(sr2_support_count, sr2_resistance_count, sr2_support_fail_count, sr2_resistance_fail_count)
sr3_perc = f_perc(sr3_support_count, sr3_resistance_count, sr3_support_fail_count, sr3_resistance_fail_count)
sr4_perc = f_perc(sr4_support_count, sr4_resistance_count, sr4_support_fail_count, sr4_resistance_fail_count)
sr5_perc = f_perc(sr5_support_count, sr5_resistance_count, sr5_support_fail_count, sr5_resistance_fail_count)
sr1_support_suc = f_success(sr1_support_count, sr1_support_fail_count)
sr1_resistance_suc = f_success(sr1_resistance_count, sr1_resistance_fail_count)
sr2_support_suc = f_success(sr2_support_count, sr2_support_fail_count)
sr2_resistance_suc = f_success(sr2_resistance_count, sr2_resistance_fail_count)
sr3_support_suc = f_success(sr3_support_count, sr3_support_fail_count)
sr3_resistance_suc = f_success(sr3_resistance_count, sr3_resistance_fail_count)
sr4_support_suc = f_success(sr4_support_count, sr4_support_fail_count)
sr4_resistance_suc = f_success(sr4_resistance_count, sr4_resistance_fail_count)
sr5_support_suc = f_success(sr5_support_count, sr5_support_fail_count)
sr5_resistance_suc = f_success(sr5_resistance_count, sr5_resistance_fail_count)
// Colours
color black = color.rgb(0, 0, 0)
color white = color.white
color csr1 = color.aqua
color csr1fill = color.new(color.aqua, 75)
color csr2 = color.purple
color csr2fill = color.new(color.purple, 75)
color csr3 = color.gray
color csr3fill = color.new(color.gray, 75)
color csr4 = color.blue
color csr4fill = color.new(color.blue, 75)
color csr5 = color.fuchsia
color csr5fill = color.new(color.fuchsia, 75)
color transp = color.new(color.white, 100)
color green = color.lime
color red = color.red
// Plot table
var table datatable = table.new(position.top_right, 10, 10, bgcolor=black, frame_color = white, frame_width = 1, border_color = white, border_width = 1)
if chrt
table.cell(datatable, 1, 1, text = "Support/ \n Resistance Level", bgcolor=black, text_color=white)
if sr1 > 0 and chrt
table.cell(datatable, 1, 2, text = str.tostring(sr1), bgcolor=csr1, text_color=white)
if sr2 > 0 and chrt
table.cell(datatable, 1, 3, text = str.tostring(sr2), bgcolor=csr2, text_color=white)
if sr3 > 0 and chrt
table.cell(datatable, 1, 4, text = str.tostring(sr3), bgcolor=csr3, text_color=white)
if sr4 > 0 and chrt
table.cell(datatable, 1, 5, text = str.tostring(sr4), bgcolor=csr4, text_color=white)
if sr5 > 0 and chrt
table.cell(datatable, 1, 6, text = str.tostring(sr5), bgcolor=csr5, text_color=white)
if chrt
table.cell(datatable, 2, 1, text = "Support Pass", bgcolor=black, text_color=white)
table.cell(datatable, 3, 1, text = "Support Fail", bgcolor=black, text_color=white)
table.cell(datatable, 4, 1, text = "% Support \n Success", bgcolor=black, text_color=white, tooltip = "The sum of total support passes divided by total passes and fails")
table.cell(datatable, 5, 1, text = "Resistance Pass", bgcolor=black, text_color=white)
table.cell(datatable, 6, 1, text = "Resistance Fail", bgcolor=black, text_color=white)
table.cell(datatable, 7, 1, text = "% Resistance \n Success", bgcolor=black, text_color=white, tooltip = "The sum of total resistance passes divided by total passes and fails")
table.cell(datatable, 8, 1, text = "# of Touches", bgcolor=black, text_color=white, tooltip = "The number of times the stock has reached a support area +/- the threshold value")
table.cell(datatable, 9, 1, text = "Cumulative \n Success", bgcolor=black, text_color=white, tooltip = "Cumulates the Support and Resistance Passes over the Total Passes and Fails")
// SR1
if sr1 > 0 and chrt
table.cell(datatable, 2, 2, text = str.tostring(sr1_support_count), bgcolor=black, text_color=white)
table.cell(datatable, 3, 2, text = str.tostring(sr1_support_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 4, 2, text = str.tostring(math.round(sr1_support_suc,2)) + "%", bgcolor=black, text_color=sr1_support_suc > 51 ? green : red)
table.cell(datatable, 5, 2, text = str.tostring(sr1_resistance_count), bgcolor=black, text_color=white)
table.cell(datatable, 6, 2, text = str.tostring(sr1_resistance_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 7, 2, text = str.tostring(math.round(sr1_resistance_suc,2)) + "%", bgcolor=black, text_color= sr1_resistance_suc > 51 ? green : red)
table.cell(datatable, 8, 2, text = str.tostring(sr1_touch_count), bgcolor=black, text_color=white)
table.cell(datatable, 9, 2, text = str.tostring(math.round(sr1_perc,2)) + "%", bgcolor=black, text_color=sr1_perc > 51 ? green : red)
// SR2
if sr2 > 0 and chrt
table.cell(datatable, 2, 3, text = str.tostring(sr2_support_count), bgcolor=black, text_color=white)
table.cell(datatable, 3, 3, text = str.tostring(sr2_support_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 4, 3, text = str.tostring(math.round(sr2_support_suc,2)) + "%", bgcolor=black, text_color=sr2_support_suc > 51 ? green : red)
table.cell(datatable, 5, 3, text = str.tostring(sr2_resistance_count), bgcolor=black, text_color=white)
table.cell(datatable, 6, 3, text = str.tostring(sr2_resistance_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 7, 3, text = str.tostring(math.round(sr2_resistance_suc,2)) + "%", bgcolor=black, text_color=sr2_resistance_suc > 51 ? green : red)
table.cell(datatable, 8, 3, text = str.tostring(sr2_touch_count), bgcolor=black, text_color=white)
table.cell(datatable, 9, 3, text = str.tostring(math.round(sr2_perc,2)) + "%", bgcolor=black, text_color=sr2_perc > 51 ? green : red)
// SR3
if sr3 > 0 and chrt
table.cell(datatable, 2, 4, text = str.tostring(sr3_support_count), bgcolor=black, text_color=white)
table.cell(datatable, 3, 4, text = str.tostring(sr3_support_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 4, 4, text = str.tostring(math.round(sr3_support_suc,2)) + "%", bgcolor=black, text_color=sr3_support_suc > 51 ? green : red)
table.cell(datatable, 5, 4, text = str.tostring(sr3_resistance_count), bgcolor=black, text_color=white)
table.cell(datatable, 6, 4, text = str.tostring(sr3_resistance_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 7, 4, text = str.tostring(math.round(sr3_resistance_suc,2)) + "%", bgcolor=black, text_color=sr3_resistance_suc > 51 ? green : red)
table.cell(datatable, 8, 4, text = str.tostring(sr3_touch_count), bgcolor=black, text_color=white)
table.cell(datatable, 9, 4, text = str.tostring(math.round(sr3_perc,2)) + "%", bgcolor=black, text_color= sr3_perc > 51 ? green : red)
// SR4
if sr4 > 0 and chrt
table.cell(datatable, 2, 5, text = str.tostring(sr4_support_count), bgcolor=black, text_color=white)
table.cell(datatable, 3, 5, text = str.tostring(sr4_support_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 4, 5, text = str.tostring(math.round(sr4_support_suc,2)) + "%", bgcolor=black, text_color=sr4_support_suc > 51 ? green : red)
table.cell(datatable, 5, 5, text = str.tostring(sr4_resistance_count), bgcolor=black, text_color=white)
table.cell(datatable, 6, 5, text = str.tostring(sr4_resistance_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 7, 5, text = str.tostring(math.round(sr4_resistance_suc,2)) + "%", bgcolor=black, text_color=sr4_resistance_suc > 51 ? green : red)
table.cell(datatable, 8, 5, text = str.tostring(sr4_touch_count), bgcolor=black, text_color=white)
table.cell(datatable, 9, 5, text = str.tostring(math.round(sr4_perc,2)) + "%", bgcolor=black, text_color=sr4_perc > 51 ? green : red)
// SR4
if sr5 > 0 and chrt
table.cell(datatable, 2, 6, text = str.tostring(sr5_support_count), bgcolor=black, text_color=white)
table.cell(datatable, 3, 6, text = str.tostring(sr5_support_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 4, 6, text = str.tostring(math.round(sr5_support_suc,2)) + "%", bgcolor=black, text_color=sr5_support_suc > 51 ? green : red)
table.cell(datatable, 5, 6, text = str.tostring(sr5_resistance_count), bgcolor=black, text_color=white)
table.cell(datatable, 6, 6, text = str.tostring(sr5_resistance_fail_count), bgcolor=black, text_color=white)
table.cell(datatable, 7, 6, text = str.tostring(math.round(sr5_resistance_suc,2)) + "%", bgcolor=black, text_color=sr5_resistance_suc > 51 ? green : red)
table.cell(datatable, 8, 6, text = str.tostring(sr5_touch_count), bgcolor=black, text_color=white)
table.cell(datatable, 9, 6, text = str.tostring(math.round(sr5_perc,2)) + "%", bgcolor=black, text_color=sr5_perc > 51 ? green : red)
// Plots//
plot(pltsr ? sr1 : na, "Support / Resistance #1", color = csr1, linewidth=3)
a = plot(pltsr and pltthresh ? sr1 + margin : na, "SR1 Threshold", color=csr1)
b = plot(pltsr and pltthresh ? sr1 - margin : na, "SR1 Threshold", color=csr1)
fill(a, b, color=csr1fill)
plot(pltsr ? sr2 : na, "Support / Resistance #2", color = csr2, linewidth=3)
c = plot(pltsr and pltthresh ? sr2 + margin : na, "SR2 Threshold", color=csr2)
d = plot(pltsr and pltthresh ? sr2 - margin : na, "SR2 Threshold", color=csr2)
fill(c, d, color=csr2fill)
plot(pltsr ? sr3 : na, "Support / Resistance #3", color = csr3, linewidth=3)
e = plot(pltsr and pltthresh ? sr3 + margin : na, "SR3 Threshold", color=csr3)
f = plot(pltsr and pltthresh ? sr3 - margin : na, "SR3 Threshold", color=csr3)
fill(e, f, color=csr3fill)
plot(pltsr ? sr4 : na, "Support / Resistance #4", color = csr4, linewidth=3)
g = plot(pltsr and pltthresh ? sr4 + margin : na, "SR4 Threshold", color=csr4)
h = plot(pltsr and pltthresh ? sr4 - margin : na, "SR4 Threshold", color=csr4)
fill(g, h, color=csr4fill)
plot(pltsr ? sr5 : na, "Support / Resistance #5", color = csr5, linewidth=3)
i = plot(pltsr and pltthresh ? sr5 + margin : na, "SR5 Threshold", color=csr5)
j = plot(pltsr and pltthresh ? sr5 - margin : na, "SR5 Threshold", color=csr5)
fill(i, j, color=csr5fill)
// Label plots //
var label sr1_label = na
var label sr2_label = na
var label sr3_label = na
var label sr4_label = na
var label sr5_label = na
if pltlbl
label.delete(sr1_label)
label.delete(sr2_label)
label.delete(sr3_label)
label.delete(sr4_label)
label.delete(sr5_label)
sr1_label := label.new(bar_index + 15, y=sr1, text = str.tostring(sr1), color = transp, style=label.style_label_right, textcolor = csr1, size = size.large)
sr2_label := label.new(bar_index + 15, y=sr2, text = str.tostring(sr2), color = transp, style=label.style_label_right, textcolor = csr2, size = size.large)
sr3_label := label.new(bar_index + 15, y=sr3, text = str.tostring(sr3), color = transp, style=label.style_label_right, textcolor = csr3, size = size.large)
sr4_label := label.new(bar_index + 15, y=sr4, text = str.tostring(sr4), color = transp, style=label.style_label_right, textcolor = csr4, size = size.large)
sr5_label := label.new(bar_index + 15, y=sr5, text = str.tostring(sr5), color = transp, style=label.style_label_right, textcolor = csr5, size = size.large)
// Plotting Passes and Fails //
if pltpasses and sr1_support
label.new(bar_index, sr1, text = str.tostring(sr1) + "\n โ๏ธ \n Support Pass", color = csr1, style=label.style_label_up, textcolor = white)
if pltpasses and sr1_resistance
label.new(bar_index, sr1, text = str.tostring(sr1) + "\n โ๏ธ \n Resistance Pass", color = csr1, textcolor = white)
if pltpasses and sr2_support
label.new(bar_index, sr2, text = str.tostring(sr2) + "\n โ๏ธ \n Support Pass", color = csr2, style=label.style_label_up, textcolor = white)
if pltpasses and sr2_resistance
label.new(bar_index, sr2, text = str.tostring(sr2) + "\n โ๏ธ \n Resistance Pass", color = csr2, textcolor = white)
if pltpasses and sr3_support
label.new(bar_index, sr3, text = str.tostring(sr3) + "\n โ๏ธ \n Support Pass", color = csr3, style=label.style_label_up, textcolor = white)
if pltpasses and sr3_resistance
label.new(bar_index, sr3, text = str.tostring(sr3) + "\n โ๏ธ \n Resistance Pass", color = csr3, textcolor = white)
if pltpasses and sr4_support
label.new(bar_index, sr4, text = str.tostring(sr4) + "\n โ๏ธ \n Support Pass", color = csr4, style=label.style_label_up, textcolor = white)
if pltpasses and sr4_resistance
label.new(bar_index, sr4, text = str.tostring(sr4) + "\n โ๏ธ \n Resistance Pass", color = csr4, textcolor = white)
if pltpasses and sr5_support
label.new(bar_index, sr5, text = str.tostring(sr5) + "\n โ๏ธ \n Support Pass", color = csr5, style=label.style_label_up, textcolor = white)
if pltpasses and sr5_resistance
label.new(bar_index, sr5, text = str.tostring(sr5) + "\n โ๏ธ \n Resistance Pass", color = csr5, textcolor = white)
if pltfails and sr1_support_fail
label.new(bar_index, sr1, text = str.tostring(sr1) + "\n โ \n Support Fail", color = csr1, style=label.style_label_down, textcolor = white)
if pltfails and sr1_resistance_fail
label.new(bar_index, sr1, text = str.tostring(sr1) + "\n โ \n Resistance Fail", color = csr1, style=label.style_label_up, textcolor = white)
if pltfails and sr2_support_fail
label.new(bar_index, sr2, text = str.tostring(sr2) + "\n โ \n Support Fail", color = csr2, style=label.style_label_down, textcolor = white)
if pltfails and sr2_resistance_fail
label.new(bar_index, sr2, text = str.tostring(sr2) + "\n โ \n Resistance Fail", color = csr2, style=label.style_label_up, textcolor = white)
if pltfails and sr3_support_fail
label.new(bar_index, sr3, text = str.tostring(sr3) + "\n โ \n Support Fail", color = csr3, style=label.style_label_down, textcolor = white)
if pltfails and sr3_resistance_fail
label.new(bar_index, sr3, text = str.tostring(sr3) + "\n โ \n Resistance Fail", color = csr3, style=label.style_label_up, textcolor = white)
if pltfails and sr4_support_fail
label.new(bar_index, sr4, text = str.tostring(sr4) + "\n โ \n Support Fail", color = csr4, style=label.style_label_down, textcolor = white)
if pltfails and sr4_resistance_fail
label.new(bar_index, sr4, text = str.tostring(sr4) + "\n โ \n Resistance Fail", color = csr4, style=label.style_label_up, textcolor = white)
if pltfails and sr5_support_fail
label.new(bar_index, sr5, text = str.tostring(sr5) + "\n โ \n Support Fail", color = csr5, style=label.style_label_down, textcolor = white)
if pltfails and sr5_resistance_fail
label.new(bar_index, sr5, text = str.tostring(sr5) + "\n โ \n Resistance Fail", color = csr5, style=label.style_label_up, textcolor = white) |
Multi-Timeframe EMA Tracker by Ox_kali | https://www.tradingview.com/script/hJNDsVrT-Multi-Timeframe-EMA-Tracker-by-Ox-kali/ | Ox_kali | https://www.tradingview.com/u/Ox_kali/ | 6 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Ox_kali
// ________________________________________________________________________________________________________________________________
// โโโโโโโ โโโ โโโ โโโ โโโ โโโโโโ โโโ โโโ โโโโโโ โโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโ โโโโ
// โโโโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโ โโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโ โโโโโ
// โโโ โโโ โโโโโโ โโโโโโโ โโโโโโโโโโโ โโโ โโโโโโโโโโโ โโโ โโโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโ
// โโโ โโโ โโโโโโ โโโโโโโ โโโโโโโโโโโ โโโ โโโโโโโโโโโ โโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโ โโโ โโโ โโโโโโ โโโ โโโ
// โโโโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโ โโโโโโโ โโโโโโโ โโโ โโโโโโ โโโ โโโ โโโโโโ โโโ
// ________________________________________________________________________________________________________________________________
//@version=5
// Indicator title and short title
// ________________________________________________________________________________________________________________________________
indicator("Multi-Timeframe EMA Tracker by Ox_kali", shorttitle="MTEMA-Tracker by Ox_kali", overlay=false)
// User trend color choice
// ________________________________________________________________________________________________________________________________
color_up = input(color.rgb(50, 183, 105), title="Up Trend Color")
color_down = input(color.rgb(151, 29, 29), title="Down Trend Color")
// User choice to display or not UT trend. (Impact on AVG trend)
// ________________________________________________________________________________________________________________________________
show_tf_1min = input(true, title="Show 1 Minute Trend")
show_tf_2min = input(true, title="Show 2 Minute Trend")
show_tf_3min = input(true, title="Show 3 Minute Trend")
show_tf_5min = input(true, title="Show 5 Minute Trend")
show_tf_10min = input(true, title="Show 10 Minute Trend")
show_tf_15min = input(true, title="Show 15 Minute Trend")
show_tf_30min = input(true, title="Show 30 Minute Trend")
show_tf_1Hour = input(true, title="Show 1 Hour Trend")
show_tf_2Hour = input(true, title="Show 2 Hour Trend")
show_tf_4Hour = input(true, title="Show 4 Hour Trend")
show_tf_6Hour = input(true, title="Show 6 Hour Trend")
show_tf_12Hour = input(true, title="Show 12 Hour Trend")
show_tf_1Day = input(true, title="Show 1 Day Trend")
show_tf_1Week = input(true, title="Show 1 Week Trend")
// Input for EMA lengths
// ________________________________________________________________________________________________________________________________
shortTerm = input(50, title="Short Term EMA Length")
longTerm = input(200, title="Long Term EMA Length")
// Function to retrieve EMA values for a given timeframe
// ________________________________________________________________________________________________________________________________
getEMAs(timeframe) =>
ema50 = request.security(syminfo.tickerid, timeframe, ta.ema(close, shortTerm))
ema200 = request.security(syminfo.tickerid, timeframe, ta.ema(close, longTerm))
[ema50, ema200]
// UT Configuration
// ________________________________________________________________________________________________________________________________
tf_1min = "1"
tf_2min = "2"
tf_3min = "3"
tf_5min = "5"
tf_10min = "10"
tf_15min = "15"
tf_30min = "30"
tf_1Hour = "60"
tf_2Hour = "120"
tf_4Hour= "240"
tf_6Hour = "360"
tf_12Hour = "720"
tf_1Day = "1440"
tf_1Week = "1W"
// Function to determine color based on EMA conditions
// ________________________________________________________________________________________________________________________________
getColor(ema50, ema200) =>
if na(ema50) or na(ema200)
color.new(color.red, 100)
else
ema50 > ema200 ? color_up : color_down
// Using the function to retrieve EMA values
// ________________________________________________________________________________________________________________________________
[ema50_1, ema200_1] = getEMAs(tf_1min)
[ema50_2, ema200_2] = getEMAs(tf_2min)
[ema50_3, ema200_3] = getEMAs(tf_3min)
[ema50_4, ema200_4] = getEMAs(tf_5min)
[ema50_5, ema200_5] = getEMAs(tf_10min)
[ema50_6, ema200_6] = getEMAs(tf_15min)
[ema50_7, ema200_7] = getEMAs(tf_30min)
[ema50_8, ema200_8] = getEMAs(tf_1Hour)
[ema50_9, ema200_9] = getEMAs(tf_2Hour)
[ema50_10, ema200_10] = getEMAs(tf_4Hour)
[ema50_11, ema200_11] = getEMAs(tf_6Hour)
[ema50_12, ema200_12] = getEMAs(tf_12Hour)
[ema50_13, ema200_13] = getEMAs(tf_1Day)
[ema50_14, ema200_14] = getEMAs(tf_1Week)
// Plot lines for each timeframe
// ________________________________________________________________________________________________________________________________
color1 = getColor(ema50_1, ema200_1)
color2 = getColor(ema50_2, ema200_2)
color3 = getColor(ema50_3, ema200_3)
color4 = getColor(ema50_4, ema200_4)
color5 = getColor(ema50_5, ema200_5)
color6 = getColor(ema50_6, ema200_6)
color7 = getColor(ema50_7, ema200_7)
color8 = getColor(ema50_8, ema200_8)
color9 = getColor(ema50_9, ema200_9)
color10 = getColor(ema50_10, ema200_10)
color11 = getColor(ema50_11, ema200_11)
color12 = getColor(ema50_12, ema200_12)
color13 = getColor(ema50_13, ema200_13)
color14 = getColor(ema50_14, ema200_14)
// Heights of the lines (these values may require adjustments)
// ________________________________________________________________________________________________________________________________
var float y1 = 32000
var float y2 = 30000
var float y3 = 28000
var float y4 = 26000
var float y5 = 24000
var float y6 = 22000
var float y7 = 20000
var float y8 = 18000
var float y9 = 16000
var float y10 = 14000
var float y11 = 12000
var float y12 = 10000
var float y13 = 8000
var float y14 = 6000
// Plot the lines
// ________________________________________________________________________________________________________________________________
plot(show_tf_1min ? y1 : na, color=color1, linewidth=5, style=plot.style_line, title="1Min")
plot(show_tf_2min ? y2 : na, color=color2, linewidth=5, style=plot.style_line, title="2Min")
plot(show_tf_3min ? y3 : na, color=color3, linewidth=5, style=plot.style_line, title="3Min")
plot(show_tf_5min ? y4 : na, color=color4, linewidth=5, style=plot.style_line, title="5Min")
plot(show_tf_10min ? y5 : na, color=color5, linewidth=5, style=plot.style_line, title="10Min")
plot(show_tf_15min ? y6 : na, color=color6, linewidth=5, style=plot.style_line, title="15Min")
plot(show_tf_30min ? y7 : na, color=color7, linewidth=5, style=plot.style_line, title="30Min")
plot(show_tf_1Hour ? y8 : na, color=color8, linewidth=5, style=plot.style_line, title="1H")
plot(show_tf_2Hour ? y9 : na, color=color9, linewidth=5, style=plot.style_line, title="2H")
plot(show_tf_4Hour ? y10 : na, color=color10, linewidth=5, style=plot.style_line, title="4H")
plot(show_tf_6Hour ? y11 : na, color=color11, linewidth=5, style=plot.style_line, title="6H")
plot(show_tf_12Hour ? y12 : na, color=color12, linewidth=5, style=plot.style_line, title="12H")
plot(show_tf_1Day ? y13 : na, color=color13, linewidth=5, style=plot.style_line, title="1D")
plot(show_tf_1Week ? y14 : na, color=color14, linewidth=5, style=plot.style_line, title="1W")
// Calculate the average trend
// ________________________________________________________________________________________________________________________________
totalTrends = 0
greenCount = 0
// Add a condition to check if EMA50 and EMA200 are not NaN or "na"
// ________________________________________________________________________________________________________________________________
if show_tf_1min and not na(ema50_1) and not na(ema200_1)
greenCount := greenCount + (ema50_1 > ema200_1 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_2min and not na(ema50_2) and not na(ema200_2)
greenCount := greenCount + (ema50_2 > ema200_2 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_3min and not na(ema50_3) and not na(ema200_3)
greenCount := greenCount + (ema50_3 > ema200_3 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_5min and not na(ema50_4) and not na(ema200_4)
greenCount := greenCount + (ema50_4 > ema200_4 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_10min and not na(ema50_5) and not na(ema200_5)
greenCount := greenCount + (ema50_5 > ema200_5 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_15min and not na(ema50_6) and not na(ema200_6)
greenCount := greenCount + (ema50_6 > ema200_6 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_30min and not na(ema50_7) and not na(ema200_7)
greenCount := greenCount + (ema50_7 > ema200_7 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_1Hour and not na(ema50_8) and not na(ema200_8)
greenCount := greenCount + (ema50_8 > ema200_8 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_2Hour and not na(ema50_9) and not na(ema200_9)
greenCount := greenCount + (ema50_9 > ema200_9 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_4Hour and not na(ema50_10) and not na(ema200_10)
greenCount := greenCount + (ema50_10 > ema200_10 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_6Hour and not na(ema50_11) and not na(ema200_11)
greenCount := greenCount + (ema50_11 > ema200_11 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_12Hour and not na(ema50_12) and not na(ema200_12)
greenCount := greenCount + (ema50_12 > ema200_12 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_1Day and not na(ema50_13) and not na(ema200_13)
greenCount := greenCount + (ema50_13 > ema200_13 ? 1 : 0)
totalTrends := totalTrends + 1
if show_tf_1Week and not na(ema50_14) and not na(ema200_14)
greenCount := greenCount + (ema50_14 > ema200_14 ? 1 : 0)
totalTrends := totalTrends + 1
// Calcul the average trend
// ________________________________________________________________________________________________________________________________
averageTrendColor = greenCount / totalTrends > 0.5 ? color_up : color_down
var float yAverage = 0
// Plot the average trend line
// ________________________________________________________________________________________________________________________________
plot(yAverage, color=averageTrendColor, linewidth=5, style=plot.style_line, title="Average Trend")
|
LBR-Volatility Breakout Bars | https://www.tradingview.com/script/YZtrmiwo-LBR-Volatility-Breakout-Bars/ | thebearfib | https://www.tradingview.com/u/thebearfib/ | 42 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//
//Original code @author LazyBear converted from version three
//
indicator('LBR-Volatility Breakout Bars',
overlay=true,
shorttitle='LBR-BARS')
//
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Inputs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//
_CB = input(false,'โโโโโโโ Color Bars โโโโโโโโโโโโโโโโโโ')
_colBars = input(true, title='Color LBR Bars?')
_colBarUL = input(true, title='Color LBR bars above/below Kelts?')
_colorall = input(false, title='Color non LBR Bars?')
_VL = input(false,'โโโโโโโ Volatility Lines โโโโโโโโโโโโโโโ')
_shoVL = input(false, title='Show Volatility Lines?')
_lenHL = input(20, title='HL Length')
_lenATR = input(50, title='ATR Length')
_ATRmult = input.float(2.5, minval=.75, title='ATR Multiplier')
_KA = input(false,'โโโโโโโ Keltner Area โโโโโโโโโโโโโโโโ')
_shoKelt = input(false, title='Show Kelts Area')
_lenKelt = input.int(21, minval=1, title='Kelt Length')
_multKelt = input(2.5, title='Kelt Multiplier')
_useTR = input(true, title='Use True Range for Kelts')
//
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Calcs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//
calc_stdev(src, _useTR, len, mult) =>
mid = ta.ema(src, len)
range_1 = _useTR ? ta.tr : high - low
rangemid = ta.ema(range_1, len)
upper = mid + rangemid * _ATRmult
lower = mid - rangemid * _ATRmult
[upper, mid, lower]
[u, b, l] = calc_stdev(close, _useTR, _lenKelt, _multKelt)
//
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Keltner โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//
_8xa = input(false,'โโโโโโโ Keltner Colors โโโโโโโโโโโโโโโ')
color _col1 = input.color(color.rgb(125, 126, 129, 80), 'Kelts Bands')
color _col2 = input.color(color.rgb(246, 132, 1), 'Kelt Mid')
_upperKelt = plot(_shoKelt ? u : na, color=_col1, linewidth=1, title='KC Upper')
_midKelt = plot(_shoKelt ? b : na, style=plot.style_circles, color=_col2, linewidth=1, title='KC Basis')
_lowerKelt = plot(_shoKelt ? l : na, color=_col1, linewidth=1, title='KC Lower')
fill(_upperKelt, _lowerKelt, _col1)
_keltCol = _colBarUL ? close >= u or close <= l : false
_atr = _ATRmult * ta.sma(ta.stdev(close, _lenATR), _lenATR)
//
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Volatility Lines โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//
_volBandLo = ta.lowest(low, _lenHL) + _atr
_volBandHi = ta.highest(high, _lenHL) - _atr
_UpperVol = close > _volBandLo and close > _volBandHi
_LowerVol = close < _volBandLo and close < _volBandHi
_8xxx = input(false,'โโโโโโโ Volatility Colors โโโโโโโโโโโโโโ')
color _col3 = input.color(color.rgb(157, 169, 156), title = 'Upper Vol')
color _col4 = input.color(color.rgb(157, 169, 156), title = 'Lower Vol')
_upVolBand = plot(_shoVL ? _volBandHi : na, style=plot.style_line, linewidth=1, color=_col3, title='Upper Vol')
_loVolBand = plot(_shoVL ? _volBandLo : na, style=plot.style_line, linewidth=1, color=_col4, title='Lower Vol')
//
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Bar Colors โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//
_bars = input(false,'โโโโโโโ Bar Colors โโโโโโโโโโโโโโโโโโ')
color _col5 = input.color(color.rgb(130, 133, 130), 'Bar Color No Mans Land') //bar color #1
color _col6 = input.color(color.rgb(9, 249, 9), 'Bar Color (Above Volatility Lines)') //bar color #2
color _col7 = input.color(color.rgb(231, 12, 12), 'Bar Color (Below Volatility Lines)') //bar color #3
color _col8 = input.color(color.rgb(234, 168, 3), "Bar Color (Inside Volatility Lines) ") //bar color #4
color _col9 = input.color(color.rgb(17, 0, 255), 'N/A') //bar Color #5
bc = _colBars ?
_keltCol ? _col5 :
_UpperVol ? _col6 :
_LowerVol ? _col7 :
_colorall ? _col8 :
na : not(_UpperVol or _LowerVol) and _colorall ? _col9 : na
barcolor(bc)
|
The Strat with Continuity [starlord_xrp] | https://www.tradingview.com/script/P6ftk3vH-The-Strat-with-Continuity-starlord-xrp/ | starlord_xrp | https://www.tradingview.com/u/starlord_xrp/ | 75 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ starlord_xrp
//@version=5
indicator("The Strat with Continuity", overlay=true)
int candle_type = na
bool bull = false
bool green = false
color bar_color = na
var float entry = na
var float target = na
var float stoploss = na
var bool open_long = false
bool enter_long = false
var bool open_short = false
bool enter_short = false
float profit_target = input(0.10, "min price target to enter")/100
int leverage = input(30, "Leverage Level - if no levearage put 1")
float trading_fee = input(0.07, "Trading Fee")*leverage
rsi = ta.rsi(close, 14)
var float total_profit = na
float profit = na
daily_open = request.security(syminfo.tickerid, "1D", open, barmerge.gaps_off)
daily_close = request.security(syminfo.tickerid, "1D", close, barmerge.gaps_off)
twelve_open = request.security(syminfo.tickerid, "720", open, barmerge.gaps_off)
twelve_close = request.security(syminfo.tickerid, "720", close, barmerge.gaps_off)
one_open = request.security(syminfo.tickerid, "60", open, barmerge.gaps_off)
one_close = request.security(syminfo.tickerid, "60", close, barmerge.gaps_off)
color new_back = na
long_continuity = daily_close>daily_open and twelve_close>twelve_open and one_close>one_open
short_continuity = daily_close<daily_open and twelve_close<twelve_open and one_close<one_open
if short_continuity
new_back := color.new(color.maroon, 80)
if long_continuity
new_back := color.new(color.lime, 80)
bool longs = input(true, "Longs?") //and long_continuity
bool shorts = input(true, "Shorts?") //and short_continuity
//bool use_continuity = input(true, "Use continuity filter?")
//if shorts and use_continuity and short_continuity
// shorts := true
//else if shorts and use_continuity==false
// shorts := true
//else
// shorts := false
//if longs and use_continuity and long_continuity
// longs := true
//else if longs and use_continuity==false
// longs := true
//else
// longs := false
if high>high[1] and low>=low[1]
candle_type := 2
bull := true
bar_color := color.lime
if high<=high[1] and low<low[1]
candle_type := 2
bull := false
bar_color := color.red
if high<=high[1] and low>=low[1]
candle_type := 1
bull := na
bar_color := color.gray
if high>high[1] and low<low[1]
candle_type := 3
if close>open
bull := true
bar_color := color.new(color.green, 50)
else
bull := false
bar_color := color.new(color.maroon, 50)
plotshape(candle_type==1, "1", shape.square, location.belowbar, color.gray, 0, "1", color.gray, false, size = size.tiny)
plotshape(candle_type==2 and bull, "2UP", shape.triangleup, location.belowbar, color.lime, 0, "2Up", color.lime, false, size = size.tiny)
plotshape(candle_type==2 and bull==false, "2DN", shape.triangledown, location.belowbar, color.red, 0, "2Dn", color.red, false, size = size.tiny)
plotshape(candle_type==3 and bull, "3", shape.square, location.belowbar, color.green, 0, "3", color.white, false, size = size.tiny)
plotshape(candle_type==3 and bull==false, "3", shape.square, location.belowbar, color.red, 0, "3", color.white, false, size = size.tiny)
barcolor(bar_color)
color back = na
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var label label312 = na
var label label22 = na
var label label212 = na
var label label122 = na
var label label322 = na
var label label1 = na
var label label2 = na
var label label3 = na
var label label4 = na
var line line1 = na
var line line2 = na
var line line3 = na
var line line4 = na
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//2-1-2 watch
if (candle_type[1]==2 and candle_type==1)
if high[1] > high+(high*profit_target)
line.delete(line3)
line.delete(line4)
label.delete(label3)
label.delete(label4)
line3 := line.new(bar_index-1, high[1], bar_index+1, high[1], color=color.green, style = line.style_dotted, width = 2)
line4 := line.new(bar_index, high, bar_index+1, high, color=color.green, style = line.style_dashed, width = 2)
label3 := label.new(bar_index+1, high[1], str.tostring(high[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label4 := label.new(bar_index+1, high, str.tostring(high), color = color.blue, size = size.tiny, style = label.style_label_left)
if low[1]<low-(low*profit_target)
line.delete(line1)
line.delete(line2)
label.delete(label1)
label.delete(label2)
line1 := line.new(bar_index-1, low[1], bar_index+1, low[1], color=color.red, style = line.style_dotted, width = 2)
line2 := line.new(bar_index, low, bar_index+1, low, color=color.red, style = line.style_dashed, width = 2)
label1 := label.new(bar_index+1, low[1], str.tostring(low[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label2 := label.new(bar_index+1, low, str.tostring(low), color = color.blue, size = size.tiny, style = label.style_label_left)
//label.delete(label212)
label212 := label.new(bar_index+1, low[1], "2-1-2", color = color.orange, size = size.tiny, style = label.style_label_up)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//2-1-2 bull reversal
//if ((candle_type[2]==2 and bull[2]==false) and (candle_type[1]==1) and (candle_type==2 and bull) and longs)
// entry := high[1]
// target := high[2]
// stoploss := hl2[1]
// if target > (entry+(entry*profit_target))
//label.new(bar_index, high[1], "2-1-2 Long Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// line.new(bar_index-1, target, bar_index+1, target)
// label.new(bar_index+2, target, str.tostring(target), color = color.blue, style = label.style_label_left, size= size.tiny)
// enter_long := true
// open_long := true
// else
// back := color.new(color.red, 80)
//2-1-2 bear reversal
//if ((candle_type[2]==2 and bull[2]) and (candle_type[1]==1) and (candle_type==2 and bull==false) and shorts)
// entry := low[1]
// target := low[2]
// stoploss := hl2[1]
// if target<(entry-(entry*profit_target))
// enter_short := true
// open_short := true
// label.new(bar_index, low[1], "2-1-2 Short Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// else
// back := color.new(color.red, 80)
//2-1-2 bear continuation
//if ((candle_type[2]==2 and bull[2]==false) and (candle_type[1]==1) and (candle_type==2 and bull==false) and shorts)
// entry := low[1]
// target := low[2]
// stoploss := hl2[1]
// if target<(entry-(entry*profit_target))
// enter_short := true
// open_short := true
// label.new(bar_index, low[1], "2-1-2 Short Cont", color = color.white, style = label.style_label_right, size = size.tiny)
// else
// back := color.new(color.red, 80)
//2-1-2 bull continuation
//if ((candle_type[2]==2 and bull[2]) and (candle_type[1]==1) and (candle_type==2 and bull) and longs)
// entry := high[1]
// target := high[2]
// stoploss := hl2[1]
// if target > (entry+(entry*profit_target))
// label.new(bar_index, high[1], "2-1-2 Long Cont", color = color.white, style = label.style_label_right, size = size.tiny)
// enter_long := true
// open_long := true
// else
// back := color.new(color.red, 80)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//3-1-2 watch
if candle_type[1]==3 and candle_type==1
if bull[1] and low[1]<low-(low*profit_target)
line.delete(line1)
line.delete(line2)
label.delete(label1)
label.delete(label2)
line1 := line.new(bar_index-1, low[1], bar_index+1, low[1], color=color.red, style = line.style_dotted, width = 2)
line2 := line.new(bar_index, low, bar_index+1, low, color=color.red, style = line.style_dashed, width = 2)
label1 := label.new(bar_index+1, low[1], str.tostring(low[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label2 := label.new(bar_index+1, low, str.tostring(low), color = color.blue, size = size.tiny, style = label.style_label_left)
if bull[1]==false and high[1]>high+(high*profit_target)
line.delete(line3)
line.delete(line4)
label.delete(label3)
label.delete(label4)
line3 := line.new(bar_index-1, high[1], bar_index+1, high[1], color=color.green, style = line.style_dotted, width = 2)
line4 := line.new(bar_index, high, bar_index+1, high, color=color.green, style = line.style_dashed, width = 2)
label3 := label.new(bar_index+1, high[1], str.tostring(high[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label4 := label.new(bar_index+1, high, str.tostring(high), color = color.blue, size = size.tiny, style = label.style_label_left)
//label.delete(label312)
label312 := label.new(bar_index+1, low[1], "3-1-2", color = color.orange, size = size.tiny, style = label.style_label_up)
//3-1-2 Bullish Reversal
//if ((candle_type[2]==3 and bull[2]==false) and (candle_type[1]==1) and (candle_type==2 and bull) and longs)
// entry := high[1]
// target := high[2]
// stoploss := hl2[1]
// if target > (entry+(entry*profit_target))
// label.new(bar_index, high[1], "3-1-2 Long Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// enter_long := true
// open_long := true
// else
// back := color.new(color.red, 80)
//3-1-2 bear reversal
//if ((candle_type[2]==3 and bull[2]) and (candle_type[1]==1) and (candle_type==2 and bull==false) and shorts)
// entry := low[1]
// target := low[2]
// stoploss := hl2[1]
// if target<(entry-(entry*profit_target))
// enter_short := true
// open_short := true
// //label.new(bar_index, low[1], "3-1-2 Short Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// else
// back := color.new(color.red, 80)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//1-2-2 watch
if candle_type[1]==1 and candle_type==2
if bull and low[1]<low-(low*profit_target)
line.delete(line1)
line.delete(line2)
label.delete(label1)
label.delete(label2)
line1 := line.new(bar_index-1, low[2], bar_index+1, low[2], color=color.red, style = line.style_dotted, width = 2)
line2 := line.new(bar_index, low, bar_index+1, low, color=color.red, style = line.style_dashed, width = 2)
label1 := label.new(bar_index+1, low[2], str.tostring(low[2]), color = color.blue, size = size.tiny, style = label.style_label_left)
label2 := label.new(bar_index+1, low, str.tostring(low), color = color.blue, size = size.tiny, style = label.style_label_left)
if bull[1]==false and high[1]>high+(high*profit_target)
line.delete(line3)
line.delete(line4)
label.delete(label3)
label.delete(label4)
line3 := line.new(bar_index-1, high[2], bar_index+1, high[2], color=color.green, style = line.style_dotted, width = 2)
line4 := line.new(bar_index, high, bar_index+1, high, color=color.green, style = line.style_dashed, width = 2)
label3 := label.new(bar_index+1, high[2], str.tostring(high[2]), color = color.blue, size = size.tiny, style = label.style_label_left)
label4 := label.new(bar_index+1, high, str.tostring(high), color = color.blue, size = size.tiny, style = label.style_label_left)
//label.delete(label122)
label122 := label.new(bar_index+1, low[1], "1-2-2", color = color.orange, size = size.tiny, style = label.style_label_up)
//1-2-2 Bullish Reversal
//if ((candle_type[2]==1) and (candle_type[1]==2 and bull[1]==false) and (candle_type==2 and bull) and longs)
// entry := high[1]
// target := high[3]
// stoploss := hl2[1]
// if target > (entry+(entry*profit_target))
// //label.new(bar_index, high[1], "1-2-2 Long Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// enter_long := true
// open_long := true
// else
// back := color.new(color.red, 80)
//1-2-2 bear reversal
//if ((candle_type[2]==1) and (candle_type[1]==2 and bull[1]) and (candle_type==2 and bull==false) and shorts)
// entry := low[1]
// target := low[3]
// stoploss := hl2[1]
// if target<(entry-(entry*profit_target))
// enter_short := true
// open_short := true
// //label.new(bar_index, low[1], "1-2-2 Short Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// else
// back := color.new(color.red, 80)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//3-2-2 watch
if candle_type[1]==3 and candle_type==2
if bull and low[1]<low-(low*profit_target)
line.delete(line1)
line.delete(line2)
label.delete(label1)
label.delete(label2)
line1 := line.new(bar_index-1, low[1], bar_index+1, low[1], color=color.red, style = line.style_dotted, width = 2)
line2 := line.new(bar_index, low, bar_index+1, low, color=color.red, style = line.style_dashed, width = 2)
label1 := label.new(bar_index+1, low[1], str.tostring(low[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label2 := label.new(bar_index+1, low, str.tostring(low), color = color.blue, size = size.tiny, style = label.style_label_left)
if bull==false and high[1]>high+(high*profit_target)
line.delete(line3)
line.delete(line4)
label.delete(label3)
label.delete(label4)
line3 := line.new(bar_index-1, high[1], bar_index+1, high[1], color=color.green, style = line.style_dotted, width = 2)
line4 := line.new(bar_index, high, bar_index+1, high, color=color.green, style = line.style_dashed, width = 2)
label3 := label.new(bar_index+1, high[1], str.tostring(high[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label4 := label.new(bar_index+1, high, str.tostring(high), color = color.blue, size = size.tiny, style = label.style_label_left)
//label.delete(label322)
label322 := label.new(bar_index+1, low[1], "3-2-2", color = color.orange, size = size.tiny, style = label.style_label_up)
//3-2-2 Bullish Reversal
//if ((candle_type[2]==3 and bull[2]==false) and (candle_type[1]==2 and bull[1]) and (candle_type==2 and bull) and longs)
// entry := high[1]
// target := high[2]
// stoploss := hl2[1]
// if target > (entry+(entry*profit_target))
//label.new(bar_index, high[1], "3-2-2 Long Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// enter_long := true
// open_long := true
// else
// back := color.new(color.red, 80)
//3-2-2 bear reversal
//if ((candle_type[2]==3 and bull[2]) and (candle_type[1]==2 and bull[1]==false) and (candle_type==2 and bull==false) and shorts)
// entry := low[1]
// target := low[2]
// stoploss := hl2[1]
// if target<(entry-(entry*profit_target))
// enter_short := true
// open_short := true
//label.new(bar_index, low[1], "3-2-2 Short Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// else
// back := color.new(color.red, 80)
/////////////////////////////////////////////////////////////////////////////////////////////
//2-2 watch
if candle_type==2
if bull and low[1]<low-(low*profit_target)
line.delete(line1)
line.delete(line2)
label.delete(label1)
label.delete(label2)
line1 := line.new(bar_index-1, low[1], bar_index+1, low[1], color=color.red, style = line.style_dotted, width = 2)
line2 := line.new(bar_index, low, bar_index+1, low, color=color.red, style = line.style_dashed, width = 2)
label1 := label.new(bar_index+1, low[1], str.tostring(low[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label2 := label.new(bar_index+1, low, str.tostring(low), color = color.blue, size = size.tiny, style = label.style_label_left)
if bull==false and high[1]>high+(high*profit_target)
line.delete(line3)
line.delete(line4)
label.delete(label3)
label.delete(label4)
line3 := line.new(bar_index-1, high[1], bar_index+1, high[1], color=color.green, style = line.style_dotted, width = 2)
line4 := line.new(bar_index, high, bar_index+1, high, color=color.green, style = line.style_dashed, width = 2)
label3 := label.new(bar_index+1, high[1], str.tostring(high[1]), color = color.blue, size = size.tiny, style = label.style_label_left)
label4 := label.new(bar_index+1, high, str.tostring(high), color = color.blue, size = size.tiny, style = label.style_label_left)
label.delete(label22)
label22 := label.new(bar_index+1, low[1], "2-2 rev", color = color.orange, size = size.tiny, style = label.style_label_up)
//2-2 Bullish Reversal
//if ((candle_type[1]==2 and bull[1]==false) and (candle_type==2 and bull) and longs)
// entry := high[1]
// target := high[2]
// stoploss := hl2[1]
// if target > (entry+(entry*profit_target))
//label.new(bar_index, high[1], "2-2 Long Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// enter_long := true
// open_long := true
// else
// back := color.new(color.red, 80)
//2-2 bear reversal
//if ((candle_type[1]==2 and bull[1]) and (candle_type==2 and bull==false) and shorts)
// entry := low[1]
// target := low[2]
// stoploss := hl2[1]
// if target<(entry-(entry*profit_target))
// enter_short := true
// open_short := true
//label.new(bar_index, low[1], "2-2 Short Rev", color = color.white, style = label.style_label_right, size = size.tiny)
// else
// back := color.new(color.red, 80)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//if low[1]>low[2] and low[2]>low[3] and low[3]>low[4] and low[4]>low[5] and low[5]>low[6]
// back := color.new(color.yellow, 80)
// line.new(bar_index-1, low[1], bar_index+5, low[1], color = color.orange)
//line.new(bar_index-2, low[2], bar_index+5, low[2], color = color.yellow)
//line.new(bar_index-3, low[3], bar_index+5, low[3], color = color.yellow)
//line.new(bar_index-4, low[4], bar_index+5, low[4], color = color.yellow)
//line.new(bar_index-5, low[5], bar_index+5, low[5], color = color.yellow)
//if high[1]<high[2] and high[2]<high[3] and high[3]<high[4] and high[4]<high[5] and high[5]<high[6]
// back := color.new(color.yellow, 80)
// line.new(bar_index-1, high[1], bar_index+5, high[1], color = color.orange)
// line.new(bar_index-2, high[2], bar_index+5, high[2], color = color.yellow)
// line.new(bar_index-3, high[3], bar_index+5, high[3], color = color.yellow)
// line.new(bar_index-4, high[4], bar_index+5, high[4], color = color.yellow)
// line.new(bar_index-5, high[5], bar_index+5, high[5], color = color.yellow)
//line.delete(line1[1])
//line.delete(line2[1])
//line.delete(line3[1])
//line.delete(line4[1])
//label.delete(label1[1])
//label.delete(label2[1])
//label.delete(label3[1])
//label.delete(label4[1])
bgcolor(new_back)
//bool just_bought = ta.barssince(enter_long)<1 or ta.barssince(enter_short)<1
//plot (entry, color = color.yellow)
//plot (target, color = color.aqua)
//plot (stoploss, color=color.white)
//var int wins = 0
//var int losses = 0
//if open_short and close>=stoploss and just_bought==false
// label.new(bar_index, stoploss, "Stoploss short", color = color.red, style = label.style_label_left, size = size.tiny)
// open_short := false
// losses += 1
//if open_short and low<=target and just_bought==false
// label.new(bar_index, target, "Money short", color = color.lime, style = label.style_label_left, size = size.tiny)
//open_short := false
// wins += 1
//if open_long and (high>=target or open>target) and just_bought==false
//label.new(bar_index, target, "Money long", color = color.lime, style = label.style_label_left, size = size.tiny)
// open_long := false
// wins += 1
//if open_long and close<=stoploss and just_bought==false
//label.new(bar_index, stoploss, "Stoplos long", color = color.red, style = label.style_label_left, size = size.tiny)
// open_long := false
// losses +=1
//newday = ta.change(time_tradingday)
//if newday
// label.new(bar_index, low-(low*0.005), "Wins: " + str.tostring(wins) + " Losses: " + str.tostring(losses), color = color.teal, style = label.style_label_center, size = size.tiny)
// wins := 0
//losses := 0
//longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
//if (longCondition)
// strategy.entry("My Long Entry Id", strategy.long)
//shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
//if (shortCondition)
// strategy.entry("My Short Entry Id", strategy.short)
//plotshape(enter_long, "enter long", shape.arrowup, location.belowbar, color.green)
|
High of Day Low of Day hourly timings: Statistics. Time of day % | https://www.tradingview.com/script/f58uWvIm-High-of-Day-Low-of-Day-hourly-timings-Statistics-Time-of-day/ | twingall | https://www.tradingview.com/u/twingall/ | 99 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//High of Day & Low of Day hourly timings.
//This is best used on the hourly chart, since the minimum time chunks for categorizing timings are 1hr. Usage on timeframes > 1hr will give less precise stats. Usage on timeframes < 1hr will give less data history.
//TODO: input user timezone (for hour() function)
//TODO: Option to print vertical lines for the new day turnover time
// ยฉ twingall
//@version=5
indicator("High/Low of day Timings: backtesting data, hour of day", shorttitle= "HoD LoD timings", overlay = true, max_labels_count = 400)
//user inputs
_userTimezone = input.string("America/New_York", "input your timezone", options =["syminfo.timezone", "America/New_York", "UTC-10", "UTC-9", "UTC-8", "UTC-7", "UTC-6", "UTC-5", "UTC-4", "UTC-3",
"UTC-2", "UTC-1","UTC", "UTC+1", "UTC+2", "UTC+3", "UTC+4","UTC+5","UTC+6","UTC+7","UTC+8","UTC+9","UTC+10","UTC+11","UTC+12","UTC+13"], tooltip = "NB: make sure this timezone is set the same as your chart's toggled timezone" )
userTimezone =_userTimezone=="syminfo.timezone"?syminfo.timezone:_userTimezone
userInputStartHr = input.bool(false, "use custom input day start hour:", inline ='2')
stHr = input.int(12, "", inline ='2', tooltip = "Toggle this OFF to use the default Tradingview Day start time.\n\nThis input will likely not match your timeframe but it's not an issue: simply adjust input until vertical lines print at your preferred/correct hour\n\nThen you can trust that timing, and verify your using the 'show line/show label' toggles below, along with bar-replay, to ensure table is populating correctly")
showVlines = input.bool(true, "show day-start lines", tooltip = "Just a visual aid:\n\nIncluded this for user to check and ensure timings are correct and avoid timezone confusion\n\nYou can also use this to along with bar replay to check your table is populating correctly", inline = '3')
lstHoDlabel = input.bool(true, "show last HoD hour label", inline = '3')
tablePos = input.string(position.bottom_right, "table position", options = [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group="~~~~ Table ~~~~", inline = '1')
textCol = input.color(color.blue, "| Text", group="~~~~ Table ~~~~", inline = '1')
textSize = input.string(size.normal, "| Size", options = [size.auto, size.tiny, size.small, size.normal, size.large, size.huge], group="~~~~ Table ~~~~", inline = '1')
showOnlyOnHourly = input.bool(false, "show only on hourly timeframe", group = "~~~~ Table ~~~~", tooltip = "This is best used on the hourly chart, since the minimum time chunks for categorizing timings are 1hr.\n\nUsage on timeframes > 1hr will give less precise stats.\n\nUsage on timeframes < 1hr will give less data history")
useStartTime = input.bool(false, "use start date", inline = "1", group="~~~~ Start Date ~~~~", tooltip = "could be used along with bar replay function to study a particular HTF market state; \n\ni.e. compare results in consolidated mkts vs trending markets")
startTime= input.time(timestamp("18 Jan 2023 00:00 +0300"), "Start Date", confirm = false, group="~~~~ Start Date ~~~~")
startLineCol = input.color(color.red, "start line color", inline = "2", group="~~~~ Start Date ~~~~", tooltip = "this line can be set manually in dialog box, or dragged across the chart to change")
startLineWidth = input.int(2, "width", options= [1,2,3,4,5], inline = "2", group="~~~~ Start Date ~~~~")
startTimeCond = useStartTime? time>startTime:true
newDayCond = userInputStartHr? hour == stHr and minute ==0:timeframe.change("D")
var line lnStrt = na
if barstate.islastconfirmedhistory and useStartTime
lnStrt:=line.new(startTime, high, startTime, low, xloc = xloc.bar_time, color= startLineCol, extend = extend.both, width = startLineWidth)
line.delete(lnStrt[1])
var array<int> hrArrHoD = array.new<int>(24,0)
var array<int> hrArrLoD = array.new<int>(24,0)
var int dayCount=0
var int hrH = na
var int hrL = na
var int count = na
if timeframe.change(timeframe.period) and not newDayCond[1]
count+=1
if newDayCond[1]
count:=1
// if timeframe.change(timeframe.period)
// label.new(bar_index, low, str.tostring(count), style = label.style_label_up, size = size.small, color = color.new(color.white, 100))
_lowest = ta.lowest(low, count!=0?count:1)
lastLoD = ta.valuewhen(low == _lowest, time, 0 )
_highest = ta.highest(high,count!=0?count:1)
lastHoD = ta.valuewhen(high == _highest, time, 0)
if newDayCond and barstate.isconfirmed and startTimeCond
dayCount+=1
hrH:= hour(lastHoD, userTimezone)
array.set(hrArrHoD,hrH, (array.get(hrArrHoD,hrH)+1))
hrL:= hour(lastLoD, userTimezone)
array.set(hrArrLoD,hrL, (array.get(hrArrLoD,hrL)+1))
if lstHoDlabel
label.new(bar_index, high, "HoD\nhour\n"+str.tostring(hrH), style = label.style_label_down, color=color.new(color.white, 100), size = size.normal, textcolor = color.red)
if showVlines
line.new(bar_index, low, bar_index, low-1, extend=extend.right, style = line.style_dashed)
pctFxn(array<int> _arr, int _ind)=>
float result = (array.get(_arr, _ind)/array.sum(_arr))*100
var Table = table.new(tablePos, columns = 26, rows = 10, border_width = 1,border_color= color.black)
table.cell(Table, 0, 1, "Days History = "+str.tostring(dayCount), bgcolor =color.new(color.red, 50), text_size = textSize, text_color =textCol, text_halign =text.align_center)
table.merge_cells(Table, 1, 1, 24, 1), table.cell(Table, 1,1, "~~~~ High of Day & Low of Day hourly timings ~~~", bgcolor =color.new(color.gray, 70), text_size = textSize, text_color = textCol, text_halign =text.align_center)
table.cell(Table, 0, 2, "HOUR of day: ", bgcolor =color.new(color.yellow, 60), text_size = textSize, text_color = textCol, text_halign =text.align_center)
table.cell(Table, 0, 3, "High of Day (freq): ", bgcolor =color.new(color.green, 60), text_size = textSize, text_color=textCol, text_halign =text.align_center)
table.cell(Table, 0, 4, "High of Day %: ", bgcolor =color.new(color.green, 60), text_size = textSize, text_color=textCol, text_halign =text.align_center)
table.cell(Table, 0, 5, "Low of Day (freq): ", bgcolor =color.new(color.red, 60), text_size = textSize, text_color=textCol, text_halign =text.align_center)
table.cell(Table, 0, 6, "Low of Day %: ", bgcolor =color.new(color.red, 60), text_size = textSize, text_color=textCol, text_halign =text.align_center)
table.cell(Table, 0, 7, "Combined %: ", bgcolor =color.new(color.purple, 60), text_size = textSize, text_color=textCol, text_halign =text.align_center)
//table cell fill functions:
titleCellFill()=>
for i=1 to 24
table.cell(Table, i, 2, str.tostring(i-1)+ " ", bgcolor =color.new(color.yellow, 70), text_size = textSize, text_color=textCol, text_halign =text.align_center)
HoDCellFill()=>
for i=1 to 24
table.cell(Table, i, 3, str.tostring(array.get(hrArrHoD, i-1)), bgcolor =color.new(color.green, 70), text_size = textSize, text_color=textCol, text_halign =text.align_center)
HoDpctFill()=>
for i=1 to 24
table.cell(Table, i, 4, str.tostring(pctFxn(hrArrHoD, i-1), '0.0')+ "%", bgcolor =color.new(color.green, 70), text_size = textSize, text_color=textCol, text_halign =text.align_center)
LoDCellFill()=>
for i=1 to 24
table.cell(Table, i, 5, str.tostring(array.get(hrArrLoD, i-1)), bgcolor =color.new(color.red, 70), text_size = textSize, text_color=textCol, text_halign =text.align_center)
LoDpctFill()=>
for i=1 to 24
table.cell(Table, i, 6, str.tostring(pctFxn(hrArrLoD, i-1), '0.0')+ "%", bgcolor =color.new(color.red, 70), text_size = textSize, text_color=textCol, text_halign =text.align_center)
combinedPctFill()=>
for i=1 to 24
table.cell(Table, i, 7, str.tostring( math.avg( pctFxn(hrArrLoD, i-1), pctFxn(hrArrHoD, i-1)), '0.0')+ "%", bgcolor =color.new(color.purple, 70), text_size = textSize, text_color=textCol, text_halign =text.align_center)
//populate the table
titleCellFill()
HoDCellFill()
HoDpctFill()
LoDCellFill()
LoDpctFill()
combinedPctFill() |
Historic Volume/Market Profiles | https://www.tradingview.com/script/ETJBzHaH-Historic-Volume-Market-Profiles/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 276 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ SamRecio
//@version=5
indicator(title = "Historic Volume/Market Profiles", shorttitle ="HVMP", overlay = true, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500, max_bars_back = 5000)
tf = input.timeframe("D", title = "Timeframe", inline = "0", group = "PROFILE SETTINGS")
vap = input.float(70, title = "Value Area %", group = "PROFILE SETTINGS")/100
lb_days = input.int(5, title = "# of Profiles", maxval = 20, minval = 1, tooltip = "Max: 20 \nLarge Display = Less Granular Profiles\nSmall Display = More Granular Profiles")
mp = input.bool(false, title = "Calculate As Market Profile", group = "PROFILE SETTINGS", tooltip = "Calculations will distribue a 1 instead of the candle's volume.")
disp_size = input.int(-20, minval = -500,maxval = 500,title = "Display Sizeย ย ย ", inline = "3", group = "DISPLAY SETTINGS", tooltip = "The entire range of your profile will scale to fit inside this range.\n When Positive, the profile will display from the start of the day. \n When Negative, the profile will display from the end of the day.\nNotes:\n-This value is # bars away from your profile's Axis.\n-The farther from 0 this value is, the more granular your (horizontal) view will be. This does not change the Profiles' value; because of this, sometimes the POC looks tied with other values widely different. The POC CAN be tied to values close to it, but if the value is far away it is likely to just be a visual constraint. \n AUTO SCALE - Fits the profile within the lookback period.")
auto_size = input.bool(true, title = "Auto-Scale", inline = "3", group = "DISPLAY SETTINGS")
hi_width = input.int(10, maxval = 100, minval = 1,title = "[HVN] Analysis Width %ย ย ย โย ย โ", group = "High/Low Volume Nodes", tooltip = "[HVN] = High Volume Node\nAnalysis Width % = % of profile to take into account when determining what is a High Volume Node and what is Not.")*0.01
lo_width = input.int(10, maxval = 100, minval = 1, title = "[LVN]ย Analysis Width %ย ย ย โย ย โ", group = "High/Low Volume Nodes", tooltip = "[LVN] = Low Volume Node\nAnalysis Width % = % of profile to take into account when determining what is a Low Volume Node and what is Not.")*0.01
poc_color = input.color(#ff033e, title = "POC Color", group = "Colors")
var_color = input.color(color.white, title = "Value High/Low Color", group = "Colors")
vaz_color = input.color(color.new(#555555,50), title = "Value Zone Color", group = "Colors")
ov_color = input.color(#555555, title = "Profile Color", group = "Colors")
lv_color = input.color(#801922, title = "Low Volume Color", group = "Colors")
hv_color = input.color(#2295BF, title = "High Volume Color", group = "Colors")
fix_z(_val) => _val>0?_val:1
round_to(_round,_to) =>
math.round(_round/_to)*_to
vgroup_pull(_var,_array,_num1,_num2) =>
_var == 1 and _num1>=_num2?array.get(_array,_num1-_num2):
_var == 2 and array.size(_array)-1 >= (_num1 + _num2)?array.get(_array,_num1+_num2)
:0
prof_color(_num,_mv,_a1,_a2,_a3,_a4) =>
_num==0?na:
_num==_mv?poc_color:
(_num==_a3 or _num==_a4)?var_color:
array.includes(_a1,_num) and array.includes(_a2,_num)?((_num>_a3 or _num<_a4)?ov_color:vaz_color):
array.includes(_a2,_num)?lv_color:
array.includes(_a1,_num)?hv_color:
(_num>_a3 or _num<_a4)?ov_color:
vaz_color
var line_array = array.new_line(na)
var box_array = array.new_box(na)
kill_bar = ta.valuewhen(timeframe.change(tf),bar_index,lb_days+1)+1
if array.size(line_array) > 0
for i = array.size(line_array)-1 to 0
ln = array.get(line_array,i)
lx = line.get_x1(ln)
if lx <= kill_bar
line.delete(ln)
array.remove(line_array,i)
if array.size(box_array) > 0
for i = array.size(box_array)-1 to 0
bx = array.get(box_array,i)
bl = box.get_left(bx)
if bl <= kill_bar or na(bl)
box.delete(bx)
array.remove(box_array,i)
if array.size(label.all) > 0
for i = array.size(label.all)-1 to 0
lb = array.get(label.all,i)
lx = label.get_x(lb)
if lx <= kill_bar
label.delete(lb)
array.remove(label.all,i)
get_prof(_mp,_tf) =>
new_calc = timeframe.change(_tf)
last_new_calc = ta.valuewhen(new_calc,bar_index,1)
index_num = math.floor(1000/lb_days)-1
start_time = request.security("",_tf,ta.valuewhen(bar_index == last_bar_index-lb_days,time,0))
calc_bars = (bar_index - ta.valuewhen(new_calc,bar_index,0))[1]+1
base = ta.lowest(low,fix_z(calc_bars)+1)[1]
roof = ta.highest(high,fix_z(calc_bars)+1)[1]
tick_size = round_to(math.max(((roof - base)/index_num),syminfo.mintick),(syminfo.mintick/100))
c_hi = round_to(high,tick_size)
c_lo = round_to(low,tick_size)
candle_range = c_hi - c_lo
candle_index = (candle_range/tick_size)+1
tick_vol = _mp?1:volume/candle_index
main = array.new_float(na)
hvn_points = array.new_int(na)
lvn_points = array.new_int(na)
if new_calc and time >= start_time
for i = 0 to index_num
index_price = base + (i*tick_size)
if index_price >= roof
break
float index_sum = 0
for e = 1 to calc_bars
if index_price <= c_hi[e] and index_price >= c_lo[e]
index_sum := index_sum + tick_vol[e]
array.push(main,index_sum)
max_index = math.round(math.avg(array.indexof(main,array.max(main)),array.lastindexof(main,array.max(main))))
poc = base + (tick_size*max_index)
max_vol = array.sum(main)*vap
vol_count = max_index >=0?array.get(main, max_index):0.0
up_count = max_index
down_count = max_index
if array.size(main) > 0
for x = 0 to array.size(main)-1
if vol_count >= max_vol
break
uppervol = up_count<array.size(main)-1?array.get(main, up_count + 1):na
lowervol = down_count>0?array.get(main, down_count - 1):na
if ((uppervol >= lowervol) and not na(uppervol)) or na(lowervol)
vol_count += uppervol
up_count += 1
else
vol_count += lowervol
down_count -= 1
val = base + (tick_size*down_count)
vah = base + (tick_size*up_count)
uc = up_count
dc = down_count
///////////////////////////////
//Cluster ID for Volume Nodes//
///////////////////////////////
if array.size(main) > 0
for i = 0 to array.size(main)-1
_val = array.get(main,i)
ary = array.new_float(na)
for e = 0 to int(array.size(main)*hi_width)
array.push(ary,vgroup_pull(1,main,i,e))
array.push(ary,vgroup_pull(2,main,i,e))
max = array.max(ary)
if _val >= math.avg(max,array.avg(ary))
array.push(hvn_points,i)
if array.size(main) > 0
for i = 0 to array.size(main)-1
_val = array.get(main,i)
ary = array.new_float(na)
for e = 0 to int(array.size(main)*lo_width)
array.push(ary,vgroup_pull(1,main,i,e))
array.push(ary,vgroup_pull(2,main,i,e))
min = array.min(ary)
if _val <= math.avg(min,array.avg(ary))
array.push(lvn_points,i)
///_________________________________________
///Cluster Merging
///โพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพโพ
merge_per = 0.02
if array.size(hvn_points)>0
for i = 0 to array.size(hvn_points)-1
hi_found = false
lo_found = false
_val = array.get(hvn_points,i)
for e = int(array.size(main)*merge_per) to 0
if array.includes(hvn_points,_val+e)
hi_found := true
if hi_found
array.push(hvn_points,_val+e)
if array.includes(hvn_points,_val-e)
lo_found := true
if lo_found
array.push(hvn_points,_val-e)
if array.size(lvn_points)>0
for i = 0 to array.size(lvn_points)-1
hi_found = false
lo_found = false
_val = array.get(lvn_points,i)
for e = int(array.size(main)*merge_per) to 0
if array.includes(lvn_points,_val+e)
hi_found := true
if hi_found
array.push(lvn_points,_val+e)
if array.includes(lvn_points,_val-e)
lo_found := true
if lo_found
array.push(lvn_points,_val-e)
prof_axis = disp_size>0?last_new_calc:bar_index[1]
display_size = auto_size and disp_size!=0?(disp_size/math.abs(disp_size))*(calc_bars-1):disp_size
if array.size(main) > 0
for i = 0 to array.size(main) - 1
scale = display_size/array.max(main)
scaled = math.round(array.get(main,i)*scale)
if ((i>uc) or (i<dc)) and (array.size(line_array) <= 499)
array.push(line_array,line.new(prof_axis,base+(i*tick_size[1]),(prof_axis+scaled),base+(i*tick_size[1]), color = prof_color(i,max_index,hvn_points,lvn_points,uc,dc), style = (i<dc or i>uc?line.style_dotted:line.style_solid)))
else if ((i<=uc) or (i>=dc)) and (array.size(box_array) <= 499)
array.push(box_array,box.new(prof_axis,base+(i*tick_size[1]),(prof_axis+scaled),base+(i*tick_size[1]), border_color = prof_color(i,max_index,hvn_points,lvn_points,uc,dc), border_style = (i<dc or i>uc?line.style_dotted:line.style_solid), border_width = 1))
else if (array.size(line_array) <= 499)
array.push(line_array,line.new(prof_axis,base+(i*tick_size[1]),(prof_axis+scaled),base+(i*tick_size[1]), color = prof_color(i,max_index,hvn_points,lvn_points,uc,dc), style = (i<dc or i>uc?line.style_dotted:line.style_solid)))
else if (array.size(box_array) <= 499)
array.push(box_array,box.new(prof_axis,base+(i*tick_size[1]),(prof_axis+scaled),base+(i*tick_size[1]), border_color = prof_color(i,max_index,hvn_points,lvn_points,uc,dc), border_style = (i<dc or i>uc?line.style_dotted:line.style_solid), border_width = 1))
lab = label.new(prof_axis,roof,size = size.small, text = (mp?"Mkt Profile [":"Vol Profile [") + tf + "] " + "\nLB [" + str.tostring(calc_bars) + " Bars]" + "\nGran: " + str.tostring(tick_size,"$#.##########"), style = (disp_size<0?label.style_label_lower_right:label.style_label_lower_left), color = color.rgb(0,0,0,100), textcolor = chart.fg_color, textalign = (disp_size<0?text.align_right:text.align_left), text_font_family = font.family_monospace)
get_prof(mp,tf)
|
Flat & Trend MACD | https://www.tradingview.com/script/0cHW3eZf-flat-trend-macd/ | Shuttle_Trader | https://www.tradingview.com/u/Shuttle_Trader/ | 82 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Shuttle_Trader
//@version=5
indicator(title='Flat & Trend MACD', shorttitle='Flat & Trend MACD', overlay=true)
fast_length = input(title='Fast Length', defval=20)
slow_length = input(title='Slow Length', defval=100)
signal_length = input.int(title='Signal Smoothing', minval=1, maxval=50, defval=10)
show_flat = input.bool(true, title='Show flat zones')
// Price channel
hline = ta.highest(fast_length)
lline = ta.lowest(fast_length)
// MACD setup
[macd, signal, hist] = ta.macd(close, fast_length, slow_length, signal_length)
// MACD flat
flat_value = math.max(ta.highest(hist,50), math.abs(ta.lowest(hist,50)))/2
// MACD trend
buyzone = bool(na), sellzone = bool(na)
buyzone := hist > 0 and math.abs(hist) > flat_value
sellzone := hist < 0 and math.abs(hist) > flat_value
if not buyzone and not sellzone
buyzone := buyzone[1]
sellzone := sellzone[1]
MACD_trend = 0
MACD_trend := buyzone ? 1 : sellzone ? -1 : nz(MACD_trend[1])
// Plot colors
trend_color = color(na)
if show_flat
trend_color :=
MACD_trend>0 and math.abs(hist) > flat_value ? color.rgb(12, 100, 14, 60) :
MACD_trend>0 and math.abs(hist) < flat_value ? color.rgb(133, 153, 133, 80) :
MACD_trend<0 and math.abs(hist) > flat_value ? color.rgb(138, 24, 24, 60) :
MACD_trend<0 and math.abs(hist) < flat_value ? color.rgb(153, 134, 134, 80) : na
if not show_flat
trend_color :=
MACD_trend>0 ? color.rgb(12, 100, 14, 60) :
MACD_trend<0 ? color.rgb(138, 24, 24, 60) : na
hl = plot(hline, title='High-line', color=color.rgb(12, 100, 14, 30))
ll = plot(lline, title='Low-line', color=color.rgb(138, 24, 24, 30))
fill(hl, ll, color=trend_color, fillgaps=true)
plotshape(MACD_trend>0 and MACD_trend[1]<=0, title='UP', style=shape.triangleup, location=location.belowbar, color=#08f108, text='', textcolor=#08f108, size=size.tiny)
plotshape(MACD_trend<0 and MACD_trend[1]>=0, title='DN', style=shape.triangledown, location=location.abovebar, color=#ee0e3f, text='', textcolor=#ee0e3f, size=size.tiny)
// Beginning flat
flat_up = math.abs(hist)<flat_value and (math.abs(hist)>flat_value)[1] and MACD_trend>0
flat_dn = math.abs(hist)<flat_value and (math.abs(hist)>flat_value)[1] and MACD_trend<0
plotshape(show_flat ? flat_up : na, title='flat up', style=shape.square, location=location.belowbar, color=#cc6e16, text='', textcolor=#08f108, size=size.tiny)
plotshape(show_flat ? flat_dn : na, title='flat dn', style=shape.square, location=location.belowbar, color=#cc6e16, text='', textcolor=#08f108, size=size.tiny)
// Alerts
if MACD_trend>0 and MACD_trend[1]<=0
alert('๐ข '+ syminfo.ticker + ' >> MACD UP-TREND',alert.freq_once_per_bar_close)
if MACD_trend<0 and MACD_trend[1]>=0
alert('๐ด '+ syminfo.ticker + ' >> MACD DOWN-TREND',alert.freq_once_per_bar_close)
if flat_up
alert('โ ๏ธ '+ syminfo.ticker + ' >> MACD Flat zone in UP-TREND',alert.freq_once_per_bar_close)
if flat_dn
alert('โ ๏ธ '+ syminfo.ticker + ' >> MACD Flat zone in DOWN-TREND',alert.freq_once_per_bar_close)
ST00 = '>>> Flat & Trend MACD <<<\n\n' + syminfo.tickerid + ' tf = ' + timeframe.period
ST01 = 'MACD TREND : ' + (MACD_trend>0 ? 'LONG' : MACD_trend<0 ? 'SHORT' : '') + (math.abs(hist)<flat_value ? '\nโ ๏ธ Flat zone!' : '')
var table state = table.new(position = position.top_right, columns=1, rows=2, border_color = color.new(#035509, 0), border_width = 1, frame_color = color.new(#035509,0), frame_width = 2)
table.cell(state, 0, 0, ST00, text_color=color.new(#000000,0), text_size = size.normal, bgcolor = color.new(#388e3c,0))
table.cell(state, 0, 1, ST01, text_color=color.new(#000000,0), text_size = size.normal, bgcolor = color.new(#388e3c,0))
|
HTF Liquidity Dashboard [TFO] | https://www.tradingview.com/script/cX21mnps-HTF-Liquidity-Dashboard-TFO/ | tradeforopp | https://www.tradingview.com/u/tradeforopp/ | 1,657 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ tradeforopp
//@version=5
indicator("HTF Liquidity Dashboard [TFO]", "HTF Liquidity Dashboard [TFO]", true, max_labels_count = 500, max_lines_count = 500)
// ------------------------------ Inputs ------------------------------
var g_SET = "Settings"
show_d = input.bool(true, "Daily", inline = "DWM", tooltip = "Select which timeframes should be displayed with their highs and lows", group = g_SET)
show_w = input.bool(false, "Weekly", inline = "DWM", group = g_SET)
show_m = input.bool(false, "Monthly", inline = "DWM", group = g_SET)
labels = input.bool(false, "Show Sweep Labels", inline = "LBL", tooltip = "Show labels when any of the selected symbols sweep their previous highs and lows", group = g_SET)
label_bg = input.color(color.black, "", inline = "LBL", group = g_SET)
label_text = input.color(color.white, "", inline = "LBL", group = g_SET)
text_size = input.string("Normal", "Text Size", options = ['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], tooltip = "Label and table text size", group = g_SET)
dash_text = input.string("Custom", "Dashboard Text", options = ['Custom', 'Levels'], tooltip = "Custom will show the strings below in the dashboard cells. Levels will show the actual numerical highs and lows", group = g_SET)
exceed_str = input.string("โ", "Swept & Exceeded โ", inline = "XC", tooltip = "When price takes a high and is currently trading above it, or takes a low and is currently trading below it", group = g_SET)
failed_str = input.string("โ", "Swept & Reversed โ โ", inline = "RV", tooltip = "When price takes a high but is currently trading back below it, or takes a low and is currently trading back above it", group = g_SET)
exceed_color = input.color(color.new(#089981, 30), "", inline = "XC", group = g_SET)
failed_color = input.color(color.new(#f23645, 30), "", inline = "RV", group = g_SET)
var g_CC = "Current Chart"
show_c = input.bool(true, "Show Levels", tooltip = "Show previous highs and lows of the current chart symbol", group = g_CC)
plimit = input.int(3, "Session Limit", 1, tooltip = "This many highs and lows will be stored and shown on the current chart (per timeframe)", group = g_CC)
before_color = input.color(#000000, "Colors Before / After Sweep", inline = "CCC", tooltip = "Levels will be drawn as the left color, but will change to the right color once price trades through them", group = g_CC)
after_color = input.color(#f23645, "", inline = "CCC", group = g_CC)
d_style = input.string('Dotted', "Daily โ โ โ โ", options = ['Solid', 'Dashed', 'Dotted'], inline = "CCD", group = g_CC)
d_width = input.int(1, "", 0, inline = "CCD", group = g_CC)
w_style = input.string('Dashed', "Weekly โ", options = ['Solid', 'Dashed', 'Dotted'], inline = "CCW", group = g_CC)
w_width = input.int(1, "", 0, inline = "CCW", group = g_CC)
m_style = input.string('Solid', "Monthly", options = ['Solid', 'Dashed', 'Dotted'], inline = "CCM", group = g_CC)
m_width = input.int(1, "", 0, inline = "CCM", group = g_CC)
var g_SYM = "Symbols"
use_s0 = input.bool(true, "", inline = "s0", group = g_SYM)
use_s1 = input.bool(true, "", inline = "s1", group = g_SYM)
use_s2 = input.bool(true, "", inline = "s2", group = g_SYM)
use_s3 = input.bool(true, "", inline = "s3", group = g_SYM)
use_s4 = input.bool(true, "", inline = "s4", group = g_SYM)
use_s5 = input.bool(true, "", inline = "s5", group = g_SYM)
use_s6 = input.bool(true, "", inline = "s6", group = g_SYM)
use_s7 = input.bool(true, "", inline = "s7", group = g_SYM)
use_s8 = input.bool(true, "", inline = "s8", group = g_SYM)
s0 = input.symbol("ES1!", "", inline = "s0", group = g_SYM)
s1 = input.symbol("NQ1!", "", inline = "s1", group = g_SYM)
s2 = input.symbol("YM1!", "", inline = "s2", group = g_SYM)
s3 = input.symbol("CL1!", "", inline = "s3", group = g_SYM)
s4 = input.symbol("GC1!", "", inline = "s4", group = g_SYM)
s5 = input.symbol("EURUSD", "", inline = "s5", group = g_SYM)
s6 = input.symbol("GBPUSD", "", inline = "s6", group = g_SYM)
s7 = input.symbol("USDJPY", "", inline = "s7", group = g_SYM)
s8 = input.symbol("AUDUSD", "", inline = "s8", group = g_SYM)
var g_TBL = "Table Style"
table_position = input.string('Top Right', "Table Position", options = ['Bottom Center', 'Bottom Left', 'Bottom Right', 'Middle Center', 'Middle Left', 'Middle Right', 'Top Center', 'Top Left', 'Top Right'], group = g_TBL)
tbl_bg = input.color(color.white, "Background Color", group = g_TBL)
tbl_bd = input.color(color.black, "Border Color", group = g_TBL)
tbl_fr = input.color(color.black, "Frame Color", group = g_TBL)
tbl_fr_w = input.int(2, "Frame Width", 1, group = g_TBL)
tbl_bd_w = input.int(1, "Border Width", 1, group = g_TBL)
// ------------------------------ Inputs ------------------------------
// ------------------------------ Functions ------------------------------
get_name(x) =>
array.get(str.split(x, ":"), 1)
get_size(x) =>
result = switch x
'Auto' => size.auto
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal
'Large' => size.large
'Huge' => size.huge
get_line_style(x) =>
result = switch x
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
get_table_position(x) =>
result = switch x
"Bottom Center" => position.bottom_center
"Bottom Left" => position.bottom_left
"Bottom Right" => position.bottom_right
"Middle Center" => position.middle_center
"Middle Left" => position.middle_left
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Left" => position.top_left
"Top Right" => position.top_right
update_arrays(o, h_arr, l_arr, h, l) =>
if o != o[1]
h_arr.unshift(h[1])
l_arr.unshift(l[1])
if h_arr.size() > 1
h_arr.pop()
l_arr.pop()
evaluate(ph, ch, pl, cl, cc) =>
color _hcolor = na
string _hstring = (dash_text == 'Levels') ? str.tostring(ph) : "-"
if ch > ph
if cc > ph
_hcolor := exceed_color
if not (dash_text == 'Levels')
_hstring := exceed_str
else
_hcolor := failed_color
if not (dash_text == 'Levels')
_hstring := failed_str
color _lcolor = na
string _lstring = (dash_text == 'Levels') ? str.tostring(pl) : "-"
if cl < pl
if cc < pl
_lcolor := exceed_color
if not (dash_text == 'Levels')
_lstring := exceed_str
else
_lcolor := failed_color
if not (dash_text == 'Levels')
_lstring := failed_str
[_hstring, _hcolor, _lstring, _lcolor]
update_table(_table, _col, _row, _use, _name, _h, _l, _c, _highs, _lows) =>
if _use and _highs.size() > 0
_size = get_size(text_size)
[_hstring, _hcolor, _lstring, _lcolor] = evaluate(_highs.get(0), _h, _lows.get(0), _l, _c)
table.cell(_table, 0, _row, str.tostring(get_name(_name)), text_size = _size)
table.cell(_table, _col, _row, _hstring, bgcolor = _hcolor, text_size = _size)
table.cell(_table, _col + 1, _row, _lstring, bgcolor = _lcolor, text_size = _size)
check_raids(_s, _use, _ph, _pl, _ch, _cl, _rah, _ral, _ri, _tf) =>
if _ph.size() > 0 and _use
took_highs = _ch > _ph.get(0)
took_lows = _cl < _pl.get(0)
_name = get_name(_s)
if took_highs and not _rah.get(_ri)
_rah.set(_ri, true)
_text = _name + " Took P" + _tf + "H"
alert(_text, freq = alert.freq_once_per_bar)
if labels
label.new(bar_index, high, _text, style = label.style_label_down, color = label_bg, textcolor = label_text, size = get_size(text_size))
if took_lows and not _ral.get(_ri)
_ral.set(_ri, true)
_text = _name + " Took P" + _tf + "L"
alert(_text, freq = alert.freq_once_per_bar)
if labels
label.new(bar_index, low, _text, style = label.style_label_up, color = label_bg, textcolor = label_text, size = get_size(text_size))
reset_raid(_d, _ah, _al) =>
result = false
if _d != _d[1]
for i = 0 to _ah.size() - 1
_ah.set(i, false)
for i = 0 to _al.size() - 1
_al.set(i, false)
chart_pivot(_open, _high, _low, _ph, _pl, _hline, _lline, _hlabel, _llabel, _tf, _style, _width) =>
if _ph.size() > 0
if _open != _open[1]
_hline.unshift(line.new(bar_index, _ph.get(0), bar_index, _ph.get(0), color = before_color, width = _width, style = _style))
_lline.unshift(line.new(bar_index, _pl.get(0), bar_index, _pl.get(0), color = before_color, width = _width, style = _style))
_hlabel.set_xy(bar_index, _ph.get(0))
_llabel.set_xy(bar_index, _pl.get(0))
_hlabel.set_text("P" + _tf + "H")
_llabel.set_text("P" + _tf + "L")
_hlabel.set_textcolor(before_color)
_llabel.set_textcolor(before_color)
else
_hline.get(0).set_x2(bar_index)
_lline.get(0).set_x2(bar_index)
_hlabel.set_x(bar_index)
_llabel.set_x(bar_index)
if _high > _hline.get(0).get_y1()
_hline.get(0).set_color(after_color)
_hlabel.set_textcolor(after_color)
if _low < _lline.get(0).get_y1()
_lline.get(0).set_color(after_color)
_llabel.set_textcolor(after_color)
if _hline.size() > plimit
line.delete(_hline.pop())
line.delete(_lline.pop())
// ------------------------------ Functions ------------------------------
// ------------------------------ DWM Data ------------------------------
// chart timeframe
[s0c_o, s0c_h, s0c_l, s0c_c] = request.security(s0, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s1c_o, s1c_h, s1c_l, s1c_c] = request.security(s1, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s2c_o, s2c_h, s2c_l, s2c_c] = request.security(s2, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s3c_o, s3c_h, s3c_l, s3c_c] = request.security(s3, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s4c_o, s4c_h, s4c_l, s4c_c] = request.security(s4, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s5c_o, s5c_h, s5c_l, s5c_c] = request.security(s5, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s6c_o, s6c_h, s6c_l, s6c_c] = request.security(s6, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s7c_o, s7c_h, s7c_l, s7c_c] = request.security(s7, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s8c_o, s8c_h, s8c_l, s8c_c] = request.security(s8, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// daily timeframe
[s0d_o, s0d_h, s0d_l, s0d_c] = request.security(s0, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s1d_o, s1d_h, s1d_l, s1d_c] = request.security(s1, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s2d_o, s2d_h, s2d_l, s2d_c] = request.security(s2, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s3d_o, s3d_h, s3d_l, s3d_c] = request.security(s3, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s4d_o, s4d_h, s4d_l, s4d_c] = request.security(s4, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s5d_o, s5d_h, s5d_l, s5d_c] = request.security(s5, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s6d_o, s6d_h, s6d_l, s6d_c] = request.security(s6, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s7d_o, s7d_h, s7d_l, s7d_c] = request.security(s7, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s8d_o, s8d_h, s8d_l, s8d_c] = request.security(s8, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// weekly timeframe
[s0w_o, s0w_h, s0w_l, s0w_c] = request.security(s0, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s1w_o, s1w_h, s1w_l, s1w_c] = request.security(s1, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s2w_o, s2w_h, s2w_l, s2w_c] = request.security(s2, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s3w_o, s3w_h, s3w_l, s3w_c] = request.security(s3, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s4w_o, s4w_h, s4w_l, s4w_c] = request.security(s4, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s5w_o, s5w_h, s5w_l, s5w_c] = request.security(s5, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s6w_o, s6w_h, s6w_l, s6w_c] = request.security(s6, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s7w_o, s7w_h, s7w_l, s7w_c] = request.security(s7, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s8w_o, s8w_h, s8w_l, s8w_c] = request.security(s8, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// monthly timeframe
[s0m_o, s0m_h, s0m_l, s0m_c] = request.security(s0, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s1m_o, s1m_h, s1m_l, s1m_c] = request.security(s1, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s2m_o, s2m_h, s2m_l, s2m_c] = request.security(s2, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s3m_o, s3m_h, s3m_l, s3m_c] = request.security(s3, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s4m_o, s4m_h, s4m_l, s4m_c] = request.security(s4, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s5m_o, s5m_h, s5m_l, s5m_c] = request.security(s5, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s6m_o, s6m_h, s6m_l, s6m_c] = request.security(s6, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s7m_o, s7m_h, s7m_l, s7m_c] = request.security(s7, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s8m_o, s8m_h, s8m_l, s8m_c] = request.security(s8, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// current chart symbol
[s9c_o, s9c_h, s9c_l, s9c_c] = request.security(syminfo.tickerid, "", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s9d_o, s9d_h, s9d_l, s9d_c] = request.security(syminfo.tickerid, "D", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s9w_o, s9w_h, s9w_l, s9w_c] = request.security(syminfo.tickerid, "W", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
[s9m_o, s9m_h, s9m_l, s9m_c] = request.security(syminfo.tickerid, "M", [open, high, low, close], barmerge.gaps_off, barmerge.lookahead_on)
// ------------------------------ DWM Data ------------------------------
// ------------------------------ Arrays ------------------------------
// daily
var s00d_highs = array.new_float()
var s0d_highs = array.new_float()
var s1d_highs = array.new_float()
var s2d_highs = array.new_float()
var s3d_highs = array.new_float()
var s4d_highs = array.new_float()
var s5d_highs = array.new_float()
var s6d_highs = array.new_float()
var s7d_highs = array.new_float()
var s8d_highs = array.new_float()
var s9d_highs = array.new_float()
var s00d_lows = array.new_float()
var s0d_lows = array.new_float()
var s1d_lows = array.new_float()
var s2d_lows = array.new_float()
var s3d_lows = array.new_float()
var s4d_lows = array.new_float()
var s5d_lows = array.new_float()
var s6d_lows = array.new_float()
var s7d_lows = array.new_float()
var s8d_lows = array.new_float()
var s9d_lows = array.new_float()
var s0d_rh = array.new_bool(10, false)
var s1d_rh = array.new_bool(10, false)
var s2d_rh = array.new_bool(10, false)
var s3d_rh = array.new_bool(10, false)
var s4d_rh = array.new_bool(10, false)
var s5d_rh = array.new_bool(10, false)
var s6d_rh = array.new_bool(10, false)
var s7d_rh = array.new_bool(10, false)
var s8d_rh = array.new_bool(10, false)
var s9d_rh = array.new_bool(10, false)
var s0d_rl = array.new_bool(10, false)
var s1d_rl = array.new_bool(10, false)
var s2d_rl = array.new_bool(10, false)
var s3d_rl = array.new_bool(10, false)
var s4d_rl = array.new_bool(10, false)
var s5d_rl = array.new_bool(10, false)
var s6d_rl = array.new_bool(10, false)
var s7d_rl = array.new_bool(10, false)
var s8d_rl = array.new_bool(10, false)
var s9d_rl = array.new_bool(10, false)
// weekly
var s00w_highs = array.new_float()
var s0w_highs = array.new_float()
var s1w_highs = array.new_float()
var s2w_highs = array.new_float()
var s3w_highs = array.new_float()
var s4w_highs = array.new_float()
var s5w_highs = array.new_float()
var s6w_highs = array.new_float()
var s7w_highs = array.new_float()
var s8w_highs = array.new_float()
var s9w_highs = array.new_float()
var s00w_lows = array.new_float()
var s0w_lows = array.new_float()
var s1w_lows = array.new_float()
var s2w_lows = array.new_float()
var s3w_lows = array.new_float()
var s4w_lows = array.new_float()
var s5w_lows = array.new_float()
var s6w_lows = array.new_float()
var s7w_lows = array.new_float()
var s8w_lows = array.new_float()
var s9w_lows = array.new_float()
var s0w_rh = array.new_bool(10, false)
var s1w_rh = array.new_bool(10, false)
var s2w_rh = array.new_bool(10, false)
var s3w_rh = array.new_bool(10, false)
var s4w_rh = array.new_bool(10, false)
var s5w_rh = array.new_bool(10, false)
var s6w_rh = array.new_bool(10, false)
var s7w_rh = array.new_bool(10, false)
var s8w_rh = array.new_bool(10, false)
var s9w_rh = array.new_bool(10, false)
var s0w_rl = array.new_bool(10, false)
var s1w_rl = array.new_bool(10, false)
var s2w_rl = array.new_bool(10, false)
var s3w_rl = array.new_bool(10, false)
var s4w_rl = array.new_bool(10, false)
var s5w_rl = array.new_bool(10, false)
var s6w_rl = array.new_bool(10, false)
var s7w_rl = array.new_bool(10, false)
var s8w_rl = array.new_bool(10, false)
var s9w_rl = array.new_bool(10, false)
// monthly
var s00m_highs = array.new_float()
var s0m_highs = array.new_float()
var s1m_highs = array.new_float()
var s2m_highs = array.new_float()
var s3m_highs = array.new_float()
var s4m_highs = array.new_float()
var s5m_highs = array.new_float()
var s6m_highs = array.new_float()
var s7m_highs = array.new_float()
var s8m_highs = array.new_float()
var s9m_highs = array.new_float()
var s00m_lows = array.new_float()
var s0m_lows = array.new_float()
var s1m_lows = array.new_float()
var s2m_lows = array.new_float()
var s3m_lows = array.new_float()
var s4m_lows = array.new_float()
var s5m_lows = array.new_float()
var s6m_lows = array.new_float()
var s7m_lows = array.new_float()
var s8m_lows = array.new_float()
var s9m_lows = array.new_float()
var s0m_rh = array.new_bool(10, false)
var s1m_rh = array.new_bool(10, false)
var s2m_rh = array.new_bool(10, false)
var s3m_rh = array.new_bool(10, false)
var s4m_rh = array.new_bool(10, false)
var s5m_rh = array.new_bool(10, false)
var s6m_rh = array.new_bool(10, false)
var s7m_rh = array.new_bool(10, false)
var s8m_rh = array.new_bool(10, false)
var s9m_rh = array.new_bool(10, false)
var s0m_rl = array.new_bool(10, false)
var s1m_rl = array.new_bool(10, false)
var s2m_rl = array.new_bool(10, false)
var s3m_rl = array.new_bool(10, false)
var s4m_rl = array.new_bool(10, false)
var s5m_rl = array.new_bool(10, false)
var s6m_rl = array.new_bool(10, false)
var s7m_rl = array.new_bool(10, false)
var s8m_rl = array.new_bool(10, false)
var s9m_rl = array.new_bool(10, false)
//current chart
var pdh = array.new_line()
var pwh = array.new_line()
var pmh = array.new_line()
var pdl = array.new_line()
var pwl = array.new_line()
var pml = array.new_line()
var pdh_label = label.new(na, na, style = label.style_label_left, color = #ffffff00, textcolor = before_color, size = get_size(text_size))
var pwh_label = label.new(na, na, style = label.style_label_left, color = #ffffff00, textcolor = before_color, size = get_size(text_size))
var pmh_label = label.new(na, na, style = label.style_label_left, color = #ffffff00, textcolor = before_color, size = get_size(text_size))
var pdl_label = label.new(na, na, style = label.style_label_left, color = #ffffff00, textcolor = before_color, size = get_size(text_size))
var pwl_label = label.new(na, na, style = label.style_label_left, color = #ffffff00, textcolor = before_color, size = get_size(text_size))
var pml_label = label.new(na, na, style = label.style_label_left, color = #ffffff00, textcolor = before_color, size = get_size(text_size))
// ------------------------------ Arrays ------------------------------
// ------------------------------ Update Arrays ------------------------------
// daily
update_arrays(s0d_o, s0d_highs, s0d_lows, s0d_h, s0d_l)
update_arrays(s1d_o, s1d_highs, s1d_lows, s1d_h, s1d_l)
update_arrays(s2d_o, s2d_highs, s2d_lows, s2d_h, s2d_l)
update_arrays(s3d_o, s3d_highs, s3d_lows, s3d_h, s3d_l)
update_arrays(s4d_o, s4d_highs, s4d_lows, s4d_h, s4d_l)
update_arrays(s5d_o, s5d_highs, s5d_lows, s5d_h, s5d_l)
update_arrays(s6d_o, s6d_highs, s6d_lows, s6d_h, s6d_l)
update_arrays(s7d_o, s7d_highs, s7d_lows, s7d_h, s7d_l)
update_arrays(s8d_o, s8d_highs, s8d_lows, s8d_h, s8d_l)
update_arrays(s9d_o, s9d_highs, s9d_lows, s9d_h, s9d_l)
// weekly
update_arrays(s0w_o, s0w_highs, s0w_lows, s0w_h, s0w_l)
update_arrays(s1w_o, s1w_highs, s1w_lows, s1w_h, s1w_l)
update_arrays(s2w_o, s2w_highs, s2w_lows, s2w_h, s2w_l)
update_arrays(s3w_o, s3w_highs, s3w_lows, s3w_h, s3w_l)
update_arrays(s4w_o, s4w_highs, s4w_lows, s4w_h, s4w_l)
update_arrays(s5w_o, s5w_highs, s5w_lows, s5w_h, s5w_l)
update_arrays(s6w_o, s6w_highs, s6w_lows, s6w_h, s6w_l)
update_arrays(s7w_o, s7w_highs, s7w_lows, s7w_h, s7w_l)
update_arrays(s8w_o, s8w_highs, s8w_lows, s8w_h, s8w_l)
update_arrays(s9w_o, s9w_highs, s9w_lows, s9w_h, s9w_l)
// monthly
update_arrays(s0m_o, s0m_highs, s0m_lows, s0m_h, s0m_l)
update_arrays(s1m_o, s1m_highs, s1m_lows, s1m_h, s1m_l)
update_arrays(s2m_o, s2m_highs, s2m_lows, s2m_h, s2m_l)
update_arrays(s3m_o, s3m_highs, s3m_lows, s3m_h, s3m_l)
update_arrays(s4m_o, s4m_highs, s4m_lows, s4m_h, s4m_l)
update_arrays(s5m_o, s5m_highs, s5m_lows, s5m_h, s5m_l)
update_arrays(s6m_o, s6m_highs, s6m_lows, s6m_h, s6m_l)
update_arrays(s7m_o, s7m_highs, s7m_lows, s7m_h, s7m_l)
update_arrays(s8m_o, s8m_highs, s8m_lows, s8m_h, s8m_l)
update_arrays(s9m_o, s9m_highs, s9m_lows, s9m_h, s9m_l)
// ------------------------------ Update Arrays ------------------------------
// ------------------------------ Reset Raids ------------------------------
// daily
reset_raid(s0d_o, s0d_rh, s0d_rl)
reset_raid(s1d_o, s1d_rh, s1d_rl)
reset_raid(s2d_o, s2d_rh, s2d_rl)
reset_raid(s3d_o, s3d_rh, s3d_rl)
reset_raid(s4d_o, s4d_rh, s4d_rl)
reset_raid(s5d_o, s5d_rh, s5d_rl)
reset_raid(s6d_o, s6d_rh, s6d_rl)
reset_raid(s7d_o, s7d_rh, s7d_rl)
reset_raid(s8d_o, s8d_rh, s8d_rl)
reset_raid(s9d_o, s9d_rh, s9d_rl)
// weeks
reset_raid(s0w_o, s0w_rh, s0w_rl)
reset_raid(s1w_o, s1w_rh, s1w_rl)
reset_raid(s2w_o, s2w_rh, s2w_rl)
reset_raid(s3w_o, s3w_rh, s3w_rl)
reset_raid(s4w_o, s4w_rh, s4w_rl)
reset_raid(s5w_o, s5w_rh, s5w_rl)
reset_raid(s6w_o, s6w_rh, s6w_rl)
reset_raid(s7w_o, s7w_rh, s7w_rl)
reset_raid(s8w_o, s8w_rh, s8w_rl)
reset_raid(s9w_o, s9w_rh, s9w_rl)
// monthly
reset_raid(s0m_o, s0m_rh, s0m_rl)
reset_raid(s1m_o, s1m_rh, s1m_rl)
reset_raid(s2m_o, s2m_rh, s2m_rl)
reset_raid(s3m_o, s3m_rh, s3m_rl)
reset_raid(s4m_o, s4m_rh, s4m_rl)
reset_raid(s5m_o, s5m_rh, s5m_rl)
reset_raid(s6m_o, s6m_rh, s6m_rl)
reset_raid(s7m_o, s7m_rh, s7m_rl)
reset_raid(s8m_o, s8m_rh, s8m_rl)
reset_raid(s9m_o, s9m_rh, s9m_rl)
// ------------------------------ Reset Raids ------------------------------
// ------------------------------ Check Raids ------------------------------
// daily
check_raids(s0, use_s0 and show_d, s0d_highs, s0d_lows, s0c_h, s0c_l, s0d_rh, s0d_rl, 0, "D")
check_raids(s1, use_s1 and show_d, s1d_highs, s1d_lows, s1c_h, s1c_l, s1d_rh, s1d_rl, 1, "D")
check_raids(s2, use_s2 and show_d, s2d_highs, s2d_lows, s2c_h, s2c_l, s2d_rh, s2d_rl, 2, "D")
check_raids(s3, use_s3 and show_d, s3d_highs, s3d_lows, s3c_h, s3c_l, s3d_rh, s3d_rl, 3, "D")
check_raids(s4, use_s4 and show_d, s4d_highs, s4d_lows, s4c_h, s4c_l, s4d_rh, s4d_rl, 4, "D")
check_raids(s5, use_s5 and show_d, s5d_highs, s5d_lows, s5c_h, s5c_l, s5d_rh, s5d_rl, 5, "D")
check_raids(s6, use_s6 and show_d, s6d_highs, s6d_lows, s6c_h, s6c_l, s6d_rh, s6d_rl, 6, "D")
check_raids(s7, use_s7 and show_d, s7d_highs, s7d_lows, s7c_h, s7c_l, s7d_rh, s7d_rl, 7, "D")
check_raids(s8, use_s8 and show_d, s8d_highs, s8d_lows, s8c_h, s8c_l, s8d_rh, s8d_rl, 8, "D")
// weekly
check_raids(s0, use_s0 and show_w, s0w_highs, s0w_lows, s0c_h, s0c_l, s0w_rh, s0w_rl, 0, "W")
check_raids(s1, use_s1 and show_w, s1w_highs, s1w_lows, s1c_h, s1c_l, s1w_rh, s1w_rl, 1, "W")
check_raids(s2, use_s2 and show_w, s2w_highs, s2w_lows, s2c_h, s2c_l, s2w_rh, s2w_rl, 2, "W")
check_raids(s3, use_s3 and show_w, s3w_highs, s3w_lows, s3c_h, s3c_l, s3w_rh, s3w_rl, 3, "W")
check_raids(s4, use_s4 and show_w, s4w_highs, s4w_lows, s4c_h, s4c_l, s4w_rh, s4w_rl, 4, "W")
check_raids(s5, use_s5 and show_w, s5w_highs, s5w_lows, s5c_h, s5c_l, s5w_rh, s5w_rl, 5, "W")
check_raids(s6, use_s6 and show_w, s6w_highs, s6w_lows, s6c_h, s6c_l, s6w_rh, s6w_rl, 6, "W")
check_raids(s7, use_s7 and show_w, s7w_highs, s7w_lows, s7c_h, s7c_l, s7w_rh, s7w_rl, 7, "W")
check_raids(s8, use_s8 and show_w, s8w_highs, s8w_lows, s8c_h, s8c_l, s8w_rh, s8w_rl, 8, "W")
// monthly
check_raids(s0, use_s0 and show_m, s0m_highs, s0m_lows, s0c_h, s0c_l, s0m_rh, s0m_rl, 0, "M")
check_raids(s1, use_s1 and show_m, s1m_highs, s1m_lows, s1c_h, s1c_l, s1m_rh, s1m_rl, 1, "M")
check_raids(s2, use_s2 and show_m, s2m_highs, s2m_lows, s2c_h, s2c_l, s2m_rh, s2m_rl, 2, "M")
check_raids(s3, use_s3 and show_m, s3m_highs, s3m_lows, s3c_h, s3c_l, s3m_rh, s3m_rl, 3, "M")
check_raids(s4, use_s4 and show_m, s4m_highs, s4m_lows, s4c_h, s4c_l, s4m_rh, s4m_rl, 4, "M")
check_raids(s5, use_s5 and show_m, s5m_highs, s5m_lows, s5c_h, s5c_l, s5m_rh, s5m_rl, 5, "M")
check_raids(s6, use_s6 and show_m, s6m_highs, s6m_lows, s6c_h, s6c_l, s6m_rh, s6m_rl, 6, "M")
check_raids(s7, use_s7 and show_m, s7m_highs, s7m_lows, s7c_h, s7c_l, s7m_rh, s7m_rl, 7, "M")
check_raids(s8, use_s8 and show_m, s8m_highs, s8m_lows, s8c_h, s8c_l, s8m_rh, s8m_rl, 8, "M")
// ------------------------------ Check Raids ------------------------------
// ------------------------------ Current Chart ------------------------------
d_style := get_line_style(d_style)
w_style := get_line_style(w_style)
m_style := get_line_style(m_style)
if show_c
if show_d
chart_pivot(s9d_o, s9d_h, s9d_l, s9d_highs, s9d_lows, pdh, pdl, pdh_label, pdl_label, "D", d_style, d_width)
if show_w
chart_pivot(s9w_o, s9w_h, s9w_l, s9w_highs, s9w_lows, pwh, pwl, pwh_label, pwl_label, "W", w_style, w_width)
if show_m
chart_pivot(s9m_o, s9m_h, s9m_l, s9m_highs, s9m_lows, pmh, pml, pmh_label, pml_label, "M", m_style, m_width)
// ------------------------------ Current Chart ------------------------------
// ------------------------------ Dashboard ------------------------------
var stats = table.new(get_table_position(table_position), 20, 20, tbl_bg, tbl_fr, tbl_fr_w, tbl_bd, tbl_bd_w)
if barstate.islast
_size = get_size(text_size)
table.cell(stats, 0, 0, "Symbol", text_size = _size)
if show_d
table.cell(stats, 1, 0, "PDH", text_size = _size)
table.cell(stats, 2, 0, "PDL", text_size = _size)
update_table(stats, 1, 1, use_s0, s0, s0d_h, s0d_l, s0d_c, s0d_highs, s0d_lows)
update_table(stats, 1, 2, use_s1, s1, s1d_h, s1d_l, s1d_c, s1d_highs, s1d_lows)
update_table(stats, 1, 3, use_s2, s2, s2d_h, s2d_l, s2d_c, s2d_highs, s2d_lows)
update_table(stats, 1, 4, use_s3, s3, s3d_h, s3d_l, s3d_c, s3d_highs, s3d_lows)
update_table(stats, 1, 5, use_s4, s4, s4d_h, s4d_l, s4d_c, s4d_highs, s4d_lows)
update_table(stats, 1, 6, use_s5, s5, s5d_h, s5d_l, s5d_c, s5d_highs, s5d_lows)
update_table(stats, 1, 7, use_s6, s6, s6d_h, s6d_l, s6d_c, s6d_highs, s6d_lows)
update_table(stats, 1, 8, use_s7, s7, s7d_h, s7d_l, s7d_c, s7d_highs, s7d_lows)
update_table(stats, 1, 9, use_s8, s8, s8d_h, s8d_l, s8d_c, s8d_highs, s8d_lows)
if show_w
table.cell(stats, 3, 0, "PWH", text_size = _size)
table.cell(stats, 4, 0, "PWL", text_size = _size)
update_table(stats, 3, 1, use_s0, s0, s0w_h, s0w_l, s0w_c, s0w_highs, s0w_lows)
update_table(stats, 3, 2, use_s1, s1, s1w_h, s1w_l, s1w_c, s1w_highs, s1w_lows)
update_table(stats, 3, 3, use_s2, s2, s2w_h, s2w_l, s2w_c, s2w_highs, s2w_lows)
update_table(stats, 3, 4, use_s3, s3, s3w_h, s3w_l, s3w_c, s3w_highs, s3w_lows)
update_table(stats, 3, 5, use_s4, s4, s4w_h, s4w_l, s4w_c, s4w_highs, s4w_lows)
update_table(stats, 3, 6, use_s5, s5, s5w_h, s5w_l, s5w_c, s5w_highs, s5w_lows)
update_table(stats, 3, 7, use_s6, s6, s6w_h, s6w_l, s6w_c, s6w_highs, s6w_lows)
update_table(stats, 3, 8, use_s7, s7, s7w_h, s7w_l, s7w_c, s7w_highs, s7w_lows)
update_table(stats, 3, 9, use_s8, s8, s8w_h, s8w_l, s8w_c, s8w_highs, s8w_lows)
if show_m
table.cell(stats, 5, 0, "PMH", text_size = _size)
table.cell(stats, 6, 0, "PML", text_size = _size)
update_table(stats, 5, 1, use_s0, s0, s0m_h, s0m_l, s0m_c, s0m_highs, s0m_lows)
update_table(stats, 5, 2, use_s1, s1, s1m_h, s1m_l, s1m_c, s1m_highs, s1m_lows)
update_table(stats, 5, 3, use_s2, s2, s2m_h, s2m_l, s2m_c, s2m_highs, s2m_lows)
update_table(stats, 5, 4, use_s3, s3, s3m_h, s3m_l, s3m_c, s3m_highs, s3m_lows)
update_table(stats, 5, 5, use_s4, s4, s4m_h, s4m_l, s4m_c, s4m_highs, s4m_lows)
update_table(stats, 5, 6, use_s5, s5, s5m_h, s5m_l, s5m_c, s5m_highs, s5m_lows)
update_table(stats, 5, 7, use_s6, s6, s6m_h, s6m_l, s6m_c, s6m_highs, s6m_lows)
update_table(stats, 5, 8, use_s7, s7, s7m_h, s7m_l, s7m_c, s7m_highs, s7m_lows)
update_table(stats, 5, 9, use_s8, s8, s8m_h, s8m_l, s8m_c, s8m_highs, s8m_lows)
// ------------------------------ Dashboard ------------------------------ |
ICT Daily Levels and Zones (fadi) | https://www.tradingview.com/script/frPlMXEa-ICT-Daily-Levels-and-Zones-fadi/ | fadizeidan | https://www.tradingview.com/u/fadizeidan/ | 350 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ fadizeidan
//@version=5
indicator("ICT Daily Levels and Zones (fadi)", overlay = true, max_lines_count = 500, max_boxes_count = 500)
//+------------------------------------------------------------------------------------------------------------+//
//+--- Types ---+//
//+--- Types are data structures that allows us to hold multiple related values in a single instance ---+//
//+-- Tradingview has some limitations so some workarounds are required. ---+//
//+------------------------------------------------------------------------------------------------------------+//
//+------------------------------------------------------------------------------------------------------------+//
//+--- Zone ---+//
//+--- Used to capture the start, end, and levels (box) of a zone such as: ---+//
//+-- Killzones, Open Range, and Open Range Gap ---+//
//+------------------------------------------------------------------------------------------------------------+//
type Zone
float o
float h
float l
float c
int o_time
int h_time
int l_time
int c_time
box b
//+------------------------------------------------------------------------------------------------------------+//
//+--- ohlc ---+//
//+--- ohlc is used to capture the daily relevant values and when they occured. ---+//
//+------------------------------------------------------------------------------------------------------------+//
type ohlc
float o
float h
float l
float c
float o_MN
int o_MN_time
float o_830
int o_830_time
float o_930
int o_930_time
int o_time
int o_idx
int h_time
int l_time
int c_time
line o_line
line h_line
line l_line
line c_line
line s_line
line o_MN_line
line o_MN_thick
line o_830_line
line o_830_thick
line o_930_line
line o_930_thick
string dow
int dow_index
//+------------------------------------------------------------------------------------------------------------+//
//+--- Candle ---+//
//+--- The daily candle drawn based on midnight level ---+//
//+--- This is similar to the MTF Candles indicator minus the time interval to map out the trace lines ---+//
//+------------------------------------------------------------------------------------------------------------+//
type Candle
float o
float h
float l
float c
string dow
box body
line wick_top
line wick_bottom
label lbl
//+------------------------------------------------------------------------------------------------------------+//
//+--- Projection ---+//
//+--- The projection level based on daily ADR range ---+//
//+------------------------------------------------------------------------------------------------------------+//
type Projection
box body_high
box body_low
line high_third
label high_third_label
line low_third
label low_third_label
line max
label max_label
line min
label min_label
//+------------------------------------------------------------------------------------------------------------+//
//+--- Settings ---+//
//+------------------------------------------------------------------------------------------------------------+//
type Settings
string hide_TF
bool show_session
bool show_open
bool show_high
bool show_low
bool show_close
bool show_MN
bool show_830
bool show_930
int max_days
color s_color
string s_style
int s_size
bool show_dayofweek
color dayofweek_color
color o_MN_color
string o_MN_style
int o_MN_size
color o_830_color
string o_830_style
int o_830_size
color o_930_color
string o_930_style
int o_930_size
bool show_asia
color asia_background
color asia_border
string asia_border_style
int asia_border_size
int asia_o_hour
int asia_o_min
int asia_c_hour
int asia_c_min
bool show_london
color london_background
color london_border
string london_border_style
int london_border_size
int london_o_hour
int london_o_min
int london_c_hour
int london_c_min
bool show_ny
color ny_background
color ny_border
string ny_border_style
int ny_border_size
int ny_o_hour
int ny_o_min
int ny_c_hour
int ny_c_min
bool show_openrange
color openrange_background
color openrange_border
string openrange_style
int openrange_size
bool openrange_extend
int openrange_o_hour
int openrange_o_min
int openrange_c_hour
int openrange_c_min
bool show_openrangegap
color openrangegap_background
color openrangegap_border
string openrangegap_style
int openrangegap_size
bool openrangegap_extend
int openrangegap_o_hour
int openrangegap_o_min
int openrangegap_c_hour
int openrangegap_c_min
bool show_TOD_thick
bool show_DC // Daily Candle
color DC_bullish
color DC_bearish
color DC_wick
int DC_buffer
int DC_spacing
int DC_count
bool DC_ignore_saturday
bool DC_ignore_sunday
bool ADR_show
int ADR_buffer
color ADR_bullish
color ADR_bearish
bool ADR_Trace
color ADR_Trace_color
string ADR_Trace_style
int ADR_Trace_size
bool ADR_Trace_Label
string ADR_Trace_Label_size
color ADR_Trace_Label_color
color ADR_Trace_Label_bgcolor
bool ADR_Trace_Third
//+------------------------------------------------------------------------------------------------------------+//
//+--- Variable declaration of the types ---+//
//+------------------------------------------------------------------------------------------------------------+//
var ohlc[] OHLC = array.new<ohlc>()
var Candle[] DC = array.new<Candle>()
var Zone[] asia = array.new<Zone>()
var Zone[] london = array.new<Zone>()
var Zone[] ny = array.new<Zone>()
var Zone[] openrange = array.new<Zone>()
var Zone[] openrangegap = array.new<Zone>()
var Projection projection = Projection.new()
Settings settings = Settings.new()
//+------------------------------------------------------------------------------------------------------------+//
//+--- Prompt for the Settings ---+//
//+------------------------------------------------------------------------------------------------------------+//
g_session = "Session"
g_dailylevels = "Daily Levels"
g_killzones = "Killzones"
g_openranges = "Open Ranges"
g_timeofday = "Time Of Day"
g_DC = "Daily"
g_weekdays = "Week Days"
g_ADR = "Projection"
settings.hide_TF := input.timeframe("15", "Hide above ", tooltip="Any value above 15 minute can result in wrong display. This is due to how Tradingview provides the data to the indicator.")
max_days = input.int(10, "Limit to last X days", minval = 1, maxval = 100)
settings.max_days := max_days
settings.show_session := input.bool(true, "Seperatorโโโ", inline='1', group=g_session)
settings.s_color := input.color(color.new(color.gray, 50), "", inline='1', group=g_session)
settings.s_style := input.string('----', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], inline='1', group=g_session)
settings.s_size := input.int(1, '', options = [1,2,3,4], inline='1', group=g_session)
settings.show_dayofweek := input.bool(true, "Days of week", inline='2', group=g_session)
settings.dayofweek_color := input.color(color.new(color.black, 0), "", inline='2', group=g_session)
settings.show_asia := input.bool(true, "Asiaโโ", group=g_killzones, inline="0")
settings.asia_background := input.color(color.new(color.green, 90), "", group=g_killzones, inline = "0")
settings.asia_border := input.color(color.new(color.green, 0), "", group=g_killzones, inline = "0")
settings.asia_border_size := input.int(1, "", options = [1,2,3,4], group=g_killzones, inline = "0")
settings.asia_border_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], group=g_killzones, inline='0')
settings.asia_o_hour := input.int(20, "โโโโโโโโโOpen Hour", group=g_killzones, inline="1", minval = 0, maxval = 24)
settings.asia_o_min := input.int(0, "Minute", group=g_killzones, inline="1", minval = 0, maxval = 59)
settings.asia_c_hour := input.int(24, "โโโโโโโโโClose Hour", group=g_killzones, inline="2", minval = 1, maxval = 24)
settings.asia_c_min := input.int(0, "Minute", group=g_killzones, inline="2", minval = 0, maxval = 59)
settings.show_london := input.bool(true, "London", group=g_killzones, inline = "3")
settings.london_background := input.color(color.new(color.blue, 90), "", group=g_killzones, inline = "3")
settings.london_border := input.color(color.new(color.blue, 0), "", group=g_killzones, inline = "3")
settings.london_border_size := input.int(1, "", options = [1,2,3,4], group=g_killzones, inline = "3")
settings.london_border_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], group=g_killzones, inline='3')
settings.london_o_hour := input.int(2, "โโโโโโโโโOpen Hour", group=g_killzones, inline="4", minval = 1, maxval = 24)
settings.london_o_min := input.int(0, "Minute", group=g_killzones, inline="4", minval = 0, maxval = 59)
settings.london_c_hour := input.int(5, "โโโโโโโโโClose Hour", group=g_killzones, inline="5", minval = 1, maxval = 24)
settings.london_c_min := input.int(0, "Minute", group=g_killzones, inline="5", minval = 0, maxval = 59)
settings.show_ny := input.bool(true, "NYโโโ", group=g_killzones, inline="6")
settings.ny_background := input.color(color.new(color.orange, 90), "", group=g_killzones, inline = "6")
settings.ny_border := input.color(color.new(color.orange, 0), "", group=g_killzones, inline = "6")
settings.ny_border_size := input.int(1, "", options = [1,2,3,4], group=g_killzones, inline = "6")
settings.ny_border_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], group=g_killzones, inline='6')
settings.ny_o_hour := input.int(8, "โโโโโโโโโOpen Hour", group=g_killzones, inline="7", minval = 1, maxval = 24)
settings.ny_o_min := input.int(30, "Minute", group=g_killzones, inline="7", minval = 0, maxval = 59)
settings.ny_c_hour := input.int(11, "โโโโโโโโโClose Hour", group=g_killzones, inline="8", minval = 1, maxval = 24)
settings.ny_c_min := input.int(0, "Minute", group=g_killzones, inline="8", minval = 0, maxval = 59)
settings.show_openrange := input.bool(false, "Open Rangeโโโ", group=g_openranges, inline="6")
settings.openrange_background := input.color(color.new(color.maroon, 90), "", group=g_openranges, inline = "6")
settings.openrange_border := input.color(color.new(color.maroon, 0), "", group=g_openranges, inline = "6")
settings.openrange_size := input.int(1, "", options = [1,2,3,4], group=g_openranges, inline = "6")
settings.openrange_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], group=g_openranges, inline='6')
settings.openrange_o_hour := input.int(9, "โโโโโโโโโOpen Hour", group=g_openranges, inline="7", minval = 1, maxval = 24)
settings.openrange_o_min := input.int(30, "Minute", group=g_openranges, inline="7", minval = 0, maxval = 59)
settings.openrange_c_hour := input.int(10, "โโโโโโโโโClose Hour", group=g_openranges, inline="8", minval = 1, maxval = 24)
settings.openrange_c_min := input.int(0, "Minute", group=g_openranges, inline="8", minval = 0, maxval = 59)
settings.openrange_extend := input.bool(false, "Extend Zone", group=g_openranges, inline = "8.5")
settings.show_openrangegap := input.bool(false, "Open Rangeโโโ", group=g_openranges, inline="9")
settings.openrangegap_background := input.color(color.new(color.yellow, 90), "", group=g_openranges, inline = "9")
settings.openrangegap_border := input.color(color.new(color.yellow, 0), "", group=g_openranges, inline = "9")
settings.openrangegap_size := input.int(1, "", options = [1,2,3,4], group=g_openranges, inline = "9")
settings.openrangegap_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], group=g_openranges, inline='9')
settings.openrangegap_o_hour := input.int(16, "โโโโโโโโโOpen Hour", group=g_openranges, inline="10", minval = 1, maxval = 24)
settings.openrangegap_o_min := input.int(15, "Minute", group=g_openranges, inline="10", minval = 0, maxval = 59)
settings.openrangegap_c_hour := input.int(9, "โโโโโโโโโClose Hour", group=g_openranges, inline="10", minval = 1, maxval = 24)
settings.openrangegap_c_min := input.int(30, "Minute", group=g_openranges, inline="10", minval = 0, maxval = 59)
settings.openrangegap_extend := input.bool(false, "Extend Zone", group=g_openranges)
settings.show_MN := input.bool(true, "Midnight Open", inline='1', group=g_timeofday)
settings.o_MN_color := input.color(color.new(color.red, 0), "", inline='1', group=g_timeofday)
settings.o_MN_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], inline='1', group=g_timeofday)
settings.o_MN_size := input.int(1, '', options = [1,2,3,4], inline='1', group=g_timeofday)
settings.show_830 := input.bool(true, "8:30 Openโโโ", inline='2', group=g_timeofday)
settings.o_830_color := input.color(color.new(color.blue, 0), "", inline='2', group=g_timeofday)
settings.o_830_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], inline='2', group=g_timeofday)
settings.o_830_size := input.int(1, '', options = [1,2,3,4], inline='2', group=g_timeofday)
settings.show_930 := input.bool(true, "9:30 Openโโโ", inline='3', group=g_timeofday)
settings.o_930_color := input.color(color.new(color.orange, 0), "", inline='3', group=g_timeofday)
settings.o_930_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], inline='3', group=g_timeofday)
settings.o_930_size := input.int(1, '', options = [1,2,3,4], inline='3', group=g_timeofday)
settings.show_TOD_thick := input.bool(true, "Show thick end", group=g_timeofday)
settings.show_DC := input.bool(true, "Daily Midnight Candle", group=g_DC, inline="1")
settings.DC_bullish := input.color(color.new(color.green, 0), "", inline='1', group=g_DC)
settings.DC_bearish := input.color(color.new(color.red, 0), "", inline='1', group=g_DC)
settings.DC_wick := input.color(color.new(color.black, 0), "", inline='1', group=g_DC)
settings.DC_count := input.int(5, "Maximum number of days", group=g_DC, minval = 1)
settings.DC_buffer := input.int(25, "Padding from current candle", group=g_DC, minval = 1)
settings.DC_spacing := input.int(3, "Spacing between candles", group=g_DC, minval = 1)
settings.DC_ignore_saturday := input.bool(true, "Ignore Saturday", group=g_DC)
settings.DC_ignore_sunday := input.bool(true, "Ignore Sunday", group=g_DC)
settings.ADR_show := input.bool(true, "Average Daily Range", group=g_ADR, inline = "1", tooltip="Project possible range to the top and bottom based on the average ADR.")
settings.ADR_bullish := input.color(color.new(color.green, 10), "", group = g_ADR, inline="1")
settings.ADR_bearish := input.color(color.new(color.red, 10), "", group = g_ADR, inline="1")
settings.ADR_Trace := input.bool(true, "Trace Lines", group=g_ADR, inline="2")
settings.ADR_Trace_color := input.color(color.new(color.black, 10), "", group = g_ADR, inline="2")
settings.ADR_Trace_style := input.string('ยทยทยทยท', '', options = ['โฏโฏโฏ', '----', 'ยทยทยทยท'], inline='2', group=g_ADR)
settings.ADR_Trace_size := input.int(1, '', options = [1,2,3,4], inline='2', group=g_ADR)
settings.ADR_Trace_Label := input.bool(true, "Labelsโโโโ", group=g_ADR, inline="3")
settings.ADR_Trace_Label_color := input.color(color.new(color.black, 10), "", group = g_ADR, inline="3")
settings.ADR_Trace_Label_bgcolor := input.color(color.new(color.black, 100), "", group = g_ADR, inline="3")
settings.ADR_Trace_Label_size := input.string(size.small, "", [size.tiny, size.small, size.normal, size.large, size.huge], group = g_ADR, inline="3")
settings.ADR_Trace_Third := input.bool(true, "Mark Midnight 30% ADR Level", group=g_ADR)
settings.ADR_buffer := input.int(14, "Offset from current candle", minval=1, maxval=50, group = g_ADR)
//+------------------------------------------------------------------------------------------------------------+//
//+--- Create time map for the Zones. The end result is in time(0000-0000) ---+//
//+--- current time falls in that interval ---+//
//+------------------------------------------------------------------------------------------------------------+//
tAsia = time("1", str.tostring(settings.asia_o_hour, "00")+str.tostring(settings.asia_o_min, "00") + "-" + str.tostring(settings.asia_c_hour, "00")+str.tostring(settings.asia_c_min, "00"), "America/New_York")
tLondon = time("1", str.tostring(settings.london_o_hour, "00")+str.tostring(settings.london_o_min, "00") + "-" + str.tostring(settings.london_c_hour, "00")+str.tostring(settings.london_c_min, "00"), "America/New_York")
tNY = time("1", str.tostring(settings.ny_o_hour, "00")+str.tostring(settings.ny_o_min, "00") + "-" + str.tostring(settings.ny_c_hour, "00")+str.tostring(settings.ny_c_min, "00"), "America/New_York")
tOpenRange = time("1", str.tostring(settings.openrange_o_hour, "00")+str.tostring(settings.openrange_o_min, "00") + "-" + str.tostring(settings.openrange_c_hour, "00")+str.tostring(settings.openrange_c_min, "00"), "America/New_York")
tOpenRangeGap = time("1", str.tostring(settings.openrangegap_o_hour, "00")+str.tostring(settings.openrangegap_o_min, "00") + "-" + str.tostring(settings.openrangegap_c_hour, "00")+str.tostring(settings.openrangegap_c_min, "00"), "America/New_York")
color color_transparent = #ffffff00
//+------------------------------------------------------------------------------------------------------------+//
//+--- Global functions ---+//
//+--- I need to convert these into Helper type but little lazy so will do it later ---+//
//+------------------------------------------------------------------------------------------------------------+//
f_get_line_style(style) =>
out = switch style
'โฏโฏโฏ' => line.style_solid
'----' => line.style_dashed
'ยทยทยทยท' => line.style_dotted
f_get_dayofweek(index) =>
switch index
1 =>
"Sunday"
2 =>
"Monday"
3 =>
"Tuesday"
4 =>
"Wednesday"
5 =>
"Thursday"
6 =>
"Friday"
7 =>
"Saturday"
na(index) =>
""
//+------------------------------------------------------------------------------------------------------------+//
//+--- f_get_day_offset ---+//
// This function calculates the length of the day taking into account Weekends ---+//
// This is mainly for Futures, I may need to come back and fix for forex and crypto ---+//
//+------------------------------------------------------------------------------------------------------------+//
f_get_day_offset(index) =>
bar_length = time-time[1]
switch index
1 =>
10800000 / bar_length
6 =>
32400000 / bar_length
=>
43200000 / bar_length
f_Validtimeframe() =>
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(settings.hide_TF)
n1 <= n2
//+------------------------------------------------------------------------------------------------------------+//
//+--- Main Methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
//+------------------------------------------------------------------------------------------------------------+//
//+--- OHLC related methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
method new(ohlc[] OHLC) =>
ohlc newDay = ohlc.new()
newDay.o := open
newDay.h := high
newDay.l := low
newDay.c := close
newDay.o_time := time
newDay.o_idx := bar_index
newDay.h_time := time
newDay.l_time := time
newDay.c_time := time
newDay.o_MN := open
newDay.o_MN_time := time
newDay.o_830_time := time+30600000
newDay.o_930_time := time+34200000
newDay.dow := f_get_dayofweek(dayofweek(time, "America/New_York"))
newDay.dow_index := dayofweek(time, "America/New_York")
OHLC.unshift(newDay)
if OHLC.size() > settings.max_days
for i = OHLC.size()-1 to settings.max_days
ohlc del = OHLC.get(i)
line.delete(del.o_line)
line.delete(del.h_line)
line.delete(del.l_line)
line.delete(del.c_line)
line.delete(del.s_line)
line.delete(del.o_MN_line)
line.delete(del.o_MN_thick)
line.delete(del.o_830_line)
line.delete(del.o_830_thick)
line.delete(del.o_930_line)
line.delete(del.o_930_thick)
if OHLC.size() > 100
OHLC.pop()
if OHLC.size() > 1
ohlc prev = OHLC.get(1)
line.delete(prev.o_MN_thick)
line.delete(prev.o_830_thick)
line.delete(prev.o_930_thick)
line.set_x2(prev.o_MN_line, prev.c_time + (time-time[1]))
line.set_x2(prev.o_830_line, prev.c_time + (time-time[1]))
line.set_x2(prev.o_930_line, prev.c_time + (time-time[1]))
prev.c_time := time
OHLC
method update(ohlc[] OHLC) =>
if OHLC.size() > 0
ohlc last = OHLC.first()
if high > last.h
last.h := high
last.h_time := time
if low < last.l
last.l := low
last.l_time := time
last.c := close
last.c_time := time
if time == last.o_830_time
last.o_830 := open
if time == last.o_930_time
last.o_930 := open
OHLC
method drawADRRange(ohlc[] OHLC) =>
if settings.ADR_show
if OHLC.size() > 7
float r = 0
float part = 0
for i = 1 to 7
d = OHLC.get(i)
if d.dow != "Saturday" and d.dow != "Sunday"
r += d.h - d.l
r := r / 5
part := r*0.3
current = OHLC.first()
idx = bar_index + settings.ADR_buffer
idxb = idx+6
if na(projection.body_high)
projection.body_high := box.new(idx, current.l+r, idx+1, current.l, border_color = color_transparent, bgcolor=settings.ADR_bullish)
if settings.ADR_Trace
if settings.ADR_Trace_Third
projection.high_third := line.new(current.o_idx, current.o+part, idxb, current.o+part, xloc.bar_index, extend.none, settings.ADR_Trace_color, f_get_line_style(settings.ADR_Trace_style), settings.ADR_Trace_size)
projection.max := line.new(current.o_idx, current.l+r, idxb, current.o-part, xloc.bar_index, extend.none, settings.ADR_Trace_color, f_get_line_style(settings.ADR_Trace_style), settings.ADR_Trace_size)
if settings.ADR_Trace_Label
if settings.ADR_Trace_Third
projection.high_third_label := label.new(idxb, current.o+part, "+0.3 ADR", xloc.bar_index, yloc.price, settings.ADR_Trace_Label_bgcolor, label.style_label_left, settings.ADR_Trace_Label_color, settings.ADR_Trace_Label_size)
projection.max_label := label.new(idxb, current.l+r, "+ADR", xloc.bar_index, yloc.price, settings.ADR_Trace_Label_bgcolor, label.style_label_left, settings.ADR_Trace_Label_color, settings.ADR_Trace_Label_size)
else
if current.l+r > current.h
box.set_lefttop(projection.body_high, idx, current.l+r)
box.set_rightbottom(projection.body_high, idx+1, current.l)
line.set_xy1(projection.max, current.o_idx, current.l+r)
line.set_xy2(projection.max, idxb, current.l+r)
label.set_xy(projection.high_third_label, idxb, current.l+r)
label.set_xy(projection.max_label, idxb, current.l+r)
else
box.set_lefttop(projection.body_high, idx, box.get_top(projection.body_low))
box.set_rightbottom(projection.body_high, idx+1, box.get_bottom(projection.body_low))
line.set_xy1(projection.max, current.o_idx, box.get_top(projection.body_low))
line.set_xy2(projection.max, idxb, box.get_top(projection.body_low))
label.set_xy(projection.max_label, idxb, box.get_top(projection.body_low))
if settings.ADR_Trace
line.set_xy1(projection.high_third, current.o_idx, current.o+part)
line.set_xy2(projection.high_third, idxb, current.o+part)
label.set_xy(projection.high_third_label, idxb, current.o+part)
if na(projection.body_low)
projection.body_low := box.new(idx+2, current.h, idx+3, current.h-r, border_color = color_transparent, bgcolor=settings.ADR_bearish)
if settings.ADR_Trace
if settings.ADR_Trace_Third
projection.low_third := line.new(current.o_idx, current.o-part, idxb, current.o-part, xloc.bar_index, extend.none, settings.ADR_Trace_color, f_get_line_style(settings.ADR_Trace_style), settings.ADR_Trace_size)
projection.min := line.new(current.o_idx, current.h-r, idxb, current.o-part, xloc.bar_index, extend.none, settings.ADR_Trace_color, f_get_line_style(settings.ADR_Trace_style), settings.ADR_Trace_size)
if settings.ADR_Trace_Label
if settings.ADR_Trace_Third
projection.low_third_label := label.new(idxb, current.o-part, "-0.3 ADR", xloc.bar_index, yloc.price, settings.ADR_Trace_Label_bgcolor, label.style_label_left, settings.ADR_Trace_Label_color, settings.ADR_Trace_Label_size)
projection.min_label := label.new(idxb, current.h-r, "-ADR", xloc.bar_index, yloc.price, settings.ADR_Trace_Label_bgcolor, label.style_label_left, settings.ADR_Trace_Label_color, settings.ADR_Trace_Label_size)
else
if current.h-r < current.l
box.set_lefttop(projection.body_low, idx+2, current.h)
box.set_rightbottom(projection.body_low, idx+3, current.h-r)
line.set_xy1(projection.min, current.o_idx, current.h-r)
line.set_xy2(projection.min, idxb, current.h-r)
label.set_xy(projection.min_label, idxb, current.h-r)
else
box.set_lefttop(projection.body_low, idx+2, box.get_top(projection.body_high))
box.set_rightbottom(projection.body_low, idx+3, box.get_bottom(projection.body_high))
line.set_xy1(projection.min, current.o_idx, box.get_bottom(projection.body_high))
line.set_xy2(projection.min, idxb, box.get_bottom(projection.body_high))
label.set_xy(projection.min_label, idxb, box.get_bottom(projection.body_high))
if settings.ADR_Trace
line.set_xy1(projection.low_third, current.o_idx, current.o-part)
line.set_xy2(projection.low_third, idxb, current.o-part)
label.set_xy(projection.low_third_label, idxb, current.o-part)
OHLC
//+------------------------------------------------------------------------------------------------------------+//
//+--- New Day related methods ---+//
//+------------------------------------------------------------------------------------------------------------+//
method newDC(Candle[] DC) =>
dow = f_get_dayofweek(dayofweek(time, "America/New_York"))
Candle candle = Candle.new()
candle.o := open
candle.c := close
candle.h := high
candle.l := low
candle.dow := str.substring(dow, 0, 1)
DC.unshift(candle)
if DC.size() > settings.DC_count
Candle c = DC.pop()
box.delete(c.body)
line.delete(c.wick_top)
line.delete(c.wick_bottom)
label.delete(c.lbl)
DC
method updateDC(Candle[] DC) =>
if DC.size() > 0
Candle candle = DC.first()
if high > candle.h
candle.h := high
if low < candle.l
candle.l := low
candle.c := close
DC
// Draw the daily candle
method drawDC(Candle[] DC) =>
int count = DC.size()
if count > 0
for i = 0 to count-1
Candle candle = DC.get(i)
int position = bar_index+settings.DC_buffer +((count-i)*(settings.DC_spacing+2))
if settings.show_DC
if na(candle.body)
candle.body := box.new(position, candle.o > candle.c ? candle.o : candle.c, position+2, candle.o > candle.c ? candle.c : candle.o, settings.DC_wick, 1, line.style_solid, extend.none, xloc.bar_index, candle.c > candle.o ? settings.DC_bullish : settings.DC_bearish)
else
box.set_lefttop(candle.body, position, candle.o > candle.c ? candle.o : candle.c)
box.set_rightbottom(candle.body, position+2, candle.o > candle.c ? candle.c : candle.o)
box.set_bgcolor(candle.body, candle.c > candle.o ? settings.DC_bullish : settings.DC_bearish)
if na(candle.wick_top)
candle.wick_top := line.new(position+1, candle.h, position+1, candle.o > candle.c ? candle.o : candle.c, xloc.bar_index, extend.none, settings.DC_wick)
else
line.set_xy1(candle.wick_top, position+1, candle.h)
line.set_xy2(candle.wick_top, position+1, candle.o > candle.c ? candle.o : candle.c)
if na(candle.wick_bottom)
candle.wick_bottom := line.new(position+1, candle.l, position+1, candle.o > candle.c ? candle.c : candle.o, xloc.bar_index, extend.none, settings.DC_wick)
else
line.set_xy1(candle.wick_bottom, position+1, candle.l)
line.set_xy2(candle.wick_bottom, position+1, candle.o > candle.c ? candle.c : candle.o)
if na(candle.lbl)
candle.lbl := label.new(position+1, candle.h, candle.dow, textcolor=settings.DC_wick, color=color_transparent, style= label.style_label_down )
else
label.set_xy(candle.lbl, position+1, candle.h)
DC
//+------------------------------------------------------------------------------------------------------------+//
//+--- Get Current Day ---+//
//+------------------------------------------------------------------------------------------------------------+//
method current(ohlc[] OHLC) =>
OHLC.size() > 0 ? OHLC.get(0) : na
//+------------------------------------------------------------------------------------------------------------+//
//+--- Create Session Seperator ---+//
//+------------------------------------------------------------------------------------------------------------+//
method session_seperator(ohlc[] OHLC) =>
if OHLC.size() > 0 and settings.show_session
ohlc step = OHLC.get(0)
if na(step.s_line)
step.s_line := line.new(step.o_time, step.o, step.o_time, step.o+1, xloc=xloc.bar_time, extend = extend.both, color=settings.s_color, style=f_get_line_style(settings.s_style), width = settings.s_size)
method session_levels(ohlc[] OHLC) =>
if OHLC.size() > 0
ohlc step = OHLC.get(0)
// We use time not bar_index because on lower timeframes, we may get too extended out and it errors
// the way to calculate the time of each candle is to get the difference between two candles. this
// resolves the issue with multi timeframe calculation.
int candletime = (time-time[1])
if settings.show_MN
step.o_line
if settings.show_MN and not na(step.o_MN)
if na(step.o_MN_line)
step.o_MN_line := line.new(step.o_MN_time, step.o_MN, time + (candletime*5), step.o_MN, xloc=xloc.bar_time, color=settings.o_MN_color, style=f_get_line_style(settings.o_MN_style), width = settings.o_MN_size)
if settings.show_TOD_thick
step.o_MN_thick := line.new(time + (candletime*5), step.o_MN, time + (candletime*10), step.o_MN, xloc=xloc.bar_time, color=settings.o_MN_color, style=line.style_solid, width = 4)
else
line.set_x2(step.o_MN_line, time + (candletime*5))
if settings.show_TOD_thick
line.set_x1(step.o_MN_thick, time + (candletime*5))
line.set_x2(step.o_MN_thick, time + (candletime*10))
if settings.show_830 and not na(step.o_830)
if na(step.o_830_line)
step.o_830_line := line.new(step.o_830_time, step.o_830, time + (candletime*5), step.o_830, xloc=xloc.bar_time, color=settings.o_830_color, style=f_get_line_style(settings.o_830_style), width = settings.o_830_size)
if settings.show_TOD_thick
step.o_830_thick := line.new(time + (candletime*5), step.o_830, time + (candletime*10), step.o_830, xloc=xloc.bar_time, color=settings.o_830_color, style=line.style_solid, width = 4)
else
line.set_x2(step.o_830_line, time + (candletime*5))
if settings.show_TOD_thick
line.set_x1(step.o_830_thick, time + (candletime*5))
line.set_x2(step.o_830_thick, time + (candletime*10))
if settings.show_930 and not na(step.o_930)
if na(step.o_930_line)
step.o_930_line := line.new(step.o_930_time, step.o_930, time + (candletime*5), step.o_930, xloc=xloc.bar_time, color=settings.o_930_color, style=f_get_line_style(settings.o_930_style), width = settings.o_930_size)
if settings.show_TOD_thick
step.o_930_thick := line.new(time + (candletime*5), step.o_930, time + (candletime*10), step.o_930, xloc=xloc.bar_time, color=settings.o_930_color, style=line.style_solid, width = 4)
else
line.set_x2(step.o_930_line, time + (candletime*5))
if settings.show_TOD_thick
line.set_x1(step.o_930_thick, time + (candletime*5))
line.set_x2(step.o_930_thick, time + (candletime*10))
OHLC
//+------------------------------------------------------------------------------------------------------------+//
//+--- Zone related methods ---+//
//+-- reused for the opening ranges ---+//
//+------------------------------------------------------------------------------------------------------------+//
method start(Zone[] KZ) =>
Zone newZone = Zone.new()
newZone.o := open
newZone.h := high
newZone.l := low
newZone.c := close
newZone.o_time := time
newZone.h_time := time
newZone.l_time := time
newZone.c_time := time
KZ.unshift(newZone)
KZ
method update(Zone[] KZ) =>
if KZ.size() > 0
Zone last = KZ.get(0)
if high > last.h
last.h := high
last.h_time := time
if low < last.l
last.l := low
last.l_time := time
last.c := close
last.c_time := time
KZ
method startGap(Zone[] KZ) =>
Zone newZone = Zone.new()
newZone.o := open
newZone.h := high
newZone.l := low
newZone.c := close
newZone.o_time := time
newZone.h_time := time
newZone.l_time := time
newZone.c_time := time
KZ.unshift(newZone)
KZ
method closeGap(Zone[] KZ) =>
if KZ.size() > 0
Zone last = KZ.get(0)
last.c := open
last.c_time := time
KZ
method display(Zone[] KZ, int session) =>
var bool show = false
var string style = na
var int width = na
var color bgcolor = na
var color bcolor = na
var bool extend = false
if KZ.size() > 0
Zone step = KZ.first()
switch session
1 =>
show := settings.show_asia
width := settings.asia_border_size
style := settings.asia_border_style
bgcolor := settings.asia_background
bcolor := settings.asia_border
2 =>
show := settings.show_london
width := settings.london_border_size
style := settings.london_border_style
bgcolor := settings.london_background
bcolor := settings.london_border
3 =>
show := settings.show_ny
width := settings.ny_border_size
style := settings.ny_border_style
bgcolor := settings.ny_background
bcolor := settings.ny_border
4 =>
show := settings.show_openrange
width := settings.openrange_size
style := settings.openrange_style
bgcolor := settings.openrange_background
bcolor := settings.openrange_border
extend := settings.openrange_extend
5 =>
show := settings.show_openrangegap
width := settings.openrangegap_size
style := settings.openrangegap_style
bgcolor := settings.openrangegap_background
bcolor := settings.openrangegap_border
extend := settings.openrangegap_extend
if show and session < 5
if na(step.b)
step.b := box.new(step.o_time, step.h, step.c_time, step.l, bcolor, width, f_get_line_style(style), extend.none, xloc.bar_time, bgcolor)
else
box.set_top(step.b, step.h)
box.set_bottom(step.b, step.l)
if extend
box.set_right(step.b, time+(time-time[1]))
else
box.set_right(step.b, step.c_time)
if show and session == 5 and step.o_time != step.c_time
if na(step.b)
step.b := box.new(step.o_time, step.c, step.c_time, step.o, bcolor, width, f_get_line_style(style), extend.none, xloc.bar_time, bgcolor)
else
box.set_top(step.b, step.c)
box.set_right(step.b, step.c_time)
if extend
box.set_right(step.b, time+(time-time[1]))
else
box.set_right(step.b, step.c_time)
KZ
//+------------------------------------------------------------------------------------------------------------+//
//+--- Main logic that starts the process ---+//
//+------------------------------------------------------------------------------------------------------------+//
// Did we start a new day? (Midnight)
newDay = dayofweek(time, "America/New_York") != dayofweek(time-(time-time[1]), "America/New_York")
// Do we have a valid timeframe? i.e. still under X timeframe
valid = f_Validtimeframe()
dow = f_get_dayofweek(dayofweek(time, "America/New_York"))
if valid
// If new day, start calculating new day metrics and drae seperators if enabled
if newDay
OHLC.new().session_seperator()
if (dow == "Saturday" and not settings.DC_ignore_saturday) or (dow == "Sunday" and not settings.DC_ignore_sunday) or (dow != "Saturday" and dow != "Sunday")
DC.newDC()
// If in Killzones
// Asia is special because it starts before the day starts. So when we have
// new asia session, we clear previous london and NY since they belong to
// previous day
if tLondon
if not tLondon[1]
london.start()
if london.size() > settings.max_days
l = london.pop()
box.delete(l.b)
london.update().display(2)
if tNY
if not tNY[1]
ny.start()
if ny.size() > settings.max_days
n = ny.pop()
box.delete(n.b)
ny.update().display(3)
if tAsia
if not tAsia[1]
asia.start()
if asia.size() > settings.max_days
Zone a = asia.pop()
box.delete(a.b)
asia.update().display(1)
if tOpenRange
if not tOpenRange[1]
openrange.start()
if openrange.size() > settings.max_days
opr = openrange.pop()
box.delete(opr.b)
openrange.update()
openrange.display(4)
if tOpenRangeGap and not tOpenRangeGap[1]
openrangegap.startGap()
if tOpenRangeGap[1] and not tOpenRangeGap
openrangegap.closeGap()
if openrangegap.size() > settings.max_days
oprg = openrangegap.pop()
box.delete(oprg.b)
openrangegap.display(5)
OHLC.update().drawADRRange().session_levels()
if (dow == "Saturday" and not settings.DC_ignore_saturday) or (dow == "Sunday" and not settings.DC_ignore_sunday) or (dow != "Saturday" and dow != "Sunday")
DC.updateDC()
DC.drawDC()
//+------------------------------------------------------------------------------------------------------------+//
//+--- Weekdays. i wish there was better way of doing this ---+//
//+------------------------------------------------------------------------------------------------------------+//
current = OHLC.current()
day = na(current) ? "" : current.dow
plotshape(settings.show_dayofweek ? newDay and day == "Monday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(2)-1, style=shape.diamond, text="MON", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
plotshape(settings.show_dayofweek ? newDay and day == "Tuesday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(3)-1, style=shape.diamond, text="TUE", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
plotshape(settings.show_dayofweek ? newDay and day == "Wednesday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(4)-1, style=shape.diamond, text="WED", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
plotshape(settings.show_dayofweek ? newDay and day == "Thursday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(5)-1, style=shape.diamond, text="THU", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
plotshape(settings.show_dayofweek ? newDay and day == "Friday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(6)-1, style=shape.diamond, text="FRI", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
plotshape(settings.show_dayofweek ? newDay and day == "saturday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(7), style=shape.diamond, text="SAT", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
plotshape(settings.show_dayofweek ? newDay and day == "Sunday" and valid : false, offset=na(current) ? 0 : f_get_day_offset(1), style=shape.diamond, text="SUN", color=color_transparent, location = location.bottom, textcolor=settings.dayofweek_color, size=size.auto)
|
Concentration of CAA Totalized (CCAAT) | https://www.tradingview.com/script/Fsffsur1-Concentration-of-CAA-Totalized-CCAAT/ | More-Than-Enough | https://www.tradingview.com/u/More-Than-Enough/ | 32 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ More-Than-Enough
//@version=5
indicator("Concentration of CAA Totalized", "CCAAT")
float KPAM = 0.0
float CCI = ta.cci(hlc3, 20) * 0.01
float RSI = ta.rsi(close, 14)
Rsi = RSI * 0.1 - 5
float Stoch = ta.sma(ta.stoch(close, high, low, 14) * 0.1 - 5, 1)
float Stoch_RSI = ta.sma(ta.stoch(Rsi, Rsi, Rsi, 14) * 0.1 - 5, 3)
if Stoch_RSI >= 0 and Stoch >= 0 and Stoch_RSI >= Stoch
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI >= 0 and Stoch >= 0 and Stoch_RSI < Stoch
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
if Stoch_RSI < 0 and Stoch < 0 and Stoch_RSI >= Stoch
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
if Stoch_RSI < 0 and Stoch < 0 and Stoch_RSI < Stoch
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI >= 0 and Stoch < 0
KPAM := Stoch_RSI - ((Stoch_RSI - Stoch) / 2)
if Stoch_RSI < 0 and Stoch >= 0
KPAM := Stoch_RSI + ((Stoch - Stoch_RSI) / 2)
/////////////////
///// Reach /////
/////////////////
Reach_Level = 0
if KPAM >= 0 and KPAM < 1
Reach_Level := 1
if KPAM >= 1 and KPAM < 2
Reach_Level := 2
if KPAM >= 2 and KPAM < 3
Reach_Level := 3
if KPAM >= 3 and KPAM < 4
Reach_Level := 4
if KPAM >= 4
Reach_Level := 5
if KPAM < 0 and KPAM > -1
Reach_Level := -1
if KPAM <= -1 and KPAM > -2
Reach_Level := -2
if KPAM <= -2 and KPAM > -3
Reach_Level := -3
if KPAM <= -3 and KPAM > -4
Reach_Level := -4
if KPAM <= -4
Reach_Level := -5
//////////////////
///// Energy /////
//////////////////
Energy_Level = 0
if CCI >= 0 and CCI < 1
Energy_Level := 1
if CCI >= 1 and CCI < 2
Energy_Level := 2
if CCI >= 2 and CCI < 3
Energy_Level := 3
if CCI >= 3 and CCI < 4
Energy_Level := 4
if CCI >= 4
Energy_Level := 5
if CCI < 0 and CCI > -1
Energy_Level := -1
if CCI <= -1 and CCI > -2
Energy_Level := -2
if CCI <= -2 and CCI > -3
Energy_Level := -3
if CCI <= -3 and CCI > -4
Energy_Level := -4
if CCI <= -4
Energy_Level := -5
/////////////////
///// Basis /////
/////////////////
Basis_Level = 0
if RSI >= 50 and RSI < 55
Basis_Level := 1
if RSI >= 55 and RSI < 60
Basis_Level := 2
if RSI >= 60 and RSI < 65
Basis_Level := 3
if RSI >= 65 and RSI < 70
Basis_Level := 4
if RSI >= 70
Basis_Level := 5
if RSI < 50 and RSI > 45
Basis_Level := -1
if RSI <= 45 and RSI > 40
Basis_Level := -2
if RSI <= 40 and RSI > 35
Basis_Level := -3
if RSI <= 35 and RSI > 30
Basis_Level := -4
if RSI <= 30
Basis_Level := -5
/////////////////////////////////
///// Total & Concentration /////
/////////////////////////////////
Extra_Sensitive = input.bool(false, "Extra Sensitive")
Sensitivity = 10
if Extra_Sensitive
Sensitivity := 9
Total = Reach_Level + Energy_Level + Basis_Level
color Total_Color = color.rgb(178, 235, 242)
if (Total >= 5 and Total < Sensitivity) or (Total <= -5 and Total > (Sensitivity * -1))
Total_Color := color.rgb(38, 198, 218)
if (Total >= Sensitivity and Total < 12) or (Total <= (Sensitivity * -1) and Total > -12)
Total_Color := color.rgb(255, 249, 196)
if Total >= 12 or Total <= -12
Total_Color := color.red
Length = input(20, "Length")
Inner_Deviation = input.float(2.0, "Inner", step = 0.1)
Outer_Deviation = input.float(3.0, "Outer", step = 0.1)
Deviation_Base = ta.stdev(Total, Length)
T_Line = 0 + (Deviation_Base * Outer_Deviation)
H_Line = 0 + (Deviation_Base * Inner_Deviation)
L_Line = 0 - (Deviation_Base * Inner_Deviation)
B_Line = 0 - (Deviation_Base * Outer_Deviation)
/////////////////
///// Plots /////
/////////////////
plot(Total, "Total", Total_Color, 2, plot.style_columns)
plot(T_Line, "Top", color.orange, 2)
plot(H_Line, "High", color.orange, 2)
plot(L_Line, "Low", color.orange, 2, display = display.all - display.status_line)
plot(B_Line, "Bottom", color.orange, 2, display = display.all - display.status_line)
hline( 15, "Lv 3", color.new(color.white, 65), hline.style_dotted)
hline( 10, "Lv 2", color.new(color.white, 50), hline.style_dotted)
hline( 5, "Lv 1", color.new(color.white, 30), hline.style_dotted)
hline( 0, "0", color.new(color.aqua , 70), hline.style_solid, display = display.none)
hline( -5, "Lv -1", color.new(color.white, 30), hline.style_dotted)
hline(-10, "Lv -2", color.new(color.white, 50), hline.style_dotted)
hline(-15, "Lv -3", color.new(color.white, 65), hline.style_dotted) |
RSI Supreme Multi-Method [JacobMagleby] | https://www.tradingview.com/script/3KGDKTfs-RSI-Supreme-Multi-Method-JacobMagleby/ | JacobMagleby | https://www.tradingview.com/u/JacobMagleby/ | 371 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ JacobMagleby
//@version=5
indicator(title = "RSI Supreme Multi-Method", overlay = false)
// { <CONSTANTS>
RSI_GROUP = "RSI Settings"
VOLATILITY_GROUP = "Volatility Method Settings"
SESSION_GROUP = "Session Method Settings"
SMOOTHED_GROUP = "Smoothed Method Settings"
DIVERGENCE_GROUP = "Divergence Settings"
TRANSPARENT = color.new(color.black, 100)
// } <CONSTANTS>
// { <INPUTS>
rsiLength = input.int(
title = "RSI Length",
defval = 14,
group = RSI_GROUP)
rsiSrc = input.source(
title = "RSI Source",
defval = close,
group = RSI_GROUP)
rsiOB = input.float(
title = "Overbought Value",
defval = 70,
group = RSI_GROUP)
rsiOS = input.float(
title = "Oversold Value",
defval = 30,
group = RSI_GROUP)
rsiMethod = input.string(
title = "RSI Type",
defval = "Standard",
options = ["Standard", "Volatility Manipulated", "Session Manipulated", "Smoothed"],
group = RSI_GROUP)
volatilityLen = input.int(
title = "Length",
defval = 50,
group = VOLATILITY_GROUP)
smoothedLength = input.int(
title = "Length",
defval = 5,
group = SMOOTHED_GROUP)
session1E = input.bool(
title = "",
defval = true,
group = SESSION_GROUP,
inline = "session1")
session1 = input.session(
title = "",
defval = "0000-0759",
group = SESSION_GROUP,
inline = "session1")
session1Mult = input.float(
title = "Mult %",
defval = 100,
group = SESSION_GROUP,
inline = "session1")
session2E = input.bool(
title = "",
defval = true,
group = SESSION_GROUP,
inline = "session2")
session2 = input.session(
title = "",
defval = "0800-1559",
group = SESSION_GROUP,
inline = "session2")
session2Mult = input.float(
title = "Mult %",
defval = 100,
group = SESSION_GROUP,
inline = "session2")
session3E = input.bool(
title = "",
defval = true,
group = SESSION_GROUP,
inline = "session3")
session3 = input.session(
title = "",
defval = "1559-2359",
group = SESSION_GROUP,
inline = "session3")
session3Mult = input.float(
title = "Mult %",
defval = 100,
group = SESSION_GROUP,
inline = "session3")
session4E = input.bool(
title = "",
defval = false,
group = SESSION_GROUP,
inline = "session4")
session4 = input.session(
title = "",
defval = "0000-0900",
group = SESSION_GROUP,
inline = "session4")
session4Mult = input.float(
title = "Mult %",
defval = 100,
group = SESSION_GROUP,
inline = "session4")
session5E = input.bool(
title = "",
defval = false,
group = SESSION_GROUP,
inline = "session5")
session5 = input.session(
title = "",
defval = "0000-0900",
group = SESSION_GROUP,
inline = "session5")
session5Mult = input.float(
title = "Mult %",
defval = 100,
group = SESSION_GROUP,
inline = "session5")
session6E = input.bool(
title = "",
defval = false,
group = SESSION_GROUP,
inline = "session6")
session6 = input.session(
title = "",
defval = "0000-0900",
group = SESSION_GROUP,
inline = "session6")
session6Mult = input.float(
title = "Mult %",
defval = 100,
group = SESSION_GROUP,
inline = "session6")
showDivs = input.bool(
title = "Show Divergences",
defval = true,
group = DIVERGENCE_GROUP)
pivotSens = input.int(
title = "Sensitivity",
defval = 5,
group = DIVERGENCE_GROUP)
divWidth = input.int(
title = "Width",
defval = 2,
group = DIVERGENCE_GROUP)
bullColor = input.color(
title = "",
defval = color.blue,
group = DIVERGENCE_GROUP,
inline = "div")
bearColor = input.color(
title = "",
defval = color.blue,
group = DIVERGENCE_GROUP,
inline = "div")
// } <INPUTS>
// { <CALCULATIONS>
vol = ta.stdev(close / close[1], volatilityLen, true)
vol_percentile = 100 - ta.percentrank(vol, volatilityLen)
var volumeArray = array.new_float()
if barstate.isconfirmed
if array.size(volumeArray) > 1000
array.shift(volumeArray)
array.push(volumeArray, volume)
maxVolume = array.max(volumeArray)
minVolume = array.min(volumeArray)
diff = maxVolume - minVolume
offMin = volume - minVolume
ratio = offMin / diff + 0.5
time1 = not na(time(timeframe.period, session1))
time2 = not na(time(timeframe.period, session2))
time3 = not na(time(timeframe.period, session3))
time4 = not na(time(timeframe.period, session4))
time5 = not na(time(timeframe.period, session5))
time6 = not na(time(timeframe.period, session6))
srcToUse = rsiMethod == "Standard" ? rsiSrc :
rsiMethod == "Volatility Manipulated" ? rsiSrc * (vol_percentile / 100) :
rsiMethod == "Session Manipulated" ?
(time1 and session1E ? rsiSrc * (session1Mult / 100) :
time2 and session2E ? rsiSrc * (session2Mult / 100) :
time3 and session3E ? rsiSrc * (session3Mult / 100) :
time4 and session4E ? rsiSrc * (session4Mult / 100) :
time5 and session5E ? rsiSrc * (session5Mult / 100) :
time6 and session6E ? rsiSrc * (session6Mult / 100) : na) : rsiSrc
baseRsiValue = ta.rsi(srcToUse, rsiLength)
prevRsiValue = baseRsiValue[1]
smoothedRsi = ta.ema(baseRsiValue, smoothedLength)
baseRsiValue := rsiMethod == "Smoothed" ? smoothedRsi : baseRsiValue
startOverSold = ta.crossunder(baseRsiValue, rsiOS)
startOverBought = ta.crossover(baseRsiValue, rsiOB)
overSold = baseRsiValue < rsiOS
overBought = baseRsiValue > rsiOB
unOverBought = baseRsiValue < rsiOB and baseRsiValue[1] >= rsiOB
unOverSold = baseRsiValue > rsiOS and baseRsiValue[1] <= rsiOS
pHigh = ta.pivothigh(baseRsiValue, pivotSens, pivotSens)
pLow = ta.pivotlow(baseRsiValue, pivotSens, pivotSens)
lastPHigh = ta.valuewhen(not na(pHigh), pHigh, 1)
lastPLow = ta.valuewhen(not na(pLow), pLow, 1)
lastPHighP = ta.valuewhen(not na(pHigh), high[pivotSens], 1)
lastPLowP = ta.valuewhen(not na(pLow), low[pivotSens], 1)
lastPHighO = ta.valuewhen(not na(pHigh), baseRsiValue[pivotSens], 1)
lastPLowO = ta.valuewhen(not na(pLow), baseRsiValue[pivotSens], 1)
lastPHighI = ta.valuewhen(not na(pHigh), bar_index[pivotSens], 1)
lastPLowI = ta.valuewhen(not na(pLow), bar_index[pivotSens], 1)
nBearDiv = pHigh < lastPHigh and high[pivotSens] > lastPHighP
nBullDiv = pLow > lastPLow and low[pivotSens] < lastPLowP
// } <CALCULATIONS>
// { <VISUALS>
topTopValue = rsiOB + 12
topBotValue = rsiOB
botTopValue = rsiOS
botBotValue = rsiOS - 12
hline(50, "mid", color.gray, hline.style_dashed, 1)
base = plot(baseRsiValue, "RSI", baseRsiValue > prevRsiValue ? color.green : color.red, 1, plot.style_line, false, 0.0, 0, false, true)
trace = plot(prevRsiValue, "Prev RSI", TRANSPARENT, 2, plot.style_line, false, 0.0, 0, false, true)
fill(base, trace,
top_value = baseRsiValue > prevRsiValue ? baseRsiValue : prevRsiValue,
bottom_value = baseRsiValue > prevRsiValue ? prevRsiValue : baseRsiValue,
top_color = baseRsiValue > prevRsiValue ? color.green : TRANSPARENT,
bottom_color = baseRsiValue > prevRsiValue ? TRANSPARENT : color.red)
t1 = plot(topBotValue, "top1", TRANSPARENT, 1, plot.style_line)
t2 = plot(topTopValue, "top2", TRANSPARENT, 1, plot.style_line)
b1 = plot(botTopValue, "bot1", TRANSPARENT, 1, plot.style_line)
b2 = plot(botBotValue, "bot2", TRANSPARENT, 1, plot.style_line)
fill(t1, t2, top_value = topTopValue, bottom_value = topBotValue, top_color = color.new(color.red, 30), bottom_color = color.new(color.red, 100))
fill(b1, b2, top_value = botTopValue, bottom_value = botBotValue, top_color = color.new(color.green, 100), bottom_color = color.new(color.green, 30))
plotshape(
series = startOverBought ? rsiOB + 15 : na,
title = "Start Overbought",
style = shape.cross,
location = location.absolute,
color = color.red,
size = size.tiny)
plotshape(
series = overBought and overBought[1] ? rsiOB + 15 : na,
title = "Overbought",
style = shape.cross,
location = location.absolute,
color = color.blue,
size = size.tiny)
plotshape(
series = startOverSold ? rsiOS - 15 : na,
title = "Start Oversold",
style = shape.cross,
location = location.absolute,
color = color.green,
size = size.tiny)
plotshape(
series = overSold and overSold[1] ? rsiOS - 15 : na,
title = "Oversold",
style = shape.cross,
location = location.absolute,
color = color.blue,
size = size.tiny)
plotshape(
series = unOverBought ? rsiOB + 15 : na,
title = "Un-Overbought",
style = shape.cross,
location = location.absolute,
color = color.orange,
size = size.tiny)
plotshape(
series = unOverSold ? rsiOS - 15 : na,
title = "Un-Oversold",
style = shape.cross,
location = location.absolute,
color = color.orange,
size = size.tiny)
if barstate.isconfirmed and showDivs
if nBearDiv
line.new(
x1 = bar_index[pivotSens], y1 = baseRsiValue[pivotSens],
x2 = lastPHighI, y2 = lastPHighO, xloc = xloc.bar_index,
color = bearColor, width = divWidth)
if nBullDiv
line.new(
x1 = bar_index[pivotSens], y1 = baseRsiValue[pivotSens],
x2 = lastPLowI, y2 = lastPLowO, xloc = xloc.bar_index,
color = bullColor, width = divWidth)
// } <VISUALS>
// { <ALERTS>
alertcondition(startOverBought, title = "New Overbought")
alertcondition(overBought, "Currently Overbought")
alertcondition(unOverBought, "Un-Overbought")
alertcondition(startOverSold, title = "New Oversold")
alertcondition(overSold, "Currently Oversold")
alertcondition(unOverSold, "Un-Oversold")
alertcondition(nBearDiv, "Bearish Divergence")
alertcondition(nBullDiv, "Bullish Divergence")
// } <ALERTS> |
EMA Power Bands | https://www.tradingview.com/script/5rWSzuoP/ | shncoskunn | https://www.tradingview.com/u/shncoskunn/ | 69 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ shncoskunn
//@version=4
study(title="EMA Power Bands", shorttitle="EMA Power Bands", overlay=true)
ATRlength = input(200, minval=1)
ATRMult = input(2.272, minval=1)
ATR = rma(tr(true), ATRlength)
//EMA
len = input(21, minval=1, title="EMA Length")
src = input(close, title="Source")
out = ema(src, len)
plot(out, title="EMA", color=color.rgb(255, 115, 0),transp=85)
//rsฤฑ
Rsi_value=input(14,title="RSI Uzunluฤu",step=1)
hl=input(80,title="RSI Aลฤฑrฤฑ Alฤฑm Eลiฤi",step=1)
ll=input(25,title="RSI Aลฤฑrฤฑ Satฤฑm Eลiฤi",step=1)
rs=rsi(close,Rsi_value)
//EMA Bands
emaup = out+(ATR*ATRMult)
emadw = out-(ATR*ATRMult)
plot(emaup, title="EMAUP", color=color.red, linewidth=3)
plot(emadw, title="EMADW", color=color.green, linewidth=3)
//Conditions for Bullish and Bearish Flags
plotshape(close > emaup, style=shape.arrowdown,location=location.abovebar,color=color.red, size=size.small, text="๐จ")
plotshape(close < emadw, style=shape.arrowup,location=location.belowbar,color=color.green, size=size.small, text="๐")
//Buy/Sell Signals based on RSI
buy_signal = rs < ll ? 1 : 0
sell_signal = rs > hl ? 1 : 0
plotshape(buy_signal, title="Buy Signal", style=shape.triangleup, location=location.belowbar, color=color.green, text="๐")
plotshape(sell_signal, title="Sell Signal", style=shape.triangledown, location=location.abovebar, color=color.red, text="๐ชซ") |
RibboNN Machine Learning [ChartPrime] | https://www.tradingview.com/script/7cUyUmXS-RibboNN-Machine-Learning-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 614 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ ChartPrime
//@version=5
indicator("RibboNN Machine Learning [ChartPrime] ",shorttitle = "RibboNN [ChartPrime]" , overlay=true)
string Core = "Core Settings"
string visual = "Visual Settings"
int ShortPriod = input.int (26, 'Slow Period', 1,group=Core)
int LongPriod = input.int (14, 'Fast Period', 2,group=Core)
int Neighbours = math.floor(math.sqrt(input.int (250,'Neighbours Count', 5,group=Core)))
float BarRange = high - low
var array<float> feature1 = array.new_float(0)
var array<float> feature2 = array.new_float(0)
var array<int> directions = array.new_int(0)
var array<float> data = array.new_float()
var array<int> predictions = array.new_int(0)
float max = input.float(5.0,"Long Sensitivity",tooltip = "The sensitivity level directly affects the number of class generated for uptrend",step = 0.1,maxval = 5.0,minval = 1.0) * 10
float max2 = input.float(9,"Short Sensitivity",tooltip = "The sensitivity level directly affects the number of class generated for uptrend",step = 0.1,maxval = 12.0,minval = 5.0) * 10
color Bull = input.color(#1f4037,title = "Bull",group=visual,inline = "005")
color Bull1 = input.color(#99f2c8,title = "",group=visual,inline = "005")
color bear = input.color(#FF416C,title = "Bear",group=visual,inline = "005")
color Bear1 = input.color(#FF4B2B,title = "",group=visual,inline = "005")
var int signal = 0
var float prediction = 0.0
var LLong = false
var SShort = false
Range_MA(period)=>
// Calculate weighted ma
weight = BarRange / math.sum(BarRange, period)
TotalSum = math.sum(close * weight, period)
TotalW= math.sum(weight, period)
rwma = TotalSum / TotalW
prediction_data(float src , int dir) =>
// RSI Data Calculation
up = ta.rma(math.max(ta.change(src), 0), dir)
down = ta.rma(-math.min(ta.change(src), 0), dir)
_ISR = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
mf = ta.mfi(src, dir)
_ISR_mfi = math.abs( _ISR + mf / 2 )
_ISR_mfi
LongData = prediction_data(hlc3,LongPriod)
ShortData = prediction_data(hlc3,ShortPriod)
longcon = LongData < max
shorton = ShortData > max2
int Class = shorton ? -1 : longcon ? 1 : 0
// Nearest Neighbor Calculation
array.push(feature1, LongData)
array.push(feature2, ShortData)
array.push(directions, Class)
int size = array.size(directions)
float dust = -999.0
for i = 0 to size - 1
// Calculate the Manhattan distance of the current point to all historic points.
float ManD = math.abs(LongData - array.get(feature1, i)) + math.abs(ShortData - array.get(feature2, i))
if ManD > dust
dust := ManD
if array.size(predictions) >= Neighbours
array.shift(predictions)
array.push(predictions, array.get(directions, i))
// Prediction and coloring Conditions
prediction := array.sum(predictions) * 5
C = not (prediction > 0) and not (prediction < 0)
signal := prediction > 0 ? 1 : prediction < 0 ? -1 : C ? 0 : nz(signal[1])
int changed = ta.change(signal)
bool Uptrend = changed and signal==1
bool DownTrend = changed and signal==-1
if Uptrend //and close > Range_MA(10)
LLong:= true
SShort:= false
if DownTrend //and close < Range_MA(10)
LLong:= false
SShort:= true
_color =
LLong ? color.new(color.from_gradient(prediction,0,55,Bull,Bull1),30) :
SShort ? color.new(color.from_gradient(-prediction,-55,-1,bear,Bear1),30) :
na
first = plot(Range_MA(10),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(11),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(12),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(13),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(14),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(15),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(16),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(17),color = color.new(_color,80),linewidth = 1,editable = false)
plot(Range_MA(18),color = color.new(_color,80),linewidth = 1,editable = false)
last = plot(Range_MA(20),color = color.new(_color,80),linewidth = 1,editable = false)
fill(first,last,color= color.new(_color,90))
|
MyLibrary | https://www.tradingview.com/script/xtURdy10-MyLibrary/ | joseph_toomarkhani | https://www.tradingview.com/u/joseph_toomarkhani/ | 1 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ joseph_toomarkhani
//@version=5
// @description TODO: add library description here
library("MyLibrary")
export init(float value) => array.new_float(1, value)
export set(float[] source, float value) => array.set(source, 0, value)
export get(float[] source) => array.get(source, 0) |
Daily Range Support & Resistance Levels [QuantVue] | https://www.tradingview.com/script/gojuqZv1-Daily-Range-Support-Resistance-Levels-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 225 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ QuantVue
//@version=5
indicator("Daily Range Support & Resistance Levels [QuantVue]", overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
//-----------------------------------------------//
//runtime errors
//-----------------------------------------------//
if timeframe.ismonthly or timeframe.isweekly
runtime.error('Please switch to lower timeframe')
else if (timeframe.in_seconds() / 60 < timeframe.in_seconds('3') / 60) and (syminfo.type == 'stock' or syminfo.type == 'fund' or syminfo.type == 'index')
runtime.error('Please switch to 3 minute chart or higher')
else if timeframe.in_seconds() / 60 <= timeframe.in_seconds('10') / 60 and (syminfo.type == 'crypto' or syminfo.type == 'forex')
runtime.error('Please switch to 15 minute time frame or higher')
else if timeframe.in_seconds() / 60 < timeframe.in_seconds('15') / 60 and syminfo.type == 'cfd'
runtime.error('Please switch to 15 minute time frame or higher')
//-----------------------------------------------//
//inputs
//-----------------------------------------------//
showTable = input.bool(true, 'Show Stats on Daily Chart', inline = '1')
yPos = input.string("Top", " ", options = ["Top", "Middle", "Bottom"], inline = '1')
xPos = input.string("Right", " ", options = ["Right","Center", "Left"], inline = '1')
statsBG = input.color(color.gray, 'Stats Table BG Color', inline = '2')
statsText = input.color(color.white, 'Stats Table Text Color', inline = '2')
averagingPerdiod = input.int(150, 'Averaging Period', minval = 5, step = 5)
multiplier = input.float(1.0, 'StDev Multiplier', minval = .25, maxval = 4, step = .25)
sLineColor = input.color(color.blue, 'Support Color', inline = '3')
rLineColor = input.color(color.rgb(255, 17, 0), 'Resistance Color', inline = '3')
showFill = input.bool(true, 'Fill', inline = '3')
showPrice = input.bool(true, 'Show Support / Resistance Prices', inline = '4')
labelTextColor = input.color(color.white, ' ', inline = '4')
showWO = input.bool(true, 'Show Daily Open Line', inline = '5')
wOColor = input.color(color.fuchsia, ' ', inline = '5')
r1Style = input.string('Solid', 'R1 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '6')
r2Style = input.string('Solid', 'R2 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '6')
s1Style = input.string('Solid', 'S1 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '7')
s2Style = input.string('Solid', 'S2 Line Style', ['Solid', 'Dashed', 'Dotted'], inline = '7')
showPrevious = input.bool(false, 'Show Previous Levls')
//-----------------------------------------------//
//methods
//-----------------------------------------------//
method switcher(string this) =>
switch this
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
//-----------------------------------------------//
//variables
//-----------------------------------------------//
var table stats = table.new(str.lower(yPos) + '_' + str.lower(xPos), 5, 4, border_color = color.new(color.white,100), border_width = 2,
frame_color = color.new(color.white,100), frame_width = 2)
var float[] upAvgArray = array.new<float>()
var float[] downAvgArray = array.new<float>()
var line r1Line = na, var line r2Line = na, var line s1Line = na, var line s2Line = na, var line WO = na
var label r1Label = na, var label r2Label = na, var label s1Label = na, var label s2Label = na, var label WOLabel = na
var box rFill = na, var box sFill = na
var dayCount = 0, var closeAboveR1 = 0, var closeAboveR2 = 0, var closeBelowS1 = 0, var closeBelowS2 = 0
var touchR1 = 0, var touchR2 = 0, var touchS1 = 0, var touchS2 = 0
var R1 = 0.0, var R2 = 0.0, var S1 = 0.0, var S2 = 0.0
[dayOpen, dayHigh, dayLow, dayClose] = request.security(syminfo.tickerid, 'D',[open,high,low,close], lookahead = barmerge.lookahead_on)
newDay = ta.change(time('D'))
idxCount = ta.barssince(newDay)
//-----------------------------------------------//
//calculations
//-----------------------------------------------//
up = newDay ? 100 * ((dayHigh - dayOpen) / dayClose) : na
down = newDay ? 100 * math.abs(((dayOpen - dayLow) / dayClose)) : na
upStdev = ta.stdev(up, averagingPerdiod) * multiplier
upSD = newDay ? upStdev[1] : na
downStdev = ta.stdev(down, averagingPerdiod) * multiplier
downSd = newDay ? downStdev[1] : na
if newDay
if upAvgArray.size() > averagingPerdiod
upAvgArray.pop()
upAvgArray.unshift(up)
else
upAvgArray.unshift(up)
upAvg = upAvgArray.size() > 0 ? upAvgArray.avg() : na
if newDay
if downAvgArray.size() > averagingPerdiod
downAvgArray.pop()
downAvgArray.unshift(down)
else
downAvgArray.unshift(down)
downAvg = downAvgArray.size() > 0 ? downAvgArray.avg() : na
R1 := newDay ? dayOpen + (upAvg / 100) * dayOpen : R1[1]
R2 := newDay ? dayOpen + ((upAvg + upSD) / 100) * dayOpen : R2[1]
S1 := newDay ? dayOpen - (downAvg / 100) * dayOpen : S1[1]
S2 := newDay ? dayOpen - ((downAvg + downSd) / 100) * dayOpen : S2[1]
//-----------------------------------------------//
//daily stats
//-----------------------------------------------//
dayCount := newDay ? dayCount + 1 : dayCount
if dayClose > R1
closeAboveR1 += 1
if dayClose > R2
closeAboveR2 += 1
if dayClose < S1
closeBelowS1 += 1
if dayClose < S2
closeBelowS2 += 1
if dayHigh >= R1
touchR1 += 1
if dayHigh >= R2
touchR2 += 1
if dayLow <= S1
touchS1 += 1
if dayLow <= S2
touchS2 += 1
closeInsideAvg = dayCount - closeAboveR1 - closeBelowS1
closeInsideAvgPlus = dayCount - closeAboveR2 - closeBelowS2
//-----------------------------------------------//
//daily stats table
//-----------------------------------------------//
if barstate.islast and showTable and timeframe.isdaily and yPos == 'Top'
stats.cell(0,0, ' ')
stats.cell(0, 1, 'Touch R1: ' + str.tostring(touchR1) + ' / ' + str.tostring((touchR1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 1, 'Close > R1: ' + str.tostring(closeAboveR1) + ' / ' + str.tostring((closeAboveR1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 1, 'Touch R2: ' + str.tostring(touchR2) + ' / ' + str.tostring((touchR2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 1, 'Close > R2: ' + str.tostring(closeAboveR2) + ' / ' + str.tostring((closeAboveR2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(0, 2, 'Touch S1: ' + str.tostring(touchS1) + ' / ' + str.tostring((touchS1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 2, 'Close < S1: ' + str.tostring(closeBelowS1) + ' / ' + str.tostring((closeBelowS1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 2, 'Touch S2: ' + str.tostring(touchS2) + ' / ' + str.tostring((touchS2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 2, 'Close < S2: ' + str.tostring(closeBelowS2) + ' / ' + str.tostring((closeBelowS2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(4, 3, 'Weeks Analyzed: ' + str.tostring(dayCount), text_color = statsText, bgcolor = statsBG)
stats.cell(4, 1, 'Total Closes Inside R1/S1: ' + str.tostring(closeInsideAvg) + ' / ' + str.tostring((closeInsideAvg/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(4, 2, 'Total Closes Inside R2/S2: ' + str.tostring(closeInsideAvgPlus) + ' / ' + str.tostring((closeInsideAvgPlus/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
else if barstate.islast and showTable and timeframe.isdaily
stats.cell(0, 0, 'Touch R1: ' + str.tostring(touchR1) + ' / ' + str.tostring((touchR1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 0, 'Close > R1: ' + str.tostring(closeAboveR1) + ' / ' + str.tostring((closeAboveR1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 0, 'Touch R2: ' + str.tostring(touchR2) + ' / ' + str.tostring((touchR2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 0, 'Close > R2: ' + str.tostring(closeAboveR2) + ' / ' + str.tostring((closeAboveR2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(0, 1, 'Touch S1: ' + str.tostring(touchS1) + ' / ' + str.tostring((touchS1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(1, 1, 'Close < S1: ' + str.tostring(closeBelowS1) + ' / ' + str.tostring((closeBelowS1/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 1, 'Touch S2: ' + str.tostring(touchS2) + ' / ' + str.tostring((touchS2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(3, 1, 'Close < S2: ' + str.tostring(closeBelowS2) + ' / ' + str.tostring((closeBelowS2/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(0, 2, 'Weeks Analyzed: ' + str.tostring(dayCount), text_color = statsText, bgcolor = statsBG)
stats.cell(1, 2, 'Total Closes Inside R1/S1: ' + str.tostring(closeInsideAvg) + ' / ' + str.tostring((closeInsideAvg/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
stats.cell(2, 2, 'Total Closes Inside R2/S2: ' + str.tostring(closeInsideAvgPlus) + ' / ' + str.tostring((closeInsideAvgPlus/dayCount), '#.#%'),
text_color = statsText, bgcolor = statsBG)
//-----------------------------------------------//
//support and resistance levels
//-----------------------------------------------//
if newDay and (syminfo.type == 'stock' or syminfo.type == 'fund' or syminfo.type == 'index')
(r1Line[1]).delete(), (r2Line[1]).delete(), (s1Line[1]).delete(), (s2Line[1]).delete()
(r1Label[1]).delete(), (r2Label[1]).delete(), (s1Label[1]).delete(), (s2Label[1]).delete()
(WO[1]).delete()
if showWO
WO := line.new(bar_index, dayOpen, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, dayOpen,
color = wOColor, width = 3)
r1Line := line.new(bar_index, R1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, R1,
color = rLineColor, width = 2, style = r1Style.switcher())
r2Line := line.new(bar_index, R2, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, R2,
color = rLineColor, width = 2, style = r2Style.switcher())
s1Line := line.new(bar_index, S1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, S1,
color = sLineColor, width = 2, style = s1Style.switcher())
s2Line := line.new(bar_index, S2, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, S2,
color = sLineColor, width = 2, style = s2Style.switcher())
if showPrice
r1Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2,
R1, 'R1 $' + str.tostring(R1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
r2Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2,
R2, 'R2 $' + str.tostring(R2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s1Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2,
S1, 'S1 $' + str.tostring(S1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s2Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2,
S2, 'S2 $' + str.tostring(S2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
if showFill
(sFill[1]).delete(), (rFill[1]).delete()
sFill := box.new(bar_index, S1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, S2,
border_width = 0, bgcolor = color.new(sLineColor,80))
rFill := box.new(bar_index, R1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((390 / (str.tonumber(timeframe.period)))) : bar_index + 2, R2,
border_width = 0, bgcolor = color.new(rLineColor,80))
else if newDay and (syminfo.type == 'crypto' or syminfo.type == 'forex' or syminfo.type == 'cfd')
(r1Line[1]).delete(), (r2Line[1]).delete(), (s1Line[1]).delete(), (s2Line[1]).delete()
(r1Label[1]).delete(), (r2Label[1]).delete(), (s1Label[1]).delete(), (s2Label[1]).delete()
(WO[1]).delete()
if showWO
WO := line.new(bar_index, dayOpen, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, dayOpen,
color = wOColor, width = 3)
r1Line := line.new(bar_index, R1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, R1,
color = rLineColor, width = 2, style = r1Style.switcher())
r2Line := line.new(bar_index, R2, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, R2,
color = rLineColor, width = 2, style = r2Style.switcher())
s1Line := line.new(bar_index, S1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, S1,
color = sLineColor, width = 2, style = s1Style.switcher())
s2Line := line.new(bar_index, S2, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, S2,
color = sLineColor, width = 2, style = s2Style.switcher())
if showPrice
r1Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2,
R1, 'R1 $' + str.tostring(R1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
r2Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2,
R2, 'R2 $' + str.tostring(R2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s1Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2,
S1, 'S1 $' + str.tostring(S1, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
s2Label := label.new(timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2,
S2, 'S2 $' + str.tostring(S2, format.mintick), style = label.style_label_left, color = color.new(color.white,100),
textcolor = labelTextColor)
if showFill
(sFill[1]).delete(), (rFill[1]).delete()
sFill := box.new(bar_index, S1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, S2,
border_width = 0, bgcolor = color.new(sLineColor,80))
rFill := box.new(bar_index, R1, timeframe.isdaily ? bar_index + 2 :
timeframe.isminutes ? bar_index + int((1440 / (str.tonumber(timeframe.period)))) : bar_index + 2, R2,
border_width = 0, bgcolor = color.new(rLineColor,80))
if showPrevious and showFill
sFill.set_left(bar_index), rFill.set_left(bar_index)
//-----------------------------------------------//
//show historical levels
//-----------------------------------------------//
fillColor = color.new(color.white,100)
r1Plot = plot(showPrevious ? R1 : na, color = color.rgb(253, 0, 0))
r2Plot = plot(showPrevious ? R2 : na, color = color.rgb(90, 0, 0))
s1Plot = plot(showPrevious ? S1 : na, color = color.rgb(0, 174, 255))
s2Plot = plot(showPrevious ? S2 : na, color = color.rgb(0, 86, 214))
woPlot = plot(showPrevious ? dayOpen : na, color = wOColor, style = plot.style_linebr)
fill(r1Plot, r2Plot, color = showFill ? color.new(rLineColor, 80) : fillColor)
fill(s1Plot, s2Plot, color = showFill ? color.new(sLineColor, 80) : fillColor)
//-----------------------------------------------//
//alert conditions
//-----------------------------------------------//
crossR1 = ta.crossover(close,R1)
crossR2 = ta.crossover(close,R2)
crossS1 = ta.crossunder(close,S1)
crossS2 = ta.crossunder(close,S2)
alertcondition(crossR1, 'Cross Above R1', 'Price crossing above R1')
alertcondition(crossR2, 'Cross Above R2', 'Price crossing above R2')
alertcondition(crossS1, 'Cross Below S1', 'Price crossing below S1')
alertcondition(crossS2, 'Cross Below S2', 'Price crossing below S2') |
Liquidation Ranges + Volume/OI Dots [Kioseff Trading] | https://www.tradingview.com/script/lLaopLoy-Liquidation-Ranges-Volume-OI-Dots-Kioseff-Trading/ | KioseffTrading | https://www.tradingview.com/u/KioseffTrading/ | 1,227 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ KioseffTrading
//@version=5
indicator("Volume Dots", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
//
import PineCoders/Time/4 as pct
import HeWhoMustNotBeNamed/BinaryInsertionSort/1 as HeWho
//
action2 = input.bool (defval = true, title = "Show Liquidation Ranges", group = "Show Liquidation Ranges" , inline = "0")
showValues = input.bool (defval = true, title = "Show VOL/OI Values in Grid", group = "Show Liquidation Ranges", inline = "0")
action = input.string(defval = "Find As Many Vol/OI Extremities As Possible", title = "Volume/OI Dots Should: ", options = ["Find As Many Vol/OI Extremities As Possible", "Show Extremities For The Data On My Screen", "Show The Highest Vol./OI Per Bar", "Off"], group = "Volume/OI Dots Main Settings"), stringBool = "Find As Many Vol/OI Extremities As Possible"
data = input.bool (defval = false, title = "Use OI Instead Of Volume For Dots?", group = "Use OI Instead")
agg = 100 - input.float (minval = 0.01, title = "Aggressiveness", maxval = 10, defval = 0.01, group = 'If You Selected "Find As Many Vol/OI Extremities As Possible"', tooltip = "Corresponds To The Required Percent Rank For A Value To Be Distinguished. Sclaed 0.01-9.99 For Simplicity; However, Uses Percent Rank (100 Subtracted By Number In This Box) - Works Only For 'Find As Many Vol/OI Extremities As Possible'")
nake = input.bool (defval = false, title = "Naked Levels Only?", group = "Naked Levels")
actint = input.int (defval = 20, title = 'If You Selected "Show Extremities For The Data On My Screen: How Many Levels Should Be Shown?', group = "Volume/OI Dots (Screen Only)", minval = 1, maxval = 500)
ti = input.bool (defval = false, title = "Use Fixed Range", inline = "1", group = "Volume/OI Dots Misc Settings")
ti2 = input.time (defval = timestamp("04 Apr 2022 00:00 +0300"), title = "Start", inline = "1", group = "Volume/OI Dots Misc Settings")
dt = input.int (defval = 15, title = "Levels In Table Shown", minval = 0, maxval = 99, group = "Volume/OI Dots Misc Settings" , inline = "Levels")
showl = input.int (defval = 10, title = "Lines Shown", minval = 0, maxval = 500, group = "Volume/OI Dots Misc Settings", inline = "Levels")
linebool = input.bool (defval = false, title = "Only Show Lines Within a % of Price", group = "Volume/OI Dots Misc Settings", inline = "line" )
linedist = input.float (defval = 3, title = "%", minval = 0, group = "Volume/OI Dots Misc Settings", inline = "line") / 100
srcol = input.bool (defval = false, title = "Color Lines As Support/Resistance", group = "Volume/OI Dots Misc Settings"), atr = ta.atr(14)
upcol = input.color (defval = color.lime, title = "Up Color Volโ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
", inline = "20", group = "Volume/OI Dots Misc Settings")
dncol = input.color (defval = color.red , title = "Down Color Volโ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
โ
", inline = "20", group = "Volume/OI Dots Misc Settings")
upcoloi = input.color (defval = color.blue, title = "OI Up + Price Upโ
โ
โ
โ
โ
โ", inline = "21", group = "Volume/OI Dots Misc Settings")
dncoloi = input.color (defval = color.orange , title = "OI Down + Price Down", inline = "21", group = "Volume/OI Dots Misc Settings")
upcoloi2 = input.color (defval = color.yellow, title = "OI Up + Price Downโ", inline = "21", group = "Volume/OI Dots Misc Settings")
dncoloi2 = input.color (defval = color.purple , title = "OI Down + Price Upโ
โ
โ
โ
โ
", inline = "21", group = "Volume/OI Dots Misc Settings")
sort = input.string(defval = "Descending", title = "Sort Table Data", options = ["Occurrence", "Descending"], group = "Volume/OI Dots Misc Settings", inline = "Misc")
siz = input.string(defval = "Normal", title = "Table Size", options = ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], inline = "Misc", group = "Volume/OI Dots Misc Settings")
move = input.bool (defval = true, title = "Show OI Delta Lines", group = "Liquidation Range")
showcir = input.bool (defval = true, title = "Show Violation Circles", group = "Liquidation Range")
box2Line = input.bool (defval = false, title = "Change Liquidation Boxes to Lines", group = "Liquidation Range")
minlevl = input.string(defval = "Auto", title = "Min Liquidation Level Shown", options = ["Auto", "10", "20", "30", "40", "50"], group = "Liquidation Range")
userDefinedTime = input.bool (defval = false, title = "Fixed Range", group = "Liquidation Range")
timtest = input.time (defval = timestamp("04 Apr 2023 00:00 +0300"), title = "Start Liquidation Range"),
timtest2 = input.time (defval = timestamp("20 Apr 2023 00:00 +0300"), title = "End Liquidation Range")
method equal (string id, value) => id == value
method notEqual (string id, value) => id != value
req() =>
cont = switch str.contains(syminfo.ticker, ".P")
true => syminfo.ticker + "_OI"
=> str.endswith(syminfo.ticker, "USDT") ? syminfo.ticker + ".P_OI" : syminfo.ticker + "T.P_OI"
switch syminfo.type
"crypto" => cont
=> string(na)
r3() =>
[R1, R2, R3, R4, R5] = switch syminfo.type
"crypto" => [ close-close[1], high, low, open, close ]
=> [float(na), float(na), float(na), float(na), float(na)]
// Thank you PineCoders
float chartTfInMinutes = timeframe.in_seconds() / 60.
int ONE_MIN = 1
int ONE_SEC = ONE_MIN / 60
int ONE_HOUR = ONE_MIN * 60
int ONE_DAY = ONE_HOUR * 24
int ONE_WEEK = ONE_DAY * 7
bool marketIs24Hours = syminfo.type == "crypto" or syminfo.type == "forex"
ltfint = switch
chartTfInMinutes <= ONE_MIN * 30 => "1"
chartTfInMinutes <= ONE_HOUR => "3"
chartTfInMinutes < ONE_HOUR * 2 => "5"
chartTfInMinutes < ONE_HOUR * 4 => "15"
chartTfInMinutes < ONE_HOUR * 6 => "30"
chartTfInMinutes < ONE_HOUR * 12 => marketIs24Hours ? "60" : "30"
chartTfInMinutes < ONE_DAY => marketIs24Hours ? "120" : "30"
chartTfInMinutes < ONE_WEEK => marketIs24Hours ? "720" : "120"
// Thank you PineCoders
[oic, oih, oil, oio, trueOic ] = request.security_lower_tf(req(), ltfint, r3() )
timeframeDiff = request.security(req(), timeframe.period, close-close[1] )
[vol, clo, clo1, hi, lo, clocalc, ltf, volSign] = request.security_lower_tf(syminfo.tickerid, ltfint,
[
volume, close, close[1], high, low, close - close[1], time, close >= open ? volume : volume * -1
])
comparison(id, value, string ) =>
switch string
">" => id > value
">=" => id >= value
"==" => id == value
"<=" => id <= value
"<" => id < value
"!=" => id != value
method floatGreatEqual (float id, value) => comparison(id, value, ">=")
method floatEqual (float id, value) => comparison(id, value, "==")
method floatLessEqual (float id, value) => comparison(id, value, "<=")
method floatNotEqual (float id, value) => comparison(id, value, "!=")
method intGreatEqual (int id, value) => comparison(id, value, ">=")
method intEqual (int id, value) => comparison(id, value, "==")
method intLessEqual (int id, value) => comparison(id, value, "<=")
method intNotEqual (int id, value) => comparison(id, value, "!=")
method HeWhoSort(float [] id, value, order) =>
HeWho.binary_insertion_sort(id, value, order)
method determine (bool id, value, value2) =>
switch id
true => value
=> value2
type timeValues
float [] Difference
float [] Close
int [] Time
type dotValues
float [] Volume
float [] Close
float [] Difference
float [] OI
float [] OI2
int [] Time
label [] Circle
line [] Zone
float [] Rank
float [] perBar
float [] volSignArr
int Start
type sortedMat
float volM
float oicM
int timM
float cloM
float clcM
float toiM
color colM
string valM
var timeMat = timeValues.new(array.new_float(), array.new_float(), array.new_int())
timeMat.Difference.unshift(timeframeDiff), timeMat.Close.unshift(close), timeMat.Time.unshift(time)
var dotMat = dotValues.new(
array.new_float(), array.new_float(),
array.new_float(), array.new_float(),
array.new_float(), array.new_int (),
array.new_label(), array.new_line (),
array.new_float(), array.new_float(),
array.new_float(), 0
)
obj = switch syminfo.type.equal("crypto")
true => oic
false => vol
if action.notEqual("Off")
conditionX = switch action
"Find As Many Vol/OI Extremities As Possible" => last_bar_index - bar_index <= (4.5e6)/(timeframe.in_seconds(timeframe.period)) and not ti or
time >= ti2 and ti and vol.size().intGreatEqual(1)
"Show Extremities For The Data On My Screen" => time >= chart.left_visible_bar_time and time <= chart.right_visible_bar_time
and not ti and vol.size().intGreatEqual(1) or time >= ti2 and ti and vol.size().intGreatEqual(1)
=> last_bar_index - bar_index <= 500
if conditionX
if obj.size().intGreatEqual(1)
if action.notEqual("Show The Highest Vol./OI Per Bar")
if nake and dotMat.Volume.size().intGreatEqual(1)
for i = 0 to dotMat.Volume.size() - 1
if not na(dotMat.Close.get(i))
if dotMat.Close.get(i).floatLessEqual(high)
if dotMat.Close.get(i).floatGreatEqual(low)
dotMat.Close.set(i, na)
for i = math.min(obj.size() - 1, clo.size() - 1) to 0 // In Honor of Spunky - Rest Comfortably Sweet Princess. You'll be Loved and Cherished Forever & Always <3
dotMat.Volume .unshift(vol.get(i)) , dotMat.Close .unshift(clo.get(i))
dotMat.Difference .unshift(clocalc.get(i)) , dotMat.OI .unshift(math.abs(oic.get(i)))
dotMat.Time .unshift(ltf.get(i)) , dotMat.OI2 .unshift(oic.get(i)),
dotMat.volSignArr.unshift(volSign.get(i))
else
for i = math.min(obj.size() - 1, clo.size() - 1) to 0
cond = switch data
false => vol.get(i).floatEqual(vol.max())
=> oic.get(i).floatEqual(math.max(oic.max(), math.abs(oic.min())))
if cond
col = switch data
false => color.new(math.sign(clocalc.get(i)).floatEqual(-1).determine(color.lime , color.red), 33)
=> color.new(math.sign(oic.get(i)).floatEqual(-1).determine (
math.sign(clocalc.get(i)) .floatEqual(-1).determine (
dncoloi, dncoloi2), math.sign(clocalc.get(i)).floatEqual (
-1).determine(upcoloi2, upcoloi)), 33)
OItxt = switch syminfo.type.equal("crypto")
true => "\nOI: " + str.tostring(oic.get(i), format.mintick)
=> ""
dotMat.Circle.unshift(
label.new(
time, clo.get(i), "โฌค",
tooltip = "VOL: " + (math.sign(clocalc.get(i)).floatEqual(-1).determine("-" , "")) +
str.tostring(vol.get(i), format.volume) + OItxt,
xloc = xloc.bar_time,
color = #000000,
textcolor = col,
size = size.tiny,
style = label.style_text_outline
))
dotMat.Zone.unshift(
line.new(time, clo.get(i), time, clo.get(i),
color = col,
xloc = xloc.bar_time
))
dotMat.perBar.unshift(data.determine(vol.get(i) , oic.get(i)))
if vol.size().intEqual(0)
dotMat.Start := time
var grid = matrix.new<box>(5, 20)
if barstate.islast and action.notEqual("Off")
if action.notEqual("Show The Highest Vol./OI Per Bar")
if dotMat.Circle.size().intGreatEqual(1)
for i = 0 to dotMat.Circle.size() - 1
dotMat.Circle.shift().delete()
if dotMat.Zone.size() .intGreatEqual(1)
for i = 0 to dotMat.Zone.size() - 1
dotMat.Zone.shift().delete()
if ti
line.new( ti2, high, ti2, low,
xloc = xloc.bar_time , extend = extend.both,
color = chart.fg_color, width = 2
)
var count = 1, vcopy = dotMat.Volume.copy(), ocopy = dotMat.OI.copy(), var SM = matrix.new<sortedMat>(8, 0), var tan3 = array.new_float()
switch data
false => vcopy.sort(order.descending)
=> ocopy.sort(order.descending)
for i = 0 to 249
[bool1, bool2, index] = switch data
false => [dotMat.Volume.includes(vcopy.get(i)), action.equal(stringBool).determine(
vcopy.percentrank(i).floatGreatEqual(agg) , i.intLessEqual(actint - 2)), dotMat.Volume.indexof(vcopy.get(i))]
=> [dotMat.OI.includes(ocopy.get(i)) , action.equal(stringBool).determine(
ocopy.percentrank(i).floatGreatEqual(agg) , i.intLessEqual(actint - 2)), dotMat.OI.indexof(ocopy.get(i))]
if bool1
if bool2
if dotMat.Close.indexof(dotMat.Close.get(index)).intNotEqual(-1)
append = switch data
false => vcopy.get(i)
true => ocopy.get(i)
[coloR, strinG] = if not data
switch math.sign(dotMat.Difference.get(index))
-1 => [dncol, "-"]
=> [upcol, "" ]
else
switch math.sign(dotMat.Difference.get(index))
-1 => [math.sign(dotMat.OI2.get(index)).floatEqual(-1).determine(dncoloi , upcoloi2) , "-"]
=> [math.sign(dotMat.OI2.get(index)).floatEqual(-1).determine(upcoloi , dncoloi2) , "" ]
SM.add_col(SM.columns(),
array.from(
sortedMat.new(volM = dotMat.Volume .get(index)) ,
sortedMat.new(oicM = dotMat.OI .get(index)) ,
sortedMat.new(timM = dotMat.Time .get(index)) ,
sortedMat.new(cloM = dotMat.Close .get(index)) ,
sortedMat.new(clcM = dotMat.Difference.get(index)) ,
sortedMat.new(toiM = dotMat.OI2 .get(index)) ,
sortedMat.new(colM = coloR ) ,
sortedMat.new(valM = strinG )
))
count += 1, dotMat.Rank.push(append),
tan3.push(sort.equal("Occurrence")
.determine(dotMat.Time.get(index), data
.determine(dotMat.OI.get(index) , dotMat.Volume.get(index)
)))
else
break
var uniArr = array.from("โถ","โท","โธ","โน","โบ","โป","โผ","โฝ","โพ","โฟ","โซ","โฌ","โญ","โฎ","โฏ","โฐ","โฑ","โฒ","โณ","โด")
colorr = array.new_color(), var tan2 = array.new_float(), var tan4 = array.new_int()
for i = 0 to SM.columns() - 1
condition = switch action
"Find As Many Vol/OI Extremities As Possible" => data.determine(ocopy.percentrank(i).floatGreatEqual(agg),
vcopy.percentrank(i).floatGreatEqual (agg))
=> i.intNotEqual(-1)
if condition
rank = dotMat.Rank.percentrank(i)
SIZE = switch rank.floatNotEqual(-1)
rank <= 10 => size.tiny
rank <= 25 => size.small
rank <= 50 => size.normal
rank <= 75 => size.large
=> size.huge
OItxt = switch syminfo.type.equal("crypto")
true => "\nOI: " + str.tostring(SM.row(5).get(i).toiM, format.mintick)
=> ""
dotMat.Circle.push(label.new(int(SM.row(2).get(i).timM), SM.row(3).get(i).cloM,
text = action.equal(stringBool) or i.intGreatEqual(uniArr.size() - 1) ? "โฌค" : uniArr.get(i),
tooltip = "VOL: " + (math.sign(SM.row(4).get(i).clcM).floatEqual(-1).determine("-" , "")) +
str.tostring(SM.row(0).get(i).volM, format.volume) + OItxt,
xloc = xloc.bar_time,
color = #000000,
textcolor = color.new(SM.row(6).get(i).colM, 33),
size = action.equal(stringBool) ? SIZE : size.normal,
style = label.style_text_outline
))
colorr.push(color.new(SM.row(6).get(i).colM, 33)), tan4.push(SM.row(2).get(i).timM)
tan2.HeWhoSort(sort.equal("Occurrence").determine(SM.row(2).get(i).timM, data.determine(SM.row(1).get(i).oicM, SM.row(0).get(i).volM)), -1)
if not nake
if showl.intNotEqual(0)
countLab = 0
for i = 0 to dotMat.Circle.size() - 1
if dotMat.Circle.get(i).get_x().intGreatEqual(tan4.max(math.min(showl, tan4.size()-1)))
if linebool and dotMat.Circle.get(i).get_y().floatGreatEqual(close * (1 - linedist))
and dotMat.Circle.get(i).get_y().floatLessEqual (close * (1 + linedist))
or not linebool
finCol = switch srcol
true => dotMat.Circle.get(i).get_y().floatGreatEqual(close).determine(dncol , upcol)
=> colorr.get(i)
dotMat.Zone.push(line.new(
dotMat.Circle.get(i).get_x(), dotMat.Circle.get(i).get_y(), pct.timeFrom("close", 40, "chart"), dotMat.Circle.get(i).get_y(),
color = finCol,
xloc = xloc.bar_time
))
countLab += 1
if countLab.intEqual(showl)
break
else
if action.equal(stringBool) or action.equal("Show Extremities For The Data On My Screen")
if dotMat.Circle.size().intGreatEqual(1)
for i = 0 to dotMat.Circle.size() - 1
if linebool and dotMat.Circle.get(i).get_y().floatGreatEqual(close * (1 - linedist))
and dotMat.Circle.get(i).get_y().floatGreatEqual(close * (1 + linedist))
or not linebool
dotMat.Zone.push(line.new(
dotMat.Circle.get(i).get_x(), dotMat.Circle.get(i).get_y(),
pct.timeFrom("bar", 40, "chart"), dotMat.Circle.get(i).get_y(),
xloc = xloc.bar_time, color = color.new(SM.row(6).get(i).colM, 33)
))
sz = switch siz
"Auto" => size.auto
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
if float(dt).floatGreatEqual(1)
var tab = table.new(position.top_right, 4, dt+2, frame_width = 1,
frame_color = color.white ,
border_width = 1,
border_color = color.white),
nakeCount = 0
for i = 0 to nake.determine(dotMat.Circle.size() - 1, math.min(dt - 1, SM.columns() - 1))
occCond = tan3.indexof(tan2.get(i))
if sort.equal("Occurrence")
tan3.set(occCond, 0)
if SM.row(0).get(i).volM.floatNotEqual(0)
tab.cell(0, i + 1, text = SM.row(7).get(occCond).valM + str.tostring(SM.row(0).get(occCond).volM, format.volume),
bgcolor = color.new(#000000, 50),
text_color = SM.row(6).get(occCond).colM,
text_size = sz,
text_font_family = font.family_monospace
)
tab.cell(1, i + 1, text = str.tostring(SM.row(3).get(occCond).cloM, format.mintick),
bgcolor = color.new(#000000, 50),
text_color = SM.row(6).get(occCond).colM,
text_size = sz,
text_font_family = font.family_monospace
)
if not na(oic.sum()) and syminfo.type.equal("crypto")
tab.cell(2, i + 1, text = str.tostring(SM.row(5).get(occCond).toiM, format.mintick),
bgcolor = color.new(#000000, 50),
text_color = data.determine(SM.row(6).get(occCond).colM ,
math.sign(SM.row(5).get(occCond).toiM).floatEqual(-1).determine(dncol , upcol)),
text_size = sz,
text_font_family = font.family_monospace
)
nakeCount += 1
if nakeCount.intEqual(dt)
break
tab.cell(0, 0, "Vol." , text_color = color.white, bgcolor = color.new(#000000, 50), text_size = sz, text_font_family = font.family_monospace)
tab.cell(1, 0, "Price", text_color = color.white, bgcolor = color.new(#000000, 50), text_size = sz, text_font_family = font.family_monospace)
if not na(oic.sum()) and syminfo.type.equal("crypto")
tab.cell(2, 0, "OI", text_color = color.white, bgcolor = color.new(#000000, 50), text_size = sz, text_font_family = font.family_monospace)
if dotMat.Circle.size().intEqual(0) and nake
tab.cell(0, 1, "No Naked Levels Detected", text_color = color.white, text_font_family = font.family_monospace, bgcolor = #000000)
tab.merge_cells(0, 1, 2, 1)
if action.notEqual(stringBool)
line.new(dotMat.Start, high, dotMat.Start, low,
extend = extend.both,
color = color.white,
width = 4,
xloc = xloc.bar_time
)
label.new(dotMat.Start, high * 1.01,
style = label.style_label_right,
color = #000000,
xloc = xloc.bar_time,
textcolor = color.white,
size = size.small,
text = "Earliest Start Date"
)
else
if dotMat.Circle.size().intGreatEqual(1)
for i = 0 to dotMat.Circle.size() - 1
dotMat.perBar.set(i, math.abs(dotMat.perBar.get(i)))
for i = 0 to dotMat.Circle.size() - 1
rank = dotMat.perBar.percentrank(i)
SIZE = switch rank.floatNotEqual(-1)
rank <= 10 => size.tiny
rank <= 25 => size.small
rank <= 50 => size.normal
rank <= 75 => size.large
=> size.huge
dotMat.Circle.get(i).set_size(SIZE)
if i.intLessEqual(showl - 2)
if linebool
if dotMat.Circle.get(i).get_y().floatGreatEqual(close * (1 - linedist))
and dotMat.Circle.get(i).get_y().floatLessEqual (close * (1 + linedist))
dotMat.Zone.get(i).set_x2(pct.timeFrom("bar", 40, "chart"))
else
dotMat.Zone.get(i).set_x2 (pct.timeFrom("bar", 40, "chart"))
switch srcol
true => dotMat.Zone.get(i).set_color(dotMat.Circle.get(i).get_y().
floatGreatEqual(close).determine(dncol , upcol))
=> continue
// Start
// Thank you Donovan Wall for the great range filter code!!
Cond_EMA(x, cond, n)=>
var val = array.new_float(0)
var ema_val = array.new_float(1)
if cond
val.push(x)
if val.size( )> 1
val.remove(0)
if na(ema_val.get(0))
ema_val.fill(val.get(0))
ema_val.set(0, (val.get(0) - ema_val.get(0))*(2/(n + 1)) + ema_val.get(0))
EMA = ema_val.get(0)
EMA
rng_size(x, scale, qty, n)=>
ATR = Cond_EMA(ta.tr(true), 1, n)
AC = Cond_EMA(math.abs(x - x[1]), 1, n)
rng_size = qty*AC
rng_filt(h, l, rng_, n, type, smooth, sn, av_rf, av_n)=>
rng_smooth = Cond_EMA(rng_, 1, sn)
r = smooth ? rng_smooth : rng_
var rfilt = array.new_float(2, (h + l)/2)
rfilt.set(1, rfilt.get(0))
if h - r > rfilt.get(1)
rfilt.set(0, h - r)
if l + r < rfilt.get(1)
rfilt.set(0, l + r)
rng_filt1 = rfilt.get(0)
hi_band1 = rng_filt1 + r, lo_band1 = rng_filt1 - r
rng_filt2 = Cond_EMA(rng_filt1, rng_filt1 != rng_filt1[1], av_n)
hi_band2 = Cond_EMA(hi_band1, rng_filt1 != rng_filt1[1], av_n)
lo_band2 = Cond_EMA(lo_band1, rng_filt1 != rng_filt1[1], av_n)
[rng_filt, hi_band, lo_band] = switch av_rf
true => [rng_filt2, hi_band2, lo_band2]
=> [rng_filt1, hi_band1, lo_band1]
[hi_band, lo_band, rng_filt]
[h_band, l_band, filt] = rng_filt(close, close, rng_size((close + close)/2, "Average Change", 20.618, 500), 500, "Type 1", true, 500, 0,0)
// Thank you Donovan Wall for great range filter code!!
// End
var int boxCount = 0
type liqValues
matrix <float> Average
matrix <int> Violations
matrix <float> TickVol
matrix <float> TickOI
float [] Levels
line [] boxLines
line rightUp
line rightDn
line leftUp
line leftDn
line startU
line startD
var liquidation = liqValues.new(
matrix.new<float>(5 , 0 ), matrix.new<int> (2 , 11, 0),
matrix.new<float>(21, 1000), matrix.new<float>(21, 1000 ),
array.new_float(), array.new_line()),
orientation = matrix.new<float>(2, 5)
method expCalc(array <float> id) =>
math.exp(id.avg())
method multiply(float id, string PM, float ) =>
switch PM
"+" => id * (1 + ((1./( float )) + 0.004))
"-" => id * (1 - ((1./( float )) + 0.004))
method reduced(array <float> id, float , string ) =>
switch string
"P" => id.expCalc().multiply("+", float )
"N" => id.expCalc().multiply("-", float )
method divSubtract(array<float> id, float, float2) =>
(id.reduced(float , "P") - id.reduced(float2, "N")) / 5
method double_binary_search_leftmost(array <float> id, column) =>
n = id.binary_search_leftmost (orientation.get(0, column))
n1 = id.binary_search_leftmost (orientation.get(1, column))
[n, n1]
method finSetVol(matrix <float> id, int i, int row, int start, int end) =>
for x = start to end
id.set (row, i, id.get(row, i) + liquidation.TickVol.get(i, x))
method finSetOI (matrix <float> id, int i, int row, int start, int end) =>
for x = start to end
id.set (row, i, id.get(row, i) + liquidation.TickOI.get(i, x))
method tickSet(matrix<float> id, float value, int column, int loop, int calc) =>
id.set(math.max(boxCount, 0), column, nz(nz(id.get(math.max(boxCount, 0), column)) + (value / math.max(1, (calc)))))
method netAdjust(array <float> id) =>
for i = 0 to id.size() - 1
if na(id.get(i))
id.set(i, 0)
for i = id.size() - 2 to 0
id.set(i, id.get(i) + id.get(i + 1))
if id.size().intGreatEqual(201)
for i = id.size() - 1 to 200
id.pop()
if action2 and syminfo.type.equal("crypto")
var oiclab = matrix.new<label>(2)
OIgrid = input.bool (defval = true , title = "Use OI For Grid Color (Instead of Volume) (Crypto Only)", group = "Grid Settings")
heatmap = input.bool (defval = true , title = "Show Heatmap (Grid)", group = "Grid Settings")
ext = input.bool (defval = false, title = "Extend Grid Boxes", group = "Grid Settings")
gridWidth = input.int (defval = 0, title = "Grid Width", group = "Grid Settings")
gridCol = input.color(defval = color.white, title = "Border Color", group = "Grid Settings", inline = "Grid")
gridUp = input.color(defval = color.lime, title = '"Up" Color', group = "Grid Settings", inline = "Grid")
gridDn = input.color(defval = color.red, title = '"Down" Color', group = "Grid Settings", inline = "Grid")
var float div = 0
if action.equal("Off") and not userDefinedTime
bx = box.all, la = label.all, li = line.all, lf = linefill.all
if bx.size().intGreatEqual(1)
row = grid.rows(), col = grid.columns()
grid.reshape(grid.elements_count(), 1)
for i = 0 to bx.size() - 1
if not grid.col(0).includes(bx.get(i))
bx.get(i).delete()
grid.reshape(row, col)
if la.size().intGreatEqual(1)
for i = 0 to la.size() - 1
if not oiclab.row(0).includes(la.get(i))
and not oiclab.row(1).includes(la.get(i))
la.get(i).delete()
if li.size().intGreatEqual(1)
for i = 0 to li.size() - 1
li.get(i).delete()
if lf.size().intGreatEqual(1)
for i = 0 to lf.size() - 1
lf.shift().delete()
var oicsum = matrix.new<float> (2, 0)
var int stime = 0, var int sbar = 0
if obj.size().intGreatEqual(1) and clocalc.size().intGreatEqual(1)
if sbar.intEqual(0)
sbar := bar_index, stime := time
cond = switch userDefinedTime
false => filt.floatGreatEqual(filt[1] - atr) and filt.floatLessEqual(filt[1] + atr)
=> time >= timtest and time <= timtest2
if cond
liquidation.Average.add_col(0, array.from(high, low, math.log(close), close > open ? volume : volume * -1, time))
for i = 0 to math.min(obj.size(), clocalc.size()) - 1
if syminfo.type.equal("crypto") and OIgrid
if math.sign(clocalc.get(i)).floatEqual(1)
switch math.sign(oic.get(i))
1 => oicsum.add_col(oicsum.columns(), array.from(oic.get(i), float(na)))
-1 => oicsum.add_col(oicsum.columns(), array.from(float(na), oic.get(i)))
else
switch math.sign(oic.get(i))
-1 => oicsum.add_col(oicsum.columns(), array.from(oic.get(i), float(na)))
1 => oicsum.add_col(oicsum.columns(), array.from(float(na), oic.get(i)))
else
switch math.sign(clocalc.get(i))
1 => oicsum.add_col(oicsum.columns(), array.from(vol.get(i), float(na)))
-1 => oicsum.add_col(oicsum.columns(), array.from(float(na), vol.get(i)))
if liquidation.Levels.size().intGreatEqual(1)
for i = 0 to math.min(obj.size(), clocalc.size()) - 1
highest = liquidation.Levels.binary_search_leftmost (hi.get(i))
lowest = liquidation.Levels.binary_search_leftmost (lo.get(i))
for x = lowest to highest
volx = switch math.sign(clocalc.get(i))
1 => vol.get(i)
=> vol.get(i) * -1
liquidation.TickVol.tickSet(volx , x, i, highest - lowest)
liquidation.TickOI .tickSet(obj.get(i), x, i, highest - lowest)
for i = 0 to 19
if not barstate.islast
con = div.floatGreatEqual(500)
[index, pIndex, startIndex] = switch con
true => [ time , time [1], stime]
=> [bar_index, bar_index[1], sbar]
if index >= math.round(startIndex + (div * (i + 1))) and pIndex < math.round(startIndex + (div * (i + 1)))
boxCount += 1
for z = 0 to 4
liquidation.TickVol.set(math.max(boxCount, 0), z, liquidation.TickVol.get(math.max(boxCount - 1, 0), z))
liquidation.TickOI .set(math.max(boxCount, 0), z, liquidation.TickOI .get(math.max(boxCount - 1, 0), z))
for x = 0 to 4
grid.set(x, boxCount,
box.new(
grid.get(x, boxCount - 1).get_right(),
liquidation.Average.row(2).reduced(100, "N") + (liquidation.Average.row(2).divSubtract(100, 100) * (x + 1)),
math.round(index + div),
liquidation.Average.row(2).reduced(100, "N") + (liquidation.Average.row(2).divSubtract(100, 100) * (x)),
xloc = div.floatGreatEqual(500).determine(xloc.bar_time, xloc.bar_index),
border_color = gridCol,
border_width = gridWidth,
bgcolor = color.white
))
break
if oicsum.elements_count().intGreatEqual(90001)
for i = 0 to 10000
oicsum.remove_col(i)
else
if filt < filt[1] - atr and not userDefinedTime or filt > filt[1] + atr and not userDefinedTime or userDefinedTime and time < timtest
liquidation.TickVol.fill(0, 0, liquidation.TickVol.rows(), 0, liquidation.TickVol.columns())
liquidation.TickOI .fill(0, 0, liquidation.TickOI .rows(), 0, liquidation.TickOI .columns())
liquidation.Levels.clear()
for i = 0 to grid.rows() - 1
for x = 0 to grid.columns() - 1
grid.get(i, x).delete()
if oicsum.columns().intGreatEqual(1)
for i = 0 to oicsum.columns() - 1
oicsum.remove_col()
if oiclab.columns().intGreatEqual(1)
for i = 0 to oiclab.columns() - 1
oiclab.get(0, i).delete()
oiclab.get(1, i).delete()
for i = 0 to oiclab.columns() - 1
oiclab.remove_col()
stime := time, sbar := bar_index, div := switch (last_bar_index - sbar) / 20 >= 500
false => (last_bar_index - sbar) / 20
=> (last_bar_time - stime) / 20
startIndex = div.floatGreatEqual(500).determine(time, bar_index)
for x = 0 to 4
grid.set(x, 0,
box.new(
startIndex,
liquidation.Average.row(2).reduced(100, "N") + (liquidation.Average.row(2).divSubtract(100, 100) * (x + 1)),
math.round(startIndex + div),
liquidation.Average.row(2).reduced(100, "N") + (liquidation.Average.row(2).divSubtract(100, 100) * (x)),
xloc = div.floatGreatEqual(500).determine(xloc.bar_time, xloc.bar_index),
border_color = gridCol,
border_width = gridWidth,
bgcolor = color.white
))
if liquidation.Average.columns().intGreatEqual(1)
for i = 0 to liquidation.Average.columns() - 1
liquidation.Average.remove_col()
liquidation.Average.add_col(0 , array.from(
high,
low,
math.log(close),
close > open ? volume : volume * -1,
time
))
for i = 0 to 499
liquidation.Levels.HeWhoSort(close * (1 + (i/1000)), 1)
liquidation.Levels.HeWhoSort(close * (1 - (i/1000)), 1)
boxCount := 0
if barstate.islast and not userDefinedTime or time[1] < timtest2 and time >= timtest2 and userDefinedTime
[endTime, endIndex] = switch userDefinedTime
false => [last_bar_time, last_bar_index]
true => [timtest2, bar_index ]
if userDefinedTime
x = timeMat.Time.get(timeMat.Time.indexof(timtest) + 1)
line.new(x, high, x, low, xloc = xloc.bar_time, extend = extend.both, color = color.new(color.white, 50) , width = 2)
line.new(timtest2, high, timtest2, low, xloc = xloc.bar_time, extend = extend.both, color = color.new(#000000, 50), width = 2)
posSum = oicsum.row(0).sum()
negSum = oicsum.row(1).sum()
minlvlu = 50, minlvld = 50, minlvl = 50, var corners = matrix.new<liqValues>(6, 1)
if minlevl.notEqual("Auto")
minlvlu := int(str.tonumber(minlevl))
minlvld := int(str.tonumber(minlevl))
else
for i = 50 to 20 by 10
if liquidation.Average.row(0).max().floatGreatEqual(liquidation.Average.row(2).reduced(i, "P"))
minlvlu := i + 10
if liquidation.Average.row(1).min().floatLessEqual (liquidation.Average.row(2).reduced(i, "N"))
minlvld := i - 10
minlvl := math.min(minlvlu, minlvld)
if syminfo.type.equal("crypto")
for i = 0 to liquidation.Average.columns() - 1
for x = 0 to 10
if liquidation.Average.get(0, i).floatGreatEqual(liquidation.Average.row(2).reduced(x * 10, "P"))
liquidation.Violations.set(0, x, nz(liquidation.Violations.get(0, x) + 1))
for i = 0 to liquidation.Average.columns() - 1
for x = 0 to 10
if liquidation.Average.get(1, i).floatLessEqual(liquidation.Average.row(2).reduced(x * 10, "N"))
liquidation.Violations.set(1, x, nz(liquidation.Violations.get(1, x) + 1))
if showcir
uCalc = liquidation.Average.row(2).reduced(100, "P")
lCalc = liquidation.Average.row(2).reduced(100, "N")
for i = liquidation.Average.columns() - 1 to 1
if liquidation.Average.get(0, i - 1).floatGreatEqual(uCalc)
and liquidation.Average.get(0, i) < uCalc
oiclab.add_col(oiclab.columns())
oiclab.set(0, oiclab.columns() - 1, label.new(math.round(liquidation.Average.get(4, i - 1)),
liquidation.Average.get(0, i - 1) , "โฌค",
textcolor = color.new(gridUp, 50),
color = #000000,
style = label.style_text_outline,
xloc = xloc.bar_time,
size = size.tiny
))
if liquidation.Average.get(1, i - 1).floatLessEqual(lCalc)
and liquidation.Average.get(1, i).floatGreatEqual(lCalc)
oiclab.add_col(oiclab.columns())
oiclab.set(1, oiclab.columns() - 1, label.new(math.round(liquidation.Average.get(4, i - 1)),
liquidation.Average.get(1, i - 1) , "โฌค",
textcolor = color.new(gridDn, 50),
color = #000000,
style = label.style_text_outline, xloc = xloc.bar_time,
size = size.tiny
))
for i = minlvl to 90 by 10
transp = array.from(45, 50, 55, 60, 65, 70, 75, 80, 85, 90)
txt = switch i.intNotEqual(90)
true => str.tostring(i, "###x")
=> box2Line ? "90x" : "90 - 100x"
switch box2Line
false =>
box.new(
stime, liquidation.Average.row(2).expCalc().multiply("-", i + 10), endTime, liquidation.Average.row(2).expCalc().multiply("-", i),
xloc = xloc.bar_time,
bgcolor = color.new( gridUp, transp.get((i - minlvl) / 10)),
text_color = color.white,
text = txt,
border_color = color.new( gridUp, transp.get((i - minlvl) / 10)),
text_halign = text.align_left,
text_size = size.auto
),
box.new(
stime, liquidation.Average.row(2).expCalc().multiply("+", i + 10), endTime, liquidation.Average.row(2).expCalc().multiply("+", i),
xloc = xloc.bar_time,
bgcolor = color.new( gridDn, transp.get((i - minlvl) / 10)),
text_color = color.white,
text = txt,
border_color = color.new( gridDn, transp.get((i - minlvl) / 10)),
text_halign = text.align_left,
text_size = size.auto
)
=>
line.new(
stime, liquidation.Average.row(2).expCalc().multiply("-", i), endTime + (time - time[3]),
liquidation.Average.row(2).expCalc().multiply("-", i),
xloc = xloc.bar_time,
color = color.new( gridUp, transp.get((i - minlvl) / 10))
),
line.new(
stime, liquidation.Average.row(2).expCalc().multiply("+", i), endTime + (time - time[3]),
liquidation.Average.row(2).expCalc().multiply("+", i),
xloc = xloc.bar_time,
color = color.new( gridDn, transp.get((i - minlvl) / 10))
)
if box2Line
label.new(bar_index + 7, liquidation.Average.row(2).expCalc().multiply("+", i),
style = label.style_label_left,
textcolor = gridDn,
color = #00000000,
text = txt
)
label.new(bar_index + 7, liquidation.Average.row(2).expCalc().multiply("-", i),
style = label.style_label_left,
textcolor = gridUp,
color = #00000000,
text = txt
)
if i.intEqual(90)
line.new(
stime, liquidation.Average.row(2).expCalc().multiply("-", i + 10), endTime + (time - time[3]),
liquidation.Average.row(2).expCalc().multiply("-", i + 10),
xloc = xloc.bar_time,
color = color.new( gridUp, transp.get((i - minlvl) / 10))
)
line.new(
stime, liquidation.Average.row(2).expCalc().multiply("+", i + 10), endTime + (time - time[3]),
liquidation.Average.row(2).expCalc().multiply("+", i + 10),
xloc = xloc.bar_time,
color = color.new( gridDn, transp.get((i - minlvl) / 10))
)
label.new(bar_index + 7, liquidation.Average.row(2).expCalc().multiply("+", i + 10),
style = label.style_label_left,
textcolor = gridDn,
text = str.tostring(i + 10, "###x"),
color = #00000000
)
label.new(bar_index + 7, liquidation.Average.row(2).expCalc().multiply("-", i + 10),
style = label.style_label_left,
textcolor = gridUp,
text = str.tostring(i + 10, "###x"),
color = #00000000
)
y1 = (liquidation.Average.row(2).divSubtract(minlvl, 100) / ((90 - minlvl) / 10) * ((i - minlvl) / 10))
colarr = array.from(11, 11, 22, 22, 33, 33, 44, 44, 55, 66, 66)
txtc = switch liquidation.Average.row(2).expCalc().multiply("+", i + 10).floatGreatEqual(liquidation.Average.row(0).max())
true => #ffffff50
=> color.new(gridDn, colarr.get((i - minlvl) / 10))
if not box2Line
label.new(endIndex + 25, liquidation.Average.row(2).reduced(minlvl, "P") - y1,
"โฐ",
textcolor = txtc,
size = size.tiny,
color = #000000,
style = label.style_text_outline
)
txtc2 = switch liquidation.Average.row(2).expCalc().multiply("-", i + 10).floatLessEqual(liquidation.Average.row(1).min())
true => #ffffff50
=> color.new(gridUp, colarr.get((i - minlvl) / 10))
if not box2Line
label.new(endIndex + 25, liquidation.Average.row(2).reduced(minlvl, "N") + y1,
"โฐ",
textcolor = txtc2 ,
size = size.tiny,
color = #000000,
style = label.style_text_outline
)
[mult, mult2, mult3] = switch minlvl
50 => [35 , 40, 30 ]
40 => [30 , 35, 25 ]
30 => [23 , 25.5, 20.5]
20 => [15 , 17, 13 ]
10 => [8 , 9 , 7 ]
liqd = math.avg(liquidation.Average.row(2).reduced(100, "N"), liquidation.Average.row(2).reduced(minlvl, "N"))
liqu = math.avg(liquidation.Average.row(2).reduced(100, "P"), liquidation.Average.row(2).reduced(minlvl, "P"))
liqd2 = liquidation.Average.row(2).reduced(mult, "N")
liqu2 = liquidation.Average.row(2).reduced(mult, "P")
sbartime = timeMat.Time.indexof(stime)
switchCond = syminfo.type.equal("crypto")
[longText, shortText, totCalc] = switch switchCond
true => [OIgrid.determine("\nNet Longs In Range", "\nBuying Vol. In Range" ),
OIgrid.determine("\nNet Shorts In Range", "\nSelling Vol. In Range"),
OIgrid.determine (posSum+negSum, posSum-negSum)]
=> ["\nBuying Vol. In Range", "\nSelling Vol. In Range", posSum-negSum]
label.new(bar_index + 15, liquidation.Average.row(2).expCalc(), str.tostring(totCalc, "###,###,###,###.00"),
color = color.white,
textcolor = color.rgb(0, 0, 0),
style = label.style_text_outline,
size = size.small
)
b = box.new(
int(
math.avg(stime, stime, endTime)),
liquidation.Average.row(2).reduced(mult2, "N"),
int(
math.avg(stime, endTime, endTime)),
liquidation.Average.row(2).reduced(mult3, "N"),
bgcolor = #00000050,
border_color = #ffffff,
text = str.tostring(posSum, "###,###,###,###,###,###.00")
+ longText ,
text_color = color.white,
text_size = size.auto,
xloc = xloc.bar_time
)
o = box.new(
int(
math.avg(stime, stime, endTime)),
liquidation.Average.row(2).reduced(mult2, "P"),
int(
math.avg(stime, endTime, endTime)),
liquidation.Average.row(2).reduced(mult3, "P"),
bgcolor = #00000050,
border_color = #ffffff,
text = str.tostring(negSum, "###,###,###,###,###,###.00") +
+ shortText ,
text_color = color.white,
text_size = size.auto,
xloc = xloc.bar_time
)
if switchCond
liquidation.boxLines.push(line.new(timeMat.Time.get(sbartime), liqd, timeMat.Time.get(sbartime + 10),
liqd,
color = gridUp,
style = line.style_dashed,
xloc = xloc.bar_time
))
corners.set(2, 0,
liqValues.new(
leftUp = line.new(timeMat.Time.get(sbartime + 10), liqd2, timeMat.Time.get(sbartime + 10),
liqd,
color = gridUp,
style = line.style_dashed,
xloc = xloc.bar_time
)))
liquidation.boxLines.push(line.new(timeMat.Time.get(sbartime + 10), liqd2, b.get_left(),liqd2,
color = gridUp,
style = line.style_dashed,
xloc = xloc.bar_time
))
corners.set(0, 0,
liqValues.new(
rightUp = line.new(endIndex + 10, liqd2, endIndex + 10, liqd,
color = gridUp,
style = line.style_dashed
)))
liquidation.boxLines.push(line.new(int(math.avg(sbar, endIndex, endIndex)), liqd2, endIndex + 10, liqd2,
color = gridUp,
style = line.style_dashed
))
liquidation.boxLines.push(line.new(endIndex, liqd, endIndex + 10,
liqd,
color = gridUp,
style = line.style_dashed
))
liquidation.boxLines.push(line.new(stime, liqu, timeMat.Time.get(sbartime + 10),
liqu,
color = gridDn,
style = line.style_dashed,
xloc = xloc.bar_time
))
corners.set(3, 0,
liqValues.new(
leftDn = line.new(timeMat.Time.get(sbartime + 10), liqu, timeMat.Time.get(sbartime + 10),
liqu2,
color = gridDn,
style = line.style_dashed,
xloc = xloc.bar_time
)))
liquidation.boxLines.push(line.new(timeMat.Time.get(sbartime + 10), liqu2, o.get_left(),liqu2,
color = gridDn,
style = line.style_dashed,
xloc = xloc.bar_time
))
corners.set(1, 0,
liqValues.new(
rightDn = line.new(endIndex + 10, liqu, endIndex + 10, liqu2,
color = gridDn,
style = line.style_dashed
)))
liquidation.boxLines.push(line.new(
int(
math.avg(sbar, endIndex, endIndex)), liqu2, endIndex + 10, liqu2,
color = gridDn,
style = line.style_dashed
))
liquidation.boxLines.push(line.new(endIndex, liqu, endIndex + 10,
liqu,
color = gridDn,
style = line.style_dashed
))
var table liqtab = table.new(
position.bottom_right, 20, 20,
bgcolor = na,
frame_color = color.white,
border_color = color.white,
frame_width = 1,
border_width = 1
)
liqtab.cell(0, 0, "Violations", text_color = color.white), liqtab.cell(0, 1, "Positive", text_color = gridDn),
liqtab.cell(2, 1, "Negative" , text_color = gridUp), liqtab.merge_cells(0, 0, 3, 0),
liqtab.merge_cells(0, 1, 1, 1)
liqtab.merge_cells(2, 1, 3, 1)
strArr = array.from("100x: ", "90x: ", "80x: ", "70x: ", "60x: ", "50x: ", "40x: ", "30x: ", "20x: ", "10x: " )
strArr2 = array.from("100x: ", "90x: ", "80x: ", "70x: ", "60x: ", "50x: ", "40x: ", "30x: ", "20x: ", "10x: " )
intMat = matrix.new<int>(0, 10)
dnRow = liquidation.Violations.row(0), dnRow.reverse()
upRow = liquidation.Violations.row(1), upRow.reverse()
for i = 0 to strArr.size() - 1
strArr .set(i, strArr.get(i) + str.tostring(dnRow.get(i)))
strArr2.set(i, strArr2.get(i) + str.tostring(upRow.get(i)))
intMat.add_row(0, array.from(0, 1, 0, 1, 0, 1, 0, 1, 0, 1))
intMat.add_row(1, array.from(2, 3, 2, 3, 2, 3, 2, 3, 2, 3))
intMat.add_row(2, array.from(2, 2, 3, 3, 4, 4, 5, 5, 6, 6))
for i = 0 to strArr.size() - 1
liqtab.cell(intMat.get(0, i), intMat.get(2, i), strArr.get (i), text_color = gridDn )
liqtab.cell(intMat.get(1, i), intMat.get(2, i), strArr2.get(i), text_color = gridUp)
if move
netLong = oicsum.row(0), netShort = oicsum.row(1)
for i = bar_index - sbar to 0
if timeMat.Close.get(i).floatGreatEqual(timeMat.Close.get(i + 1))
switch math.sign(timeMat.Difference.get(i)).floatEqual(1)
true => netLong .set(i, timeMat.Difference.get(i)),
netShort.set(i, 0)
=> netLong .set(i, 0),
netShort.set(i, timeMat.Difference.get(i))
else
switch math.sign(timeMat.Difference.get(i)).floatEqual(1)
true => netLong .set(i, 0),
netShort.set(i, timeMat.Difference.get(i))
=> netLong .set(i, timeMat.Difference.get(i)),
netShort.set(i, 0)
netLong.netAdjust(), netShort.netAdjust()
b.set_top(liquidation.Average.row(2).reduced(mult, "N"))
o.set_top(liquidation.Average.row(2).reduced(mult, "P"))
if switchCond
linefill.new(corners.get(2, 0).leftUp, corners.get(0, 0).rightUp, #00000050)
linefill.new(corners.get(3, 0).leftDn, corners.get(1, 0).rightDn, #00000050)
avgN = (math.avg(liquidation.Average.row(2).reduced(mult + 1, "N"), liquidation.Average.row(2).reduced(minlvl - 1, "N")))
avgP = (math.avg(liquidation.Average.row(2).reduced(mult + 1, "P"), liquidation.Average.row(2).reduced(minlvl - 1, "P")))
for i = 1 to math.min(bar_index - sbar, netLong.size() - 1)
netCalc = (liquidation.Average.row(2).reduced(mult + 1, "N")) + ((liquidation.Average.row(2).reduced(minlvl - 1, "N"))
- (liquidation.Average.row(2).reduced(mult + 1, "N" )))
* (netLong.get(i) - netLong.min()) / (netLong.range ())
snetCalc = (liquidation.Average.row(2).reduced(minlvl - 1, "P")) - ((liquidation.Average.row(2).reduced(minlvl - 1, "P"))
- (liquidation.Average.row(2).reduced(mult + 1, "P" )))
* (netShort.get(i) - netShort.min()) / (netShort.range ())
netCalc2 = (liquidation.Average.row(2) .reduced(mult + 1, "N")) + ((liquidation.Average.row(2) .reduced (minlvl - 1, "N"))
- (liquidation.Average.row(2).reduced(mult + 1, "N" )))
* (netLong.get(i - 1) - netLong.min()) / (netLong.range ()),
snetCalc2 = (liquidation.Average.row(2).reduced(minlvl-1, "P")) - ((liquidation.Average.row(2) .reduced(minlvl - 1, "P" ))
- (liquidation.Average.row(2).reduced(mult + 1, "P" )))
* (netShort.get(i - 1) - netShort.min()) / (netShort.range())
line.new(timeMat.Time.get(i + 1), snetCalc, timeMat.Time.get(i),
snetCalc2,
color = gridDn,
xloc = xloc.bar_time,
width = 2
)
line.new(timeMat.Time.get(i + 1), netCalc, timeMat.Time.get(i),
netCalc2,
color = gridUp,
xloc = xloc.bar_time,
width = 2
)
if not move and switchCond
if liquidation.boxLines.size().intGreatEqual(1)
for i = 0 to liquidation.boxLines.size() - 1
liquidation.boxLines.shift().delete()
for i = 0 to 3
if not na(corners.get(i, 0))
switch i % 4
0 => corners.get(0, 0).rightUp.delete()
1 => corners.get(1, 0).rightDn.delete()
2 => corners.get(2, 0).leftUp .delete()
3 => corners.get(3, 0).leftDn .delete()
if linefill.all.size().intGreatEqual(1)
for i = 0 to linefill.all.size() - 1
linefill.all.shift().delete()
if heatmap
count = 0
for i = 0 to grid.rows() - 1
for x = 0 to grid.columns() - 1
grid.get(i, x).set_bottom(liquidation.Average.row(2).reduced(100, "N") + (liquidation.Average.row(2).divSubtract(100, 100) * i))
grid.get(i, x).set_top (liquidation.Average.row(2).reduced(100, "N") + (liquidation.Average.row(2).divSubtract(100, 100) * (i + 1)))
for i = 0 to 4
orientation.set(0, i, grid.get(i, 0).get_top ())
orientation.set(1, i, grid.get(i, 0).get_bottom())
[up1, dn1] = liquidation.Levels.double_binary_search_leftmost (0), [up2, dn2] = liquidation.Levels.double_binary_search_leftmost (1),
[up3, dn3] = liquidation.Levels.double_binary_search_leftmost (2), [up4, dn4] = liquidation.Levels.double_binary_search_leftmost (3),
[up5, dn5] = liquidation.Levels.double_binary_search_leftmost (4)
var finTick = matrix.new<float>(5, 1, 0), var finTick2 = matrix.new<float>(5, 1, 0)
for i = 0 to 20
finTick .finSetVol(i, 0, dn1, up1), finTick .finSetVol(i, 1, dn2, up2)
finTick2.finSetOI (i, 0, dn1, up1), finTick2.finSetOI (i, 1, dn2, up2)
finTick .finSetVol(i, 2, dn3, up3), finTick .finSetVol(i, 3, dn4, up4)
finTick2.finSetOI (i, 2, dn3, up3), finTick2.finSetOI (i, 3, dn4, up4),
finTick .finSetVol(i, 4, dn5, up5),
finTick2.finSetOI (i, 4, dn5, up5)
finTick .add_col(finTick .columns(), finTick .col(finTick .columns() - 1))
finTick2.add_col(finTick2.columns(), finTick2.col(finTick2.columns() - 1))
for i = 0 to grid.rows() - 1
for x = 0 to grid.columns() - 1
[datax, datamin, datamax] = switch OIgrid
false => [finTick .get(i, x), finTick .min(), finTick .max()]
true and syminfo.type.notEqual("crypto") => [finTick .get(i, x), finTick .min(), finTick .max()]
=> [finTick2.get(i, x), finTick2.min(), finTick2.max()]
col = switch math.sign(datax)
0 => color.new(color.gray, 80)
1 => color.from_gradient(datax, 0, datamax, color.new(gridUp, 90), color.new(gridUp, 50))
-1 => color.from_gradient(datax, datamin, 0, color.new(gridDn, 50), color.new(gridDn, 90))
grid.get(i, x).set_bgcolor(col)
if showValues
oiTxt = switch switchCond
true => "\n\nOI: " +
(finTick2.get(i, x).floatGreatEqual(0).determine("+" , "")) + str.tostring(finTick2.get(i, x), "###,###,###.##")
=> ""
grid.get(i, x).set_text(
"VOL: " + str.tostring(finTick.get(i, x), format.volume) + oiTxt)
grid.get(i, x).set_text_color(color.white)
if ext
for i = 0 to grid.rows() - 1
for x = 1 to grid.columns() - 1
[dataCur, dataPrev] = switch OIgrid
false => [finTick .get(i, x), finTick .get(i, x - 1)]
true and syminfo.type.notEqual("crypto") => [finTick .get(i, x), finTick .get(i, x - 1)]
=> [finTick2.get(i, x), finTick2.get(i, x - 1)]
if dataCur.floatEqual(dataPrev)
grid.get(i, x).set_left(grid.get(i, x - 1).get_left())
grid.get(i, x - 1).delete()
if not switchCond
distanceTop = o.get_bottom() - o.get_top()
distanceBot = b.get_top() - b.get_bottom()
o.set_bottom(grid.get(4, 0) .get_top()) , o.set_top(o.get_bottom() + distanceTop)
b.set_top (grid.get(0, 0) .get_bottom()), b.set_bottom(b.get_top() - distanceBot)
else
for i = 0 to grid.rows() - 1
for x = 0 to grid.columns() - 1
grid.get(i, x).delete() |
Adaptive Moving Average with ATR bands | https://www.tradingview.com/script/r4kX90qP-Adaptive-Moving-Average-with-ATR-bands/ | raminyazdanpanah | https://www.tradingview.com/u/raminyazdanpanah/ | 19 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ raminyazdanpanah - 2023
//@version=5
indicator(title = "Adaptive Moving Average with ATR bands", shorttitle="iMA", overlay=true)
// Inputs
length = input.int(title = "Length", defval=8, minval = 0, confirm = true)
fastLength = input.int(title = "Fast EMA Length", defval = 5, minval = 0, confirm = true)
slowLength = input.int(title = "Slow EMA Length", defval = 14, minval = 0, confirm = true)
atrPeriod = input.int(title = "ATR period", defval=14, minval = 0, confirm = true)
atrFactor = input.float(title = "ATR Factor", defval = 0.5, minval = 0, confirm = true)
src = input.source(title="Source", defval=close)
slAtr = input.int(title = "X ATR stop loss", defval = 2, minval = 0, confirm = true)
// Fast and slow constants for EMA's
fastAlpha = 2 / (fastLength + 1)
slowAlpha = 2 / (slowLength + 1)
// Direction
hh = ta.highest(length + 1)
ll = ta.lowest(length + 1)
// Efficiency Ratio
mltp = hh - ll != 0 ? math.abs(2 * src - ll - hh) / (hh - ll) : 0
// Scalable Constant
ssc = mltp * (fastAlpha - slowAlpha) + slowAlpha
// adaptive moving average
ama = 0.0
ama := nz(ama[1]) + math.pow(ssc, 2) * (src - nz(ama[1]))
// ATR bands
halfAtr = ta.atr(atrPeriod) * atrFactor
upperBnad = ama + halfAtr
lowerBand = ama - halfAtr
// Stop loss
sl = slAtr * ta.atr(atrPeriod)
// ploting
plot(ama, title="AMA", linewidth=2, color= color.yellow)
plot(upperBnad, title = "Upper Band", linewidth = 2, color = color.blue)
plot(lowerBand, title = "Lower Band", linewidth = 2, color = color.red)
plot(slAtr*ta.atr(atrPeriod), title = "X ATR stop loss", color = color.orange, display = display.status_line) |
Lower timeframe chart | https://www.tradingview.com/script/0QM38gkn-Lower-timeframe-chart/ | mickes | https://www.tradingview.com/u/mickes/ | 88 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ mickes
//@version=5
indicator("Lower timeframe chart", overlay = true)
var _intMax = 2147483647.
var _intMin = -2147483648.
_timeFrame = input.timeframe("15", "Lower time frame", group = "General")
_slotSizeAtrFactor = input.float(0.1, "Slot size ATR factor", group = "General", tooltip = "Bars are divided into slots (rows), that are decided by this factor of the ATR (14 bars)")
_bigRangeAtrMultiplier = input.float(0.5, "Big range ATR multiplier", group = "General", tooltip = "A bar is considered having a big range if it overgrows ATR (14 bars) times this factor")
_calculateBigRange = input.bool(true, "Calculate big range", group = "General", tooltip = "Takes time to calculate, disable to make the script faster")
_volumeMovingAverageLength = input.int(20, "Volume SMA length", group = "General", tooltip = "Used for defining if a bar is concidered having 'big volume' (when the volume is higher than the SMA it's concidered having 'big volume')")
_calculateBigVolume = input.bool(true, "Calculate big volume", group = "General", tooltip = "Takes time to calculate, disable to make the script faster")
_superTrendBullPercent = input.float(80, "Supertrend bull %", group = "Trend detection", tooltip = "The percentage of bars that must have a bull super trend to be in a bullish trend")
_showTrend = input.bool(true, "Show trend", group = "Trend detection", tooltip = "Shows the current lower timeframe trend (based on super trend), the percentage of bars in bull/bear trend, the bars in bull/bear trend ('/' the total number of bars) and the trend changes")
type TrendType
string TrendString = ""
string Progress = ""
type ChartType
matrix<string> Matrix
TrendType Trend
type LowerTimeFrameBarType
float High = -1
float Low = -1
float Atr = -1
int SuperTrend = -1
bool BigRange = false
bool BigVolume = false
bool Green = false
float Slot = -1
createSlots(slots, min, max, slotSize) =>
i = 0
while true
slot = min + (slotSize * i)
array.push(slots, slot)
if slot >= max
break
i += 1
giveSlots(slots, bars) =>
for [i, bar] in bars
highLow2 = (bar.High + bar.Low) / 2
slotIndex = array.binary_search_leftmost(slots, highLow2)
slot = array.get(slots, slotIndex)
bar.Slot := slot
getUsedSlots(bars) =>
usedSlots = array.new<float>(), filledSlots = 0
for bar in bars
exists = array.includes(usedSlots, bar.Slot)
if not exists
array.push(usedSlots, bar.Slot)
filledSlots += 1
array.sort(usedSlots, order.descending)
[usedSlots, filledSlots]
getChartMatrix(bars, barsSize, usedSlots, filledSlots) =>
greenBar = "โผ", greenBarWick = "โ", redBar = "โ", redBarWick = "โ", greenBarBigVolume = "โช", greenBarBigVolumeTail = "โ", redBarBigVolume = "โฌ", redBarBigVolumeTail = "โ", noRange = "โ", noRangeBigVolume = "โ"
matrixRows = filledSlots + 2, matrixColumns = barsSize + 1, m = matrix.new<string>(matrixRows, matrixColumns, "โ ")
for [row, usedSlot] in usedSlots
for [column, rowBar] in bars
if rowBar.Slot == usedSlot
if rowBar.BigVolume
if rowBar.Green
if rowBar.Low == rowBar.High
matrix.set(m, row + 1, column, noRangeBigVolume)
else
matrix.set(m, row + 1, column, greenBarBigVolume)
if rowBar.BigRange
matrix.set(m, row, column, greenBarBigVolumeTail)
else
if rowBar.Low == rowBar.High
matrix.set(m, row + 1, column, noRangeBigVolume)
else
matrix.set(m, row + 1, column, redBarBigVolume)
if rowBar.BigRange
matrix.set(m, row + 2, column, redBarBigVolumeTail)
else
if rowBar.Green
if rowBar.Low == rowBar.High
matrix.set(m, row + 1, column, noRange)
else
matrix.set(m, row + 1, column, greenBar)
if rowBar.BigRange
matrix.set(m, row, column, greenBarWick)
else
if rowBar.Low == rowBar.High
matrix.set(m, row + 1, column, noRange)
else
matrix.set(m, row + 1, column, redBar)
if rowBar.BigRange
matrix.set(m, row + 2, column, redBarWick)
[m, matrixRows, matrixColumns]
getChartFromMatrix(m, matrixRows) =>
chart = ""
for i = 0 to matrixRows - 1
matrixRow = matrix.row(m, i)
rowString = array.join(matrixRow, "")
if str.length(str.replace_all(rowString, "โ ", "")) == 0
continue // skip empty row
if str.length(chart) == 0
chart += str.format("{0}", rowString)
else
chart += str.format("\n{0}", rowString)
chart
// taken from KivancOzbilgic script SuperTrend (https://www.tradingview.com/script/r6dAP7yi)
superTrend(atrLength, source, atrFactor) =>
atr = ta.atr(atrLength)
up = source - (atrFactor * atr)
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = source + (atrFactor * atr)
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == 0 and close > dn1 ? 1 : trend == 1 and close < up1 ? 0 : trend
trend
getSuperTrendString(superTrends, barsSize) =>
string superTrendString = na
for i = 0 to barsSize - 1
superTrend = array.get(superTrends, i)
currentSuperTrend = superTrend == 1 ? "๐" : "๐"
if i > 0
previousSuperTrend = array.get(superTrends, i - 1)
if previousSuperTrend != superTrend
superTrendString += currentSuperTrend
else if i == 0
superTrendString += currentSuperTrend
superTrendString
getTrend(superTrends, bars) =>
trend = TrendType.new()
trends = array.sum(superTrends)
superTrendString = getSuperTrendString(superTrends, bars)
supertrendMinimumBull = bars * (_superTrendBullPercent * 0.01)
if trends >= supertrendMinimumBull
trend.TrendString := "Bull"
trend.Progress := str.format("{0,number,###.#}% ({1}/{2}) {3}", (trends / bars) * 100, trends, bars, superTrendString)
else
trend.TrendString := "Bear"
trend.Progress := str.format("{0,number,###.#}% ({1}/{2}) {3}", ((bars - trends) / bars) * 100, bars - trends, bars, superTrendString)
trend
getLowerTimeFrameBar() =>
atr = ta.atr(14)
superTrend = superTrend(10, hl2, 3)
volumeMovingAverage = ta.sma(volume, _volumeMovingAverageLength)
bigRange = _calculateBigRange ? ((high - low) / 2) > (atr * _bigRangeAtrMultiplier) : false
bigVolume = _calculateBigVolume ? volume > volumeMovingAverage : false
Green = close >= open ? true : false
bar = LowerTimeFrameBarType.new(high, low, atr, superTrend, bigRange, bigVolume, Green)
bar
getLowerTimeFrameChart(lowerTimeFrameBars, lowerTimeFrameBarsSize) =>
lowerTimeFramechart = ChartType.new()
slotSize = 0., slots = array.new<float>(), superTrends = array.new<int>()
for [i, bar] in lowerTimeFrameBars
if i == lowerTimeFrameBarsSize - 1
slotSize := bar.Atr * _slotSizeAtrFactor // get last atr for slot size
if _showTrend
array.push(superTrends, bar.SuperTrend)
bars = array.size(lowerTimeFrameBars)
createSlots(slots, low, high, slotSize)
giveSlots(slots, lowerTimeFrameBars)
[usedSlots, filledSlots] = getUsedSlots(lowerTimeFrameBars)
[m, matrixRows, matrixColumns] = getChartMatrix(lowerTimeFrameBars, bars, usedSlots, filledSlots)
lowerTimeFramechart.Matrix := m
if _showTrend
lowerTimeFramechart.Trend := getTrend(superTrends, bars)
lowerTimeFramechart
drawChart(lowerTimeFramechart) =>
matrixRows = matrix.rows(lowerTimeFramechart.Matrix), matrixColumns = matrix.columns(lowerTimeFramechart.Matrix)
chart = getChartFromMatrix(lowerTimeFramechart.Matrix, matrixRows)
var lightTheme = color.r(chart.bg_color) == 255
var labelColor = lightTheme ? color.new(color.black, 90) : color.new(color.white, 90)
var labelTextColor = lightTheme ? color.black : color.white
var l = label.new(bar_index, 0, "", style = label.style_label_lower_left, color = labelColor, textcolor = labelTextColor, text_font_family = font.family_monospace)
txt = _showTrend ? str.format("{0}\n{1} ({2})", chart, lowerTimeFramechart.Trend.TrendString, lowerTimeFramechart.Trend.Progress) : chart
label.set_text(l,txt)
label.set_x(l, bar_index)
label.set_y(l, high)
alertIfTrendChange(trend) =>
var string originalTrend = na
if not na(originalTrend)
if trend != originalTrend
alert(str.format("Lower time frame trend change (from {0} to {1})", str.lower(originalTrend), str.lower(trend)), alert.freq_once_per_bar_close)
originalTrend := trend
if na(originalTrend)
originalTrend := trend
lowerTimeFrameBars = request.security_lower_tf(syminfo.tickerid, _timeFrame, getLowerTimeFrameBar())
lowerTimeFrameBarsSize = array.size(lowerTimeFrameBars)
if barstate.islast
and lowerTimeFrameBarsSize > 0
lowerTimeFrameChart = getLowerTimeFrameChart(lowerTimeFrameBars, lowerTimeFrameBarsSize)
if lowerTimeFrameBarsSize > 1 // only draw chart if more than one bar is available
drawChart(lowerTimeFrameChart)
if _showTrend
alertIfTrendChange(lowerTimeFrameChart.Trend.TrendString) |
Drawdown Dynamics Indicator | https://www.tradingview.com/script/pBkbqw3d-Drawdown-Dynamics-Indicator/ | TradeAutomation | https://www.tradingview.com/u/TradeAutomation/ | 17 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// Author ยฉ TradeAutomation
indicator("Drawdown Dynamics Indicator")
//Measures All Time High of Asset
var float ATH = na
ATH := if na(ATH[1])
high
else
math.max(high,ATH[1])
//Measures Drawdown
Drawdown=100-(low/ATH)*100
//Measures Total Max Drawdown
var float MaxDrawdown = Drawdown
MaxDrawdown := if na(MaxDrawdown[1])
Drawdown
else
math.max(Drawdown,MaxDrawdown[1])
//Measures Rolling Period Max Drawdown
RollingMDD = ta.highest(Drawdown, input.int(200, "Length of Rolling Period Max Drawdown"))
UseAllTime = input.bool(false, "Use All Time Max Drawdown Instead of Rolling Period?")
//Visualizations
plot(UseAllTime==false ? RollingMDD : MaxDrawdown, "Max Drawdown", color=color.gray,linewidth=2)
plot(Drawdown, "Current Drawdown", color=color.blue,linewidth=1) |
ICT Friday's Asian Rangeยฐ | https://www.tradingview.com/script/ZNxT4jDx-ICT-Friday-s-Asian-Range/ | toodegrees | https://www.tradingview.com/u/toodegrees/ | 619 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ toodegrees
//@version=5
indicator("ICT Friday's Asian Range", shorttitle="Fri Asian Rangeยฐ", overlay=true, max_bars_back=500, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
if not(timeframe.in_seconds(timeframe.period) == timeframe.in_seconds("5") or timeframe.in_seconds(timeframe.period) == timeframe.in_seconds("15"))
runtime.error("Go to the 5 Minute or 15 Minute Chart!")
//#region[GLOBAL]
tooUtils_lineStyle(string _style) =>
style = switch _style
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
"Solid" => line.style_solid
style
noColor = color.new(color.white,100)
//#endregion
//#region[USER INPUT]
showLast = input.int(0 , title="Historical Sessions" , minval=0 , maxval=20)
arBodyBoxColor = input.color(color.new(#000000, 80), title="Box" , group="Asian Range (Body)", inline='B')
arBodyLineColor = input.color(#000000 , title="Line" , group="Asian Range (Body)", inline='B')
arBodyLineStyle = tooUtils_lineStyle(input.string("Dotted" , title="" , group="Asian Range (Body)", inline='B', options=["Dotted", "Dashed", "Solid"]))
arBodyLineWidth = input.int(1 , title="" , group="Asian Range (Body)", inline='B', minval=1)
arWickBoxColor = input.color(color.new(#388e3c, 80), title="Box" , group="Asian Range (Wick)", inline='W')
arWickLineColor = input.color(#388e3c , title="Line" , group="Asian Range (Wick)", inline='W')
arWickLineStyle = tooUtils_lineStyle(input.string("Dotted" , title="" , group="Asian Range (Wick)", inline='W', options=["Dotted", "Dashed", "Solid"]))
arWickLineWidth = input.int(1 , title="" , group="Asian Range (Wick)", inline='W', minval=1)
arBodyAlert = input.bool(false , title="" , group="Alerts" , inline='b')
arBodyAlertLine = input.string("3B" , title="+/- Stdev" , group="Alerts" , inline='b', options=["1B", "2B", "3B", "4B", "5B"])
arWickAlert = input.bool(false , title="" , group="Alerts" , inline='w')
arWickAlertLine = input.string("3W" , title="+/- Stdev" , group="Alerts" , inline='w', options=["1W", "2W", "3W", "4W", "5W"])
//#endregion
//#region[DECLARATIONS & FUNCTION]
var asian_range = array.new_box(), var asian_stdev = array.new_line(), var asian_label = array.new_label()
var int ar_start = na , var float ar_bodyHigh = na , var float ar_wickHigh = na
var int ar_end = na , var float ar_bodyLow = na , var float ar_wickLow = na
var alert_BodyUp = false , var float alert_level_BodyUp = na
var alert_BodyDw = false , var float alert_level_BodyDw = na
var alert_WickUp = false , var float alert_level_WickUp = na
var alert_WickDw = false , var float alert_level_WickDw = na
tooUtils_alertLine(string ID, string TYPE, float PRICE=na) =>
if na(PRICE)
if ID+TYPE == arBodyAlertLine
ar_start+(7*86400000)
else if ID+TYPE == arWickAlertLine
ar_start+(7*86400000)
else
ar_end
else
if ID+TYPE == arBodyAlertLine
PRICE
else if ID+TYPE == arWickAlertLine
PRICE
else
na
//#endregion
//#region[LOGIC]
range_time = time("1","1900-2359:5","America/New_York")
if range_time
if not(range_time[1])
ar_start := time
ar_bodyHigh := math.max(open,close)
ar_bodyLow := math.min(open,close)
ar_wickHigh := high
ar_wickLow := low
ar_bodyHigh := math.max(math.max(open,close), ar_bodyHigh)
ar_bodyLow := math.min(math.min(open,close), ar_bodyLow )
ar_wickHigh := math.max(high, ar_wickHigh)
ar_wickLow := math.min(low , ar_wickLow )
//#endregion
//#region[PLOT]
else
if range_time[1]
alert_BodyUp := true
alert_BodyDw := true
alert_WickUp := true
alert_WickDw := true
ar_end := time
body_Range = ar_bodyHigh-ar_bodyLow
wick_Range = ar_wickHigh-ar_wickLow
asian_range.unshift(box.new(ar_start, ar_bodyHigh, ar_end, ar_bodyLow, noColor, 0, xloc=xloc.bar_time, bgcolor=arBodyBoxColor))
asian_range.unshift(box.new(ar_start, ar_wickHigh, ar_end, ar_wickLow, noColor, 0, xloc=xloc.bar_time, bgcolor=arWickBoxColor))
for i=1 to 5 by 1
stdev_bodyUp = ar_bodyHigh+(i*body_Range)
stdev_bodyDw = ar_bodyLow-(i*body_Range)
stdev_wickUp = ar_wickHigh+(i*wick_Range)
stdev_wickDw = ar_wickLow-(i*wick_Range)
level_BodyUp = tooUtils_alertLine(str.tostring(i), "B", stdev_bodyUp)
level_BodyDw = tooUtils_alertLine(str.tostring(i), "B", stdev_bodyDw)
level_WickUp = tooUtils_alertLine(str.tostring(i), "W", stdev_wickUp)
level_WickDw = tooUtils_alertLine(str.tostring(i), "W", stdev_wickDw)
alert_level_BodyUp := na(level_BodyUp)?alert_level_BodyUp:level_BodyUp
alert_level_BodyDw := na(level_BodyDw)?alert_level_BodyDw:level_BodyDw
alert_level_WickUp := na(level_WickUp)?alert_level_WickUp:level_WickUp
alert_level_WickDw := na(level_WickDw)?alert_level_WickDw:level_WickDw
asian_stdev.unshift(line.new(ar_start, stdev_bodyUp, int(tooUtils_alertLine(str.tostring(i), "B")), stdev_bodyUp, color=arBodyLineColor, style=arBodyLineStyle, width=arBodyLineWidth, xloc=xloc.bar_time))
asian_stdev.unshift(line.new(ar_start, stdev_bodyDw, int(tooUtils_alertLine(str.tostring(i), "B")), stdev_bodyDw, color=arBodyLineColor, style=arBodyLineStyle, width=arBodyLineWidth, xloc=xloc.bar_time))
asian_stdev.unshift(line.new(ar_start, stdev_wickUp, int(tooUtils_alertLine(str.tostring(i), "W")), stdev_wickUp, color=arWickLineColor, style=arWickLineStyle, width=arWickLineWidth, xloc=xloc.bar_time))
asian_stdev.unshift(line.new(ar_start, stdev_wickDw, int(tooUtils_alertLine(str.tostring(i), "W")), stdev_wickDw, color=arWickLineColor, style=arWickLineStyle, width=arWickLineWidth, xloc=xloc.bar_time))
asian_label.unshift(label.new(ar_start, stdev_bodyUp, "+"+str.tostring(i)+"B", color=noColor, style=label.style_label_right, textcolor=arBodyLineColor, size=size.small, text_font_family=font.family_monospace, xloc=xloc.bar_time, tooltip=str.tostring(stdev_bodyUp)))
asian_label.unshift(label.new(ar_start, stdev_bodyDw, "-"+str.tostring(i)+"B", color=noColor, style=label.style_label_right, textcolor=arBodyLineColor, size=size.small, text_font_family=font.family_monospace, xloc=xloc.bar_time, tooltip=str.tostring(stdev_bodyDw)))
asian_label.unshift(label.new(ar_start, stdev_wickUp, "+"+str.tostring(i)+"W", color=noColor, style=label.style_label_right, textcolor=arWickLineColor, size=size.small, text_font_family=font.family_monospace, xloc=xloc.bar_time, tooltip=str.tostring(stdev_wickUp)))
asian_label.unshift(label.new(ar_start, stdev_wickDw, "-"+str.tostring(i)+"W", color=noColor, style=label.style_label_right, textcolor=arWickLineColor, size=size.small, text_font_family=font.family_monospace, xloc=xloc.bar_time, tooltip=str.tostring(stdev_wickDw)))
if asian_range.size() > (showLast+1)*2
for i=1 to 2 by 1
box.delete(asian_range.pop())
for i=1 to 20 by 1
line.delete(asian_stdev.pop())
label.delete(asian_label.pop())
//#endregion
//#region[ALERTS]
if arBodyAlert
if high>alert_level_BodyUp and alert_BodyUp
alert_BodyUp := false
alert(ticker.standard(syminfo.ticker)+" Crossing Friday's Asian Range +"+arBodyAlertLine+" Standard Deviation @ "+str.tostring(alert_level_BodyUp), alert.freq_once_per_bar)
if low<alert_level_BodyDw and alert_BodyDw
alert_BodyDw := false
alert(ticker.standard(syminfo.ticker)+" Crossing Friday's Asian Range -"+arBodyAlertLine+" Standard Deviation @ "+str.tostring(alert_level_BodyDw), alert.freq_once_per_bar)
if arWickAlert
if high>alert_level_WickUp and alert_WickUp
alert_WickUp := false
alert(ticker.standard(syminfo.ticker)+" Crossing Friday's Asian Range +"+arWickAlertLine+" Standard Deviation @ "+str.tostring(alert_level_WickUp), alert.freq_once_per_bar)
if low<alert_level_WickDw and alert_WickDw
alert_WickDw := false
alert(ticker.standard(syminfo.ticker)+" Crossing Friday's Asian Range -"+arWickAlertLine+" Standard Deviation @ "+str.tostring(alert_level_WickDw), alert.freq_once_per_bar)
//#endregion |
AlexD Intraday market footprint | https://www.tradingview.com/script/uKBJlxwg-alexd-intraday-market-footprint/ | AlexD169 | https://www.tradingview.com/u/AlexD169/ | 9 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Aleksey Demchenko / AlexD
//@version=5
indicator(title="AlexD Intraday market footprint", shorttitle="IMF", format=format.price, precision=2, max_bars_back=5000)
//Init
DaysN = input.int(30, title="Number of days", minval=1, maxval=128)
FilterK = input.int(10, title="SMA filter period", minval=1, maxval=64)
Smooth = input.int(2, title="IMF smooth period", minval=1, maxval=64)
SignalLine = input.int(6, title="IMF predict period", minval=1, maxval=64)
Preshift = input.int(8, title="Skip N hours in days(optimisation)", minval=0, maxval=23)
i = FilterK
DaysChecked = 0
ReversalsFound = 0
IMF_Base = 0.0
IMF_Predict = 0.0
PrevDayBarIndex = 0
PrevDayIMF_Base = 0.0
PrevDayIMF_Predict = 0.0
//Levels
hline(1.0, "Maximum level", color=color.gray)
hline(0.9, "Linearity level", color=color.green)
hline(0.5, "Middle level", color=color.gray)
hline(0.33, "Reversal level", color=color.maroon)
//Chart filter
price_signal = ta.sma((high+low+close)/3, FilterK)
if((timeframe.isminutes) and (timeframe.multiplier < 61))
//IMF calculation
while( (DaysChecked < DaysN) and (i < 4999 - (FilterK+Smooth+Preshift)*(60/timeframe.multiplier)) )
i += 1
if( (hour == hour[i]) and (minute == minute[i]) )
if(DaysChecked == 0)
PrevDayBarIndex := bar_index[i]
DaysChecked += 1
if( ((price_signal[i-int(FilterK/2.0)] > price_signal[i-int(FilterK/2.0)+1]) and (price_signal[i-int(FilterK/2.0)+1] > price_signal[i-int(FilterK/2.0)+2])) or
((price_signal[i-int(FilterK/2.0)] < price_signal[i-int(FilterK/2.0)+1]) and (price_signal[i-int(FilterK/2.0)+1] < price_signal[i-int(FilterK/2.0)+2])) )
ReversalsFound += 1
i += int(60/timeframe.multiplier*Preshift)
IMF_Base := ta.sma(ReversalsFound/DaysChecked, Smooth)
//IMF Predict calculation
IMF_Predict := IMF_Base
i := 1
while i < SignalLine
IMF_Predict *= IMF_Base[i]
i += 1
//Drawing the first values according to the data of the previous day
if(bar_index > last_bar_index-SignalLine-int(Smooth/2.0))
PrevDayIMF_Predict := IMF_Predict[bar_index-PrevDayBarIndex-SignalLine-int(Smooth/2.0)+1]
if(bar_index > last_bar_index-int(Smooth/2.0)-1)
PrevDayIMF_Base := IMF_Base[bar_index-PrevDayBarIndex-int(Smooth/2.0)]
else
PrevDayIMF_Base := na
else
PrevDayIMF_Predict := na
PrevDayIMF_Base := na
else if barstate.islastconfirmedhistory
//TIMEFRAME ERROR
label.new(bar_index, 0, style=label.style_label_right,
size=size.normal, color=color.black, textcolor=color.white,
text="Invalid timeframe! Choose a chart from 1M to 1H.")
//Indicator view
plot(IMF_Base, title="IMF", color=color.silver, offset=-int(Smooth/2.0))
plot(IMF_Predict, title="IMF Predict", color=color.fuchsia, offset=-SignalLine-int(Smooth/2.0)+1)
plot(PrevDayIMF_Base, title="Prev day IMF", color=color.red, style=plot.style_line)
plot(PrevDayIMF_Predict, title="Prev day IMF Predict", color=color.red, style=plot.style_line) |
Crunchster's Real Price | https://www.tradingview.com/script/XSAfS653-Crunchster-s-Real-Price/ | Crunchster1 | https://www.tradingview.com/u/Crunchster1/ | 14 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Crunchster1
//@version=5
indicator("Crunchster's Real Price", overlay = true, scale = scale.none)
//Inputs
src = input(close, "Source")
length = input.int(title="Lookback period for normalisation filter", defval=14, minval=2, tooltip='This adjusts the lookback period for the volatility filter used to transform the original price series.')
roll = input.int(title="Rolling window length", defval=365, minval=10, tooltip='This value will adjust the length of the rolling lookback period over which the normalised price is summated. This only affects the normalised price over a rolling period')
// Calculation of normalised period returns
returns = (src - src[1]) / ta.stdev((src - src[1]), length)
// Convert the Normalised returns per period into a price series
nReal = ta.cum(returns)
nRolling = math.sum(returns, roll)
plot(nReal, title = "Real Price", color=color.new(#3d3ddd, 0))
plot(nRolling, title = "Normalised price series over rolling period", color=color.new(#000000, 0), display=display.none)
|
JeeSauceScripts | https://www.tradingview.com/script/1901t5ve-JeeSauceScripts/ | jeesauce | https://www.tradingview.com/u/jeesauce/ | 6 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ jeesauce
//Some of the formula here in the library are from https://www.tradingview.com/script/NlM312nK-CVD-Cumulative-Volume-Delta-Candles/
//@version=5
library("JeeSauceScripts", overlay = true)
//Get Up and Down Volume
export getupdnvol() =>
float positivevol = 0.0
float negativevol = 0.0
switch
//
close > open => positivevol += volume
close < open => negativevol -= volume
//
close > nz(close[1]) => positivevol += volume
close < nz(close[1]) => negativevol -= volume
//
nz(positivevol[1]) > 0 => positivevol += volume
nz(negativevol[1]) < 0 => negativevol -= volume
[positivevol, negativevol]
//Get Total Positive Volume
export GetTotalUpVolume(float[] upvolume) =>
nz(array.sum(upvolume))
//Get Total Negative Volume
export GetTotalDnVolume(float[] downvolume) =>
nz(array.sum(downvolume))
//Get Delta
export GetDelta(float totalupvolume, float totaldownvolume) =>
totalupvolume + totaldownvolume
//Get Max Positive Volume
export GetMaxUpVolume(float[] upvolume) =>
nz(array.max(upvolume))
//Get Max Negative Volume
export GetMaxDnVolume(float[] downvolume) =>
nz(array.min(downvolume))
//Get CVD
export Getcvd() =>
var float cvd = 0.0
//Get CVD Open
export Getcvdopen(float cvd) =>
cvd
//Get CVD High
export Getcvdhigh(float cvd, float maxvolumeup) =>
cvd + maxvolumeup
//Get CVD Low
export Getcvdlow(float cvd, float maxvolumedown) =>
cvd + maxvolumedown
//Get CVD Close
export Getcvdclose(float cvd, float delta) =>
cvd + delta
//Add 6 numbers
export CombineData(float data1, float data2, float data3, float data4, float data5, float data6) =>
data1 + data2 + data3 + data4 + data5 + data6
//Find a Certain Character
export FindData(string data, string find) =>
str.contains(data, find)
|
EMA Envelope - Signal with Stoploss and Takeprofit Levels | https://www.tradingview.com/script/1F0CF76a-EMA-Envelope-Signal-with-Stoploss-and-Takeprofit-Levels/ | hellomuthu23 | https://www.tradingview.com/u/hellomuthu23/ | 70 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ hellomuthu23
//@version=5
indicator("EMA Envelope Indicator with Buy/Sell Signal with Stoploss and Takeprofit Levels","EMA Envelope Signal",true)
// Input Parameters
EMA_Length=input(title="EMA Length", defval=20) // Short-term Exponential Moving Average length
EMA_LongTerm_Length = input(title = "Long Term EMA length",defval = 200) // Long-term Exponential Moving Average length
TakeProfit_Ratio = input.float(title="Take Profit Ratio", defval = 2.0, minval = 0.1) // Take Profit ratio for calculating take-profit levels
Filter_Signal_On_LongTerm_EMA = input(title="Filter Signal on Long Term EMA", defval = true) // Option to filter signals using long-term EMA
Show_Only_Recent_Signals = input(title = "Show only recent signal", defval = false) // Option to show only recent buy/sell signals
// Data Setup
src = close // Source data for calculations
e = ta.ema(close, EMA_Length) // Short-term Exponential Moving Average
eu = ta.ema(high, EMA_Length) // Upper EMA (based on high prices)
el = ta.ema(low, EMA_Length) // Lower EMA (based on low prices)
LongTermEMA=ta.ema(close, EMA_LongTerm_Length) // Long-term Exponential Moving Average
// Plotting EMAs
plot(e, style=plot.style_circles, color=color.gray)
plot1 = plot(eu, title="Upper EMA", color=color.lime, linewidth=2 )
plot2 = plot(el, title="Lower EMA", color=color.aqua, linewidth=2 )
fill(plot1=plot1, plot2=plot2, color=color.gray, transp=50)
plot(LongTermEMA, title = "LongTerm EMA", color=color.new(color.blue, 30), linewidth=3)
// Buy and Sell Signal Conditions
longCond = low[0] > eu and low[1] < eu[1]
if Filter_Signal_On_LongTerm_EMA
longCond := longCond and close > LongTermEMA
shortCond = high[0] < el and high[1] > el[1]
if Filter_Signal_On_LongTerm_EMA
shortCond := shortCond and close < LongTermEMA
// Plot Buy and Sell Signals
plotshape(series=longCond, title="Buy signal", show_last = Show_Only_Recent_Signals? 100: 10000, style=shape.triangleup, location=location.belowbar, color=color.green, text="Buy", textcolor = color.lime, size=size.tiny)
plotshape(series=shortCond, title="Sell signal",show_last = Show_Only_Recent_Signals? 100: 10000, style=shape.triangledown, location=location.abovebar, color=color.red, text="Sell", textcolor = color.red, size=size.tiny)
// Calculate Stop-Loss and Take-Profit Levels
longStopLoss = el // Long position stop-loss at the lower EMA
longTakProfit = ((low - longStopLoss) * TakeProfit_Ratio) + low // Long position take-profit calculation
if longCond == false // If not in a long position, set stop-loss and take-profit to 'na' (not available)
longStopLoss := na
longTakProfit := na
shortStopLoss = eu // Short position stop-loss at the upper EMA
shortTakProfit = high - (( shortStopLoss - high) * TakeProfit_Ratio) // Short position take-profit calculation
if shortCond == false // If not in a short position, set stop-loss and take-profit to 'na'
shortStopLoss := na
shortTakProfit := na
// Plot Stop-Loss and Take-Profit Levels
plot(longTakProfit , "Long TP", color.green, 3, plot.style_linebr, show_last = Show_Only_Recent_Signals? 100: 10000)
plot(longStopLoss , "Long SL", color.purple, 5, plot.style_linebr, show_last = Show_Only_Recent_Signals? 100: 10000)
plot(shortTakProfit , "Short TP", color.green, 3, plot.style_linebr,show_last = Show_Only_Recent_Signals? 100: 10000 )
plot(shortStopLoss , "Short SL", color.purple, 5, plot.style_linebr, show_last = Show_Only_Recent_Signals? 100: 10000)
|
Retest Support Resistance Signals [ChartPrime] | https://www.tradingview.com/script/E4joH77u-Retest-Support-Resistance-Signals-ChartPrime/ | ChartPrime | https://www.tradingview.com/u/ChartPrime/ | 1,398 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// รยฉ ChartPrime
//@version=5
indicator(title = "Support/Resistance Re-test Finder [ChartPrime]", overlay = true, max_lines_count = 500)
// { <CONSTANTS>
MAIN_GROUP = "Main Settings"
DELETE_GROUP = "Deletion Settings"
COSMETIC_GROUP = "Cosmetic Settings"
// } <CONSTANTS>
// { <INPUTS>
levelMethod = input.string(
title = "Detection Method",
defval = "Wick",
options = ["Wick", "Body"],
group = MAIN_GROUP)
leftBars = input.int(
title = "Left Bars",
defval = 20,
group = MAIN_GROUP,
inline = "pivot")
rightBars = input.int(
title = "Right Bars",
defval = 20,
group = MAIN_GROUP,
inline = "pivot")
retestLogic = input.bool(
title = "Retest Weaker",
defval = false,
tooltip = "Retest makes level weaker vs retest makes level stronger",
group = MAIN_GROUP)
definitionOfDelete = input.string(
title = "Delete Definition",
defval = "Stop Updating Level",
options = ["Stop Updating Level", "Completely Delete Level", "Stop Updating Level & Turn Level Unique Color"],
group = DELETE_GROUP)
flipsUntilDeletion = input.int(
title = "Breakouts Until Level Deletes",
defval = 1,
group = DELETE_GROUP)
ageUntilDeletion = input.int(
title = "Bars Until Level Deletes",
defval = 300,
group = DELETE_GROUP)
supportColor = input.color(
title = "Initial Support Re-Test Color",
defval = color.rgb(76, 175, 79, 50),
group = COSMETIC_GROUP)
resistanceColor = input.color(
title = "Initial Resistance Re-Test Color",
defval = color.rgb(255, 82, 82, 50),
group = COSMETIC_GROUP)
uniqueDeleteColor = input.color(
title = "Unique Deletion Color",
defval = color.rgb(120, 123, 134, 50),
group = COSMETIC_GROUP)
changeColorMethod = input.string(
title = "Change Color Method",
defval = "Price Above/Below",
options = ["Price Above/Below", "Fade Out Based On Age"],
group = COSMETIC_GROUP)
lineWidth = input.int(
title = "Line Width",
defval = 10,
group = COSMETIC_GROUP)
// } <INPUTS>
// { <USER DEFINED TYPES>
type flipLevelManager
array<string> variation
array<line> lineArray
array<int> lineAge
array<int> lineFlips
array<int> linePhase
// } <USER DEFINED TYPES>
// { <CALCULATIONS>
pivotHigh = ta.pivothigh(
levelMethod == "Wick" ?
high : close > open ? close : open,
leftBars,
rightBars)
pivotLow = ta.pivotlow(
levelMethod == "Wick" ?
low : close < open ? close : open,
leftBars,
rightBars)
newHigh = not na(pivotHigh)
newLow = not na(pivotLow)
newTestedSupport = false
newTestedResistance = false
supportBrokeDownside = false
supportBrokeUpside = false
resistanceBrokeDownside = false
resistanceBrokeUpside = false
var firstPhaseHigh = array.new_float()
var firstPhaseHighI = array.new_int()
var firstPhaseLow = array.new_float()
var firstPhaseLowI = array.new_int()
var secondPhaseHigh = array.new_float()
var secondPhaseHighI = array.new_int()
var secondPhaseLow = array.new_float()
var secondPhaseLowI = array.new_int()
var flipManager = flipLevelManager.new(
array.new_string(),
array.new_line(),
array.new_int(),
array.new_int(),
array.new_int())
if barstate.isconfirmed
if newHigh
array.push(firstPhaseHigh, pivotHigh)
array.push(firstPhaseHighI, bar_index[rightBars])
if newLow
array.push(firstPhaseLow, pivotLow)
array.push(firstPhaseLowI, bar_index[rightBars])
for i = array.size(secondPhaseHigh) > 0 ? array.size(secondPhaseHigh) - 1 : na to 0
price = array.get(secondPhaseHigh, i)
index = array.get(secondPhaseHighI, i)
if low <= price and close > price and close > open
newLine = line.new(
x1 = index, y1 = price,
x2 = bar_index, y2 = price,
xloc = xloc.bar_index, extend = extend.none,
color = supportColor, width = lineWidth)
array.push(flipManager.lineArray, newLine)
array.push(flipManager.variation, "Support")
array.push(flipManager.lineAge, 0)
array.push(flipManager.lineFlips, 0)
array.push(flipManager.linePhase, 1)
array.remove(secondPhaseHigh, i)
array.remove(secondPhaseHighI, i)
newTestedSupport := true
else if bar_index - index > 1000 or close < price
array.remove(secondPhaseHigh, i)
array.remove(secondPhaseHighI, i)
for i = array.size(secondPhaseLow) > 0 ? array.size(secondPhaseLow) - 1 : na to 0
price = array.get(secondPhaseLow, i)
index = array.get(secondPhaseLowI, i)
if high >= price and close < price and close < open
newLine = line.new(
x1 = index, y1 = price,
x2 = bar_index, y2 = price,
xloc = xloc.bar_index, extend = extend.none,
color = resistanceColor, width = lineWidth)
array.push(flipManager.lineArray, newLine)
array.push(flipManager.variation, "Resistance")
array.push(flipManager.lineAge, 0)
array.push(flipManager.lineFlips, 0)
array.push(flipManager.linePhase, -1)
array.remove(secondPhaseLow, i)
array.remove(secondPhaseLowI, i)
newTestedResistance := true
else if bar_index - index > 1000 or close > price
array.remove(secondPhaseLow, i)
array.remove(secondPhaseLowI, i)
for i = array.size(firstPhaseHigh) > 0 ? array.size(firstPhaseHigh) - 1 : na to 0
price = array.get(firstPhaseHigh, i)
index = array.get(firstPhaseHighI, i)
if low > price
array.push(secondPhaseHigh, price)
array.push(secondPhaseHighI, index)
array.remove(firstPhaseHigh, i)
array.remove(firstPhaseHighI, i)
else if bar_index - index > 1000
array.remove(firstPhaseHigh, i)
array.remove(firstPhaseHighI, i)
for i = array.size(firstPhaseLow) > 0 ? array.size(firstPhaseLow) - 1 : na to 0
price = array.get(firstPhaseLow, i)
index = array.get(firstPhaseLowI, i)
if high < price
array.push(secondPhaseLow, price)
array.push(secondPhaseLowI, index)
array.remove(firstPhaseLow, i)
array.remove(firstPhaseLowI, i)
else if bar_index - index > 1000
array.remove(firstPhaseLow, i)
array.remove(firstPhaseLowI, i)
for i = array.size(flipManager.lineArray) > 0 ? array.size(flipManager.lineArray) - 1 : na to 0
lineObject = array.get(flipManager.lineArray, i)
lineAge = array.get(flipManager.lineAge, i)
lineType = array.get(flipManager.variation, i)
lineFlips = array.get(flipManager.lineFlips, i)
linePhase = array.get(flipManager.linePhase, i)
linePrice = line.get_y1(lineObject)
line.set_x2(lineObject, bar_index + 1)
lineColor = lineType == "Support" ? supportColor : resistanceColor
gradientLineColor = color.from_gradient(lineAge, 0, ageUntilDeletion, lineColor, color.new(lineColor, 100))
newLineColor = changeColorMethod == "Fade Out Based On Age" ?
gradientLineColor : close > linePrice ? supportColor : resistanceColor
line.set_color(lineObject, newLineColor)
array.set(flipManager.lineAge, i, lineAge + 1)
if lineType == "Support"
if linePhase == 1 and close < linePrice
array.set(flipManager.lineFlips, i, lineFlips + 1)
array.set(flipManager.linePhase, i, -1)
supportBrokeDownside := true
else if linePhase == -1 and close > linePrice
array.set(flipManager.lineFlips, i, lineFlips + 1)
array.set(flipManager.linePhase, i, 1)
supportBrokeUpside := true
if lineType == "Resistance"
if linePhase == -1 and close > linePrice
array.set(flipManager.lineFlips, i, lineFlips + 1)
array.set(flipManager.linePhase, i, 1)
resistanceBrokeUpside := true
else if linePhase == 1 and close < linePrice
array.set(flipManager.lineFlips, i, lineFlips + 1)
array.set(flipManager.linePhase, i, -1)
resistanceBrokeDownside := true
lineFlips := array.get(flipManager.lineFlips, i)
if lineFlips >= flipsUntilDeletion or lineAge >= ageUntilDeletion
if definitionOfDelete == "Completely Delete Level"
line.delete(lineObject)
array.remove(flipManager.lineArray, i)
array.remove(flipManager.lineAge, i)
array.remove(flipManager.lineFlips, i)
array.remove(flipManager.variation, i)
array.remove(flipManager.linePhase, i)
else if definitionOfDelete == "Stop Updating Level"
array.remove(flipManager.lineArray, i)
array.remove(flipManager.lineAge, i)
array.remove(flipManager.lineFlips, i)
array.remove(flipManager.variation, i)
array.remove(flipManager.linePhase, i)
else if definitionOfDelete == "Stop Updating Level & Turn Level Unique Color"
line.set_color(lineObject, uniqueDeleteColor)
array.remove(flipManager.lineArray, i)
array.remove(flipManager.lineAge, i)
array.remove(flipManager.lineFlips, i)
array.remove(flipManager.variation, i)
array.remove(flipManager.linePhase, i)
// } <CALCULATIONS>
// { <VISUALS>
plotshape(
series = newTestedSupport,
title = "New Support Re-Test X",
style = retestLogic ? shape.labeldown : shape.labelup,
text = "R",
textcolor = color.white,
location = retestLogic ? location.abovebar : location.belowbar,
color = retestLogic ? color.red :color.green,
size = size.tiny,
show_last = 20000)
plotshape(
series = newTestedResistance,
title = "New Resistance Re-Test X",
style = retestLogic ? shape.labelup : shape.labeldown,
text = "R",
textcolor = color.white,
location = retestLogic ? location.belowbar : location.abovebar,
color = retestLogic ? color.green : color.red,
size = size.tiny,
show_last = 20000)
// } <VISUALS>
// { <ALERTS>
alertcondition(
condition = newTestedSupport,
title = "New Support Re-Test")
alertcondition(
condition = newTestedResistance,
title = "New Resistance Re-Test")
alertcondition(
condition = supportBrokeDownside,
title = "Support Re-Test Downside Break")
alertcondition(
condition = supportBrokeUpside,
title = "Support Re-Test Upside Break")
alertcondition(
condition = resistanceBrokeDownside,
title = "Resistance Re-Test Downside Break")
alertcondition(
condition = resistanceBrokeUpside,
title = "Resistance Re-Test Upside Break")
alertcondition(
condition = supportBrokeDownside or resistanceBrokeDownside,
title = "Any Downside Break")
alertcondition(
condition = supportBrokeUpside or resistanceBrokeUpside,
title = "Any Upside Break")
// } <ALERTS> |
InteliTrend StableFX | https://www.tradingview.com/script/8Fh9PVdV-InteliTrend-StableFX/ | d1g1talshad0w | https://www.tradingview.com/u/d1g1talshad0w/ | 91 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Originally developed for MT4 by Mario Jemic. https://mario-jemic.com/ (If you are still using Windows 95 that is the version for you!)
// Recoded for the 21st century by d1g1talshad0w
//@version=5
indicator("InteliTrend StableFX", overlay = false)
// โกโกโกโกโกโกโกโก INPUTS & SETTINGS โกโกโกโกโกโกโกโก
int cci_len = input.int(34, "CCI Length", group = "Commodity Channel Index")
cci_src = input(hlc3, "CCI Source", group = "Commodity Channel Index")
// weighting and smoothing
float c1 = input.float(0.5, title = "c1", group = "Weights & Smoothing")
float c2 = input.float(0.5, title = "c2", group = "Weights & Smoothing")
float c3 = input.float(0.5, title = "c3", group = "Weights & Smoothing")
int p = input.int(6, title = "Smoothing 'p'", group = "Weights & Smoothing")
// moving averages
int ma_len = input(61, title = "MA Length", group = "Moving Averages")
string ma_type = input.string("SMA"
, title = "MA Type"
, options = ["SMA", "SMMA", "EMA", "HMA", "LVMA", "Alma"]
, group = "Moving Averages")
int lvma_wt = input.int(6
, title = "LVMA Weight"
, group = "Moving Averages"
, tooltip = "Only used if LVMA is selected")
float alma_os = input.float(0.86
, title = "Alma Offset"
, maxval = 1
, minval = 0
, group = "Moving Averages"
, tooltip = "Only used if Alma is selected. Lower is smoother, higher is more responsive.")
int alma_sig = input.int(6
, title = "Alma Sigma"
, group = "Moving Averages"
, tooltip = "Only used if Alma is selected. Higher is smoother, lower is more responsive.")
// visual settings
color sfx_css = input.color(defval = color.new(color.orange, 0)
, title = "StableFX"
, group = "Visuals"
, inline = "color")
color ma_css = input.color(defval = color.new(color.red, 0)
, title = "Moving Average"
, group = "Visuals"
, inline = "color")
// โกโกโกโกโกโกโกโก FUNCTIONS โกโกโกโกโกโกโกโก
// calculate linear weighted moving average
get_lwma(src, period, weight) =>
price = src
sub = weight / period - 1
float per = na
float wt = na
float sum = 0
float divider = 0
for i = 0 to period - 1 by 1
per := price[i] * (weight - i - sub)
wt := weight - i - sub
sum += per
divider += wt
divider
sum / divider
// select moving average type
select_ma(src, len, ma_type) =>
switch ma_type
"SMA" => ta.sma(src, len)
"SMMA" => ta.rma(src, len)
"EMA" => ta.ema(src, len)
"HMA" => ta.hma(src, len)
"LVMA" => get_lwma(src, len, lvma_wt)
"Alma" => ta.alma(src, len, alma_os, alma_sig)
// โกโกโกโกโกโกโกโก CALCULATIONS โกโกโกโกโกโกโกโก
// calculate commodity channel index
float cci_val = ta.cci(cci_src, cci_len)
// apply weights to the CCI and store to an array
wts = array.new_float(0, p)
for i = 0 to p - 1
a = cci_val[i] * c1 + cci_val[i] * c2 - cci_val[i] * c3 + cci_val[i] * c2 - cci_val[i] * c3 + cci_val[i] * c2 - cci_val[i] * c3 + cci_val[i] * c2 - cci_val[i] * c3 + cci_val[i] * c2 - cci_val[i] * c3
array.push(wts, a)
// sum the max and min values in the array
cci_wt = array.max(wts) + array.min(wts)
// calculate the moving average
ma = select_ma(cci_wt, ma_len, ma_type)
plot(cci_wt, title = "StableFX", color = sfx_css, editable = false)
plot(ma, title = "Moving Average", color = ma_css, editable = false)
|
ATRLevels 1.0.0 | https://www.tradingview.com/script/sgrEwPNt-atrlevels-1-0-0/ | stupean | https://www.tradingview.com/u/stupean/ | 93 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ stupean
//@version=5
indicator("ATRLevels 1.0.0", overlay = true)
int atrLength = input.int(defval = 5, title = "Daily ATR length", minval = 1)
color defaultColor100 = input.color(defval = color.new(color.gray, 20), title = "100% lines")
color defaultColor50 = input.color(defval = color.new(color.gray, 50), title = "50% lines")
color defaultColor25 = input.color(defval = color.new(color.gray, 80), title = "25% and 75% lines")
type LevelOption
float ratio
color lvlColor
string style = line.style_solid
int width = 1
type Options
array<LevelOption> levelOptions
type Level
line ln
label lb
type ATRLevels
array<Level> levels
Options options
createDefaultLevelsOptions() =>
array.from(
LevelOption.new(1, defaultColor100),
LevelOption.new(0.75, defaultColor25),
LevelOption.new(0.5, defaultColor50),
LevelOption.new(0.25, defaultColor25),
LevelOption.new(0, defaultColor100),
LevelOption.new(-0.25, defaultColor25),
LevelOption.new(-0.5, defaultColor50),
LevelOption.new(-0.75, defaultColor25),
LevelOption.new(-1, defaultColor100))
enrichOptions(Options options) =>
options.levelOptions := na(options.levelOptions) ? createDefaultLevelsOptions() : options.levelOptions
newInstance(Options options = na) =>
Options _options = na(options) ? Options.new() : options
enrichOptions(_options)
array<Level> levels = array.new<Level>()
for i = 0 to _options.levelOptions.size() - 1
LevelOption lvlOption = _options.levelOptions.get(i)
line ln = line.new(bar_index, open, bar_index, open, color = lvlOption.lvlColor)
label lb = label.new(bar_index, open, str.format("{0,number,percent}", lvlOption.ratio), style = label.style_none, textcolor = lvlOption.lvlColor)
Level lvl = Level.new(ln, lb)
levels.push(lvl)
ATRLevels.new(levels = levels, options = _options)
method update(ATRLevels this, float atr) =>
float priceStep = atr / 4
for i = 0 to this.levels.size() - 1
Level lvl = this.levels.get(i)
LevelOption lvlOption = this.options.levelOptions.get(i)
line ln = lvl.ln
label lb = lvl.lb
ln.set_x2(bar_index + 300)
if session.isfirstbar_regular
float price = open + (lvlOption.ratio * atr)
ln.set_x1(bar_index)
ln.set_y1(price)
ln.set_y2(price)
lb.set_x(bar_index)
lb.set_y(price)
// main
var Options options = Options.new(levelOptions = createDefaultLevelsOptions())
var ATRLevels atrLevels = newInstance(options)
float atr = request.security(syminfo.tickerid, "D", ta.atr(atrLength))[1]
atrLevels.update(atr)
|
Price Deviation Indicator (PDI) | https://www.tradingview.com/script/tRFSScEC-price-deviation-indicator-pdi/ | bashseo | https://www.tradingview.com/u/bashseo/ | 39 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ bashseo, development by "DimArt" company
//@version=5
indicator(title="Price Deviation Indicator (PDI)", overlay=false)
// Define the number of bars to calculate the average value
length = input(20, title="Length")
// Calculate the average price over the period
avg_price = ta.sma(close, length)
// Calculate the relative difference between the current price and the average value
price_diff = ((close - avg_price) / avg_price) * 100
// Determine levels to change the histogram color
histogram_color = price_diff > 5 ? color.red : price_diff < -5 ? color.green : color.blue
// Draw a histogram of the price deviation from the average value
plot(title="Price Deviation Indicator (PDI)", series=price_diff, color=histogram_color, style=plot.style_histogram)
|
Fair Value Gap Chart | https://www.tradingview.com/script/IYA9g0BE-Fair-Value-Gap-Chart/ | alexgrover | https://www.tradingview.com/u/alexgrover/ | 151 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ alexgrover
//Some FVG's are dogs
//@version=5
indicator("Fair Value Gap Chart", "Fair Value Gap Chart", overlay = true, max_lines_count = 500, max_boxes_count = 500)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
showEma = input(false, 'Show EMA', inline = 'ema')
length = input(20, '', inline = 'ema')
//Style
bull = input.color(color.teal, 'Bullish Candle', group = 'Style')
bear = input.color(color.red, 'Bearish Candle', group = 'Style')
emaCSs = input.color(#2157f3, 'EMA Color', group = 'Style')
showDates = input(true, 'Show Start/End Date')
//-----------------------------------------------------------------------------}
//UDT
//-----------------------------------------------------------------------------{
type fvg_candle
float max
float top_body
float btm_body
float min
bool bullish
int timestamp
//-----------------------------------------------------------------------------}
//Detect and append FVG's to array
//-----------------------------------------------------------------------------{
var candles = array.new<fvg_candle>(0)
//Bullish fvg
if low > high[2] and close[1] > high[2]
candles.unshift(fvg_candle.new(high, low, high[2], low[2], true, time))
//Bearish fvg
if high < low[2] and close[1] < low[2]
candles.unshift(fvg_candle.new(high[2], low[2], high, low, false, time))
//-----------------------------------------------------------------------------}
//Display FVG chart
//-----------------------------------------------------------------------------{
var float minval = na
n = bar_index
//Date labels
var start = label.new(na, na, na, color = color(na)
, style = label.style_label_up
, textcolor = chart.fg_color
, size = size.small)
var end = label.new(na, na, na, color = color(na)
, style = label.style_label_up
, textcolor = chart.fg_color
, size = size.small)
//Delete displayed boxes/lines
if candles.size() < 500
for l in line.all
l.delete()
for b in box.all
b.delete()
//Set candles/ema
if barstate.islast
size = math.min(candles.size()-1, 499)
left = n - (size * 2) - 2
minval := candles.get(size).min
//Initial ema values
float ema = candles.get(size).top_body
float prev_ema = na
//Loop trough fvg's array and set candle
for i = size to 0
get = candles.get(i)
right = left + 2
//Candle body
box.new(left, get.top_body, right, get.btm_body, na
, bgcolor = get.bullish ? bull : bear)
//Candle wicks
if not showEma
line.new(right - 1, get.max, right - 1, get.min
, color = get.bullish ? bull : bear)
minval := math.min(get.min, minval)
//Compute ema value
if showEma
ema := ema + 2/(length+1) * ((get.bullish ? get.top_body : get.btm_body) - ema)
line.new(left - 1, prev_ema, right - 1, ema)
prev_ema := ema
left := right
//Set labels
if showDates
start_t = candles.get(size).timestamp
start.set_xy(n - (size * 2) - 2, minval)
start.set_text(str.format('{0, number, #}-{1}-{2} {3}:{4}', year(start_t), month(start_t), dayofmonth(start_t), hour(start_t), minute(start_t)))
end_t = candles.get(0).timestamp
end.set_xy(n, minval)
end.set_text(str.format('{0, number, #}-{1}-{2} {3}:{4}', year(end_t), month(end_t), dayofmonth(end_t), hour(end_t), minute(end_t)))
//Horizontal line
plot(showDates ? minval : na, 'X axis', chart.fg_color, trackprice = true)
//-----------------------------------------------------------------------------} |
OnChart_RSI | https://www.tradingview.com/script/vj20slRb-onchart-rsi/ | Shuttle_Trader | https://www.tradingview.com/u/Shuttle_Trader/ | 224 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@Shuttle_Trader
//@version=5
indicator(title="OnChart_RSI", overlay=true, shorttitle="OnChart_RSI")
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="==== RSI SETTINGS ====")
rsiSourceInput = input.source(close, "Source", group="==== RSI SETTINGS ====")
up_level = input.int(75, title='UP', minval=51, maxval=99, inline='s3', group='==== RANGE FOR RSI ====')
dn_level = input.int(25, title='DN', minval=1, maxval=49, inline='s3', group='==== RANGE FOR RSI ====')
show_trend = input.bool(true, title = 'Show TREND')
use_take = input.bool(false, title='', inline='t1', group='==== TAKE CONTROL ====')
take = input.float(1.0,minval=0,title='Take level controlโโโ', inline='t1', group='==== TAKE CONTROL ====')
maValue = ta.rma(ohlc4, rsiLengthInput)
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
up_lev_line = ta.rma(ta.highest(rsiLengthInput)[1], rsiLengthInput)
dn_lev_line = ta.rma(ta.lowest(rsiLengthInput)[1], rsiLengthInput)
rsi_range = (up_lev_line-dn_lev_line)/(up_level-dn_level)*100
rsi_line_chart = maValue+(rsi-50)/100*rsi_range
plot(rsi_line_chart, "RSI", color=#e4c200, linewidth=2)
rsiUpperBand = plot(up_lev_line, "RSI Upper Band", color=#ee0e3f)
rsiLowerBand = plot(dn_lev_line, "RSI Lower Band", color=#08f108)
buy = ta.crossover(rsi,dn_level)
sell = ta.crossunder(rsi,up_level)
l=0, l:=nz(l[1])
s=0, s:=nz(s[1])
var prev_buy = float(na)
var prev_sell = float(na)
if buy
l+=1, s:=0
if sell
l:=0, s+=1
plotshape(buy, title='UP', style=shape.triangleup, location=location.belowbar, color=#08f108, text='', textcolor=#08f108, size=size.tiny)
plotshape(sell, title='DN', style=shape.triangledown, location=location.abovebar, color=#ee0e3f, text='', textcolor=#ee0e3f, size=size.tiny)
ltake = float(na)
stake = float(na)
long_price = float(na), long_price := nz(long_price[1])
short_price = float(na), short_price := nz(short_price[1])
if buy and l==1
long_price := close
prev_buy := close
if buy and l>1
long_price := (long_price*(l-1)+close)/l
prev_buy := close
if sell and s==1
short_price := close
prev_sell := close
if sell and s>1
short_price := (short_price*(s-1)+close)/s
prev_sell := close
ltake := math.round_to_mintick(long_price*(1+take/100))
stake := math.round_to_mintick(short_price*(1-take/100))
plot(use_take and l>0 ? ltake : na, title='Long tp-line', style=plot.style_steplinebr)
plot(use_take and s>0 ? stake : na, title='Short tp-line', style=plot.style_steplinebr)
ltake_profit = high>=ltake and l>0 and use_take and not buy
stake_profit = low<=stake and s>0 and use_take and not sell
ltake_profit_add = l>0 and (high>=up_lev_line or high>=up_lev_line[1]) and ((high>=long_price and use_take) or not use_take) and not buy
stake_profit_add = s>0 and (low<=dn_lev_line or low<=dn_lev_line[1]) and ((low<=short_price and use_take) or not use_take) and not sell
plotshape(ltake_profit or ltake_profit_add, style=shape.square, location=location.abovebar, color=#005cf1, size=size.tiny, editable=false)
plotshape(stake_profit or stake_profit_add, style=shape.square, location=location.belowbar, color=#005cf1, size=size.tiny, editable=false)
if ltake_profit or ltake_profit_add
l:=0
if stake_profit or stake_profit_add
s:=0
UP = ta.crossover(close, up_lev_line)
DN = ta.crossunder(close, dn_lev_line)
rsi_channel_trend = 0
rsi_channel_trend := UP ? 1 : DN ? -1 : nz(rsi_channel_trend[1])
top_color1 = rsi>=up_level or (rsi>=up_level)[1] ? color.rgb(255, 82, 82, 40) : na
bottom_color1 = color.rgb(255, 82, 82, 100)
top_color2 = color.rgb(76, 175, 79, 100)
bottom_color2 = rsi<=dn_level or (rsi<=dn_level)[1] ? color.rgb(76, 175, 79, 40) : na
pp1_line = math.max(ohlc4,rsi_line_chart,rsi_line_chart[1])
pp2_line = math.min(ohlc4,rsi_line_chart,rsi_line_chart[1])
price = plot(ohlc4, display=display.none, editable=false)
pp1 = plot(pp1_line, display=display.none, editable=false)
pp2 = plot(pp2_line, display=display.none, editable=false)
fill(pp1, rsiUpperBand, pp1_line, up_lev_line, top_color1, bottom_color1)
fill(rsiLowerBand, pp2, dn_lev_line, pp2_line, top_color2, bottom_color2)
fill(rsiUpperBand,rsiLowerBand,color=rsi_channel_trend>0?color.rgb(76, 175, 79, 80):rsi_channel_trend<0?color.rgb(255, 82, 82, 80):na,title='TREND')
if buy
alert('๐ข '+ syminfo.ticker + ' >> Good buying chance!\n\n RSI = ' + str.tostring(rsi),alert.freq_once_per_bar_close)
if sell
alert('๐ด '+ syminfo.ticker + ' >> Good selling chance!\n\n RSI = ' + str.tostring(rsi),alert.freq_once_per_bar_close)
if UP
alert('๐ข '+ syminfo.ticker + ' >> UP-TREND',alert.freq_once_per_bar_close)
if DN
alert('๐ด '+ syminfo.ticker + ' >> DOWN-TREND',alert.freq_once_per_bar_close)
if ltake_profit or ltake_profit_add
alert('๐ข '+ syminfo.ticker + ' >> Good point to take profit!\n\n RSI = ' + str.tostring(rsi),alert.freq_once_per_bar)
if stake_profit or stake_profit_add
alert('๐ด '+ syminfo.ticker + ' >> Good point to take profit!\n\n RSI = ' + str.tostring(rsi),alert.freq_once_per_bar)
|
Liquidity Voids (FVG) [LuxAlgo] | https://www.tradingview.com/script/rRKtzvFt-Liquidity-Voids-FVG-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 2,091 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ LuxAlgo
//@version=5
indicator("Liquidity Voids (FVG) [LuxAlgo]", "LuxAlgo - Liquidity Voids (FVG)", overlay = true, max_boxes_count = 500)
//------------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------{
mdTT = 'The mode option controls the number of visual objects presented, where\n\n- Historical, takes into account all data available to the user\n- Present, takes into account only the last X bars specified in the \'# Bars\' option'
mode = input.string('Historical', title = 'Mode', options =['Present', 'Historical'], inline = 'MOD')
back = input.int (360, 'ย # Bars', minval = 100, maxval = 5000, step = 10, inline = 'MOD', tooltip = mdTT)
lqGR = 'Liquidity Detection'
lqTT = 'Act as a filter while detecting the Liquidity Voids. When set to 0 means no filtering is applied, increasing the value causes the script to check the width of the void compared to a fixed-length ATR value'
lqTH = input.float(.5, 'Liquidity Voids Threshold', minval = 0, step = .1, group = lqGR, tooltip = lqTT)
lqBC = input.color(color.new(#089981, 73), 'Bullish', inline = 'VD', group = lqGR)
lqSC = input.color(color.new(#f23645, 73), 'Bearish', inline = 'VD', group = lqGR)
lqTX = input.bool (false, 'Label', inline = 'VD', group = lqGR)
lqFT = 'Toggles the visibility of the Filled Liquidity Voids'
lqVF = input.bool (true, 'Filled Liquidity Voids', inline = 'FL', group = lqGR, tooltip = lqFT)
lqFC = input.color(color.new(#787b86, 73), '', inline = 'FL', group = lqGR)
//-----------------------------------------------------------------------------}
// User Defined Types
//-----------------------------------------------------------------------------{
// @type bar properties with their values
//
// @field h (float) high price of the bar
// @field l (float) low price of the bar
// @field c (float) close price of the bar
// @field i (int) index of the bar
type bar
float h = high
float l = low
float c = close
int i = bar_index
//-----------------------------------------------------------------------------}
// Variables
//-----------------------------------------------------------------------------{
bar b = bar.new()
var lqV = array.new_box()
//-----------------------------------------------------------------------------}
// Calculations
//-----------------------------------------------------------------------------{
per = mode == 'Present' ? last_bar_index - b.i <= back : true
atr = ta.atr(144) * lqTH
if per
bull = (b.l - b.h[2]) > atr and b.l > b.h[2] and b.c[1] > b.h[2]
if bull
l = 13
if bull[1]
st = math.abs(b.l - b.l[1]) / l
for i = 0 to l - 1
array.push(lqV, box.new(b.i - 2, b.l[1] + (i + 1) * st, b.i, b.l[1] + i * st, na, bgcolor = lqBC ))
else
st = math.abs(b.l - b.h[2]) / l
for i = 0 to l - 1
if lqTX and i == 0
array.push(lqV, box.new(b.i - 2, b.h[2] + (i + 1) * st, b.i, b.h[2] + i * st, na, text = 'Liquidity Void ', text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_bottom, text_color = na, bgcolor = lqBC ))
else
array.push(lqV, box.new(b.i - 2, b.h[2] + (i + 1) * st, b.i, b.h[2] + i * st, na, bgcolor = lqBC ))
bear = (b.l[2] - b.h) > atr and b.h < b.l[2] and b.c[1] < b.l[2]
if bear
l = 13
if bear[1]
st = math.abs(b.h[1] - b.h) / l
for i = 0 to l - 1
array.push(lqV, box.new(b.i - 2, b.h + (i + 1) * st, b.i, b.h + i * st, na, bgcolor = lqSC ))
else
st = math.abs(b.l[2] - b.h) / l
for i = 0 to l - 1
if lqTX and i == l - 1
array.push(lqV, box.new(b.i - 2, b.h + (i + 1) * st, b.i, b.h + i * st, na, text = 'Liquidity Void ', text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_top, text_color = na, bgcolor = lqSC ))
else
array.push(lqV, box.new(b.i - 2, b.h + (i + 1) * st, b.i, b.h + i * st, na, bgcolor = lqSC ))
if lqV.size() > 0
qt = lqV.size()
for bn = qt - 1 to 0
if bn < lqV.size()
cb = lqV.get(bn)
tBX = cb.get_top()
bBX = cb.get_bottom()
if b.h > bBX and b.l < tBX
if lqVF
cb.set_bgcolor(lqFC)
else
cb.delete()
lqV.remove(bn)
else
cb.set_right(b.i + 1)
if b.i - cb.get_left() > 21
cb.set_text_color(chart.fg_color)
if lqV.size() > 500
lqV.shift()
//-----------------------------------------------------------------------------} |
HiveLibrary | https://www.tradingview.com/script/6n3DNcxE-HiveLibrary/ | HTrade17 | https://www.tradingview.com/u/HTrade17/ | 8 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ HTrade17
//@version=5
// @description : Custom library
library("HiveLibrary")
// @function RoundDown() rounds the specified number down to the given number
// of decimal places.
// @param number is the argument for rounding down & decimals is the number of digits after dot
// @returns return is the rounded down value of the number
export RoundDown(float number, float decimals) =>
factor=math.pow(10,decimals)
math.floor(number*factor)/factor
|
DataCorrelation | https://www.tradingview.com/script/JZCroSfn-DataCorrelation/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 43 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
// @description Implementation of functions related to data correlation calculations. Formulas have been transformed in such a way that we avoid running loops and instead make use of time series to gradually build the data we need to perform calculation. This allows the calculations to run on unbound series, and/or higher number of samples
library("DataCorrelation")
import HeWhoMustNotBeNamed/BinaryInsertionSort/1 as bis
// @function Calculates chatterjee correlation between two series. Formula is - ฮพnโแตง = 1 - (3 * โ |rแตขโโ - rแตข|)/ (nยฒ-1)
// @param x First series for which correlation need to be calculated
// @param y Second series for which correlation need to be calculated
// @param sampleSize number of samples to be considered for calculattion of correlation. Default is 20000
// @param plotSize How many historical values need to be plotted on chart.
// @returns float correlation - Chatterjee correlation value if falls within plotSize, else returns na
export chatterjeeCorrelation(float x, float y, simple int sampleSize = 20000, simple int plotSize = 500) =>
float correlation = na
if(bar_index > last_bar_index-sampleSize)
[xArray, xSortedArray, xSortIndices] = bis.get_sorted_arrays(x)
[yArray, ySortedArray, ySortIndices] = bis.get_sorted_arrays(y)
if(bar_index >= last_bar_index-plotSize)
coefficient = 0.0
n = array.size(xArray)
index = array.get(xSortIndices, 0)
for i=1 to n > 1? n -1 : na
indexNext = array.get(xSortIndices, i)
coefficient := coefficient + math.abs(array.get(ySortIndices, indexNext)-array.get(ySortIndices, index))
index := indexNext
correlation := 1 - 3*coefficient/(math.pow(n,2)-1)
correlation
// @function Calculates spearman correlation between two series. Formula is - ฯ = 1 - (6โdแตขยฒ/n(nยฒ-1))
// @param x First series for which correlation need to be calculated
// @param y Second series for which correlation need to be calculated
// @param sampleSize number of samples to be considered for calculattion of correlation. Default is 20000
// @param plotSize How many historical values need to be plotted on chart.
// @returns float correlation - Spearman correlation value if falls within plotSize, else returns na
export spearmanCorrelation(float x, float y, simple int sampleSize = 20000, simple int plotSize = 500) =>
float correlation = na
if(bar_index > last_bar_index-sampleSize)
[xArray, xSortedArray, xSortIndices] = bis.get_sorted_arrays(x)
[yArray, ySortedArray, ySortIndices] = bis.get_sorted_arrays(y)
if(bar_index >= last_bar_index-plotSize)
n = array.size(xArray)
dSquareSum = 0.0
for i=0 to n > 0? n -1 : na
d = array.get(xSortIndices, i) - array.get(ySortIndices, i)
dSquareSum += d*d
correlation := 1 - (6*dSquareSum/(math.pow(n, 3)-n))
correlation
// @function Calculates covariance between two series of unbound length. Formula is Covโแตง = โ ((xแตข-xฬ)(yแตข-yฬ)) / (n-1) for sample and Covโแตง = โ ((xแตข-xฬ)(yแตข-yฬ)) / n for population
// @param x First series for which covariance need to be calculated
// @param y Second series for which covariance need to be calculated
// @param include boolean flag used for selectively including sample
// @param biased boolean flag representing population covariance instead of sample covariance
// @returns float covariance - covariance of selective samples of two series x, y
export covariance(float x, float y, bool include=true, simple bool biased = true)=>
var float xySum = 0.0
var float xSum = 0.0
var float ySum = 0.0
var n=0
var float covariance = na
if(include)
xy = x*y
n+=1
xSum += x
ySum += y
xySum += xy
xMean = xSum/n
yMean = ySum/n
covariance := (xySum + (n*xMean*yMean) - (yMean*xSum) - (xMean*ySum))/(n-(biased?0:1))
covariance
// @function Calculates Standard Deviation of a series. Formula is ฯ = โ( โ(xแตข-xฬ)ยฒ / n ) for sample and ฯ = โ( โ(xแตข-xฬ)ยฒ / (n-1) ) for population
// @param x Series for which Standard Deviation need to be calculated
// @param include boolean flag used for selectively including sample
// @param biased boolean flag representing population covariance instead of sample covariance
// @returns float stddev - standard deviation of selective samples of series x
export stddev(float x, bool include=true, simple bool biased = true)=>
var float xSquareSum = 0.0
var float xSum = 0.0
var n=0
var float stddev = na
if(include)
n+=1
xSquareSum += x*x
xSum += x
xMean = xSum/n
stddev := math.sqrt( (xSquareSum + n*xMean*xMean - 2*xMean*xSum)/(n-(biased?0:1)) )
stddev
// @function Calculates pearson correlation between two series of unbound length. Formula is r = Covโแตง / ฯโฯแตง
// @param x First series for which correlation need to be calculated
// @param y Second series for which correlation need to be calculated
// @param include boolean flag used for selectively including sample
// @returns float correlation - correlation between selective samples of two series x, y
export correlation(float x, float y, bool include=true)=>
covariance = covariance(x,y, include)
sdX = stddev(x, include)
sdY = stddev(y, include)
covariance/(sdX * sdY) |
FibRatios | https://www.tradingview.com/script/TyGVp4sD-FibRatios/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 45 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ HeWhoMustNotBeNamed
// โโ
// โโโ โโ
// โโโโโ โโ
// โโโโโโโโ โ โโ
// โโโโโโ โ โโ
// โโโโ โ โโโโโโโโโโโ
// โโโโโโโโโโโ โ โโโโโโโโโโโโโโโโโโโโ
// โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโ โโ
// โโโโโ โโโโโโโ
// โโโโโโโโโ
// โโโโโ โโโโโ
// โโโโโ โโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ
// โโโโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโ
// โโโโโ โโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโ โโโโโโ
// โโโโโ โโโโโ โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโ
// โโ โ
//@version=5
// @description Library with calculation logic for fib retracement, extension and ratios
library("FibRatios")
round(value, precision)=> precision < 0? math.round_to_mintick(value) : math.round(value, precision)
// @function Calculates the retracement for points a, b with given ratio and scale
// @param a Starting point a
// @param b Second point b
// @param ratio Ratio for which we need to calculate retracement c
// @param logScale Flag to get calculations in log scale. Default is false
// @param precision rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
// @returns retracement point c for points a,b with given ratio and scale
export retracement(float a, float b, float ratio, bool logScale = false, int precision = -1) => round(logScale? b * math.pow(a/b, ratio) : b - (b-a)*ratio, precision)
// @function Calculates the retracement ratio for points a, b, c with given scale
// @param a Starting point a
// @param b Second point b
// @param c Retracement point. c should be placed between a and b
// @param logScale Flag to get calculations in log scale. Default is false
// @param precision rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
// @returns retracement ratio for points a,b,c on given scale
export retracementRatio(float a, float b, float c, bool logScale = false, int precision = 3) => round(logScale? math.log(c/b)/math.log(a/b) : (b-c)/(b-a), precision)
// @function Calculates the extensions for points a, b, c with given ratio and scale
// @param a Starting point a
// @param b Second point b
// @param c Retracement point. c should be placed between a and b
// @param ratio Ratio for which we need to calculate extension d
// @param logScale Flag to get calculations in log scale. Default is false
// @param precision rounding precision. If set to netagive number, round_to_mintick is applied. Default is -1
// @returns extensoin point d for points a,b,c with given ratio and scale
export extension(float a, float b, float c, float ratio, bool logScale = false, int precision = -1) => round(logScale? c * math.pow(b/a, ratio) : c + (b-a)*ratio, precision)
// @function Calculates the extension ratio for points a, b, c, d with given scale
// @param a Starting point a
// @param b Second point b
// @param c Retracement point. c should be placed between a and b
// @param d Extension point. d should be placed beyond a, c. But, can be with b,c or beyond b
// @param logScale Flag to get calculations in log scale. Default is false
// @param precision rounding precision. If set to netagive number, round_to_mintick is applied. Default is 3
// @returns extension ratio for points a,b,c,d on given scale
export extensionRatio(float a, float b, float c, float d, bool logScale = false, int precision = 3) => round(logScale? math.log(d/c)/math.log(b/a) : (d-c)/(b-a), precision)
|
Visible Range Streaks of Unbroken Prior Highs/Lows [vnhilton] | https://www.tradingview.com/script/dfbDoK8b-Visible-Range-Streaks-of-Unbroken-Prior-Highs-Lows-vnhilton/ | vnhilton | https://www.tradingview.com/u/vnhilton/ | 42 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ vnhilton
// ADVICE: Put this indicator visually in front of the price chart, so plots are not hidden from behind
//@version=5
indicator("Visible Range Streaks of Unbroken Prior Highs/Lows [vnhilton]", "VRSOUP H/L", true, max_lines_count = 500, max_labels_count = 500)
//Parameters
showLowPlot = input.bool(true, "", "These will override the other toggles", "Main Plot Settings", "Main Settings")
showhighPlot = input.bool(true, "Show Low/High Plots?", inline = "Main Plot Settings", group = "Main Settings")
minNumber = input.int(3, "Minimum Number of Unbroken Prior Highs/Lows", 0, tooltip = "To start displaying streaks (streak breaks lower than this number will not be shown)", group = "Main Settings")
showText = input.bool(true, "", inline = "Content Settings", group = "Toggle Settings")
showNumbers = input.bool(true, "Show Text/Numbers?", inline = "Content Settings", group = "Toggle Settings")
showBreakShape = input.bool(true, "Show Break Shape?", "This is the shape placed at the location where the prior high/low is broken", group = "Toggle Settings")
showZigZag = input.bool(true, "Show Zig Zag?", "Draws lines between break shapes", group = "Toggle Settings")
lineThickness = input.int(2, "Zig Zag Line Width", 1, group = "Zig Zag Settings")
lineStyle = input.string("Solid", "Zig Zag Line Style", ["Dashed", "Dotted", "Solid"], group = "Zig Zag Settings")
sellSignalText = input.string("SELL", "Prior Low/High Break Text", inline = "Signal Settings", group = "Text Settings")
buySignalText = input.string("BUY", "", inline = "Signal Settings", group = "Text Settings")
labelSize = input.string("Auto", "Label/Break Shape Size", ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], inline = "Size Settings", group = "Label Settings")
shapeSize = input.string("Auto", "", ["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], inline = "Size Settings", group = "Label Settings")
sellNumberLabel = input.string("Label Text Outline", "Low/High Numbers Label Type", ["None", "X-Cross", "Cross", "Triangle Up", "Triangle Down", "Flag", "Circle", "Arrow Up", "Arrow Down", "Label Up", "Label Down", "Label Left", "Label Right", "Label Lower Left", "Label Lower Right", "Label Upper Left", "Label Upper Right", "Label Center", "Label Square", "Label Diamond", "Label Text Outline"], inline = "Number Settings", group = "Label Settings")
buyNumberLabel = input.string("Label Text Outline", "", ["None", "X-Cross", "Cross", "Triangle Up", "Triangle Down", "Flag", "Circle", "Arrow Up", "Arrow Down", "Label Up", "Label Down", "Label Left", "Label Right", "Label Lower Left", "Label Lower Right", "Label Upper Left", "Label Upper Right", "Label Center", "Label Square", "Label Diamond", "Label Text Outline"], inline = "Number Settings", group = "Label Settings")
sellSignalLabel = input.string("Label Text Outline", "Low/High Streak Break Label Type", ["None", "X-Cross", "Cross", "Triangle Up", "Triangle Down", "Flag", "Circle", "Arrow Up", "Arrow Down", "Label Up", "Label Down", "Label Left", "Label Right", "Label Lower Left", "Label Lower Right", "Label Upper Left", "Label Upper Right", "Label Center", "Label Square", "Label Diamond", "Label Text Outline"], inline = "Break Settings", group = "Label Settings")
buySignalLabel = input.string("Label Text Outline", "", ["None", "X-Cross", "Cross", "Triangle Up", "Triangle Down", "Flag", "Circle", "Arrow Up", "Arrow Down", "Label Up", "Label Down", "Label Left", "Label Right", "Label Lower Left", "Label Lower Right", "Label Upper Left", "Label Upper Right", "Label Center", "Label Square", "Label Diamond", "Label Text Outline"], inline = "Break Settings", group = "Label Settings")
sellShapeLabel = input.string("Label Center", "Break Sell/Buy Shape Type", ["None", "X-Cross", "Cross", "Triangle Up", "Triangle Down", "Flag", "Circle", "Arrow Up", "Arrow Down", "Label Up", "Label Down", "Label Left", "Label Right", "Label Lower Left", "Label Lower Right", "Label Upper Left", "Label Upper Right", "Label Center", "Label Square", "Label Diamond"], inline = "Break Settings", group = "Label Settings")
buyShapeLabel = input.string("Label Center", "", ["None", "X-Cross", "Cross", "Triangle Up", "Triangle Down", "Flag", "Circle", "Arrow Up", "Arrow Down", "Label Up", "Label Down", "Label Left", "Label Right", "Label Lower Left", "Label Lower Right", "Label Upper Left", "Label Upper Right", "Label Center", "Label Square", "Label Diamond"], inline = "Break Settings", group = "Label Settings")
unbrokenLowColor = input.color(color.red, "Unbroken Low/High Numbers Color", inline = "Number Color Settings", group = "Color Settings")
unbrokenHighColor = input.color(color.green, "", inline = "Number Color Settings", group = "Color Settings")
sellSignalColor = input.color(color.red, "Prior Low/High Break Text Color", inline = "Signal Color Settings", group = "Color Settings")
buySignalColor = input.color(color.green, "", inline = "Signal Color Settings", group = "Color Settings")
labelLowColor = input.color(color.new(color.red, 100), "Unbroken Low/High Label Color", inline = "Label Color Settings", group = "Color Settings")
labelHighColor = input.color(color.new(color.green, 100), "", inline = "Label Color Settings", group = "Color Settings")
labelLowBrokeColor = input.color(color.new(color.red, 100), "Broken Low/High Label Color", inline = "Label Broke Color Settings", group = "Color Settings")
labelHighBrokeColor = input.color(color.new(color.green, 100), "", inline = "Label Broke Color Settings", group = "Color Settings")
sellShapeColor = input.color(color.new(color.red, 50), "Prior Low/High Break Shape Color", inline = "Shape Color Settings", group = "Color Settings")
buyShapeColor = input.color(color.new(color.green, 50), "", inline = "Shape Color Settings", group = "Color Settings")
upLineColor = input.color(color.new(color.green, 50), "Up/Down Zig Zag Line Color", inline = "Line Color Settings", group = "Color Settings")
downLineColor = input.color(color.new(color.red, 50), "", inline = "Line Color Settings", group = "Color Settings")
//Label Size Selection
LabelSizing(choice) =>
switch
choice == "Auto" => size.auto
choice == "Tiny" => size.tiny
choice == "Small" => size.small
choice == "Normal" => size.normal
choice == "Large" => size.large
choice == "Huge" => size.huge
chosenLabelSize = LabelSizing(labelSize)
chosenShapeSize = LabelSizing(shapeSize)
//Label Type Selection
LabelType(choice) =>
switch
choice == "None" => label.style_none
choice == "X-Cross" => label.style_xcross
choice == "Cross" => label.style_cross
choice == "Triangle Up" => label.style_triangleup
choice == "Triangle Down" => label.style_triangledown
choice == "Flag" => label.style_flag
choice == "Circle" => label.style_circle
choice == "Arrow Up" => label.style_arrowup
choice == "Arrow Down" => label.style_arrowdown
choice == "Label Up" => label.style_label_up
choice == "Label Down" => label.style_label_down
choice == "Label Left" => label.style_label_left
choice == "Label Right" => label.style_label_right
choice == "Label Lower Left" => label.style_label_lower_left
choice == "Label Lower Right" => label.style_label_lower_right
choice == "Label Upper Left" => label.style_label_upper_left
choice == "Label Upper Right" => label.style_label_upper_right
choice == "Label Center" => label.style_label_center
choice == "Label Square" => label.style_square
choice == "Label Diamond" => label.style_diamond
choice == "Label Text Outline" => label.style_text_outline
chosenSellNumberLabel = LabelType(sellNumberLabel)
chosenBuyNumberLabel = LabelType(buyNumberLabel)
chosenSellSignalLabel = LabelType(sellSignalLabel)
chosenBuySignalLabel = LabelType(buySignalLabel)
chosenSellShapeLabel = LabelType(sellShapeLabel)
chosenBuyShapeLabel = LabelType(buyShapeLabel)
//Line Style Selection
LineStyling(choice) =>
switch lineStyle
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
"Solid" => line.style_solid
chosenLineStyle = LineStyling(lineStyle)
//Variables
var int lows = 0
var int lastLows = 0
var float prevLow = na
var int highs = 0
var int lastHighs = 0
var float prevHigh = na
var float[] coords = array.new<float>()
//Visible Chart Times
leftTime = chart.left_visible_bar_time
rightTime = chart.right_visible_bar_time
//Plots Function
Plots(streak, prevStreak, prevValue, ylock) =>
if streak > 0
if streak >= minNumber and showNumbers and ((ylock == yloc.abovebar and showLowPlot) or (ylock == yloc.belowbar and showhighPlot))
label.new(bar_index, na, str.tostring(streak), yloc = ylock, color = ylock == yloc.abovebar ? labelLowColor : labelHighColor, style = ylock == yloc.abovebar ? chosenSellNumberLabel : chosenBuyNumberLabel, textcolor = ylock == yloc.abovebar ? unbrokenLowColor : unbrokenHighColor, size = chosenLabelSize)
else
if prevStreak != 0 and prevStreak >= minNumber and ((ylock == yloc.abovebar and showLowPlot) or (ylock == yloc.belowbar and showhighPlot))
if showText
label.new(bar_index, na, ylock == yloc.abovebar ? sellSignalText : buySignalText, yloc = ylock, color = ylock == yloc.abovebar ? labelLowBrokeColor : labelHighBrokeColor, style = ylock == yloc.abovebar ? chosenSellSignalLabel : chosenBuySignalLabel, textcolor = ylock == yloc.abovebar ? sellSignalColor : buySignalColor, size = chosenLabelSize)
if showZigZag
array.push(coords, float(bar_index))
array.push(coords, prevValue)
if array.size(coords) == 4
line.new(int(array.get(coords, 0)), array.get(coords, 1), int(array.get(coords, 2)), array.get(coords, 3), color = array.get(coords, 3) - array.get(coords, 1) >= 0 ? upLineColor : downLineColor, style = chosenLineStyle, width = lineThickness)
array.set(coords, 0, array.get(coords, 2))
array.set(coords, 1, array.get(coords, 3))
array.remove(coords, 3)
array.remove(coords, 2)
if showBreakShape
label.new(bar_index, prevValue, color = ylock == yloc.abovebar ? sellShapeColor : buyShapeColor, style = ylock == yloc.abovebar ? chosenSellShapeLabel : chosenBuyShapeLabel, size = chosenShapeSize)
//Streak Logic
if ((barstate.isconfirmed and timeframe.isintraday) or (not timeframe.isintraday and not barstate.isrealtime)) and time >= leftTime and time <= rightTime
if bar_index != 0
if close >= prevLow
lows += 1
else
lastLows := lows
lows := 0
Plots(lows, lastLows, prevLow, yloc.abovebar)
if close <= prevHigh
highs += 1
else
lastHighs := highs
highs := 0
Plots(highs, lastHighs, prevHigh, yloc.belowbar)
prevLow := low
prevHigh := high |
Quarterly Earnings | https://www.tradingview.com/script/oBswL9v2-Quarterly-Earnings/ | finallynitin | https://www.tradingview.com/u/finallynitin/ | 1,277 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ finallynitin & ยฉ EquityCraze
//The script builds upon the Volume Price and Fundamentals script by Mohit_Kakkar08:
//https://www.tradingview.com/script/WQCSvzGz-Volume-Price-and-Fundamentals/
//@version=5
indicator('Quarterly Earnings', overlay=true)
//Table Options
string GRP1 = "โโโโโโโโ Modes โโโโโโโโโ"
toggleDarkColors = input(title="Dark Mode", defval=false, group = GRP1, tooltip = 'Select this if you use a dark color theme')
toggleMiniMode = input(title="Mini Mode", defval=false, group = GRP1, tooltip = 'Select this to get the Mini mode where the values are replaced by traffic lights for a quick visual')
datasize = input.int(4, 'Long Mode ?', minval = 4, inline='line 3', group=GRP1, tooltip = 'Input the number of previous quarters to be displayed in the table') +5
string GRP2 = "โโโโโโโโ Table Options โโโโโโโโโ"
string tablesize = input.string("small", "Size", inline = "21", group = GRP2, options = ["tiny", "small", "normal", "large", "huge", "auto"])
string tableposY = input.string("bottom", "โ", inline = "21", group = GRP2, options = ["top", "middle", "bottom"])
string tableposX = input.string("right", "โ", inline = "21", group = GRP2, options = ["left", "center", "right"])
string GRP3 = "โโโโโโโโ Inputs โโโโโโโโโ"
per = input.string('FQ', 'Period', options=['FQ', 'FY'], inline='line 3', group=GRP3, tooltip = 'Option to change the data from Quarterly (FQ) to Yearly (FY)')
topleft = input.string('FF','Top-left cell displays', group = GRP3, options = ['FF', 'Mcap'], tooltip = 'Option to display either the Free Float (FF) or the Marketcap (Mcap) of the stock')
FrameCol = toggleDarkColors ? color.new(#999999, 50) : color.rgb(241, 241, 241)
BorderCol = toggleDarkColors ? color.new(#999999, 50) : color.rgb(241, 241, 241)
TextColor = toggleDarkColors ? color.new(color.white, 0): color.new(color.black, 0)
BGColor = toggleDarkColors ? color.new(color.white, 100): color.new(color.black, 100)
HeadColor = toggleDarkColors ? color.new(color.white, 100): color.new(color.black, 100)
BodyColor = toggleDarkColors ? color.new(color.white, 100): color.new(color.black, 100)
UpColor = toggleDarkColors ? color.new(color.lime, 0) : color.new(color.rgb(31, 12, 239, 16), 0)
DownColor = toggleDarkColors ? color.new(color.red, 0) : color.new(color.rgb(213, 27, 182), 10)
UnchangedColor = toggleDarkColors ? color.new(color.yellow, 0) : color.new(color.orange, 30)
// Creating ID for Financials
financial01 = 'EPS'
financial02 = 'Sales'
financial01id = 'EARNINGS_PER_SHARE_DILUTED'
financial02id = 'TOTAL_REVENUE',
// Creating functions to fetch financial data from Tradingview
getFinFQ(_id, _per) =>
_financials = request.financial(syminfo.tickerid, _id, _per, barmerge.gaps_on, ignore_invalid_symbol = true)
if _id == financial02id
_financials := math.round(_financials / 10.0, 2)
_financials
f_array(arrayId, val) =>
array.unshift(arrayId, val)
array.pop(arrayId)
finID1 = financial01
finID2 = financial02
get_finx(finID) =>
finx = switch finID
financial02 => financial02id
financial01 => financial01id
finx
// Reference if data is true
rev = request.financial(syminfo.tickerid,'TOTAL_REVENUE',per,barmerge.gaps_on, ignore_invalid_symbol=true)
// Calculating
finx1 = get_finx(finID1)
finx2 = get_finx(finID2)
finData1 = getFinFQ(finx1, per)
finData2 = getFinFQ(finx2, per)
var date = array.new_int(datasize) // Date
var arrayFinData1 = array.new_float(datasize) // EPS
var arrayFinData2 = array.new_float(datasize) // Sales
if rev
f_array(date, time)
f_array(arrayFinData1, finData1)
f_array(arrayFinData2, finData2)
ft(_table, _column, _row, _value) =>
table.cell(table_id = _table, column = _column, row = _row, text = _value, bgcolor = HeadColor, text_color = TextColor, text_size = tablesize)
ftdate(_table, _column, _row, _value) =>
_new_value = str.contains(_value, "70") ? "" : _value
table.cell(table_id = _table, column = _column, row = _row, text = _new_value, bgcolor = BodyColor, text_color = TextColor, text_size = tablesize, text_halign = text.align_left )
fcell(finID, _table, _column, _row, _value, _i) =>
divider = 0
divider :=
finID == 'EPS' ? 1 : 1000000
suffix =
finID == 'EPS' or finID == financial02 ? '' : ' M'
strFormat =
finID == 'EPS' ? '#.#' : finID == financial02 ? '#,###.#' : '#,##0'
val = array.get(_value, _i)/ divider
table.cell(table_id = _table, column = _column, row = _row, text = na(val) ? "" : str.tostring(val, strFormat) +suffix, text_color = TextColor, text_size = tablesize)
fyoy(_table, _column, _row, _value, _i, _cmpr) =>
sym = ""
dif = 0.0
if na(_value)
na
else
val1 = array.get(_value, _i)
val2 = array.get(_value, _i+_cmpr)
val1 := val1 == 0 ? 1 : val1
val2 := math.round(val2, 1) == 0 or math.round(val2, 1) == -0 ? 0.1 : val2
dif := math.round(((val1-val2) / math.abs(val2)) * 100) // Change to absolute value
sym := na(dif) ? "" : dif > 0 ? '+'+str.tostring(dif)+'%' : str.tostring(dif)+'%'
table.cell( table_id = _table, column = _column, row = _row, text = na(dif) ? "โ" : toggleMiniMode ? "โ" : sym,text_halign = text.align_right, text_color = na(dif) ? FrameCol : dif >0 ? UpColor : dif <0 ? DownColor : dif ==0 ? UnchangedColor : FrameCol,text_size = tablesize)
// Free Float
free_float = nz(request.financial(syminfo.tickerid, 'FLOAT_SHARES_OUTSTANDING', 'FY'))
ff = na(ta.vwap) ? free_float / 10000000 : free_float * ta.vwap / 10000000
validated_ff = na(ff) or nz(ff) == 0 ? '' : str.tostring(math.round(ff)) + ' Cr'
//Marketcap
outstanding = request.financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")
mc = outstanding*close / 10000000
validated_mc = na(mc) or nz(mc) == 0 ? '' : str.tostring(math.round(mc,0)) + ' Cr'
// Creating the table with final outputs
var table t = table.new(tableposY + "_" + tableposX, columns = 7, rows = datasize, bgcolor = BGColor, frame_color=FrameCol, frame_width=1,border_color=BorderCol, border_width=1)
if barstate.islast and not toggleMiniMode
ft(t,0,0, topleft == 'FF' ? validated_ff : topleft == 'Mcap' ? validated_mc : '')
ft(t,1,0,finID1)
ft(t,2,0, per == 'FY' ? 'YoY' : '%Chg')
ft(t,3,0,finID2)
ft(t,4,0, per == 'FY' ? 'YoY' : '%Chg')
if barstate.islast
if not toggleMiniMode
for i = 0 to datasize-5
// Column #1 Date
ftdate(t, 0, i+1, str.format('{0, date, MMM-yy}', array.get(date, i)))
// Column #2 EPS Data
fcell(finID=finID1, _table=t, _column=1, _row=i+1, _value=arrayFinData1, _i=i)
// Column #3 EPS YoY
fyoy(t, 2, i+1, arrayFinData1, i, per == 'FY' ? 1 : 4)
// Column #4 Sales Data
fcell(finID=finID2, _table=t, _column=3, _row=i+1, _value=arrayFinData2, _i=i)
// Column #5 Sales YoY
fyoy(t, 4, i+1, arrayFinData2, i, per == 'FY' ? 1 : 4)
else if toggleMiniMode
for i = 0 to datasize-5
// Column #1 Date
ftdate(t, 0, i+1, str.format('{0, date, MMM-yy}', array.get(date, i)))
// Column #2 EPS YoY
fyoy(t, 2, i+1, arrayFinData1, i, per == 'FY' ? 1 : 4)
// Column #3 Sales YoY
fyoy(t, 4, i+1, arrayFinData2, i, per == 'FY' ? 1 : 4)
|
Top - Bottom Using MA | https://www.tradingview.com/script/KOM8PdVK-Top-Bottom-Using-MA/ | jadeja_rajdeep | https://www.tradingview.com/u/jadeja_rajdeep/ | 129 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ jadeja_rajdeep
//@version=5
indicator("Top - Bottom From MA",precision = 3)
length=input.int(50,"MA Length",20,252,1,group = "Inputs")
h_l_length=input.int(63,"Highest / Lowest Value Length",20,252,1,group = "Inputs")
p_diff=input.float(0.15,"Diffrence Between High and Low point",0.10,0.50,0.01,group = "Inputs")
sma=ta.sma(ohlc4,length)
ratio=close/sma
h=ta.highest(ratio,h_l_length)
l=ta.lowest(ratio,h_l_length)
m=math.avg(h,l)
msma=ta.linreg(ratio,length,0)
plot(ratio,color =(ratio > msma? color.green : color.red))
hl_color=((h-l) > p_diff ? color.gray : color.orange)
plot(h,color = hl_color)
plot(msma,color = (msma > msma[1] and msma >= l ? color.green : color.red))
plot(m,color = hl_color)
plot(l,color = hl_color)
|
Fair Value Gap [JacobMagleby] | https://www.tradingview.com/script/RQHq3r1m-Fair-Value-Gap-JacobMagleby/ | JacobMagleby | https://www.tradingview.com/u/JacobMagleby/ | 240 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ JacobMagleby
//@version=5
indicator(title = "Fair Value Gap [JacobMagleby]", shorttitle = "Fair Value Gap [JacobMagleby] - Version 1.0.0", overlay = true)
// { <CONSTANTS>
COSMETIC_GROUP = "Cosmetic Settings"
INVALIDATION_GROUP = "Invalidation Settings"
// } <CONSTANTS>
// { <INPUTS>
invalidationOutcome = input.string(
title = "Invalidation Outcome",
defval = "Stop Updating Gap",
options = ["Stop Updating Gap", "Delete Gap"],
group = INVALIDATION_GROUP)
invalidationMethod = input.string(
title = "Invalidation Method",
defval = "Gap Fill",
options = ["Gap Fill", "Number Of Breakouts", "Age Of Gap"],
group = INVALIDATION_GROUP)
maximumBreaks = input.int(
title = "Breakouts Until Invalidation(If Enabled)",
defval = 1,
group = INVALIDATION_GROUP)
maximumAge = input.int(
title = "Bars Until Invalidation(If Enabled)",
defval = 50,
group = INVALIDATION_GROUP)
bullishBorderColor = input.color(
title = "Bullish Border Color",
defval = color.green,
group = COSMETIC_GROUP)
bearishBorderColor = input.color(
title = "Bearish Border Color",
defval = color.red,
group = COSMETIC_GROUP)
midLineColor = input.color(
title = "Middle Line Color",
defval = color.blue,
group = COSMETIC_GROUP)
bullishBackgroundColor = input.color(
title = "Bullish Background Color",
defval = color.new(color.green, 50),
group = COSMETIC_GROUP)
bearishBackgroundColor = input.color(
title = "Bearish Background Color",
defval = color.new(color.red, 50),
group = COSMETIC_GROUP)
borderLineWidth = input.int(
title = "Border Line Width",
defval = 2,
group = COSMETIC_GROUP)
midLineWidth = input.int(
title = "Middle Line Width",
defval = 2,
group = COSMETIC_GROUP)
// } <INPUTS>
// { <USER DEFINED TYPES>
type fairValueGap
line topLine
line botLine
line midLine
linefill bg
float topPrice
float botPrice
float midPrice
int phase
string kind
int age
int flips
// } <USER DEFINED TYPES>
// { <CALCULATIONS>
bullishGapFilled = false
bearishGapFilled = false
bullishGapPartiallyFilled = false
bearishGapPartiallyFilled = false
gapBreakoutUp = false
gapBreakoutDown = false
bullishGapInvalidated = false
bearishGapInvalidated = false
newBullishGap = false
newBearishGap = false
priceInsideBullishGap = false
priceInsideBearishGap = false
bullishGap = low > high[2]
bearishGap = high < low[2]
var fvgArray = array.new<fairValueGap>()
if barstate.isconfirmed
if bullishGap
newTopLine = line.new(
x1 = bar_index[2], y1 = low,
x2 = bar_index, y2 = low,
color = bullishBorderColor, width = borderLineWidth)
newBotLine = line.new(
x1 = bar_index[2], y1 = high[2],
x2 = bar_index, y2 = high[2],
color = bullishBorderColor, width = borderLineWidth)
midLine = line.new(
x1 = bar_index[2], y1 = (low + high[2]) / 2,
x2 = bar_index, y2 = (low + high[2]) / 2, style = line.style_dashed,
color = midLineColor, width = midLineWidth)
bg = linefill.new(newTopLine, newBotLine, bullishBackgroundColor)
fvg = fairValueGap.new(newTopLine, newBotLine, midLine, bg, low, high[2], (low + high[2]) / 2, 1, "Bullish", 0, 0)
array.push(fvgArray, fvg)
newBullishGap := true
if bearishGap
newTopLine = line.new(
x1 = bar_index[2], y1 = low[2],
x2 = bar_index, y2 = low[2],
color = bearishBorderColor, width = borderLineWidth)
newBotLine = line.new(
x1 = bar_index[2], y1 = high,
x2 = bar_index, y2 = high,
color = bearishBorderColor, width = borderLineWidth)
midLine = line.new(
x1 = bar_index[2], y1 = (low[2] + high) / 2,
x2 = bar_index, y2 = (low[2] + high) / 2, style = line.style_dashed,
color = midLineColor, width = midLineWidth)
bg = linefill.new(newTopLine, newBotLine, bearishBackgroundColor)
fvg = fairValueGap.new(newTopLine, newBotLine, midLine, bg, low[2], high, (low[2] + high) / 2, -1, "Bearish", 0, 0)
array.push(fvgArray, fvg)
newBearishGap := true
for fvg in fvgArray
i = array.indexof(fvgArray, fvg)
line.set_x2(fvg.topLine, bar_index + 1)
line.set_x2(fvg.botLine, bar_index + 1)
line.set_x2(fvg.midLine, bar_index + 1)
fvg.age += 1
if invalidationMethod == "Gap Fill"
if fvg.kind == "Bullish"
if low <= fvg.botPrice
line.delete(fvg.topLine)
line.delete(fvg.botLine)
line.delete(fvg.midLine)
linefill.delete(fvg.bg)
array.remove(fvgArray, i)
bullishGapFilled := true
bullishGapInvalidated := true
else if low < fvg.topPrice
fvg.topPrice := low
line.set_y1(fvg.topLine, low)
line.set_y2(fvg.topLine, low)
fvg.midPrice := (low + fvg.botPrice) / 2
line.set_y1(fvg.midLine, fvg.midPrice)
line.set_y2(fvg.midLine, fvg.midPrice)
bullishGapPartiallyFilled := true
else if fvg.kind == "Bearish"
if high >= fvg.topPrice
line.delete(fvg.topLine)
line.delete(fvg.botLine)
line.delete(fvg.midLine)
linefill.delete(fvg.bg)
array.remove(fvgArray, i)
bearishGapFilled := true
bearishGapInvalidated := true
else if high > fvg.botPrice
fvg.botPrice := high
line.set_y1(fvg.botLine, high)
line.set_y2(fvg.botLine, high)
fvg.midPrice := (high + fvg.topPrice) / 2
line.set_y1(fvg.midLine, fvg.midPrice)
line.set_y2(fvg.midLine, fvg.midPrice)
bearishGapPartiallyFilled := true
else if invalidationMethod == "Number Of Breakouts"
if fvg.phase == 1
if close < fvg.botPrice
fvg.phase := -1
fvg.flips += 1
gapBreakoutDown := true
else if fvg.phase == -1
if close > fvg.topPrice
fvg.phase := 1
fvg.flips += 1
gapBreakoutUp := true
if fvg.flips >= maximumBreaks
if invalidationOutcome == "Delete Gap"
line.delete(fvg.topLine)
line.delete(fvg.botLine)
line.delete(fvg.midLine)
linefill.delete(fvg.bg)
array.remove(fvgArray, i)
if fvg.kind == "Bullish"
bullishGapInvalidated := true
else
bearishGapInvalidated := true
else if invalidationMethod == "Age Of Gap"
if fvg.age >= maximumAge
if invalidationOutcome == "Delete Gap"
line.delete(fvg.topLine)
line.delete(fvg.botLine)
line.delete(fvg.midLine)
linefill.delete(fvg.bg)
array.remove(fvgArray, i)
if fvg.kind == "Bullish"
bullishGapInvalidated := true
else
bearishGapInvalidated := true
priceInGap = close <= fvg.topPrice and close >= fvg.botPrice
if fvg.kind == "Bullish" and priceInGap
priceInsideBullishGap := true
else if fvg.kind == "Bearish" and priceInGap
priceInsideBearishGap := true
// } <CALCULATIONS>
// { <ALERTS>
alertcondition(
condition = newBullishGap,
title = "New Bullish Gap")
alertcondition(
condition = newBearishGap,
title = "New Bearish Gap")
alertcondition(
condition = bullishGapFilled,
title = "Bullish Gap Completely Filled")
alertcondition(
condition = bearishGapFilled,
title = "Bearish Gap Completely Filled")
alertcondition(
condition = bullishGapPartiallyFilled,
title = "Bullish Gap Partially Filled")
alertcondition(
condition = bearishGapPartiallyFilled,
title = "Bearish Gap Partially Filled")
alertcondition(
condition = gapBreakoutUp,
title = "Upside Breakout")
alertcondition(
condition = gapBreakoutDown,
title = "Downside Breakout")
alertcondition(
condition = bullishGapInvalidated,
title = "Bullish Gap Invalidated")
alertcondition(
condition = bearishGapInvalidated,
title = "Bearish Gap Invalidated")
alertcondition(
condition = priceInsideBullishGap,
title = "Price Is Inside Bullish Gap")
alertcondition(
condition = priceInsideBearishGap,
title = "Price Is Inside Bearish Gap")
// } <ALERTS> |
Earnings Yield Spread | https://www.tradingview.com/script/UR0OvENS-Earnings-Yield-Spread/ | All_Verklempt | https://www.tradingview.com/u/All_Verklempt/ | 9 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ All_Verklempt
//@version=5
indicator("Earnings Yield Spread", overlay = false)
// earnings yield caluclation
EPS = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE", "TTM")
EarningsYield = (EPS / close) * 100
// us10y & spread calculation
US10Y = request.security("US10Y", timeframe.period, close)
Spread = EarningsYield - US10Y
// plotting
plot(Spread, "Spread", color = color.blue, linewidth = 3, editable = true)
hline(0,"Zero Line", color = color.gray, linestyle = hline.style_dashed, linewidth = 1) |
Previous Day Values | https://www.tradingview.com/script/30DqxLZV-Previous-Day-Values/ | jjustingreyy | https://www.tradingview.com/u/jjustingreyy/ | 89 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ jjustingreyy
//@version=5
indicator("Previous Day Values", overlay = true)
//Previous Day Values
// to highlight the session
var line[] prevDayLines = array.new_line()
prevDayOpen = na(nz(request.security(syminfo.tickerid, "D", time[1])))
isNewDay = not(na(prevDayOpen)) and prevDayOpen != request.security(syminfo.tickerid, "D", time)
if isNewDay and array.size(prevDayLines) > 0
for i = 0 to array.size(prevDayLines) - 1
line.delete(array.get(prevDayLines, i))
array.clear(prevDayLines)
[dh,dl,dc, dv] = request.security(syminfo.ticker, "D", [high[1],low[1], close[1], ta.vwap[1]], lookahead=barmerge.lookahead_on)
// Function to create line and label
f_line_and_label(_p, _color, _text) =>
if (not na(_p))
l = line.new(x1=na, y1=_p, x2=bar_index + 50, y2=_p, width = 1, color=_color, extend = extend.right)
array.push(prevDayLines, l)
var label lb = na
if (na(lb))
lb := label.new(na, na, "", color = color.rgb(255, 255, 255), style = label.style_none, textcolor=color.rgb(255, 255, 255))
label.set_xy(lb, bar_index + 60, _p + syminfo.mintick*0.5)
label.set_text(lb, _text + ": " + str.tostring(_p))
label.set_color(lb, _color)
// Toggle for previous day levels
show_prev_day_high = input(true, title="Show Previous Day High")
show_prev_day_low = input(true, title="Show Previous Day Low")
show_prev_day_vwap = input(true, title="Show Previous Day Vwap")
show_prev_day_close = input(true, title="Show Previous Day Close")
// Display Previous Day Values if toggle is on
if show_prev_day_high
f_line_and_label(dh, color.rgb(254, 101, 101), "Prev Day High")
if show_prev_day_low
f_line_and_label(dl, color.rgb(84, 232, 128), "Prev Day Low")
if show_prev_day_close
f_line_and_label(dc, color.rgb(97, 197, 255), "Prev Day Close")
if show_prev_day_vwap
f_line_and_label(dv, color.rgb(239, 204, 79), "Prev Day VWAP Close") |
Variety Step RSI w/ Dynamic Zones [Loxx] | https://www.tradingview.com/script/065dSPKc-Variety-Step-RSI-w-Dynamic-Zones-Loxx/ | loxx | https://www.tradingview.com/u/loxx/ | 188 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ loxx
//@version=5
indicator("Variety Step RSI w/ Dynamic Zones [Loxx]")
greencolor = #2DD204
redcolor = #D2042D
import loxx/loxxvarietyrsi/1
fema(float src, simple int len)=>
alpha = (2.0 / (2.0 + (len - 1.0) / 2.0))
out = 0.
out := nz(out[1]) + alpha * (src - nz(out[1]))
out
variant(simple string typein, src, per)=>
out = 0.
if typein == "Exponential Moving Average - EMA"
out := ta.ema(src, per)
if typein == "Fast Exponential Moving Average - FEMA"
out := fema(src, per)
out
stepMACalc(float rsi, simple int size)=>
float smax = rsi + 2.0 * size
float smin = rsi - 2.0 * size
var trend = 0
float result = 0
if nz(trend[1]) <= 0 and rsi > nz(smax[1])
trend := 1
if nz(trend[1]) >= 0 and rsi < nz(smin[1])
trend := -1
if trend > 0
if smin < nz(smin[1])
smin := nz(smin[1])
result := smin + size
else
if smax > nz(smax[1])
smax := nz(smax[1])
result := smax - size
result
src = input.source(close, "Source", group = "Basic Settings")
rsitype = input.string("Slow", "RSI Type", options = ["RSX", "Regular", "Slow", "Rapid", "Harris", "Cuttler", "Ehlers Smoothed"], group = "Basic Settings")
rsiper = input.int(14, "RSI Period", group = "Basic Settings")
stpsize = input.int(5, "Step Size", group = "Basic Settings")
signal_length = input.int(9, "Signal Period", group = "Signal/DSL Settings")
sigmatype = input.string("Exponential Moving Average - EMA", "Signal/DSL Smoothing", options = ["Exponential Moving Average - EMA", "Fast Exponential Moving Average - FEMA"], group = "Signal/DSL Settings")
bool colorbars = input.bool(true, "Color bars?", group = "UI Options")
bool showSigs = input.bool(false, "Show signals?", group = "UI Options")
rsimode = switch rsitype
"RSX" => "rsi_rsx"
"Regular" => "rsi_rsi"
"Slow" => "rsi_slo"
"Rapid" => "rsi_rap"
"Harris" => "rsi_har"
"Cuttler" => "rsi_cut"
"Ehlers Smoothed" => "rsi_ehl"
=> "rsi_rsi"
rsiout = loxxvarietyrsi.rsiVariety(rsimode, src, rsiper)
sig = stepMACalc(rsiout, stpsize)
levelu = 0., leveld = 0., mid = 0.
tmp = variant(sigmatype, rsiout, signal_length)
levelu := (rsiout > sig) ? tmp : nz(levelu[1])
leveld := (rsiout < sig) ? tmp: nz(leveld[1])
colorout = rsiout > levelu ? greencolor : rsiout < leveld ? redcolor : color.gray
plot(rsiout, "RSI", color = colorout, linewidth = 2)
plot(levelu, "Upper Level", color = greencolor)
plot(leveld, "Lower Level", color = redcolor)
barcolor(colorbars ? colorout : na)
goLong = ta.crossover(rsiout, levelu)
goShort = ta.crossunder(rsiout, leveld)
plotshape(showSigs and goLong, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.bottom, size = size.auto)
plotshape(showSigs and goShort, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.top, size = size.auto)
alertcondition(goLong, title="Long", message="Step RSI [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")
alertcondition(goShort, title="Short", message="Step RSI [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}") |
Pseudo-Entropy Oscillator with Standard Deviation (modified) | https://www.tradingview.com/script/4c5dwup1-Pseudo-Entropy-Oscillator-with-Standard-Deviation-modified/ | jawauntb | https://www.tradingview.com/u/jawauntb/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ jawauntb
//@version=5
indicator(title="Pseudo-Entropy Oscillator with Standard Deviation", shorttitle="PEO_SD", overlay=false)
entropyPeriod = input(3, title="Entropy Period")
entropyMomentum = input(9, title="Entropy Momentum Length")
entropyMALength = input(3, title="Entropy MA Length")
fastPeriod = input(13, title="Fast Period")
slowPeriod = input(33, title="Slow Period")
// Calculate pseudo-entropy using standard deviation
pseudoEntropy = ta.stdev(close, entropyPeriod)
entropyDelta = ta.mom(pseudoEntropy, entropyMomentum)
entropySMA = ta.sma(pseudoEntropy, entropyMALength)
// Combine the pseudo entropy delta and SMA similar to RSI code
pseudoEntropyCombined = entropyDelta + entropySMA
// Calculate fast, medium and slow SMAs of combined pseudo-entropy
fastSMA = ta.sma(pseudoEntropyCombined, fastPeriod)
mediumSMA = ta.sma(pseudoEntropyCombined, entropyPeriod)
slowSMA = ta.sma(pseudoEntropyCombined, slowPeriod)
// Normalize the values to an unbounded oscillator using Z-score normalization
fastSMA_norm = 50 + ((fastSMA - ta.sma(fastSMA, fastPeriod)) / ta.stdev(fastSMA, fastPeriod)) * 10
mediumSMA_norm = 50 + ((mediumSMA - ta.sma(mediumSMA, entropyPeriod)) / ta.stdev(mediumSMA, entropyPeriod)) * 10
slowSMA_norm = 50 + ((slowSMA - ta.sma(slowSMA, slowPeriod)) / ta.stdev(slowSMA, slowPeriod)) * 10
// Plot pseudo-entropy oscillator
plot(fastSMA_norm, title="Fast Pseudo-Entropy", color=color.rgb(62, 159, 255))
plot(mediumSMA_norm, title="Medium Pseudo-Entropy", color=color.rgb(255, 255, 0))
plot(slowSMA_norm, title="Slow Pseudo-Entropy", color=color.rgb(243, 33, 68))
hline(50, title="Mid Line", color=color.gray)
hline(20, title="Lower Bound", color=color.gray)
hline(80, title="Upper Bound", color=color.gray)
|
QuantBot 3:Ultimate MA Crossover | https://www.tradingview.com/script/LNGkkvkt-QuantBot-3-Ultimate-MA-Crossover/ | TheQuantBot | https://www.tradingview.com/u/TheQuantBot/ | 15 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ TheQuantBot
//@version=4
study("QuantBot 3:Ultimate MA Crossover",overlay = true)
mav = input(title="Moving Average Type", defval="SMA", options=["SMA", "EMA", "HMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"],group = "Fast Moving Average",inline = "a")
length =input(20, "Moving Average Length", minval=1,group = "Fast Moving Average")
color_ = input(color.maroon,"",inline = "a",group = "Fast Moving Average")
src = input(close,"source",group = "Fast Moving Average")
mav2 = input(title="Moving Average Type", defval="SMA", options=["SMA", "EMA", "HMA", "WMA", "TMA", "VAR", "WWMA", "ZLEMA", "TSF"],group = "Slow Moving Average",inline = "b")
length2 =input(50, "Moving Average Length", minval=1,group = "Slow Moving Average")
color2_ = input(color.purple,"",inline = "b",group = "Slow Moving Average")
src2 = input(close,"source",group = "Slow Moving Average")
valpha=2/(length+1)
vud1=src>src[1] ? src-src[1] : 0
vdd1=src<src[1] ? src[1]-src : 0
vUD=sum(vud1,9)
vDD=sum(vdd1,9)
vCMO=nz((vUD-vDD)/(vUD+vDD))
VAR=0.0
VAR:=nz(valpha*abs(vCMO)*src)+(1-valpha*abs(vCMO))*nz(VAR[1])
wwalpha = 1/ length
WWMA = 0.0
WWMA := wwalpha*src + (1-wwalpha)*nz(WWMA[1])
zxLag = length/2==round(length/2) ? length/2 : (length - 1) / 2
zxEMAData = (src + (src - src[zxLag]))
ZLEMA = ema(zxEMAData, length)
lrc = linreg(src, length, 0)
lrc1 = linreg(src,length,1)
lrs = (lrc-lrc1)
TSF = linreg(src, length, 0)+lrs
getMA(src, length) =>
ma = 0.0
if mav == "SMA"
ma := sma(src, length)
ma
if mav == "HMA"
ma := hma(src, length)
ma
if mav == "EMA"
ma := ema(src, length)
ma
if mav == "WMA"
ma := wma(src, length)
ma
if mav == "TMA"
ma := sma(sma(src, ceil(length / 2)), floor(length / 2) + 1)
ma
if mav == "VAR"
ma := VAR
ma
if mav == "WWMA"
ma := WWMA
ma
if mav == "ZLEMA"
ma := ZLEMA
ma
if mav == "TSF"
ma := TSF
ma
ma
getMA2(src, length) =>
ma = 0.0
if mav2 == "SMA"
ma := sma(src, length)
ma
if mav2 == "HMA"
ma := hma(src, length)
ma
if mav2 == "EMA"
ma := ema(src, length)
ma
if mav2 == "WMA"
ma := wma(src, length)
ma
if mav2 == "TMA"
ma := sma(sma(src, ceil(length / 2)), floor(length / 2) + 1)
ma
if mav2 == "VAR"
ma := VAR
ma
if mav2 == "WWMA"
ma := WWMA
ma
if mav2 == "ZLEMA"
ma := ZLEMA
ma
if mav2 == "TSF"
ma := TSF
ma
ma
MAvg1=getMA(src, length)
ma1 = plot(MAvg1,title = "Fast Moving Average",linewidth = 2,color = color_)
MAvg2=getMA2(src2, length2)
ma2 = plot(MAvg2,title = "Slow Moving Average",linewidth = 3,color = color2_)
fillcolor = MAvg1>MAvg2?color.green:color.red
fill(ma1,ma2,color = fillcolor ,transp = 85)
long = MAvg1 > MAvg2 and MAvg1[1] < MAvg2[1]
short = MAvg1 < MAvg2 and MAvg1[1] > MAvg2[1]
////////////////////////////////////////////////////////////////////////////////
buyline = 0.0
sellline = 0.0
strategy_position_avg_price = 0.0
strategy_position_size = 0
longtpline = 0.0
shorttpline = 0.0
broker = input("Angel Broking","Broker",options = ["Alice Blue","Angel Broking","Fyers","Profitmart","Upstox","Zerodha","Paper Trading"],inline = "l1",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
segment = input("Equity","Segment",options = ["Equity","Futures","Options","Commodity"],inline = "l1",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
exchange = syminfo.prefix
strike = "Automatic"//,"Strike",options = ["Automatic","Manual"])
quantity = input(100,"Quantity (IMPORTANT: Enter no of Lots for Futures and options)",minval = 1,group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
pmd = input(false,"Pyramiding",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |"),pyramid = pmd == false?"False":"True"
ticker = syminfo.ticker
ltp = tostring(close)
action = strategy_position_size > strategy_position_size[1]?"Buy":strategy_position_size < strategy_position_size[1]?"Sell":"Default Value"//-------------------------------------------------------------------------------------
net_position = strategy_position_size > 0 ? "Long":strategy_position_size < 0? "Short":"Flat"
validity = input("Day","Validity",options = ["Day","IOC"],inline = "l1",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
variety = input("Regular","Order Type ----------------",options = ["Regular","Bracket","Cover","AMO"],inline = "op",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
product_type = input("Intraday","",options = ["Intraday","Delivery"],inline = "op",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
type = input("Market","", options = ["Market","Limit","Stop-market","Stop-limit"],inline = "op",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
limit_price = input(0.0,"Limit Price ------(Only for Limit/SL order*)",inline = "lp",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
stop_loss = input(0.0,"Stop Loss --(Only For BO,CO, SL-M and SL*)",inline = "sl",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
take_profit = input(0.0,"Take Profit -------(Only For BO Order type*)",inline = "tp",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
lpp = input(false,"Percentage (%)",inline = "lp",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
limit_price_percentage = lpp?"True":"False"
slp = input(false,"Percentage (%)",inline = "sl",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
stop_loss_percentage = slp?"True":"False"
tpp = input(false,"Percentage (%)",inline = "tp",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
take_profit_percentage = tpp?"True":"False"
near_by = input(100,"Minimum difference between two strike prices",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
diff_atm = input(1,"Distance from ATM option",group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
option_side = input("Buy","Option Buy or sell",options = ["Buy","Sell"],group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
expiry = input("Current Week","Expiry",options = ["Current Week","Next Week", "Current Month", "Next Month"],group = "|--------- QuantBot Automation Settings --------| |============================================||=== Help +91 8016200637 (Whatsapp, Telegram) |")
if long[1]
strategy_position_size := quantity
else if short[1]
strategy_position_size := -quantity
else if short[1] and false // only long Exit
strategy_position_size := 0
else if long[1] and false // only short exit
strategy_position_size := 0
else
strategy_position_size := strategy_position_size[1]
onlylong = long[1] and strategy_position_size[1] == 0
onlyshort = short[1] and strategy_position_size[1] == 0
onlylongexit = false
onlyshortexit = false
shortexitlong = long[1] and strategy_position_size[1] < 0
longexitshort = short[1] and strategy_position_size[1] > 0
// Automation alret handeling
if onlylong
strategy_position_avg_price := close[1]
else if shortexitlong
strategy_position_avg_price := close[1]
else if onlyshort
strategy_position_avg_price := close[1]
else if longexitshort
strategy_position_avg_price := close[1]
else
strategy_position_avg_price := strategy_position_avg_price[1]
// plot(strategy_position_avg_price)
if onlylong
//Send alert for buy
alert('{"broker":"'+broker+'","segment":"'+segment+'","exchange":"'+exchange +'","strike":"'+strike+'","quantity":'+tostring(quantity)+',"pyramid":"'+pyramid+'","ticker":"'+syminfo.ticker+'","ltp":'+tostring(close)+',"action":"'+"Buy"+'","net_position":"'+"Long"+'","validity":"'+validity+'","variety":"'+variety+'","product_type":"'+product_type+'","type":"'+type+'","limit_price_percentage":"'+limit_price_percentage+'","stop_loss_percentage":"'+stop_loss_percentage+'","take_profit_percentage":"'+take_profit_percentage+'","limit_price":'+tostring(limit_price)+',"stop_loss":'+tostring(stop_loss)+',"take_profit":'+tostring(take_profit)+',"option_side":"'+option_side+'","near_by":'+tostring(near_by)+',"diff_atm":'+tostring(diff_atm)+',"expiry":"'+ expiry +'"}')
else if shortexitlong
// send alert for short exit and make flat
alert('{"broker":"'+broker+'","segment":"'+segment+'","exchange":"'+exchange +'","strike":"'+strike+'","quantity":'+tostring(2*quantity)+',"pyramid":"'+pyramid+'","ticker":"'+syminfo.ticker+'","ltp":'+tostring(close)+',"action":"'+"Buy"+'","net_position":"'+"Long"+'","validity":"'+validity+'","variety":"'+variety+'","product_type":"'+product_type+'","type":"'+type+'","limit_price_percentage":"'+limit_price_percentage+'","stop_loss_percentage":"'+stop_loss_percentage+'","take_profit_percentage":"'+take_profit_percentage+'","limit_price":'+tostring(limit_price)+',"stop_loss":'+tostring(stop_loss)+',"take_profit":'+tostring(take_profit)+',"option_side":"'+option_side+'","near_by":'+tostring(near_by)+',"diff_atm":'+tostring(diff_atm)+',"expiry":"'+ expiry +'"}')
else if onlyshort
//Send alert for sell
alert('{"broker":"'+broker+'","segment":"'+segment+'","exchange":"'+exchange +'","strike":"'+strike+'","quantity":'+tostring(quantity)+',"pyramid":"'+pyramid+'","ticker":"'+syminfo.ticker+'","ltp":'+tostring(close)+',"action":"'+"Sell"+'","net_position":"'+"Short"+'","validity":"'+validity+'","variety":"'+variety+'","product_type":"'+product_type+'","type":"'+type+'","limit_price_percentage":"'+limit_price_percentage+'","stop_loss_percentage":"'+stop_loss_percentage+'","take_profit_percentage":"'+take_profit_percentage+'","limit_price":'+tostring(limit_price)+',"stop_loss":'+tostring(stop_loss)+',"take_profit":'+tostring(take_profit)+',"option_side":"'+option_side+'","near_by":'+tostring(near_by)+',"diff_atm":'+tostring(diff_atm)+',"expiry":"'+ expiry +'"}')
else if longexitshort
// send alert for long exit and make flat
alert('{"broker":"'+broker+'","segment":"'+segment+'","exchange":"'+exchange +'","strike":"'+strike+'","quantity":'+tostring(2*quantity)+',"pyramid":"'+pyramid+'","ticker":"'+syminfo.ticker+'","ltp":'+tostring(close)+',"action":"'+"Sell"+'","net_position":"'+"Short"+'","validity":"'+validity+'","variety":"'+variety+'","product_type":"'+product_type+'","type":"'+type+'","limit_price_percentage":"'+limit_price_percentage+'","stop_loss_percentage":"'+stop_loss_percentage+'","take_profit_percentage":"'+take_profit_percentage+'","limit_price":'+tostring(limit_price)+',"stop_loss":'+tostring(stop_loss)+',"take_profit":'+tostring(take_profit)+',"option_side":"'+option_side+'","near_by":'+tostring(near_by)+',"diff_atm":'+tostring(diff_atm)+',"expiry":"'+ expiry +'"}')
else if onlylongexit
//Send alert for buy
alert('{"broker":"'+broker+'","segment":"'+segment+'","exchange":"'+exchange +'","strike":"'+strike+'","quantity":'+tostring(quantity)+',"pyramid":"'+pyramid+'","ticker":"'+syminfo.ticker+'","ltp":'+tostring(close)+',"action":"'+"Sell"+'","net_position":"'+"Flat"+'","validity":"'+validity+'","variety":"'+variety+'","product_type":"'+product_type+'","type":"'+type+'","limit_price_percentage":"'+limit_price_percentage+'","stop_loss_percentage":"'+stop_loss_percentage+'","take_profit_percentage":"'+take_profit_percentage+'","limit_price":'+tostring(limit_price)+',"stop_loss":'+tostring(stop_loss)+',"take_profit":'+tostring(take_profit)+',"option_side":"'+option_side+'","near_by":'+tostring(near_by)+',"diff_atm":'+tostring(diff_atm)+',"expiry":"'+ expiry +'"}')
else if onlyshortexit
//Send alert for buy
alert('{"broker":"'+broker+'","segment":"'+segment+'","exchange":"'+exchange +'","strike":"'+strike+'","quantity":'+tostring(quantity)+',"pyramid":"'+pyramid+'","ticker":"'+syminfo.ticker+'","ltp":'+tostring(close)+',"action":"'+"Buy"+'","net_position":"'+"Flat"+'","validity":"'+validity+'","variety":"'+variety+'","product_type":"'+product_type+'","type":"'+type+'","limit_price_percentage":"'+limit_price_percentage+'","stop_loss_percentage":"'+stop_loss_percentage+'","take_profit_percentage":"'+take_profit_percentage+'","limit_price":'+tostring(limit_price)+',"stop_loss":'+tostring(stop_loss)+',"take_profit":'+tostring(take_profit)+',"option_side":"'+option_side+'","near_by":'+tostring(near_by)+',"diff_atm":'+tostring(diff_atm)+',"expiry":"'+ expiry +'"}')
plotshape(onlylong?close:na,title = "Long Entry",location = location.belowbar,color = color.green,text = "Long Entry",textcolor = color.white,size = size.normal,style = shape.labelup)
plotshape(shortexitlong?close:na,title = "Short Exit and Long Entry",location = location.belowbar,color = color.green,text = "Short Exit and Long Entry",textcolor = color.white,size = size.normal,style = shape.labelup)
plotshape(onlyshortexit?close:na,title = "Short Exit",location = location.belowbar,color = color.green,text = "Short Exit",textcolor = color.white,size = size.normal,style = shape.labelup)
plotshape(onlyshort ?close:na,title = "Short Entry",location = location.abovebar,color = color.red,text = "Short Entry",textcolor = color.white,size = size.normal,style = shape.labeldown)
plotshape(longexitshort?close:na,title = "Long Exit and Short Entry",location = location.abovebar,color = color.red,text = "Long Exit and Short Entry",textcolor = color.white,size = size.normal,style = shape.labeldown)
plotshape(onlylongexit?close:na,title = "Long Exit",location = location.abovebar,color = color.red,text = "Long Exit",textcolor = color.white,size = size.normal,style = shape.labeldown)
|
eHarmonicpatternsLogScale | https://www.tradingview.com/script/dWGLjquM-eHarmonicpatternsLogScale/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 28 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ HeWhoMustNotBeNamed
// โโ
// โโโ โโ
// โโโโโ โโ
// โโโโโโโโ โ โโ
// โโโโโโ โ โโ
// โโโโ โ โโโโโโโโโโโ
// โโโโโโโโโโโ โ โโโโโโโโโโโโโโโโโโโโ
// โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโ โโ
// โโโโโ โโโโโโโ
// โโโโโโโโโ
// โโโโโ โโโโโ
// โโโโโ โโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ
// โโโโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโ
// โโโโโ โโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโ โโโโโโ
// โโโโโ โโโโโ โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโ
// โโ โ
//@version=5
// @description Library provides functions to scan harmonic patterns both or normal and log scale
library("eHarmonicpatternsLogScale", overlay=true)
import HeWhoMustNotBeNamed/FibRatios/1 as fibs
isInRange(ratio, min, max)=> ratio >= min and ratio <= max
getadj(p1, p2, adj, logScale)=>math.max(0, fibs.retracement(p1, p2, adj, logScale))
getrange(float p1, float p2, simple float min, simple float max,
simple float ep, simple float adjs, simple float adje,
bool[] pArray, float[] startRange, float[] endRange, simple int index, bool logScale)=>
returnval = false
if(array.get(pArray, index))
eamin = (100 - (ep+adjs)) / 100
eamax = (100 + ep+adje) / 100
start = getadj(p1, p2, min*eamin, logScale)
end = getadj(p1, p2, max*eamax, logScale)
array.set(startRange, index, start)
array.set(endRange, index, end)
returnval := true
returnval
getrange(float p1, float p2, simple float min1, simple float max1,
float p3, float p4, simple float min2, simple float max2,
bool[] pArray, float[] startRange, float[] endRange, simple int index, simple bool logScale)=>
returnval = false
if(array.get(pArray, index))
start1 = getadj(p1, p2, min1, logScale)
end1 = getadj(p1, p2, max1, logScale)
start2 = getadj(p3, p4, min2, logScale)
end2 = getadj(p3, p4, max2, logScale)
start = start1 > end1? math.min(start1, start2) : math.max(start1, start2)
end = start1 > end1? math.max(end1, end2) : math.min(end1, end2)
d1 = start1>end1? 1 : -1
d2 = start2>end2? 1 : -1
d = start>end? 1 : -1
if(d1 == d2 and d == d1 and (start > 0 or end > 0))
returnval := true
array.set(startRange, index, start)
array.set(endRange, index, end)
else
array.set(pArray, index, false)
returnval
getrange(float p1, float p2, simple float min1, simple float max1,
float p3, float p4, simple float min2, simple float max2,
simple float ep1, simple float ep2,
simple float adjs, simple float adje,
bool[] pArray, float[] startRange, float[] endRange, simple int index, bool logScale)=>
returnval = false
if(array.get(pArray, index))
eamin1 = (100 - (ep1+adjs)) / 100
eamax1 = (100 + ep1+adje) / 100
eamin2 = (100 - (ep2+adjs)) / 100
eamax2 = (100 + ep2+adje) / 100
start1 = getadj(p1, p2, min1*eamin1, logScale)
end1 = getadj(p1, p2, max1*eamax1, logScale)
start2 = getadj(p3, p4, min2*eamin2, logScale)
end2 = getadj(p3, p4, max2*eamax2, logScale)
start = start1 > end1? math.min(start1, start2) : math.max(start1, start2)
end = start1 > end1? math.max(end1, end2) : math.min(end1, end2)
d1 = start1>end1? 1 : -1
d2 = start2>end2? 1 : -1
d = start>end? 1 : -1
if(d1 == d2 and d == d1 and (start > 0 or end > 0))
returnval := true
array.set(startRange, index, start)
array.set(endRange, index, end)
else
array.set(pArray, index, false)
returnval
getNumberOfSupportedPatterns()=>25
evaluate(patternArray, index, ratio, min, max, err_min, err_max)=>
if array.get(patternArray, index)
array.set(patternArray, index, isInRange(ratio, min*err_min, max*err_max))
export getSupportedPatterns()=>
patternLabelArray = array.new_string()
array.push(patternLabelArray, "Gartley")
array.push(patternLabelArray, "Crab")
array.push(patternLabelArray, "DeepCrab")
array.push(patternLabelArray, "Bat")
array.push(patternLabelArray, "Butterfly")
array.push(patternLabelArray, "Shark")
array.push(patternLabelArray, "Cypher")
array.push(patternLabelArray, "NenStar")
array.push(patternLabelArray, "Anti NenStar")
array.push(patternLabelArray, "Anti Shark")
array.push(patternLabelArray, "Anti Cypher")
array.push(patternLabelArray, "Anti Crab")
array.push(patternLabelArray, "Anti Butterfly")
array.push(patternLabelArray, "Anti Bat")
array.push(patternLabelArray, "Anti Gartley")
array.push(patternLabelArray, "Navarro200")
array.push(patternLabelArray, "Five Zero")
array.push(patternLabelArray, "Three Drives")
array.push(patternLabelArray, "White Swan")
array.push(patternLabelArray, "Black Swan")
array.push(patternLabelArray, "Sea Pony")
array.push(patternLabelArray, "Leonardo")
array.push(patternLabelArray, "121")
array.push(patternLabelArray, "Snorm")
array.push(patternLabelArray, "Total")
patternLabelArray
scan_xab(float xabRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
//Gartley
evaluate(patternArray, 0, xabRatio, 0.618, 0.618, err_min, err_max)
//Crab
evaluate(patternArray, 1, xabRatio, 0.382, 0.618, err_min, err_max)
//DeepCrab
evaluate(patternArray, 2, xabRatio, 0.886, 0.886, err_min, err_max)
//Bat
evaluate(patternArray, 3, xabRatio, 0.382, 0.500, err_min, err_max)
//Butterfly
evaluate(patternArray, 4, xabRatio, 0.786, 0.786, err_min, err_max)
//Shark
evaluate(patternArray, 5, xabRatio, 0.446, 0.618, err_min, err_max)
//Cypher
evaluate(patternArray, 6, xabRatio, 0.382, 0.618, err_min, err_max)
//NenStar
evaluate(patternArray, 7, xabRatio, 0.382, 0.618, err_min, err_max)
//Anti NenStar
evaluate(patternArray, 8, xabRatio, 0.500, 0.786, err_min, err_max)
//Anti Shark
evaluate(patternArray, 9, xabRatio, 0.446, 0.618, err_min, err_max)
//Anti Cypher
evaluate(patternArray, 10, xabRatio, 0.500, 0.786, err_min, err_max)
//Anti Crab
evaluate(patternArray, 11, xabRatio, 0.276, 0.446, err_min, err_max)
//Anti Butterfly
evaluate(patternArray, 12, xabRatio, 0.382, 0.618, err_min, err_max)
//Anti Bat
evaluate(patternArray, 13, xabRatio, 0.382, 0.618, err_min, err_max)
//Anti Gartley
evaluate(patternArray, 14, xabRatio, 0.618, 0.786, err_min, err_max)
//Navarro200
evaluate(patternArray, 15, xabRatio, 0.382, 0.786, err_min, err_max)
//5-0
evaluate(patternArray, 16, xabRatio, 1.270, 1.618, err_min, err_max)
//Three Drives
evaluate(patternArray, 17, xabRatio, 0.618, 0.786, err_min, err_max)
//White Swan
evaluate(patternArray, 18, xabRatio, 0.382, 0.786, err_min, err_max)
//Black Swan
evaluate(patternArray, 19, xabRatio, 1.382, 2.618, err_min, err_max)
//Sea Pony
evaluate(patternArray, 20, xabRatio, 0.128, 3.618, err_min, err_max)
//Leonardo
evaluate(patternArray, 21, xabRatio, 0.500, 0.500, err_min, err_max)
//121
evaluate(patternArray, 22, xabRatio, 0.500, 0.786, err_min, err_max)
//Snorm
evaluate(patternArray, 23, xabRatio, 0.900, 1.100, err_min, err_max)
//Total
evaluate(patternArray, 24, xabRatio, 0.236, 0.786, err_min, err_max)
scan_abc_axc(float abcRatio, float axcRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
//Gartley
evaluate(patternArray, 0, abcRatio, 0.382, 0.886, err_min, err_max)
//Crab
evaluate(patternArray, 1, abcRatio, 0.382, 0.886, err_min, err_max)
//DeepCrab
evaluate(patternArray, 2, abcRatio, 0.382, 0.886, err_min, err_max)
//Bat
evaluate(patternArray, 3, abcRatio, 0.382, 0.886, err_min, err_max)
//Butterfly
evaluate(patternArray, 4, abcRatio, 0.382, 0.886, err_min, err_max)
//Shark
evaluate(patternArray, 5, abcRatio, 1.130, 1.618, err_min, err_max)
//Cypher
evaluate(patternArray, 6, axcRatio, 1.130, 1.414, err_min, err_max)
//NenStar
evaluate(patternArray, 7, abcRatio, 1.414, 2.140, err_min, err_max)
//Anti NenStar
evaluate(patternArray, 8, abcRatio, 0.467, 0.707, err_min, err_max)
//Anti Shark
evaluate(patternArray, 9, abcRatio, 0.618, 0.886, err_min, err_max)
//Anti Cypher
evaluate(patternArray, 10, abcRatio, 0.467, 0.707, err_min, err_max)
//Anti Crab
evaluate(patternArray, 11, abcRatio, 1.128, 2.618, err_min, err_max)
//Anti Butterfly
evaluate(patternArray, 12, abcRatio, 1.128, 2.618, err_min, err_max)
//Anti Bat
evaluate(patternArray, 13, abcRatio, 1.128, 2.618, err_min, err_max)
//Anti Gartley
evaluate(patternArray, 14, abcRatio, 1.128, 2.618, err_min, err_max)
//Navarro200
evaluate(patternArray, 15, abcRatio, 0.886, 1.127, err_min, err_max)
//5-0
evaluate(patternArray, 16, abcRatio, 1.168, 2.240, err_min, err_max)
//Three Drives
evaluate(patternArray, 17, abcRatio, 1.272, 1.618, err_min, err_max)
//White Swan
evaluate(patternArray, 18, abcRatio, 2.000, 4.237, err_min, err_max)
//Black Swan
evaluate(patternArray, 19, abcRatio, 0.236, 0.500, err_min, err_max)
//Sea Pony
evaluate(patternArray, 20, abcRatio, 0.382, 0.500, err_min, err_max)
//Leonardo
evaluate(patternArray, 21, abcRatio, 0.382, 0.886, err_min, err_max)
//121
evaluate(patternArray, 22, abcRatio, 1.128, 3.618, err_min, err_max)
//Snorm
evaluate(patternArray, 23, abcRatio, 0.900, 1.100, err_min, err_max)
//Total
evaluate(patternArray, 24, abcRatio, 0.382, 2.618, err_min, err_max)
scan_bcd(float bcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
//Gartley
evaluate(patternArray, 0, bcdRatio, 1.272, 1.618, err_min, err_max)
//Crab
evaluate(patternArray, 1, bcdRatio, 2.240, 3.618, err_min, err_max)
//DeepCrab
evaluate(patternArray, 2, bcdRatio, 2.000, 3.618, err_min, err_max)
//Bat
evaluate(patternArray, 3, bcdRatio, 1.618, 2.618, err_min, err_max)
//Butterfly
evaluate(patternArray, 4, bcdRatio, 1.618, 2.618, err_min, err_max)
//Shark
evaluate(patternArray, 5, bcdRatio, 1.618, 2.236, err_min, err_max)
//Cypher
// Not required
//NenStar
evaluate(patternArray, 7, bcdRatio, 1.272, 2.000, err_min, err_max)
//Anti NenStar
evaluate(patternArray, 8, bcdRatio, 1.618, 2.618, err_min, err_max)
//Anti Shark
evaluate(patternArray, 9, bcdRatio, 1.618, 2.618, err_min, err_max)
//Anti Cypher
evaluate(patternArray, 10, bcdRatio, 1.618, 2.618, err_min, err_max)
//Anti Crab
evaluate(patternArray, 11, bcdRatio, 1.618, 2.618, err_min, err_max)
//Anti Butterfly
evaluate(patternArray, 12, bcdRatio, 1.272, 1.272, err_min, err_max)
//Anti Bat
evaluate(patternArray, 13, bcdRatio, 2.000, 2.618, err_min, err_max)
//Anti Gartley
evaluate(patternArray, 14, bcdRatio, 1.618, 1.618, err_min, err_max)
//Navarro200
evaluate(patternArray, 15, bcdRatio, 0.886, 3.618, err_min, err_max)
//5-0
evaluate(patternArray, 16, bcdRatio, 0.500, 0.500, err_min, err_max)
//Three Drives
evaluate(patternArray, 17, bcdRatio, 0.618, 0.786, err_min, err_max)
//White Swan
evaluate(patternArray, 18, bcdRatio, 0.500, 0.886, err_min, err_max)
//Black Swan
evaluate(patternArray, 19, bcdRatio, 1.128, 2.000, err_min, err_max)
//Sea Pony
evaluate(patternArray, 20, bcdRatio, 1.618, 2.618, err_min, err_max)
//Leonardo
evaluate(patternArray, 21, bcdRatio, 1.128, 2.618, err_min, err_max)
//121
evaluate(patternArray, 22, bcdRatio, 0.388, 0.786, err_min, err_max)
//Snorm
evaluate(patternArray, 23, bcdRatio, 0.900, 1.100, err_min, err_max)
//Total
evaluate(patternArray, 24, bcdRatio, 1.272, 4.236, err_min, err_max)
scan_xad_xcd(float xadRatio, float xcdRatio, simple float err_min, simple float err_max, bool[] patternArray)=>
if(array.includes(patternArray, true))
//Gartley
evaluate(patternArray, 0, xadRatio, 0.786, 0.786, err_min, err_max)
//Crab
evaluate(patternArray, 1, xadRatio, 1.618, 1.618, err_min, err_max)
//DeepCrab
evaluate(patternArray, 2, xadRatio, 1.618, 1.618, err_min, err_max)
//Bat
evaluate(patternArray, 3, xadRatio, 0.886, 0.886, err_min, err_max)
//Butterfly
evaluate(patternArray, 4, xadRatio, 1.272, 1.618, 1, 1)
//Shark
evaluate(patternArray, 5, xadRatio, 0.886, 0.886, err_min, err_max)
//Cypher
evaluate(patternArray, 6, xcdRatio, 0.786, 0.786, err_min, err_max)
//NenStar
evaluate(patternArray, 7, xadRatio, 1.272, 1.272, err_min, err_max)
//Anti NenStar
evaluate(patternArray, 8, xadRatio, 0.786, 0.786, err_min, err_max)
//Anti Shark
evaluate(patternArray, 9, xadRatio, 1.130, 1.130, err_min, err_max)
//Anti Cypher
evaluate(patternArray, 10, xadRatio, 1.272, 1.272, err_min, err_max)
//Anti Crab
evaluate(patternArray, 11, xadRatio, 0.618, 0.618, err_min, err_max)
//Anti Butterfly
evaluate(patternArray, 12, xadRatio, 0.618, 0.786, err_min, err_max)
//Anti Bat
evaluate(patternArray, 13, xadRatio, 1.128, 1.128, err_min, err_max)
//Anti Gartley
evaluate(patternArray, 14, xadRatio, 1.272, 1.272, err_min, err_max)
//Navarro200
evaluate(patternArray, 15, xadRatio, 0.886, 1.127, 1, 1)
//5-0
evaluate(patternArray, 16, xadRatio, 0.886, 1.130, 1, 1)
//Three Drives
evaluate(patternArray, 17, xadRatio, 0.130, 0.886, 1, 1)
//White Swan
evaluate(patternArray, 18, xadRatio, 0.230, 0.886, 1, 1)
//Black Swan
evaluate(patternArray, 19, xadRatio, 1.128, 2.618, 1, 1)
//Sea Pony
evaluate(patternArray, 20, xadRatio, 0.618, 3.618, 1, 1)
//Leonardo
evaluate(patternArray, 21, xadRatio, 0.786, 0.786, err_min, err_max)
//121
evaluate(patternArray, 22, xadRatio, 0.382, 0.786, 1, 1)
//Snorm
evaluate(patternArray, 23, xadRatio, 0.618, 1.618, 1, 1)
//Total
evaluate(patternArray, 24, xadRatio, 0.618, 1.618, 1, 1)
// @function Provides PRZ range based on BCD and XAD ranges
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @param logScale - calculate on log scale. Default is false
// @returns [dStart, dEnd] Start and end of consolidated PRZ range
export get_prz_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0, bool logScale=false)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, b, c, 1.272, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0, logScale)
//Crab
getrange(x, a, 1.618, 1.618, b, c, 2.240, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1, logScale)
//DeepCrab
getrange(x, a, 1.618, 1.618, b, c, 2.000, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2, logScale)
//Bat
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3, logScale)
//Butterfly
getrange(x, a, 1.272, 1.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4, logScale)
//Shark
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5, logScale)
//Cypher
getrange(x, c, 0.786, 0.786, x, c, 0.786, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6, logScale)
//NenStar
getrange(x, a, 1.272, 1.272, b, c, 1.272, 2.000, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7, logScale)
//Anti NenStar
getrange(x, a, 0.786, 0.786, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8, logScale)
//Anti Shark
getrange(x, a, 1.130, 1.130, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9, logScale)
//Anti Cypher
getrange(x, a, 1.272, 1.272, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10, logScale)
//Anti Crab
getrange(x, a, 0.618, 0.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11, logScale)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, b, c, 1.272, 1.272, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12, logScale)
//Anti Bat
getrange(x, a, 1.128, 1.128, b, c, 2.000, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13, logScale)
//Anti Gartley
getrange(x, a, 1.272, 1.272, b, c, 1.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14, logScale)
//Navarro200
getrange(x, a, 0.886, 1.127, b, c, 0.886, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15, logScale)
//5-0
getrange(x, a, 0.886, 1.13, b, c, 0.5, 0.5, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 16, logScale)
//Three Drives
getrange(x, a, 0.13, 1.886, b, c, 0.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 17, logScale)
//White Swan
getrange(x, a, 0.236, 0.886, b, c, 0.5, 0.886, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 18, logScale)
//Black Swan
getrange(x, a, 1.128, 2.618, b, c, 1.128, 2.0, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 19, logScale)
//Sea Pony
getrange(x, a, 0.618, 3.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 20, logScale)
//Leonardo
getrange(x, a, 0.786, 0.786, b, c, 1.128, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 21, logScale)
//121
getrange(x, a, 0.382, 0.786, b, c, 0.382, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 22, logScale)
//Snorm
getrange(x, a, 0.618, 1.618, b, c, 0.9, 1.1, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 23, logScale)
//Total
getrange(x, a, 0.618, 1.618, b, c, 1.272, 4.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 24, logScale)
dStart = b > c? array.min(startRange) : array.max(startRange)
dEnd = b > c? array.max(endRange) : array.min(endRange)
[dStart, dEnd]
// @function Provides PRZ range based on XAD range only
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @param logScale - calculate on log scale. Default is false
// @returns [dStart, dEnd] Start and end of consolidated PRZ range
export get_prz_range_xad(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0, bool logScale=false)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0, logScale)
//Crab
getrange(x, a, 1.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1, logScale)
//DeepCrab
getrange(x, a, 1.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2, logScale)
//Bat
getrange(x, a, 0.886, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3, logScale)
//Butterfly
getrange(x, a, 1.272, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4, logScale)
//Shark
getrange(x, a, 0.886, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5, logScale)
//Cypher
getrange(x, c, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6, logScale)
//NenStar
getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7, logScale)
//Anti NenStar
getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8, logScale)
//Anti Shark
getrange(x, a, 1.130, 1.130, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9, logScale)
//Anti Cypher
getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10, logScale)
//Anti Crab
getrange(x, a, 0.618, 0.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11, logScale)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12, logScale)
//Anti Bat
getrange(x, a, 1.128, 1.128, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13, logScale)
//Anti Gartley
getrange(x, a, 1.272, 1.272, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14, logScale)
//Navarro200
getrange(x, a, 0.886, 1.127, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15, logScale)
//5-0
getrange(x, a, 0.886, 1.130, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 16, logScale)
//Three Drives
getrange(x, a, 0.130, 1.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 17, logScale)
//White Swan
getrange(x, a, 0.236, 0.886, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 18, logScale)
//Black Swan
getrange(x, a, 1.128, 2.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 19, logScale)
//Sea Pony
getrange(x, a, 0.618, 3.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 20, logScale)
//Leonardo
getrange(x, a, 0.786, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 21, logScale)
//121
getrange(x, a, 0.382, 0.786, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 22, logScale)
//Snorm
getrange(x, a, 0.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 23, logScale)
//Total
getrange(x, a, 0.618, 1.618, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 24, logScale)
dStart = b > c? array.min(startRange) : array.max(startRange)
dEnd = b > c? array.max(endRange) : array.min(endRange)
[dStart, dEnd]
// @function Provides Projection range based on BCD and XAD ranges
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param patternArray Pattern flags for which PRZ range needs to be calculated
// @param errorPercent Error threshold
// @param start_adj - Adjustments for entry levels
// @param end_adj - Adjustments for stop levels
// @param logScale - calculate on log scale. Default is false
// @returns [startRange, endRange] Array containing start and end ranges
export get_projection_range(float x, float a, float b, float c, bool[] patternArray, simple float errorPercent = 8, simple float start_adj=0, simple float end_adj=0, bool logScale=false)=>
startRange = array.new_float(array.size(patternArray), na)
endRange = array.new_float(array.size(patternArray), na)
if(array.includes(patternArray, true))
//Gartley
getrange(x, a, 0.786, 0.786, b, c, 1.272, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 0, logScale)
//Crab
getrange(x, a, 1.618, 1.618, b, c, 2.240, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 1, logScale)
//DeepCrab
getrange(x, a, 1.618, 1.618, b, c, 2.000, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 2, logScale)
//Bat
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 3, logScale)
//Butterfly
getrange(x, a, 1.272, 1.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 4, logScale)
//Shark
getrange(x, a, 0.886, 0.886, b, c, 1.618, 2.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 5, logScale)
//Cypher
getrange(x, c, 0.786, 0.786, x, c, 0.786, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 6, logScale)
//NenStar
getrange(x, a, 1.272, 1.272, b, c, 1.272, 2.000, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 7, logScale)
//Anti NenStar
getrange(x, a, 0.786, 0.786, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 8, logScale)
//Anti Shark
getrange(x, a, 1.130, 1.130, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 9, logScale)
//Anti Cypher
getrange(x, a, 1.272, 1.272, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 10, logScale)
//Anti Crab
getrange(x, a, 0.618, 0.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 11, logScale)
//Anti Butterfly
getrange(x, a, 0.618, 0.786, b, c, 1.272, 1.272, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 12, logScale)
//Anti Bat
getrange(x, a, 1.128, 1.128, b, c, 2.000, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 13, logScale)
//Anti Gartley
getrange(x, a, 1.272, 1.272, b, c, 1.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 14, logScale)
//Navarro200
getrange(x, a, 0.886, 1.127, b, c, 0.886, 3.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 15, logScale)
//5-0
getrange(x, a, 0.886, 1.13, b, c, 0.5, 0.5, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 16, logScale)
//Three Drives
getrange(x, a, 0.13, 1.886, b, c, 0.618, 1.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 17, logScale)
//White Swan
getrange(x, a, 0.236, 0.886, b, c, 0.5, 0.886, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 18, logScale)
//Black Swan
getrange(x, a, 1.128, 2.618, b, c, 1.128, 2.0, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 19, logScale)
//Sea Pony
getrange(x, a, 0.618, 3.618, b, c, 1.618, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 20, logScale)
//Leonardo
getrange(x, a, 0.786, 0.786, b, c, 1.128, 2.618, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 21, logScale)
//121
getrange(x, a, 0.382, 0.786, b, c, 0.382, 0.786, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 22, logScale)
//Snorm
getrange(x, a, 0.618, 1.618, b, c, 0.9, 1.1, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 23, logScale)
//Total
getrange(x, a, 0.618, 1.618, b, c, 1.272, 4.236, errorPercent, errorPercent, start_adj, end_adj, patternArray, startRange, endRange, 24, logScale)
[startRange, endRange]
// @function Checks for harmonic patterns
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param d D coordinate value
// @param flags flags to check patterns. Send empty array to enable all
// @param errorPercent Error threshold
// @param logScale - calculate on log scale. Default is false
// @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names
export isHarmonicPattern(float x, float a, float b, float c, float d,
simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8, bool logScale=false)=>
numberOfPatterns = getNumberOfSupportedPatterns()
err_min = (100 - errorPercent) / 100
err_max = (100 + errorPercent) / 100
xabRatio = fibs.retracementRatio(x,a,b,logScale)
abcRatio = fibs.retracementRatio(a,b,c,logScale)
axcRatio = fibs.retracementRatio(a,x,c,logScale)
bcdRatio = fibs.retracementRatio(b,c,d,logScale)
xadRatio = fibs.retracementRatio(x,a,d,logScale)
xcdRatio = fibs.retracementRatio(x,c,d,logScale)
patternArray = array.new_bool()
for i=0 to numberOfPatterns-1
array.push(patternArray, array.size(flags)>i ? array.get(flags, i) : defaultEnabled)
scan_xab(xabRatio, err_min, err_max, patternArray)
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray)
scan_bcd(bcdRatio, err_min, err_max, patternArray)
scan_xad_xcd(xadRatio, xcdRatio, err_min, err_max, patternArray)
patternArray
// @function Checks for harmonic pattern projection
// @param x X coordinate value
// @param a A coordinate value
// @param b B coordinate value
// @param c C coordinate value
// @param flags flags to check patterns. Send empty array to enable all
// @param errorPercent Error threshold
// @param logScale - calculate on log scale. Default is false
// @returns [patternArray, patternLabelArray] Array of boolean values which says whether valid pattern exist and array of corresponding pattern names.
export isHarmonicProjection(float x, float a, float b, float c,
simple bool[] flags, simple bool defaultEnabled = true, simple int errorPercent = 8, bool logScale=false)=>
numberOfPatterns = getNumberOfSupportedPatterns()
err_min = (100 - errorPercent) / 100
err_max = (100 + errorPercent) / 100
xabRatio = fibs.retracementRatio(x,a,b,logScale)
abcRatio = fibs.retracementRatio(a,b,c,logScale)
axcRatio = fibs.retracementRatio(a,x,c,logScale)
patternArray = array.new_bool()
for i=0 to numberOfPatterns-1
array.push(patternArray, array.size(flags)>i ? array.get(flags, i) : defaultEnabled)
scan_xab(xabRatio, err_min, err_max, patternArray)
scan_abc_axc(abcRatio, axcRatio, err_min, err_max, patternArray)
patternArray |
Reversion Zone Index | https://www.tradingview.com/script/c8ydw2Xb-Reversion-Zone-Index/ | profitprotrading | https://www.tradingview.com/u/profitprotrading/ | 343 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ profitprotrading
//@version=5
indicator(title='Reversion Zone Index', shorttitle='RZI', overlay=false, precision = 0)
//CCI
lengthX = input.int(20, minval=1, group = "CCI")
srcX = input(hlc3, title="Source", group = "CCI")
maX = ta.sma(srcX, lengthX)
cci = (srcX - maX) / (0.015 * ta.dev(srcX, lengthX))
cci := cci/2
// Choppiness Index Calculation
length = input(14, 'CI Length', group = "Choppiness Index")
chopLength = input(14, 'Chop Length', group = "Choppiness Index")
ci = 100 * math.log10(math.sum(ta.atr(1), chopLength) / (ta.highest(chopLength) - ta.lowest(chopLength))) / math.log10(chopLength)
//BB%
length1 = input.int(20, minval=1)
src = input(close, title="Source", group = "BB Percentile")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev", group = "BB Percentile")
basis = ta.sma(src, length1)
dev = mult * ta.stdev(src, length1)
upper = basis + dev
lower = basis - dev
bbr = (src - lower)/(upper - lower)
bbr := bbr*80
comb = (ci + bbr) / 2
comb := comb*3
comb2 = (ci + cci + bbr)/3
combX = ta.ema(comb2, 10)
//Plotting
col = color.from_gradient(combX, 7, 60, color.rgb(0, 200, 7), color.rgb(222, 0, 0))
up = 60
dn = 10
up1 = plot(up, "Overbought", color = color.rgb(255, 255, 255))
dn1 = plot(dn, "Oversold", color = color.white)
mid = plot(33.5, display = display.none)
combX1 = plot(combX, linewidth = 4, color = col, style = plot.style_line)
plotshape(comb2 < -10, style = shape.triangleup, color = color.rgb(0, 235, 8), location = location.bottom, size = size.tiny)
plotshape(comb2 > 70, style = shape.triangledown, color = color.rgb(255, 0, 0), location = location.top, size = size.tiny)
fill(combX1, mid, 75, 40, top_color = color.new(#d50000, 0), bottom_color = color.new(#000000, 100), title = "Overbought Gradient Fill")
fill(combX1, mid, 15, -5, top_color = color.new(#000000, 100), bottom_color = color.new(#23bf00, 0), title = "Overbought Gradient Fill") |
Multi-Band Breakout Indicator | https://www.tradingview.com/script/6KCUXygZ-Multi-Band-Breakout-Indicator/ | LeafAlgo | https://www.tradingview.com/u/LeafAlgo/ | 186 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ LeafAlgo
//@version=5
indicator("Multi-Band Breakout Indicator", overlay=true)
// Calculation Inputs
length = input(14, "ATR Length")
dLength = input(40, 'Donchian Length')
multiplier = input(2.0, "Multiplier")
malength = input(40, 'MA Length')
// Calculate ATR
atr = ta.atr(length)
// Calculate Bands and Basis
upperBand = ta.ema(ta.highest(high, length) + multiplier * atr, length)
lowerBand = ta.ema(ta.lowest(low, length) - multiplier * atr, length)
trend = (upperBand + lowerBand) / 2
trendMA = ta.ema(trend, malength)
// Calculate Donchians
hhigh = ta.highest(upperBand, dLength)
llow = ta.lowest(lowerBand, dLength)
// Breakouts
//breakoutUp = trend > trendMA and close > trend and close > trendMA and high >= hhigh and high >= upperBand
//breakoutDown = trend < trendMA and close < trend and close < trendMA and low <= llow and low <= lowerBand
//breakoutUp2 = high > upperBand and upperBand >= hhigh[1] and close > trendMA and close[1] <= trendMA[1] and trend > trendMA
//breakoutDown2 = low < lowerBand and lowerBand <= llow[1] and close < trendMA and close[1] >= trendMA[1] and trend < trendMA
breakoutUp3 = ta.crossover(trend, trendMA) and upperBand >= hhigh[1] and close > trendMA
breakoutDown3 = ta.crossunder(trend, trendMA) and lowerBand <= llow[1] and close < trendMA
// Color
tColor = trend > close and trendMA > close ? color.fuchsia : trend < close and trendMA < close ? color.lime : color.yellow
maColor = trend > trendMA ? color.new(color.lime, 70) : color.new(color.fuchsia, 70)
barcolor(tColor)
highColor = hhigh > upperBand ? color.new(color.olive, 90) : color.new(color.green,90)
lowColor = llow < lowerBand ? color.new(color.red, 90) : color.new(color.fuchsia, 90)
// Plotting
upperBandplot = plot(upperBand, color=color.lime, title="Upper", linewidth = 2)
lowerBandplot = plot(lowerBand, color=color.fuchsia, title='Lower', linewidth=2)
hhighplot = plot(hhigh, title='Highest Point in Last X Periods', color=color.green, linewidth = 2)
llowplot = plot(llow, title='Lowest Point in X Periods', linewidth = 2, color=color.red)
trendplot = plot(trend, color=color.aqua, title='Basis', linewidth = 4)
trendMAplot = plot(trendMA, color=color.orange, title='Trend MA', linewidth = 4)
fill(plot1=trendplot, plot2=trendMAplot, color=maColor)
fill(plot1=llowplot, plot2=lowerBandplot, color=lowColor)
fill(plot1=hhighplot, plot2=upperBandplot, color=highColor)
plotshape(breakoutUp3, "Long Entry", shape.triangleup, location.belowbar, color=color.green, size=size.large)
plotshape(breakoutDown3, "Short Entry", shape.triangledown, location.abovebar, color=color.red, size=size.large) |
Sessioned EMA - Frozen EMA in post market hours | https://www.tradingview.com/script/lbJwniAa-Sessioned-EMA-Frozen-EMA-in-post-market-hours/ | MalibuKenny | https://www.tradingview.com/u/MalibuKenny/ | 51 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ MalibuKenny
//@version=5
indicator("v1.0 Sessioned EMA", overlay = true, max_labels_count = 100)
group0 = 'Session Volatility (Realtime)============'
startDate = input.time(title='Start Date', defval=timestamp('6 Oct 1000 17:00 +0000'), tooltip='Date & time to begin analysis', group=group0)
endDate = input.time(title='End Date', defval=timestamp('1 Jan 2099 12:00 +0000'), tooltip='Date & time to stop analysis', group=group0)
ema9_sessioned = input.bool(title = "ema9_sessioned", defval = false)
timeSession = input.string(defval = '0930-1600', group = group0)
show_ema_final_difference = input.bool(title = "show_ema_final_difference", defval = false)
// This function returns true if the current bar falls within the given time session (:1234567 is to include all weekdays)
inSession(sess) => //custom function input sess
na(time(timeframe.period, sess + ':1234567', 'GMT+8')) == false and time >= startDate and time <= endDate
// Declaring Variable
// Check if a new session has begun (not in ==> in)
var withinSession = false
if not inSession(timeSession)[1] and inSession(timeSession)
withinSession := true
if inSession(timeSession)[1] and not inSession(timeSession)
withinSession := false
//Change the background color for the in sessioin part (colorBG is a check box)
bgcolor(inSession(timeSession) ? color.new(color.blue, 90) : na)
pine_ema(source, length) =>
alpha = 2 / (length + 1)
sum = 0.0
sum := na(sum[1]) ?
ta.sma(source, length) :
alpha * source + (1 - alpha) * nz(sum[1])
// EMA = (Close - EMA(previous day)) x multiplier + EMA(previous day)
smoothing = 2
var ema9 = 0.0
var ema9b = 0.0
var ema25 = 0.0
var ema55 = 0.0
var ema100 = 0.0
var ema160 = 0.0
if inSession(timeSession)
ema9b:= pine_ema(ohlc4, 9)
ema25:= pine_ema(ohlc4, 25)
ema55:= pine_ema(ohlc4, 55)
ema100:= pine_ema(ohlc4, 100)
ema160:= pine_ema(ohlc4, 160)
else
ema9b:= ema9b[1]
ema25:= ema25[1]
ema55:= ema55[1]
ema100:= ema100[1]
ema160:= ema160[1]
ema3=ta.ema(ohlc4,3)
if ema9_sessioned
ema9:=ema9b
else
ema9:=ta.ema(ohlc4,9)
plot(ema3, linewidth = 1, color = color.new(color.black,0))
plot(ema9, linewidth = 3, color = color.new(color.fuchsia,30))
plot(ema25, linewidth = 2, color = color.new(color.blue,0))
plot(ema55, linewidth = 2, color = color.new(color.green,0))
plot(ema100, linewidth = 2, color = color.new(color.orange,0))
plot(ema160, linewidth = 2, color = color.new(color.black,0))
max_ema= math.max(ema25, ema55, ema100, ema160)
min_ema= math.min(ema25, ema55, ema100, ema160)
delta_ema = max_ema -min_ema
label_ema_diff = label.new(x=bar_index, y = max_ema, text = str.tostring(delta_ema, "#"), color = color.new(color.blue,70))
if withinSession
label.delete(label_ema_diff)
if delta_ema == delta_ema[1]
label.delete(label_ema_diff[1])
|
MW Volume Impulse | https://www.tradingview.com/script/c8A2cQb7-MW-Volume-Impulse/ | moluv | https://www.tradingview.com/u/moluv/ | 236 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ MWRIGHT, INC
//
// Credit to @Ankit_1618 for the Cumulative Volume Delta indicator that served as the inspiration
// https://www.tradingview.com/script/lsDHdn0H-Cumulative-Volume-Delta/
//@version=5
indicator('MW Volume Impulse')
i_period = input.int(14, "Moving Average Period", maxval=3600, minval=1)
i_dotSize = input.int(10, "Dot Size", minval=1, step=1)
i_dotTransparency = input.int(50, "Dot Transparency", maxval=100, minval=0, step=10)
i_ema = input(7,"EMA")
ema = ta.sma(close,i_ema)
upperWick = close > open ? high - close : high - open
lowerWick = close > open ? open - low : close - low
spread = high - low
bodyLength = spread - (upperWick + lowerWick)
percentUpperWick = upperWick / spread
percentLowerWick = lowerWick / spread
percentBodyLength = bodyLength / spread
buyingVolume = close > open ? (percentBodyLength + (percentUpperWick + percentLowerWick) / 2) * volume : (percentUpperWick + percentLowerWick) / 2 * volume
sellingVolume = close < open ? (percentBodyLength + (percentUpperWick + percentLowerWick) / 2) * volume : (percentUpperWick + percentLowerWick) / 2 * volume
accumulationLength = input(14)
cumulativeBuyingVolume = ta.ema(buyingVolume, accumulationLength)
cumulativeSellingVolume = ta.ema(sellingVolume, accumulationLength)
cumulativeVolumeDelta = cumulativeBuyingVolume - cumulativeSellingVolume
// Functions
flippedUp(_series,_period=1) =>
_series > 0 and _series[_period] < 0
flippedDown(_series,_period=1) =>
_series < 0 and _series[_period] > 0
cvdMaDifference = cumulativeVolumeDelta - ta.ema(cumulativeVolumeDelta,i_period)
cvdMaDiffFlipUp = flippedUp(cvdMaDifference)
cvdMaDiffFlipDown = flippedDown(cvdMaDifference)
flipUpPlusMA = cvdMaDiffFlipUp and close > ta.ema(close,7) and (close > open[1] or close > open[2])
flipDownPlusMA = cvdMaDiffFlipDown and close < ta.ema(close,7) and (close < open[1] or close < open[2])
plot(cumulativeVolumeDelta, color = cumulativeVolumeDelta > 0 ? color.green : color.red, style=plot.style_columns)
plot(flipUpPlusMA ? cvdMaDifference : na, color = flipUpPlusMA ? color.new(color.green, i_dotTransparency) : na, style=plot.style_circles, linewidth=i_dotSize)
plot(flipDownPlusMA ? cvdMaDifference : na, color = flipDownPlusMA ? color.new(color.red, i_dotTransparency) : na, style=plot.style_circles, linewidth=i_dotSize)
plot(flipUpPlusMA ? cvdMaDifference : na, color = flipUpPlusMA ? color.new(color.white, i_dotTransparency) : na, style=plot.style_circles, linewidth=i_dotSize/2)
plot(flipDownPlusMA ? cvdMaDifference : na, color = flipDownPlusMA ? color.new(color.white, i_dotTransparency) : na, style=plot.style_circles, linewidth=i_dotSize/2)
plot(ta.ema(cumulativeVolumeDelta,i_period), color=color.new(color.white,0))
alertcondition(cvdMaDiffFlipUp, title="LONG! MW - CVD went above its MA", message="LONG: Cumulative Volume Delta just went above its Moving Average!\nPrice: {{close}}")
alertcondition(cvdMaDiffFlipDown, title="SHORT! MW - CVD went below its MA", message="SHORT: Cumulative Volume Delta just went below its Moving Average!\nPrice: {{close}}")
alertcondition(flipUpPlusMA, title="LONG! MW - CVD above its MA/Price in Zone", message="LONG: Cumulative Volume Delta just went above its Moving Average, and its in the green zone of the selected EMA and SMA!\nPrice: {{close}}")
alertcondition(flipDownPlusMA, title="SHORT! MW - CVD below its MA/Price in Zone", message="SHORT: Cumulative Volume Delta just went below its Moving Average, and its in the red zone of the selected EMA and SMA!\nPrice: {{close}}")
|
Main Market Opener Breakout [RH] | https://www.tradingview.com/script/TeodAWFB-Main-Market-Opener-Breakout-RH/ | HasanRifat | https://www.tradingview.com/u/HasanRifat/ | 385 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ HasanRifat
//@version=5
indicator("Main Market Opener Breakout [RH]", overlay=true, max_lines_count = 500, max_labels_count = 500)
// New York main market settings
newyorkShow = input.bool(defval = true, title = "", inline = "newyork")
newyorkName = input.string(defval = "New York", title = "", inline = "newyork")
newyorkTimeIn = input.session(defval = "0930-1600:23456", title = "", inline = "newyork", tooltip = "Timezone: America/New_York")
newyorkColor = input.color(defval = color.rgb(4, 159, 9), title = "", inline = "newyork")
// London main market settings
londonShow = input.bool(defval = false, title = "", inline = "london")
londonName = input.string(defval = "London", title = "", inline = "london")
londonTimeIn = input.session(defval = "0800-1630:23456", title = "", inline = "london", tooltip = "Timezone: Europe/London")
londonColor = input.color(defval = color.rgb(9, 101, 177), title = "", inline = "london")
// Tokyo main market settings
tokyoShow = input.bool(defval = false, title = "", inline = "tokyo")
tokyoName = input.string(defval = "Tokyo", title = "", inline = "tokyo")
tokyoTimeIn = input.session(defval = "0900-1500:23456", title = "", inline = "tokyo", tooltip = "Timezone: Japan")
tokyoColor = input.color(defval = color.rgb(247, 154, 14), title = "", inline = "tokyo")
// ATR settings
length = input.int(title="ATR Length", defval=14, minval=1)
smoothing = input.string(title="ATR Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"])
// ATR value calculation
ma_function(source, length) =>
switch smoothing
"RMA" => ta.rma(source, length)
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
=> ta.wma(source, length)
atrValue = ma_function(ta.tr(true), length)
newyorkTime = time(timeframe.period, newyorkTimeIn, "America/New_York")
londonTime = time(timeframe.period, londonTimeIn, "Europe/London")
tokyoTime = time(timeframe.period, tokyoTimeIn, "Japan")
stocks = syminfo.type == "stock"
notStocks = syminfo.type != "stock"
// Get first candle's high, low, ATR-high, ATR-low of the session
getValue(time1, sessionColor) =>
var int lineX = na
var float line1Y = na
var float line2Y = na
var float atr1Y = na
var float atr2Y = na
if notStocks
if time1 and not time1[1]
lineX := bar_index
line1Y := high
line2Y := low
atr1Y := high+atrValue
atr2Y := low-atrValue
if stocks
if timeframe.change("D")
lineX := bar_index
line1Y := high
line2Y := low
atr1Y := high+atrValue
atr2Y := low-atrValue
[lineX, line1Y, line2Y, atr1Y, atr2Y]
// Draw lines based on the user settings and candle value
drawLine(lineDex, lineH, lineL, atrH, atrL, sessionColor) =>
var int indexPlus = na
if notStocks
indexPlus := 1440/timeframe.multiplier
if stocks
indexPlus := 360/timeframe.multiplier
dexDif = (lineDex+(indexPlus-1)) - last_bar_index
currDex = last_bar_index + 498
line.new(lineDex, lineH, dexDif > 499 ? currDex : lineDex+(indexPlus-1), lineH, color = sessionColor)
line.new(lineDex, lineL, dexDif > 499 ? currDex : lineDex+(indexPlus-1), lineL, color = sessionColor)
line.new(lineDex, atrH, dexDif > 499 ? currDex : lineDex+(indexPlus-1), atrH, style = line.style_dashed, color = sessionColor)
line.new(lineDex, atrL, dexDif > 499 ? currDex : lineDex+(indexPlus-1), atrL, style = line.style_dashed, color = sessionColor)
// Candle high, low, ATR-high, ATR-low value breakout finding
breakAlert(valueH, valueL, cls, time1) =>
var bullBreakStatus = 0
var bearBreakStatus = 0
if bullBreakStatus == 0
if cls[1] > valueH
bullBreakStatus := 1
if bearBreakStatus == 0
if cls[1] < valueL
bearBreakStatus := -1
if notStocks
if time1 and not time1[1]
bullBreakStatus := 0
bearBreakStatus := 0
if stocks
if timeframe.change("D")
bullBreakStatus := 0
bearBreakStatus := 0
bullBreak = bullBreakStatus == 1 and bullBreakStatus[1] == 0
bearBreak = bearBreakStatus == -1 and bearBreakStatus[1] == 0
[bullBreak, bearBreak]
[yorkX ,yorkH, yorkL, yorkatrH, yorkatrL] = getValue(newyorkTime, newyorkColor)
[donX, donH, donL, donatrH, donatrL] = getValue(londonTime, londonColor)
[toyX, toyH, toyL, toyatrH, toyatrL] = getValue(tokyoTime, tokyoColor)
// Line plotting for tickers other than stocks
if newyorkShow and notStocks and newyorkTime and not newyorkTime[1]
drawLine(yorkX ,yorkH, yorkL, yorkatrH, yorkatrL, newyorkColor)
if londonShow and notStocks and londonTime and not londonTime[1]
drawLine(donX, donH, donL, donatrH, donatrL, londonColor)
if tokyoShow and notStocks and tokyoTime and not tokyoTime[1]
drawLine(toyX, toyH, toyL, toyatrH, toyatrL, tokyoColor)
// Line plotting for stock tickers
if (newyorkShow or londonShow or tokyoShow) and stocks and timeframe.change("D")
drawLine(yorkX ,yorkH, yorkL, yorkatrH, yorkatrL, newyorkColor)
[yorkBullBreak, yorkBearBreak] = breakAlert(yorkH, yorkL, close, newyorkTime)
[donBullBreak, donBearBreak] = breakAlert(donH, donL, close, londonTime)
[toyBullBreak, toyBearBreak] = breakAlert(toyH, toyL, close, tokyoTime)
[yorkatrBullBreak, yorkatrBearBreak] = breakAlert(yorkatrH, yorkatrL, close, newyorkTime)
[donatrBullBreak, donatrBearBreak] = breakAlert(donatrH, donatrL, close, londonTime)
[toyatrBullBreak, toyatrBearBreak] = breakAlert(toyatrH, toyatrL, close, tokyoTime)
// Shapes plotting for break-above and break-down of the candle high, low, ATR-high and ATR-low
plotshape(newyorkShow ? yorkBullBreak : na, title = "New York Candle High Break", style = shape.triangleup, location = location.belowbar, color = color.green, offset = -1, size = size.tiny)
plotshape(newyorkShow ? yorkBearBreak : na, title = "New York Candle Low Break", style = shape.triangledown, location = location.abovebar, color = color.red, offset = -1, size = size.tiny)
plotshape(newyorkShow ? yorkatrBullBreak : na, title = "New York ATR High Break", style = shape.diamond, location = location.belowbar, color = color.green, offset = -1, size = size.tiny)
plotshape(newyorkShow ? yorkatrBearBreak : na, title = "New York ATR Low Break", style = shape.diamond, location = location.abovebar, color = color.red, offset = -1, size = size.tiny)
plotshape(londonShow ? donBullBreak : na, title = "London Candle High Break", style = shape.triangleup, location = location.belowbar, color = color.green, offset = -1, size = size.tiny)
plotshape(londonShow ? donBearBreak : na, title = "London Candle Low Break", style = shape.triangledown, location = location.abovebar, color = color.red, offset = -1, size = size.tiny)
plotshape(londonShow ? donatrBullBreak : na, title = "London ATR High Break", style = shape.diamond, location = location.belowbar, color = color.green, offset = -1, size = size.tiny)
plotshape(londonShow ? donatrBearBreak : na, title = "London ATR Low Break", style = shape.diamond, location = location.abovebar, color = color.red, offset = -1, size = size.tiny)
plotshape(tokyoShow ? toyBullBreak : na, title = "Tokyo Candle High Break", style = shape.triangleup, location = location.belowbar, color = color.green, offset = -1, size = size.tiny)
plotshape(tokyoShow ? toyBearBreak : na, title = "Tokyo Candle Low Break", style = shape.triangledown, location = location.abovebar, color = color.red, offset = -1, size = size.tiny)
plotshape(tokyoShow ? toyatrBullBreak : na, title = "Tokyo ATR High Break", style = shape.diamond, location = location.belowbar, color = color.green, offset = -1, size = size.tiny)
plotshape(tokyoShow ? toyatrBearBreak : na, title = "Tokyo ATR Low Break", style = shape.diamond, location = location.abovebar, color = color.red, offset = -1, size = size.tiny)
// Background coloring for different market sessions
bgcolor(newyorkShow ? (newyorkTime ? color.new(color.green, 90) : na) : na, title = "New York")
bgcolor(londonShow ? (londonTime ? color.new(color.blue, 90) : na) : na, title = "London")
bgcolor(tokyoShow ? (tokyoTime ? color.new(color.orange, 90) : na) : na, title = "Tokyo")
// Alerts
alertcondition(yorkBullBreak, title = "New York Candle High Break", message = "New York Candle High Break")
alertcondition(yorkBearBreak, title = "New York Candle Low Break", message = "New York Candle Low Break")
alertcondition(yorkatrBullBreak, title = "New York ATR High Break", message = "New York ATR High Break")
alertcondition(yorkatrBearBreak, title = "New York ATR Low Break", message = "New York ATR Low Break")
alertcondition(donBullBreak, title = "London Candle High Break", message = "London Candle High Break")
alertcondition(donBearBreak, title = "London Candle Low Break", message = "London Candle Low Break")
alertcondition(donatrBullBreak, title = "London ATR High Break", message = "London ATR High Break")
alertcondition(donatrBearBreak, title = "London ATR Low Break", message = "London ATR Low Break")
alertcondition(toyBullBreak, title = "Tokyo Candle High Break", message = "Tokyo Candle High Break")
alertcondition(toyBearBreak, title = "Tokyo Candle Low Break", message = "Tokyo Candle Low Break")
alertcondition(toyatrBullBreak, title = "Tokyo ATR High Break", message = "Tokyo ATR High Break")
alertcondition(toyatrBearBreak, title = "Tokyo ATR Low Break", message = "Tokyo ATR Low Break")
|
20/200MAs+LTF+4HTF and HighLowBox+3HTF | https://www.tradingview.com/script/W5zsnzSb/ | nazomobile | https://www.tradingview.com/u/nazomobile/ | 26 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ nazo
//@version=5
indicator(title="20/200MAs and HighLowBox HTF+RSI",shorttitle="220MAs+HLBox",overlay=true, max_boxes_count=500,max_labels_count=500, max_lines_count=500)
//
f_gt(x,y) => x>y?x:y
f_lt(x,y) => x<y?x:y
//***
//input options(except tf/ma)
//***
l00="solid",l01="dashed",l02="dotted"
f_linestyle (x) => x==l00?line.style_solid: x==l01?line.style_dashed: x==l02?line.style_dotted:na
s00="auto",s01="huge",s02="large",s03="normal",s04="small",s05="tiny"
f_textsize (x) => x==s00?size.auto: x==s01?size.huge: x==s02?size.large: x==s03?size.normal: x==s04?size.small: x==s05?size.tiny:na
p01="top_left",p02="top_center",p03="top_right",p04="middle_left",p05="middle_center",p06="middle_right",p07="bottom_left",p08="bottom_center",p09="bottom_right"
f_position(x) =>
x==p01?position.top_left: x==p02?position.top_center: x==p03?position.top_right:
x==p04?position.middle_left: x==p05?position.middle_center: x==p06?position.middle_right:
x==p07?position.bottom_left: x==p08?position.bottom_center: x==p09?position.bottom_right:na
ps00="steplinebr",ps01="line",ps02="linebr",ps03="stepline",ps04="stepline_diamond",ps05="histogram",ps06="areabr",ps07="cross",ps08="columns",ps09="circles"
f_plotstyle(x) =>
x==ps00?plot.style_steplinebr: x==ps01?plot.style_line: x==ps02?plot.style_linebr: x==ps03?plot.style_stepline: x==ps04?plot.style_stepline_diamond:
x==ps05?plot.style_histogram: x==ps06?plot.style_areabr: x==ps07?plot.style_cross: x==ps08?plot.style_columns: x==ps09?plot.style_circles:na
//RSI span string
//rsi01,rsi02,rsi03,rsi04,rsi05,rsi06,rsi07,rsi08,rsi09,rsi10,rsi11,rsi12,rsi13,rsi14,rsi15,rsi16,rsi17,rsi18,rsi19,rsi20,rsi21,rsi22,rsi23,rsi24,rsi25,rsi26,rsi27,rsi28,rsi29,rsi30
rsi01="โ ",rsi02="โก",rsi03="โข",rsi04="โฃ",rsi05="โค",rsi06="โฅ",rsi07="โฆ",rsi08="โง",rsi09="โจ",rsi10="โฉ",
rsi11="โช",rsi12="โซ",rsi13="โฌ",rsi14="โญ",rsi15="โฎ",rsi16="โฏ",rsi17="โฐ",rsi18="โฑ",rsi19="โฒ",rsi20="โณ",
rsi21="ใ",rsi22="ใ",rsi23="ใ",rsi24="โญ",rsi25="ใ",rsi26="ใ",rsi27="ใ",rsi28="ใ",rsi29="ใ",rsi30="ใ"
f_rsi_span2label(_i) => _i==1?rsi01: _i==2?rsi02: _i==3?rsi03: _i==4?rsi04: _i==5?rsi05: _i==6?rsi06: _i==7?rsi07: _i==8?rsi08: _i==9?rsi09: _i==10?rsi10:
_i==11?rsi11: _i==12?rsi12: _i==13?rsi13: _i==14?rsi14: _i==15?rsi15: _i==16?rsi16: _i==17?rsi17: _i==18?rsi18: _i==19?rsi19: _i==20?rsi20:
_i==21?rsi21: _i==22?rsi22: _i==23?rsi23: _i==24?rsi14: _i==25?rsi25: _i==26?rsi26: _i==27?rsi27: _i==28?rsi28: _i==29?rsi29: _i==30?rsi30:na
rsi00="โผ", rsi99="โฒ"
f_rsi_direc(_isup)=>_isup?rsi99:rsi00
//*****
//end of input options
//*****
//*****
//colors
//*****
colorSMA=color.new(color.aqua,5)
colorEMA=color.new(color.yellow,5)
colorVWAP=color.new(color.blue,5)
colorLabelText=color.new(color.white,60)
colorBoxT=color.new(color.white,5)
colorBoxU=color.new(#aaffaa,5)
colorBoxD=color.new(#ffaaaa,5)
//minimap colors(exprimental)
colorMinimap_middle_low= color.new(color.orange,20)
colorMinimap_low=color.new(color.red,60)
colorMinimap_low2=color.new(color.red,40)
colorMinimap_break_bottom=color.new(color.red,20)
colorMinimap_middle_high=color.new(color.yellow,20)
colorMinimap_high=color.new(color.blue,60)
colorMinimap_high2=color.new(color.blue,40)
colorMinimap_break_top=color.new(color.blue,20)
colorRSIi=color.new(color.white,5)
colorRSIt1=color.new(color.yellow,5)
colorRSIt2=color.new(color.orange,5)
colorRSIt3=color.new(color.red,5)
colorRSIb1=color.new(color.aqua,5)
colorRSIb2=color.new(color.blue,5)
colorRSIb3=color.new(color.green,5)
//*****
//end of colors
//*****
//*****
//tf functions
//****
idChart = syminfo.tickerid
tfChart = timeframe.period
// t00,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15
t00="Chart", t01="1", t02="3", t03="5", t04="15", t05="30",t06="60",t07="120", t08="180",t09="240",
t10="D", t11='W',t12="M",t13="3M", t14="6M",t15="Y"
th1="higher1", th2="higher2", th3="higher3", th4="higher4"
tl1="lower1", tl2="lower2", tl3="lower3", tl4="lower4"
f_tfMultiplier(tf) =>
x=
str.endswith(tf,"M")? str.length(tf)==1?"1":str.replace(tf,"M",""):
str.endswith(tf,"W")? str.length(tf)==1?"1":str.replace(tf,"W",""):
str.endswith(tf,"D")? str.length(tf)==1?"1":str.replace(tf,"D",""):
str.endswith(tf,"S")? str.length(tf)==1?"1":str.replace(tf,"S",""):
tf
str.tonumber(x)
f_tfUp (tf) =>
m = f_tfMultiplier(tf)
x= str.endswith(tf,"M")? m<3?"3M": m<6?"6M": m<12?"12M":na:
str.endswith(tf,"W")? "M":
str.endswith(tf,"D")? "W":
str.endswith(tf,"S")? "1":
m<15?"15": m<60?"60": m<240?"240": m>=240?"D":na
f_tfDn (tf) =>
m = f_tfMultiplier(tf)
x= str.endswith(tf,"M")? m>6?"6M": m>3?"3M":"W":
str.endswith(tf,"W")? "D":
str.endswith(tf,"D")? "240":
str.endswith(tf,"S")? na:
m>240?"240": m>60?"60": m>15?"15": m>5?"5": m>3?"3":"1"
string tfHigher1 = f_tfUp(tfChart)
string tfHigher2 = f_tfUp(tfHigher1)
string tfHigher3 = f_tfUp(tfHigher2)
string tfHigher4 = f_tfUp(tfHigher3)
string tfLower1 = f_tfDn(tfChart)
string tfLower2 = f_tfDn(tfLower1)
string tfLower3 = f_tfDn(tfLower2)
string tfLower4 = f_tfDn(tfLower3)
f_opt2tf(opt) => opt==t00?tfChart:
opt==th1?tfHigher1: opt==th2?tfHigher2: opt==th3?tfHigher3: opt==th4?tfHigher4:
opt==tl1?tfLower1: opt==tl2?tfLower2: opt==tl3?tfLower3: opt==tl4?tfLower4:
opt
f_time_ddHHmm (_t)=>
_s=1000
_m=60*_s
_h=60*_m
_d=24*_h
_sec = _t
_day = int(_sec/_d)
_mod = _sec%_d
_hour= int(_mod/_h)
_mod:= _mod%_h
_min = int(_mod/_m)
(_day>0?str.tostring(_day,"00")+"d":"")+str.tostring(_hour,"00")+"h"+str.tostring(_min,"00")+"m"
b_tfgt(tfa,tfb) => timeframe.in_seconds(tfa)>timeframe.in_seconds(tfb)
b_tflt(tfa,tfb) => timeframe.in_seconds(tfa)<timeframe.in_seconds(tfb)
b_tfgtCur(tf) => timeframe.in_seconds(tf)>timeframe.in_seconds(tfChart)
b_tfltCur(tf) => timeframe.in_seconds(tf)<timeframe.in_seconds(tfChart)
f_getMtfLowerAvg(tf,x) => na(tf)?na:array.avg(request.security_lower_tf(idChart,tf,x))
f_getMtfLowerMax(tf,x) => na(tf)?na:array.avg(request.security_lower_tf(idChart,tf,x))
f_getMtf(tf,x) => na(tf)?na: tf==tfChart?x:
b_tfgtCur(tf)?request.security(idChart,tf,x, gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_off):na
//*****
//end of tf functions
//*****
//*****
//bb/fibo etc...
//*****
f_bb (center,std,sigma) => center + std*sigma
f_bbsetup(center,std) => [
f_bb(center,std,4),
f_bb(center,std,3),
f_bb(center,std,2),
f_bb(center,std,1),
f_bb(center,std,-1),
f_bb(center,std,-2),
f_bb(center,std,-3),
f_bb(center,std,-4)
]
f_bb3sigma1side (val, center, std) => center<val?f_bb(center,std,3):f_bb(center,std,-3)
f_madev(val, ma) => (val - ma) / ma * 100
s_madev(val, ma) => str.tostring(val-ma,"0.0000")+"("+str.tostring(math.round(f_madev(val,ma),2))+"%)"
f_fibo(a,z) =>
diff = z-a
[z-diff*3.618,z-diff*2.618,z-diff*1.618,
a+diff*0.236,a+diff*0.382,a+diff*0.5,a+diff*0.618,a+diff*0.786,
a+diff*1.618,a+diff*2.618,a+diff*3.618]
f_fibo_range(a,z,x) =>
diff = z-a
_rti=-1
_rbi=-1
listfibo = array.from(z-diff*3.618,z-diff*2.618,z-diff*1.618,a,a+diff*0.236,a+diff*0.382,a+diff*0.5,a+diff*0.618,a+diff*0.786,z,a+diff*1.618,a+diff*2.618,a+diff*3.618)
s_listfibo = array.from("3.618fromT","2.618fromT","1.618fromT","____Bottom","0.236fromB","0.382fromB","____Center","0.382fromT","0.236fromT","_______Top","1.618fromB","2.618fromB","3.618fromB")
for i = 0 to array.size(listfibo)-1
if x<array.get(listfibo,i)
_rti:=i
break
for i = array.size(listfibo)-1 to 0
if x>array.get(listfibo,i)
_rbi:=i
break
[_rti==-1?na:array.get(listfibo,_rti),_rti==-1?na:array.get(s_listfibo,_rti),
_rbi==-1?na:array.get(listfibo,_rbi),_rbi==-1?na:array.get(s_listfibo,_rbi)]
f_fibo_level(a,z,x) =>
diff = z-a
level = x<=a+diff*0.5? x>a+diff*0.382?"ML": x>a+diff*0.236?"L": x>a?"L-": "BB":
x<a+diff*0.618?"MH": x<a+diff*0.786?"H": x<z?"H+": "BT"
f_fl_va(_fl) =>
switch _fl
"ML" => text.align_center
"L" => text.align_bottom
"L-" => text.align_bottom
"BB" => text.align_bottom
"MH" => text.align_center
"H" => text.align_top
"H+" => text.align_top
"BT" => text.align_top
f_fl_c(_fl) =>
switch _fl
"ML" => colorMinimap_middle_high
"L" => colorMinimap_low
"L-" => colorMinimap_low2
"BB" => colorMinimap_break_bottom
"MH" => colorMinimap_middle_high
"H" => colorMinimap_high
"H+" => colorMinimap_high2
"BT" => colorMinimap_break_top
//*****
//end of bb/fibo etc...
//*****
//*****
//MAs
//*****
ma00="sma",ma01="ema",ma02="rma",ma03="wma",ma04="vwma"
f_ma(x,src,len) =>
switch x
ma00 => ta.sma(src,len)
ma01 => ta.ema(src,len)
ma02 => ta.rma(src,len)
ma03 => ta.wma(src,len)
ma04 => ta.vwma(src,len)
f_ma_label (_s,_offset,_tf,_span,_type,_color) => na(_s)?na:
label.new(x=bar_index+_offset,y=_s,
text=_tf+": "+str.tostring(_span)+_type+": "+s_madev(close,_s),style=label.style_none,textcolor=_color,textalign=text.align_left)
//*****
//end of MAs
//*****
//*****
//renew high and low
//*****
//4 "var matrix" for high, return_high, low, return_low are needed
f_renew_high(_last_renew,_high,_high_time,_m_high,_m_return_high,_m_low,_m_return_low) =>
_i_renew =0
_a_high = matrix.row(_m_high,0)
_a_high_time = matrix.row(_m_high,1)
_a_return_high = matrix.row(_m_return_high,0)
_a_return_high_time = matrix.row(_m_return_high,1)
_a_low = matrix.row(_m_low,0)
_a_low_time = matrix.row(_m_low,1)
_a_return_low = matrix.row(_m_return_low,0)
_a_return_low_time = matrix.row(_m_return_low,1)
if array.size(_a_return_high)>0
if array.last(_a_return_high)<_high
while(array.size(_a_return_high)>0)
if array.last(_a_return_high)<_high
array.pop(_a_return_high)
array.pop(_a_return_high_time)
else
break
array.push(_a_return_high,_high)
array.push(_a_return_high_time,_high_time)
if array.last(_a_high)<array.last(_a_return_high)
_i_renew:=1
if _i_renew==_last_renew
array.pop(_a_high)
array.pop(_a_high_time)
array.push(_a_high,array.last(_a_return_high))
array.push(_a_high_time,array.last(_a_return_high_time))
array.push(_a_low,array.last(_a_return_low))
array.push(_a_low_time,array.last(_a_return_low_time))
o_m_high = matrix.new<float>(2,array.size(_a_high),na)//0: price, 1:time
matrix.add_row(o_m_high,0,_a_high)
matrix.add_row(o_m_high,1,_a_high_time)
o_m_return_high = matrix.new<float>(2,array.size(_a_return_high),na)//0: price, 1:time
matrix.add_row(o_m_return_high,0,_a_return_high)
matrix.add_row(o_m_return_high,1,_a_return_high_time)
o_m_low = matrix.new<float>(2,array.size(_a_low),na)//0: price, 1:time
matrix.add_row(o_m_low,0,_a_low)
matrix.add_row(o_m_low,1,_a_low_time)
o_m_return_low = matrix.new<float>(2,array.size(_a_return_low),na)//0: price, 1:time
matrix.add_row(o_m_return_low,0,_a_return_low)
matrix.add_row(o_m_return_low,1,_a_return_low_time)
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]
f_renew_low(_last_renew,_low,_low_time,_m_low,_m_return_low,_m_high,_m_return_high) =>
_i_renew =0
_a_high = matrix.row(_m_high,0)
_a_high_time = matrix.row(_m_high,1)
_a_return_high = matrix.row(_m_return_high,0)
_a_return_high_time = matrix.row(_m_return_high,1)
_a_low = matrix.row(_m_low,0)
_a_low_time = matrix.row(_m_low,1)
_a_return_low = matrix.row(_m_return_low,0)
_a_return_low_time = matrix.row(_m_return_low,1)
if array.size(_a_return_low)>0
if array.last(_a_return_low)>_low
while(array.size(_a_return_low)>0)
if array.last(_a_return_low)>_low
array.pop(_a_return_low)
array.pop(_a_return_low_time)
else
break
array.push(_a_return_low,_low)
array.push(_a_return_low_time,_low_time)
if array.last(_a_low)>array.last(_a_return_low)
_i_renew:=-1
if _i_renew==_last_renew
array.pop(_a_low)
array.pop(_a_low_time)
array.push(_a_low,array.last(_a_return_low))
array.push(_a_low_time,array.last(_a_return_low_time))
array.push(_a_high,array.last(_a_return_high))
array.push(_a_high_time,array.last(_a_return_high_time))
o_m_high = matrix.new<float>(2,array.size(_a_high),na)//0: price, 1:time
matrix.add_row(o_m_high,0,_a_high)
matrix.add_row(o_m_high,1,_a_high_time)
o_m_return_high = matrix.new<float>(2,array.size(_a_return_high),na)//0: price, 1:time
matrix.add_row(o_m_return_high,0,_a_return_high)
matrix.add_row(o_m_return_high,1,_a_return_high_time)
o_m_low = matrix.new<float>(2,array.size(_a_low),na)//0: price, 1:time
matrix.add_row(o_m_low,0,_a_low)
matrix.add_row(o_m_low,1,_a_low_time)
o_m_return_low = matrix.new<float>(2,array.size(_a_return_low),na)//0: price, 1:time
matrix.add_row(o_m_return_low,0,_a_return_low)
matrix.add_row(o_m_return_low,1,_a_return_low_time)
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]
//*****
//end of high and low
//*****
//*****
//MAs
//*****
var spanS = 20
var spanL = 200
string limit200 = "3M"
src = input.source(title="src",defval=hlc3,inline="MA params",group="MA params")//open,close,oc2,hl2,olc3,ohcc4,ohlc4
span1MA = input.int(defval=spanS,minval=1,maxval=200,title="SPAN1",inline="MA params",group="MA params")
span2MA = input.int(defval=spanL,minval=1,maxval=200,title="SPAN2",inline="MA params",group="MA params")
typeMAs = input.string(defval=ma00,options=[ma00,ma01,ma03,ma04],title="MAspan1",inline="MA params1",group="MA params")
_cMAs1 = input.color(defval=colorSMA,title="",inline="MA params1",group="MA params")
typeMAl1 = input.string(defval=ma00,options=[ma00,ma01,ma03,ma04],title="MAspan2 1st",inline="MA params2",group="MA params")
_cMAl1 = input.color(defval=colorSMA,title="",inline="MA params2",group="MA params")
typeMAl2 = input.string(defval=ma01,options=[ma00,ma01,ma03,ma04],title="2nd",inline="MA params2",group="MA params")
_cMAl2 = input.color(defval=colorEMA,title="",inline="MA params2",group="MA params")
b_MAlabel = input.bool(defval=true,title="show MA label",inline="MA",group="MA params")
b_MAlimit = input.bool(defval=true,title="dont show SPAN2 MA if tf>",inline="MAlim",group="MA params")
_limit200 = input.timeframe(defval=t13, title="", options=[t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15],inline="MAlim",group="MA params")
limit200:=b_MAlimit?_limit200:"0S"
b_VWAP = input.bool(defval=false, title="show vwap",inline="MA",group="MA params")
_cVWAP = input.color(defval=colorVWAP,title="vwap",inline="MA",group="MA params")
b_MA = input.bool(defval=true,title="show current TF",inline="MA",group="MA current TF")
_transMA = input.int(defval=20,minval=0,maxval=99,title="transpar",inline="MA",group="MA current TF")
cMAs1=color.new(_cMAs1,_transMA)
cMAl1=color.new(_cMAl1,_transMA)
cMAl2=color.new(_cMAl2,_transMA)
cVWAP=color.new(_cVWAP,_transMA)
labeloffset = input.int(defval=4,minval=0,maxval=10,title="labeloffset",inline="MA",group="MA current TF")
widthMAs = input.int(defval=2,minval=1,maxval=4,title="SPAN1:width",inline="MAs",group="MA current TF")
_styleMAs = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAs",group="MA current TF")
styleMAs = f_plotstyle(_styleMAs)
widthMAl = input.int(defval=2,minval=1,maxval=4,title="SPAN2:width",inline="MAl",group="MA current TF")
_styleMAl = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAl",group="MA current TF")
styleMAl = f_plotstyle(_styleMAl)
b_MA_1 = input.bool(defval=false,title="show LTF",inline="MA",group="MA lower TF")
_tfMA_1 = input.timeframe(defval=tl1, title="", inline="MA", group="MA lower TF",
options=[tl1,tl2,tl3,tl4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tfMA_1 = f_opt2tf(_tfMA_1)
_transMA_1 = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="MA",group="MA lower TF")
cMA_1s1=color.new(_cMAs1,_transMA_1)
cMA_1l1=color.new(_cMAl1,_transMA_1)
cMA_1l2=color.new(_cMAl2,_transMA_1)
cVWAP_1=color.new(_cVWAP,_transMA_1)
labeloffset_1 = input.int(defval=2,minval=0,maxval=10,title="labeloffset",inline="MA",group="MA lower TF")
widthMA_1s = input.int(defval=1,minval=1,maxval=4,title="SPAN1:width",inline="MAs",group="MA lower TF")
_styleMA_1s = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAs",group="MA lower TF")
styleMA_1s = f_plotstyle(_styleMA_1s)
widthMA_1l = input.int(defval=1,minval=1,maxval=4,title="SPAN2:width",inline="MAl",group="MA lower TF")
_styleMA_1l = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAl",group="MA lower TF")
styleMA_1l = f_plotstyle(_styleMA_1l)
b_MA1 = input.bool(defval=true,title="show HTF1",inline="MA",group="MA higher TF1")
_tfMA1 = input.timeframe(defval=th1, title="", inline="MA", group="MA higher TF1",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tfMA1 = f_opt2tf(_tfMA1)
_transMA1 = input.int(defval=20,minval=0,maxval=99,title="transpar",inline="MA",group="MA higher TF1")
cMA1s1=color.new(_cMAs1,_transMA1)
cMA1l1=color.new(_cMAl1,_transMA1)
cMA1l2=color.new(_cMAl2,_transMA1)
cVWAP1=color.new(_cVWAP,_transMA1)
labeloffset1 = input.int(defval=6,minval=0,maxval=10,title="labeloffset",inline="MA",group="MA higher TF1")
widthMA1s = input.int(defval=3,minval=1,maxval=4,title="SPAN1:width",inline="MAs",group="MA higher TF1")
_styleMA1s = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAs",group="MA higher TF1")
styleMA1s = f_plotstyle(_styleMA1s)
widthMA1l = input.int(defval=3,minval=1,maxval=4,title="SPAN2:width",inline="MAl",group="MA higher TF1")
_styleMA1l = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAl",group="MA higher TF1")
styleMA1l = f_plotstyle(_styleMA1l)
b_MA2 = input.bool(defval=true,title="show HTF2",inline="MA",group="MA higher TF2")
_tfMA2 = input.timeframe(defval=th2, title="", inline="MA", group="MA higher TF2",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tfMA2 = f_opt2tf(_tfMA2)
_transMA2 = input.int(defval=30,minval=0,maxval=99,title="transpar",inline="MA",group="MA higher TF2")
cMA2s1=color.new(_cMAs1,_transMA2)
cMA2l1=color.new(_cMAl1,_transMA2)
cMA2l2=color.new(_cMAl2,_transMA2)
cVWAP2=color.new(_cVWAP,_transMA2)
labeloffset2 = input.int(defval=8,minval=0,maxval=10,title="labeloffset",inline="MA",group="MA higher TF2")
widthMA2s = input.int(defval=4,minval=1,maxval=4,title="SPAN1:width",inline="MAs",group="MA higher TF2")
_styleMA2s = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAs",group="MA higher TF2")
styleMA2s = f_plotstyle(_styleMA2s)
widthMA2l = input.int(defval=4,minval=1,maxval=4,title="SPAN2:width",inline="MAl",group="MA higher TF2")
_styleMA2l = input.string(defval=ps01,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAl",group="MA higher TF2")
styleMA2l = f_plotstyle(_styleMA2l)
b_MA3 = input.bool(defval=true,title="show HTF3",inline="MA",group="MA higher TF3")
_tfMA3 = input.timeframe(defval=th3, title="", inline="MA", group="MA higher TF3",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tfMA3 = f_opt2tf(_tfMA3)
_transMA3 = input.int(defval=40,minval=0,maxval=99,title="transpar",inline="MA",group="MA higher TF3")
cMA3s1=color.new(_cMAs1,_transMA3)
cMA3l1=color.new(_cMAl1,_transMA3)
cMA3l2=color.new(_cMAl2,_transMA3)
cVWAP3=color.new(_cVWAP,_transMA3)
labeloffset3 = input.int(defval=9,minval=0,maxval=10,title="labeloffset",inline="MA",group="MA higher TF3")
widthMA3s = input.int(defval=4,minval=1,maxval=4,title="SPAN1:width",inline="MAs",group="MA higher TF3")
_styleMA3s = input.string(defval=ps07,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAs",group="MA higher TF3")
styleMA3s = f_plotstyle(_styleMA3s)
widthMA3l = input.int(defval=4,minval=1,maxval=4,title="SPAN2:width",inline="MAl",group="MA higher TF3")
_styleMA3l = input.string(defval=ps07,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAl",group="MA higher TF3")
styleMA3l = f_plotstyle(_styleMA3l)
b_MA4 = input.bool(defval=true,title="show HTF4",inline="MA",group="MA higher TF4")
_tfMA4 = input.timeframe(defval=th4, title="", inline="MA", group="MA higher TF4",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tfMA4 = f_opt2tf(_tfMA4)
_transMA4 = input.int(defval=50,minval=0,maxval=99,title="transpar",inline="MA",group="MA higher TF4")
cMA4s1=color.new(_cMAs1,_transMA4)
cMA4l1=color.new(_cMAl1,_transMA4)
cMA4l2=color.new(_cMAl2,_transMA4)
cVWAP4=color.new(_cVWAP,_transMA4)
labeloffset4 = input.int(defval=10,minval=0,maxval=10,title="labeloffset",inline="MA",group="MA higher TF4")
widthMA4s = input.int(defval=4,minval=1,maxval=4,title="SPAN1:width",inline="MAs",group="MA higher TF4")
_styleMA4s = input.string(defval=ps09,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAs",group="MA higher TF4")
styleMA4s = f_plotstyle(_styleMA4s)
widthMA4l = input.int(defval=4,minval=1,maxval=4,title="SPAN2:width",inline="MAl",group="MA higher TF4")
_styleMA4l = input.string(defval=ps09,options=[ps00,ps01,ps02,ps03,ps04,ps05,ps06,ps07,ps08,ps09],title="style",inline="MAl",group="MA higher TF4")
styleMA4l = f_plotstyle(_styleMA4l)
//200MA
s_200SMA = b_MA and b_tfgt(limit200,tfChart)?f_ma(typeMAl1,src,span2MA):na
s_200EMA = b_MA and b_tfgt(limit200,tfChart)?f_ma(typeMAl2,src,span2MA):na
//20MA
s_20SMA = b_MA?f_ma(typeMAs,src,span1MA):na
//VWAP
s_VWAP = b_MA and b_VWAP?ta.vwap(src):na
//Lower
s_200SMA_1 = b_MA_1 and b_tfgt(limit200,tfMA_1)?f_getMtfLowerAvg(tfMA_1,f_ma(typeMAl1,src,span2MA)):na
s_200EMA_1 = b_MA_1 and b_tfgt(limit200,tfMA_1)?f_getMtfLowerAvg(tfMA_1,f_ma(typeMAl2,src,span2MA)):na
s_20SMA_1 = b_MA_1?f_getMtfLowerAvg(tfMA_1,f_ma(typeMAs,src,span1MA)):na
s_VWAP_1 = b_MA_1 and b_VWAP?f_getMtfLowerAvg(tfMA_1,ta.vwap(src)):na
//Higher
s_200SMA1 = b_MA1 and b_tfgt(limit200,tfMA1)?f_getMtf(tfMA1,f_ma(typeMAl1,src,span2MA)):na
s_200EMA1 = b_MA1 and b_tfgt(limit200,tfMA1)?f_getMtf(tfMA1,f_ma(typeMAl2,src,span2MA)):na
s_20SMA1 = b_MA1?f_getMtf(tfMA1,f_ma(typeMAs,src,span1MA)):na
s_VWAP1 = b_MA1 and b_VWAP?f_getMtf(tfMA1,ta.vwap(src)):na
s_200SMA2 = b_MA2 and b_tfgt(limit200,tfMA1)?f_getMtf(tfMA2,f_ma(typeMAl1,src,span2MA)):na
s_200EMA2 = b_MA2 and b_tfgt(limit200,tfMA1)?f_getMtf(tfMA2,f_ma(typeMAl2,src,span2MA)):na
s_20SMA2 = b_MA2?f_getMtf(tfMA2,f_ma(typeMAs,src,span1MA)):na
s_VWAP2 = b_MA2 and b_VWAP?f_getMtf(tfMA2,ta.vwap(src)):na
s_200SMA3 = b_MA3 and b_tfgt(limit200,tfMA3)?f_getMtf(tfMA3,f_ma(typeMAl1,src,span2MA)):na
s_200EMA3 = b_MA3 and b_tfgt(limit200,tfMA3)?f_getMtf(tfMA3,f_ma(typeMAl2,src,span2MA)):na
s_20SMA3 = b_MA3?f_getMtf(tfMA3,f_ma(typeMAs,src,span1MA)):na
s_VWAP3 = b_MA3 and b_VWAP?f_getMtf(tfMA3,ta.vwap(src)):na
s_200SMA4 = b_MA4 and b_tfgt(limit200,tfMA4)?f_getMtf(tfMA4,f_ma(typeMAl1,src,span2MA)):na
s_200EMA4 = b_MA4 and b_tfgt(limit200,tfMA4)?f_getMtf(tfMA4,f_ma(typeMAl2,src,span2MA)):na
s_20SMA4 = b_MA4?f_getMtf(tfMA4,f_ma(typeMAs,src,span1MA)):na
s_VWAP4 = b_MA4 and b_VWAP?f_getMtf(tfMA4,ta.vwap(src)):na
//plot MAs
plot(s_20SMA,linewidth=widthMAs,style=styleMAs,color=cMAs1,title="MAspan1tf0")
label_MAs = f_ma_label(b_MAlabel?s_20SMA:na,labeloffset,tfChart,span1MA,typeMAs,cMAs1)
label.delete(label_MAs[1])
plot(s_200SMA,linewidth=widthMAl,style=styleMAl,color=cMAl1,title="MAspan2-1tf0")
plot(s_200EMA,linewidth=widthMAl,style=styleMAl,color=cMAl2,title="MAspan2-2tf0")
label_MAl1 = f_ma_label(b_MAlabel?s_200SMA:na,labeloffset,tfChart,span2MA,typeMAl1,cMAl1)
label_MAl2 = f_ma_label(b_MAlabel?s_200EMA:na,labeloffset,tfChart,span2MA,typeMAl2,cMAl2)
label.delete(label_MAl1[1])
label.delete(label_MAl2[1])
plot(s_VWAP,linewidth=widthMAs,style=styleMAs,color=cVWAP,title="VWAPtf0")
label_VWAP = f_ma_label(b_MAlabel?s_VWAP:na,labeloffset,tfChart,"","vwap",cVWAP)
label.delete(label_VWAP[1])
//plot lower
plot(s_20SMA_1,linewidth=widthMA_1s,style=styleMA_1s,color=cMA_1s1,title="MAspan1tf-1")
label_MA_1s = f_ma_label(b_MAlabel?s_20SMA_1:na,labeloffset_1,tfMA_1,span1MA,typeMAs,cMA_1s1)
label.delete(label_MA_1s[1])
plot(s_200SMA_1,linewidth=widthMA_1l,style=styleMA_1l,color=cMA_1l1,title="MAspan2-1tf-1")
plot(s_200EMA_1,linewidth=widthMA_1l,style=styleMA_1l,color=cMA_1l2,title="MAspan2-2tf-1")
label_MA_1l1 = f_ma_label(b_MAlabel?s_200SMA_1:na,labeloffset_1,tfMA_1,span2MA,typeMAl1,cMA_1l1)
label_MA_1l2 = f_ma_label(b_MAlabel?s_200EMA_1:na,labeloffset_1,tfMA_1,span2MA,typeMAl2,cMA_1l2)
label.delete(label_MA_1l1[1])
label.delete(label_MA_1l2[1])
plot(s_VWAP_1,linewidth=widthMA_1s,style=styleMA_1s,color=cVWAP_1,title="VWAPtf-1")
label_VWAP_1 = f_ma_label(b_MAlabel?s_VWAP_1:na,labeloffset_1,tfMA_1,"","vwap",cVWAP_1)
label.delete(label_VWAP_1[1])
//plot higher1
plot(s_20SMA1,linewidth=widthMA1s,style=styleMA1s,color=cMA1s1,title="MAspan1tf+1")
label_MA1s = f_ma_label(b_MAlabel?s_20SMA1:na,labeloffset1,tfMA1,span1MA,typeMAs,cMA1s1)
label.delete(label_MA1s[1])
plot(s_200SMA1,linewidth=widthMA1l,style=styleMA1l,color=cMA1l1,title="MAspan2-1tf+1")
plot(s_200EMA1,linewidth=widthMA1l,style=styleMA1l,color=cMA1l2,title="MAspan2-2tf+1")
label_MA1l1 = f_ma_label(b_MAlabel?s_200SMA1:na,labeloffset1,tfMA1,span2MA,typeMAl1,cMA1l1)
label_MA1l2 = f_ma_label(b_MAlabel?s_200EMA1:na,labeloffset1,tfMA1,span2MA,typeMAl2,cMA1l2)
label.delete(label_MA1l1[1])
label.delete(label_MA1l2[1])
plot(s_VWAP1,linewidth=widthMA1s,style=styleMA1s,color=cVWAP1,title="VWAPtf+1")
label_VWAP1 = f_ma_label(b_MAlabel?s_VWAP1:na,labeloffset1,tfMA1,"","vwap",cVWAP1)
label.delete(label_VWAP1[1])
//plot higher2
plot(s_20SMA2,linewidth=widthMA2s,style=styleMA2s,color=cMA2s1,title="MAspan1tf+2")
label_MA2s = f_ma_label(b_MAlabel?s_20SMA2:na,labeloffset2,tfMA2,span1MA,typeMAs,cMA2s1)
label.delete(label_MA2s[1])
plot(s_200SMA2,linewidth=widthMA2l,style=styleMA2l,color=cMA2l1,title="MAspan2-1tf+2")
plot(s_200EMA2,linewidth=widthMA2l,style=styleMA2l,color=cMA2l2,title="MAspan2-2tf+2")
label_MA2l1 = f_ma_label(b_MAlabel?s_200SMA2:na,labeloffset2,tfMA2,span2MA,typeMAl1,cMA2l1)
label_MA2l2 = f_ma_label(b_MAlabel?s_200EMA2:na,labeloffset2,tfMA2,span2MA,typeMAl2,cMA2l2)
label.delete(label_MA2l1[1])
label.delete(label_MA2l2[1])
plot(s_VWAP2,linewidth=widthMA2s,style=styleMA2s,color=cVWAP2,title="VWAPtf+2")
label_VWAP2 = f_ma_label(b_MAlabel?s_VWAP2:na,labeloffset2,tfMA2,"","vwap",cVWAP2)
label.delete(label_VWAP2[1])
//plot higher3
plot(s_20SMA3,linewidth=widthMA3s,style=styleMA3s,color=cMA3s1,title="MAspan1tf+3")
label_MA3s = f_ma_label(b_MAlabel?s_20SMA3:na,labeloffset3,tfMA3,span1MA,typeMAs,cMA3s1)
label.delete(label_MA3s[1])
plot(s_200SMA3,linewidth=widthMA3l,style=styleMA3l,color=cMA3l1,title="MAspan2-1tf+3")
plot(s_200EMA3,linewidth=widthMA3l,style=styleMA3l,color=cMA3l2,title="MAspan2-2tf+3")
label_MA3l1 = f_ma_label(b_MAlabel?s_200SMA3:na,labeloffset3,tfMA3,span2MA,typeMAl1,cMA3l1)
label_MA3l2 = f_ma_label(b_MAlabel?s_200EMA3:na,labeloffset3,tfMA3,span2MA,typeMAl2,cMA3l2)
label.delete(label_MA3l1[1])
label.delete(label_MA3l2[1])
plot(s_VWAP3,linewidth=widthMA3s,style=styleMA3s,color=cVWAP3,title="VWAPtf+3")
label_VWAP3 = f_ma_label(b_MAlabel?s_VWAP3:na,labeloffset3,tfMA3,"","vwap",cVWAP3)
label.delete(label_VWAP3[1])
//plot higher4
plot(s_20SMA4,linewidth=widthMA4s,style=styleMA4s,color=cMA4s1,title="MAspan1tf+4")
label_MA4s = f_ma_label(b_MAlabel?s_20SMA4:na,labeloffset4,tfMA4,span1MA,typeMAs,cMA4s1)
label.delete(label_MA4s[1])
plot(s_200SMA4,linewidth=widthMA4l,style=styleMA4l,color=cMA4l1,title="MAspan2-1tf+4")
plot(s_200EMA4,linewidth=widthMA4l,style=styleMA4l,color=cMA4l2,title="MAspan2-2tf+4")
label_MA4l1 = f_ma_label(b_MAlabel?s_200SMA4:na,labeloffset4,tfMA4,span2MA,typeMAl1,cMA4l1)
label_MA4l2 = f_ma_label(b_MAlabel?s_200EMA4:na,labeloffset4,tfMA4,span2MA,typeMAl2,cMA4l2)
label.delete(label_MA4l1[1])
label.delete(label_MA4l2[1])
plot(s_VWAP4,linewidth=widthMA4s,style=styleMA4s,color=cVWAP4,title="VWAPtf+4")
label_VWAP4 = f_ma_label(b_MAlabel?s_VWAP4:na,labeloffset4,tfMA4,"","vwap",cVWAP4)
label.delete(label_VWAP4[1])
//*****
//end of MAs
//*****
//*****
//HighLowBox
//*****
show0 = input.bool(defval=true,title="show current TF",inline="Box",group="HighLowBox")
transBox = input.int(defval=40,minval=0,maxval=99,title="border transpar",inline="tfC",group="HighLowBox")
cBoxU = input.color(defval=colorBoxU,title="newHigh",inline="tfC",group="HighLowBox")
cBoxD = input.color(defval=colorBoxD,title="newLow",inline="tfC",group="HighLowBox")
cBoxU:=color.new(cBoxU,transBox)
cBoxD:=color.new(cBoxD,transBox)
widthBox = input.int(defval=1,minval=1,maxval=4,title="width",inline="tfC",group="HighLowBox")
_styleBox = input.string(defval=l01,options=[l00,l01,l02],title="box style",inline="tfC",group="HighLowBox")
styleBox = f_linestyle(_styleBox)
b_fillBox = input.bool(defval=true,title="fill box",inline="tfCf",group="HighLowBox")
transFill = input.int(defval=90,minval=0,maxval=99,title="fill transpar",inline="tfCf",group="HighLowBox")
cBoxUf = input.color(defval=colorBoxU,title="newHigh",inline="tfCf",group="HighLowBox")
cBoxDf = input.color(defval=colorBoxD,title="newLow",inline="tfCf",group="HighLowBox")
cBoxUf:=b_fillBox?color.new(cBoxUf,transFill):na
cBoxDf:=b_fillBox?color.new(cBoxDf,transFill):na
b_fibo = input.bool(defval=true,title="show fibonacci scale",inline="tfCF",group="HighLowBox")
b_info = input.bool(defval=true,title="range info",inline="tfCi",group="HighLowBox")
_infoSize = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfCi",group="HighLowBox")
infoSize = f_textsize(_infoSize)
_cBoxT = input.color(defval=colorBoxT,title="info color",inline="tfCi",group="HighLowBox")
transInfo = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfCi",group="HighLowBox")
cBoxT = color.new(_cBoxT,transInfo)
show1 = input.bool(defval=true,title="show TF1",group="HighLowBox")
_tf1 = input.timeframe(defval=th1, title="", inline="tfH1",group="HighLowBox",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf1 = f_opt2tf(_tf1)
transBox1 = input.int(defval=50,minval=0,maxval=99,title="border transpar",inline="tfH1",group="HighLowBox")
cBoxU1 = input.color(defval=colorBoxU,title="newHigh",inline="tfH1",group="HighLowBox")
cBoxD1 = input.color(defval=colorBoxD,title="newLow",inline="tfH1",group="HighLowBox")
cBoxU1:=color.new(cBoxU1,transBox1)
cBoxD1:=color.new(cBoxD1,transBox1)
widthBox1 = input.int(defval=2,minval=1,maxval=4,title="width",inline="tfH1",group="HighLowBox")
_styleBox1 = input.string(defval=l00,options=[l00,l01,l02],title="box style",inline="tfH1",group="HighLowBox")
styleBox1 = f_linestyle(_styleBox1)
b_fibo1 = input.bool(defval=true,title="show fibonacci level",inline="tfH1",group="HighLowBox")
b_info1 = input.bool(defval=true,title="range info",inline="tfH1i",group="HighLowBox")
_infoSize1 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH1i",group="HighLowBox")
infoSize1 = f_textsize(_infoSize1)
_cBoxT1 = input.color(defval=colorBoxT,title="info color",inline="tfH1i",group="HighLowBox")
transInfo1 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH1i",group="HighLowBox")
cBoxT1 = color.new(_cBoxT1,transInfo1)
show2 = input.bool(defval=true,title="show TF2",group="HighLowBox")
_tf2 = input.timeframe(defval=th2, title="", inline="tfH2",group="HighLowBox",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf2 = f_opt2tf(_tf2)
transBox2 = input.int(defval=60,minval=0,maxval=99,title="border transpar",inline="tfH2",group="HighLowBox")
cBoxU2 = input.color(defval=colorBoxU,title="newHigh",inline="tfH2",group="HighLowBox")
cBoxD2 = input.color(defval=colorBoxD,title="newLow",inline="tfH2",group="HighLowBox")
cBoxU2:=color.new(cBoxU2,transBox2)
cBoxD2:=color.new(cBoxD2,transBox2)
widthBox2 = input.int(defval=3,minval=1,maxval=4,title="width",inline="tfH2",group="HighLowBox")
_styleBox2 = input.string(defval=l01,options=[l00,l01,l02],title="box style",inline="tfH2",group="HighLowBox")
styleBox2 = f_linestyle(_styleBox2)
b_fibo2 = input.bool(defval=true,title="show fibonacci level",inline="tfH2",group="HighLowBox")
b_info2 = input.bool(defval=true,title="range info",inline="tfH2i",group="HighLowBox")
_infoSize2 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH2i",group="HighLowBox")
infoSize2 = f_textsize(_infoSize2)
_cBoxT2 = input.color(defval=colorBoxT,title="info color",inline="tfH2i",group="HighLowBox")
transInfo2 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH2i",group="HighLowBox")
cBoxT2 = color.new(_cBoxT2,transInfo2)
show3 = input.bool(defval=true,title="show TF3",group="HighLowBox")
_tf3 = input.timeframe(defval=th3, title="", inline="tfH3",group="HighLowBox",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf3 = f_opt2tf(_tf3)
transBox3 = input.int(defval=70,minval=0,maxval=99,title="border transpar",inline="tfH3",group="HighLowBox")
cBoxU3 = input.color(defval=colorBoxU,title="newHigh",inline="tfH3",group="HighLowBox")
cBoxD3 = input.color(defval=colorBoxD,title="newLow",inline="tfH3",group="HighLowBox")
cBoxU3:=color.new(cBoxU3,transBox3)
cBoxD3:=color.new(cBoxD3,transBox3)
widthBox3 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH3",group="HighLowBox")
_styleBox3 = input.string(defval=l00,options=[l00,l01,l02],title="box style",inline="tfH3",group="HighLowBox")
styleBox3 = f_linestyle(_styleBox3)
b_fibo3 = input.bool(defval=true,title="show fibonacci level",inline="tfH3",group="HighLowBox")
b_info3 = input.bool(defval=true,title="range info",inline="tfH3i",group="HighLowBox")
_infoSize3 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH3i",group="HighLowBox")
infoSize3 = f_textsize(_infoSize3)
_cBoxT3 = input.color(defval=colorBoxT,title="info color",inline="tfH3i",group="HighLowBox")
transInfo3 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH3i",group="HighLowBox")
cBoxT3 = color.new(_cBoxT3,transInfo3)
show4 = input.bool(defval=false,title="show TF4",group="HighLowBox")
_tf4 = input.timeframe(defval=th4, title="", inline="tfH4",group="HighLowBox",
options=[th1,th2,th3,th4,t01,t02,t03,t04,t05,t06,t07,t08,t09,t10,t11,t12,t13,t14,t15])
tf4 = f_opt2tf(_tf4)
transBox4 = input.int(defval=80,minval=0,maxval=99,title="border transpar",inline="tfH4",group="HighLowBox")
cBoxU4 = input.color(defval=colorBoxU,title="newHigh",inline="tfH4",group="HighLowBox")
cBoxD4 = input.color(defval=colorBoxD,title="newLow",inline="tfH4",group="HighLowBox")
cBoxU4:=color.new(cBoxU4,transBox4)
cBoxD4:=color.new(cBoxD4,transBox4)
widthBox4 = input.int(defval=4,minval=1,maxval=4,title="width",inline="tfH4",group="HighLowBox")
_styleBox4 = input.string(defval=l02,options=[l00,l01,l02],title="box style",inline="tfH4",group="HighLowBox")
styleBox4 = f_linestyle(_styleBox4)
b_fibo4 = input.bool(defval=true,title="show fibonacci level",inline="tfH4",group="HighLowBox")
b_info4 = input.bool(defval=true,title="range info",inline="tfH4i",group="HighLowBox")
_infoSize4 = input.string(defval=s04,options=[s01,s02,s03,s04,s05],title="info size",inline="tfH4i",group="HighLowBox")
infoSize4 = f_textsize(_infoSize4)
_cBoxT4 = input.color(defval=colorBoxT,title="info color",inline="tfH4i",group="HighLowBox")
transInfo4 = input.int(defval=30,minval=0,maxval=99,title="text transpar",inline="tfH4i",group="HighLowBox")
cBoxT4 = color.new(_cBoxT4,transInfo4)
showMinimap = input.bool(defval=false,title="show minimap(experimental)",inline="tfM",group="HighLowBox")
minimapHist = input.int(defval=32,minval=10,maxval=99,title="minimap hist",inline="tfM",group="HighLowBox")
srcRSI = input.source(defval=hlc3,title="RSI src",group="RSI")
spanRSI_1 = input.int(defval=9,minval=1,maxval=30,title="span1", inline="RSIspan", group="RSI")
spanRSI_2 = input.int(defval=14,minval=1,maxval=30,title="span2", inline="RSIspan", group="RSI")
_cRSIi = input.color(defval=colorRSIi,title="only span1>=70 or only span1<=30",inline="top",group="RSI >= 70")
_cRSIt1 = input.color(defval=colorRSIt1,title="both>=70 and span1>span2",inline="top",group="RSI >= 70")
_cRSIt2 = input.color(defval=colorRSIt2,title="both>=70 and span1<span2",inline="top",group="RSI >= 70")
_cRSIt3 = input.color(defval=colorRSIt3,title="span1<70",inline="top",group="RSI >= 70")
_cRSIb1 = input.color(defval=colorRSIb1,title="both<=30 and span1<span2",inline="top",group="RSI <= 30")
_cRSIb2 = input.color(defval=colorRSIb2,title="both<=30 and span1>span2",inline="top",group="RSI <= 30")
_cRSIb3 = input.color(defval=colorRSIb3,title="span1>30",inline="top",group="RSI <= 30")
showRSI = input.bool(defval=true,title="use RSI in current TF",inline="tf",group="RSI")
transRSI = input.int(defval=80,minval=0,maxval=99,title="border transpar",inline="tf",group="RSI")
cRSIi=color.new(_cRSIi,transRSI)
cRSIt1=color.new(_cRSIt1,transRSI)
cRSIt2=color.new(_cRSIt2,transRSI)
cRSIt3=color.new(_cRSIt3,transRSI)
cRSIb1=color.new(_cRSIb1,transRSI)
cRSIb2=color.new(_cRSIb2,transRSI)
cRSIb3=color.new(_cRSIb3,transRSI)
showRSI1 = input.bool(defval=true,title="use RSI in Higher TF1",inline="tf1",group="RSI")
transRSI1 = input.int(defval=70,minval=0,maxval=99,title="border transpar",inline="tf1",group="RSI")
cRSI1i=color.new(_cRSIi,transRSI1)
cRSI1t1=color.new(_cRSIt1,transRSI1)
cRSI1t2=color.new(_cRSIt2,transRSI1)
cRSI1t3=color.new(_cRSIt3,transRSI1)
cRSI1b1=color.new(_cRSIb1,transRSI1)
cRSI1b2=color.new(_cRSIb2,transRSI1)
cRSI1b3=color.new(_cRSIb3,transRSI1)
showRSI2 = input.bool(defval=true,title="use RSI in Higher TF2",inline="tf2",group="RSI")
transRSI2 = input.int(defval=60,minval=0,maxval=99,title="border transpar",inline="tf2",group="RSI")
cRSI2i=color.new(_cRSIi,transRSI2)
cRSI2t1=color.new(_cRSIt1,transRSI2)
cRSI2t2=color.new(_cRSIt2,transRSI2)
cRSI2t3=color.new(_cRSIt3,transRSI2)
cRSI2b1=color.new(_cRSIb1,transRSI2)
cRSI2b2=color.new(_cRSIb2,transRSI2)
cRSI2b3=color.new(_cRSIb3,transRSI2)
showRSI3 = input.bool(defval=true,title="use RSI in Higher TF3",inline="tf3",group="RSI")
transRSI3 = input.int(defval=50,minval=0,maxval=99,title="border transpar",inline="tf3",group="RSI")
cRSI3i=color.new(_cRSIi,transRSI3)
cRSI3t1=color.new(_cRSIt1,transRSI3)
cRSI3t2=color.new(_cRSIt2,transRSI3)
cRSI3t3=color.new(_cRSIt3,transRSI3)
cRSI3b1=color.new(_cRSIb1,transRSI3)
cRSI3b2=color.new(_cRSIb2,transRSI3)
cRSI3b3=color.new(_cRSIb3,transRSI3)
showRSI4 = input.bool(defval=true,title="use RSI in Higher TF4",inline="tf4",group="RSI")
transRSI4 = input.int(defval=40,minval=0,maxval=99,title="border transpar",inline="tf4",group="RSI")
cRSI4i=color.new(_cRSIi,transRSI4)
cRSI4t1=color.new(_cRSIt1,transRSI4)
cRSI4t2=color.new(_cRSIt2,transRSI4)
cRSI4t3=color.new(_cRSIt3,transRSI4)
cRSI4b1=color.new(_cRSIb1,transRSI4)
cRSI4b2=color.new(_cRSIb2,transRSI4)
cRSI4b3=color.new(_cRSIb3,transRSI4)
//
//high low box
//
var a_hist_top = array.new_float(0,na)
var a_hist_bottom = array.new_float(0,na)
var a_hist_time = array.new_int(0,na)
var a_hist_tf = array.new_string(0,na)
var a_hist_close = array.new_float(0,na)
var a_hist_cbox = array.new_color(0,na)
var m_high = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp=close[1]>open[1]?true:false
b_isUp=close>open?true:false
b_peak=b_isLastUp and not b_isUp
b_bottom=not b_isLastUp and b_isUp
i_renew=0
var i_last_renew=0
if b_peak or b_bottom
if b_peak
_high=close[1]>=open?close[1]:open
_high_time=close[1]>=open?time_close[1]:time_close
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew,_high,_high_time,m_high,m_return_high,m_low,m_return_low)
i_renew:=_i_renew
m_high:= o_m_high
m_return_high:=o_m_return_high
m_low:= o_m_low
m_return_low:= o_m_return_low
else if b_bottom
_low=close[1]<=open?close[1]:open
_low_time=close[1]<=open?time_close[1]:time_close
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew,_low,_low_time,m_low,m_return_low,m_high,m_return_high)
i_renew:=_i_renew
m_high:= o_m_high
m_return_high:= o_m_return_high
m_low:= o_m_low
m_return_low:= o_m_return_low
else
na
else
na
//
i_last_renew:=i_renew
var mybox=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
var myfibo23=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo38=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo50=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo61=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo78=line.new(na,na,na,na,xloc=xloc.bar_time)
var myfibo161=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibo261=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibo361=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibom161=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibom261=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var myfibom361=label.new(na,na,na,xloc=xloc.bar_time,style=label.style_none)
var i_breakT=0
var i_breakf161=0
var i_breakf261=0
var i_breakB=0
var i_breakfm161=0
var i_breakfm261=0
top= matrix.get(m_high,0,matrix.columns(m_high)-1)
top_time= matrix.get(m_high,1,matrix.columns(m_high)-1)
bottom= matrix.get(m_low,0,matrix.columns(m_low)-1)
bottom_time= matrix.get(m_low,1,matrix.columns(m_low)-1)
c_box_bg=bottom_time<top_time?cBoxUf:cBoxDf
c_box=bottom_time<top_time?cBoxU:cBoxD
_h = array.from(int(top_time),int(bottom_time))
_v = array.from(top,bottom)
_t = array.max(_v)
_b = array.min(_v)
_l = array.min(_h)
[fm361,fm261,fm161,f23,f38,f50,f61,f78,f161,f261,f361] = f_fibo(_b,_t)
if show0 and i_renew!=0
mybox:=box.new(_l,na,na,na,xloc=xloc.bar_time,border_width=widthBox,text_halign=text.align_center,text_size=infoSize,
border_color=c_box,text_color=cBoxT,bgcolor=c_box_bg,border_style=styleBox)
array.push(a_hist_time,_l)
array.push(a_hist_tf,tfChart)
array.push(a_hist_top,_t)
array.push(a_hist_bottom,_b)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if b_fibo
myfibo23:=line.new(_l,f23,na,f23,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo38:=line.new(_l,f38,na,f38,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo50:=line.new(_l,f50,na,f50,xloc.bar_time,extend.none,c_box,line.style_solid,1)
myfibo61:=line.new(_l,f61,na,f61,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo78:=line.new(_l,f78,na,f78,xloc.bar_time,extend.none,c_box,line.style_dashed,1)
myfibo161:=label.new(na,f161,"___1.618:"+str.tostring(f161,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibo261:=label.new(na,f261,"___2.618:"+str.tostring(f261,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibo361:=label.new(na,f361,"___3.618:"+str.tostring(f361,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibom161:=label.new(na,fm161,"___1.618:"+str.tostring(fm161,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibom261:=label.new(na,fm261,"___2.618:"+str.tostring(fm261,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
myfibom361:=label.new(na,fm361,"___3.618:"+str.tostring(fm361,"#.0000")+"___",xloc.bar_time,yloc.price,c_box_bg,label.style_none,c_box,infoSize)
else
label.delete(myfibo161),label.delete(myfibo261),label.delete(myfibo361)
label.delete(myfibom161),label.delete(myfibom261),label.delete(myfibo361)
i_breakT:=0
i_breakB:=0
i_breakf161:=0
i_breakf261:=0
i_breakfm161:=0
i_breakfm261:=0
i_breakT+=high>_t?1:0
i_breakB+=low<_t?1:0
i_breakf161:=high>f161?1:0
i_breakf261:=high>f261?1:0
i_breakfm161:=low<fm161?1:0
i_breakfm261:=low<fm261?1:0
if show0
box.set_right(mybox,time_close)
box.set_bottom(mybox,_b)
box.set_top(mybox,_t)
box.set_text(mybox,
b_info?
"TF="+tfChart+":"+f_time_ddHHmm(box.get_right(mybox)-box.get_left(mybox))+":"+
str.tostring(math.abs(box.get_top(mybox)-box.get_bottom(mybox))):na)
if array.lastindexof(a_hist_tf,tfChart)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tfChart),_t)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tfChart),_b)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tfChart),close)
line.set_x2(myfibo23,time_close)
line.set_x2(myfibo38,time_close)
line.set_x2(myfibo50,time_close)
line.set_x2(myfibo61,time_close)
line.set_x2(myfibo78,time_close)
if i_breakT>0
label.set_xy(myfibo161,(_l+time_close)/2,f161)
if i_breakf161>0
label.set_xy(myfibo261,(_l+time_close)/2,f261)
if i_breakf261>0
label.set_xy(myfibo361,(_l+time_close)/2,f361)
if i_breakB>0
label.set_xy(myfibom161,(_l+time_close)/2,fm161)
if i_breakfm161>0
label.set_xy(myfibom261,(_l+time_close)/2,fm261)
if i_breakfm261>0
label.set_xy(myfibom361,(_l+time_close)/2,fm361)
//box H1
close1=f_getMtf(tf1,close)
open1=f_getMtf(tf1,open)
time1=f_getMtf(tf1,time)
time_close1=f_getMtf(tf1,time_close)
var m_high1 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high1 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low1 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low1 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp1=close1[1]>open1[1]?true:false
b_isUp1=close1>open1?true:false
b_peak1=b_isLastUp1 and not b_isUp1
b_bottom1=not b_isLastUp1 and b_isUp1
i_renew1=0
var i_last_renew1=0//laststate
if b_peak1 or b_bottom1
if b_peak1
_high=close1[1]>=open1?close1[1]:open1
_high_time=close1[1]>=open1?time_close1[1]:time_close1
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew1,_high,_high_time,m_high1,m_return_high1,m_low1,m_return_low1)
i_renew1:=_i_renew
m_high1:= o_m_high
m_return_high1:=o_m_return_high
m_low1:= o_m_low
m_return_low1:= o_m_return_low
else if b_bottom1
_low=close1[1]<=open1?close1[1]:open1
_low_time=close1[1]<=open1?time_close1[1]:time_close1
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew1,_low,_low_time,m_low1,m_return_low1,m_high1,m_return_high1)
i_renew1:=_i_renew
m_high1:= o_m_high
m_return_high1:= o_m_return_high
m_low1:= o_m_low
m_return_low1:= o_m_return_low
else
na
else
na
//
i_last_renew1:=i_renew1
var mybox1=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top1= matrix.get(m_high1,0,matrix.columns(m_high1)-1)
top_time1= matrix.get(m_high1,1,matrix.columns(m_high1)-1)
bottom1= matrix.get(m_low1,0,matrix.columns(m_low1)-1)
bottom_time1= matrix.get(m_low1,1,matrix.columns(m_low1)-1)
c_box1=bottom_time1<top_time1?cBoxU1:cBoxD1
va1=bottom_time1<top_time1?text.align_top:text.align_bottom
_h1 = array.from(int(top_time1),int(bottom_time1))
_v1 = array.from(top1,bottom1)
_t1 = array.max(_v1)
_b1 = array.min(_v1)
_l1 = array.min(_h1)
if show1 and i_renew1!=0
mybox1:=box.new(_l1,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox1,border_style=styleBox1,
text_halign=text.align_right,text_valign=va1,text_size=infoSize1,border_color=c_box1,text_color=cBoxT1)
array.push(a_hist_time,_l1)
array.push(a_hist_tf,tf1)
array.push(a_hist_top,_t1)
array.push(a_hist_bottom,_b1)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show1
box.set_right(mybox1,time_close1)
box.set_bottom(mybox1,_b1)
box.set_top(mybox1,_t1)
box.set_text(mybox1,b_info1?"TFโ="+tf1+"\n"+
f_time_ddHHmm(box.get_right(mybox1)-box.get_left(mybox1))+"\n"+
str.tostring(math.abs(box.get_top(mybox1)-box.get_bottom(mybox1))):na)
if array.lastindexof(a_hist_tf,tf1)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf1),_t1)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf1),_b1)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf1),close1)
//box H2
close2=f_getMtf(tf2,close)
open2=f_getMtf(tf2,open)
time2=f_getMtf(tf2,time)
time_close2=f_getMtf(tf2,time_close)
var m_high2 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high2 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low2 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low2 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp2=close2[1]>open2[1]?true:false
b_isUp2=close2>open2?true:false
b_peak2=b_isLastUp2 and not b_isUp2
b_bottom2=not b_isLastUp2 and b_isUp2
i_renew2=0
var i_last_renew2=0//laststate
if b_peak2 or b_bottom2
if b_peak2
_high=close2[1]>=open2?close2[1]:open2
_high_time=close2[1]>=open2?time_close2[1]:time_close2
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew2,_high,_high_time,m_high2,m_return_high2,m_low2,m_return_low2)
i_renew2:=_i_renew
m_high2:= o_m_high
m_return_high2:=o_m_return_high
m_low2:= o_m_low
m_return_low2:= o_m_return_low
else if b_bottom2
_low=close2[1]<=open2?close2[1]:open2
_low_time=close2[1]<=open2?time_close2[1]:time_close2
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew2,_low,_low_time,m_low2,m_return_low2,m_high2,m_return_high2)
i_renew2:=_i_renew
m_high2:= o_m_high
m_return_high2:= o_m_return_high
m_low2:= o_m_low
m_return_low2:= o_m_return_low
else
na
else
na
//
i_last_renew2:=i_renew2
var mybox2=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top2= matrix.get(m_high2,0,matrix.columns(m_high2)-1)
top_time2= matrix.get(m_high2,1,matrix.columns(m_high2)-1)
bottom2= matrix.get(m_low2,0,matrix.columns(m_low2)-1)
bottom_time2= matrix.get(m_low2,1,matrix.columns(m_low2)-1)
c_box2=bottom_time2<top_time2?cBoxU2:cBoxD2
va2=bottom_time2<top_time2?text.align_top:text.align_bottom
_h2 = array.from(int(top_time2),int(bottom_time2))
_v2 = array.from(top2,bottom2)
_t2 = array.max(_v2)
_b2 = array.min(_v2)
_l2 = array.min(_h2)
if show2 and i_renew2!=0
mybox2:=box.new(_l2,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox2,border_style=styleBox2,
text_halign=text.align_right,text_valign=va2,text_size=infoSize2,border_color=c_box2,text_color=cBoxT2)
array.push(a_hist_time,_l2)
array.push(a_hist_tf,tf2)
array.push(a_hist_top,_t2)
array.push(a_hist_bottom,_b2)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show2
box.set_right(mybox2,time_close2)
box.set_bottom(mybox2,_b2)
box.set_top(mybox2,_t2)
box.set_text(mybox2,b_info2?"TFโ="+tf2+"\n"+
f_time_ddHHmm(box.get_right(mybox2)-box.get_left(mybox2))+"\n"+
str.tostring(math.abs(box.get_top(mybox2)-box.get_bottom(mybox2))):na)
if array.lastindexof(a_hist_tf,tf2)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf2),_t2)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf2),_b2)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf2),close2)
//box H3
close3=f_getMtf(tf3,close)
open3=f_getMtf(tf3,open)
time3=f_getMtf(tf3,time)
time_close3=f_getMtf(tf3,time_close)
var m_high3 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high3 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low3 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low3 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp3=close3[1]>open3[1]?true:false
b_isUp3=close3>open3?true:false
b_peak3=b_isLastUp3 and not b_isUp3
b_bottom3=not b_isLastUp3 and b_isUp3
i_renew3=0
var i_last_renew3=0
if b_peak3 or b_bottom3
if b_peak3
_high=close3[1]>=open3?close3[1]:open3
_high_time=close3[1]>=open3?time_close3[1]:time_close3
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew3,_high,_high_time,m_high3,m_return_high3,m_low3,m_return_low3)
i_renew3:=_i_renew
m_high3:= o_m_high
m_return_high3:=o_m_return_high
m_low3:= o_m_low
m_return_low3:= o_m_return_low
else if b_bottom3
_low=close3[1]<=open3?close3[1]:open3
_low_time=close3[1]<=open3?time_close3[1]:time_close3
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew3,_low,_low_time,m_low3,m_return_low3,m_high3,m_return_high3)
i_renew3:=_i_renew
m_high3:= o_m_high
m_return_high3:= o_m_return_high
m_low3:= o_m_low
m_return_low3:= o_m_return_low
else
na
else
na
//
i_last_renew3:=i_renew3
var mybox3=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top3= matrix.get(m_high3,0,matrix.columns(m_high3)-1)
top_time3= matrix.get(m_high3,1,matrix.columns(m_high3)-1)
bottom3= matrix.get(m_low3,0,matrix.columns(m_low3)-1)
bottom_time3= matrix.get(m_low3,1,matrix.columns(m_low3)-1)
c_box3=bottom_time3<top_time3?cBoxU3:cBoxD3
va3=bottom_time3<top_time3?text.align_top:text.align_bottom
_h3 = array.from(int(top_time3),int(bottom_time3))
_v3 = array.from(top3,bottom3)
_t3 = array.max(_v3)
_b3 = array.min(_v3)
_l3 = array.min(_h3)
if show3 and i_renew3!=0
mybox3:=box.new(_l3,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox3,border_style=styleBox3,
text_halign=text.align_right,text_valign=va3,text_size=infoSize3,border_color=c_box3,text_color=cBoxT3)
array.push(a_hist_time,_l3)
array.push(a_hist_tf,tf3)
array.push(a_hist_top,_t3)
array.push(a_hist_bottom,_b3)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show3
box.set_right(mybox3,time_close3)
box.set_bottom(mybox3,_b3)
box.set_top(mybox3,_t3)
box.set_text(mybox3,b_info3?"TFโ="+tf3+"\n"+
f_time_ddHHmm(box.get_right(mybox3)-box.get_left(mybox3))+"\n"+
str.tostring(math.abs(box.get_top(mybox3)-box.get_bottom(mybox3))):na)
if array.lastindexof(a_hist_tf,tf3)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf3),_t3)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf3),_b3)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf3),close3)
//box H4
close4=f_getMtf(tf4,close)
open4=f_getMtf(tf4,open)
time4=f_getMtf(tf4,time)
time_close4=f_getMtf(tf4,time_close)
var m_high4 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_high4 = matrix.new<float>(2,1,time)//0: price, 1:time
var m_low4 = matrix.new<float>(2,1,hl2)//0: price, 1:time
var m_return_low4 = matrix.new<float>(2,1,time)//0: price, 1:time
b_isLastUp4=close4[1]>open4[1]?true:false
b_isUp4=close4>open4?true:false
b_peak4=b_isLastUp4 and not b_isUp4
b_bottom4=not b_isLastUp4 and b_isUp4
i_renew4=0
var i_last_renew4=0
if b_peak4 or b_bottom4
if b_peak4
_high=close4[1]>=open4?close4[1]:open4
_high_time=close4[1]>=open4?time_close4[1]:time_close4
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_high(i_last_renew4,_high,_high_time,m_high4,m_return_high4,m_low4,m_return_low4)
i_renew4:=_i_renew
m_high4:= o_m_high
m_return_high4:=o_m_return_high
m_low4:= o_m_low
m_return_low4:= o_m_return_low
else if b_bottom4
_low=close4[1]<=open4?close4[1]:open4
_low_time=close4[1]<=open4?time_close4[1]:time_close4
[_i_renew,o_m_high,o_m_return_high,o_m_low,o_m_return_low]=
f_renew_low(i_last_renew4,_low,_low_time,m_low4,m_return_low4,m_high4,m_return_high4)
i_renew4:=_i_renew
m_high4:= o_m_high
m_return_high4:= o_m_return_high
m_low4:= o_m_low
m_return_low4:= o_m_return_low
else
na
else
na
//
i_last_renew4:=i_renew4
var mybox4=box.new(na,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_color=na)
top4= matrix.get(m_high4,0,matrix.columns(m_high4)-1)
top_time4= matrix.get(m_high4,1,matrix.columns(m_high4)-1)
bottom4= matrix.get(m_low4,0,matrix.columns(m_low4)-1)
bottom_time4= matrix.get(m_low4,1,matrix.columns(m_low4)-1)
c_box4=bottom_time4<top_time4?cBoxU4:cBoxD4
va4=bottom_time4<top_time4?text.align_top:text.align_bottom
_h4 = array.from(int(top_time4),int(bottom_time4))
_v4 = array.from(top4,bottom4)
_t4 = array.max(_v4)
_b4 = array.min(_v4)
_l4 = array.min(_h4)
if show4 and i_renew4!=0
mybox4:=box.new(_l4,na,na,na,xloc=xloc.bar_time,bgcolor=na,border_width=widthBox4,border_style=styleBox4,
text_halign=text.align_right,text_valign=va4,text_size=infoSize4,border_color=c_box4,text_color=cBoxT4)
array.push(a_hist_time,_l4)
array.push(a_hist_tf,tf4)
array.push(a_hist_top,_t4)
array.push(a_hist_bottom,_b4)
array.push(a_hist_close,close)
array.push(a_hist_cbox,c_box)
if show4
box.set_right(mybox4,time_close4)
box.set_bottom(mybox4,_b4)
box.set_top(mybox4,_t4)
box.set_text(mybox4,b_info4?"TFโ="+tf4+"\n"+
f_time_ddHHmm(box.get_right(mybox4)-box.get_left(mybox4))+"\n"+
str.tostring(math.abs(box.get_top(mybox4)-box.get_bottom(mybox4))):na)
if array.lastindexof(a_hist_tf,tf4)!=-1
array.set(a_hist_top,array.lastindexof(a_hist_tf,tf4),_t4)
array.set(a_hist_bottom,array.lastindexof(a_hist_tf,tf4),_b4)
array.set(a_hist_close,array.lastindexof(a_hist_tf,tf4),close4)
//
//fibonacci levels of higher boxes
//
var l_mybox1_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize1,text.align_left)
var l_mybox1_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize1,text.align_left)
var l_mybox2_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize2,text.align_left)
var l_mybox2_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize2,text.align_left)
var l_mybox3_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
var l_mybox3_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
var l_mybox4_rt=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
var l_mybox4_rb=label.new(na,na,na,xloc.bar_time,yloc.price,na,label.style_none,na,infoSize3,text.align_left)
if show1 and b_fibo1
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox1),box.get_top(mybox1),close)
label.set_xy(l_mybox1_rt,box.get_right(mybox1),_top)
label.set_textcolor(l_mybox1_rt,c_box1)
label.set_text(l_mybox1_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@โ"+tf1)
label.set_xy(l_mybox1_rb,box.get_right(mybox1),_bottom)
label.set_textcolor(l_mybox1_rb,c_box1)
label.set_text(l_mybox1_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@โ"+tf1)
if show2 and b_fibo2
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox2),box.get_top(mybox2),close)
label.set_xy(l_mybox2_rt,box.get_right(mybox2),_top)
label.set_textcolor(l_mybox2_rt,c_box2)
label.set_text(l_mybox2_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@โ"+tf2)
label.set_xy(l_mybox2_rb,box.get_right(mybox2),_bottom)
label.set_textcolor(l_mybox2_rb,c_box2)
label.set_text(l_mybox2_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@โ"+tf2)
if show3 and b_fibo3
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox3),box.get_top(mybox3),close)
label.set_xy(l_mybox3_rt,box.get_right(mybox3),_top)
label.set_textcolor(l_mybox3_rt,c_box3)
label.set_text(l_mybox3_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@โ"+tf3)
label.set_xy(l_mybox3_rb,box.get_right(mybox3),_bottom)
label.set_textcolor(l_mybox3_rb,c_box3)
label.set_text(l_mybox3_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@โ"+tf3)
if show4 and b_fibo4
[_top,_tops,_bottom,_bottoms] = f_fibo_range(box.get_bottom(mybox4),box.get_top(mybox4),close)
label.set_xy(l_mybox4_rt,box.get_right(mybox4),_top)
label.set_textcolor(l_mybox4_rt,c_box4)
label.set_text(l_mybox4_rt,"_____"+_tops+":"+str.tostring(_top,"#.0000")+"@โ"+tf4)
label.set_xy(l_mybox4_rb,box.get_right(mybox4),_bottom)
label.set_textcolor(l_mybox4_rb,c_box4)
label.set_text(l_mybox4_rb,"_____"+_bottoms+":"+str.tostring(_bottom,"#.0000")+"@โ"+tf4)
var max=minimapHist
a_hist_top_mm=array.new_float(0,na)
a_hist_bottom_mm=array.new_float(0,na)
a_hist_time_mm=array.new_int(0,na)
a_hist_tf_mm=array.new_string(0,na)
a_hist_close_mm=array.new_float(0,na)
a_hist_cbox_mm=array.new_color(0,na)
a_hist_top_mm :=array.size(a_hist_top)>max?array.slice(a_hist_top,array.size(a_hist_top)-max,array.size(a_hist_top)-1):a_hist_top
a_hist_bottom_mm :=array.size(a_hist_bottom)>max?array.slice(a_hist_bottom,array.size(a_hist_bottom)-max,array.size(a_hist_bottom)-1):a_hist_bottom
a_hist_time_mm :=array.size(a_hist_time)>max?array.slice(a_hist_time,array.size(a_hist_time)-max,array.size(a_hist_time)-1):a_hist_time
a_hist_tf_mm :=array.size(a_hist_tf)>max?array.slice(a_hist_tf,array.size(a_hist_tf)-max,array.size(a_hist_tf)-1):a_hist_tf
a_hist_close_mm :=array.size(a_hist_close)>max?array.slice(a_hist_close,array.size(a_hist_close)-max,array.size(a_hist_close)-1):a_hist_close
a_hist_cbox_mm :=array.size(a_hist_cbox)>max?array.slice(a_hist_cbox,array.size(a_hist_cbox)-max,array.size(a_hist_cbox)-1):a_hist_cbox
hist_top = array.max(a_hist_top_mm)
hist_bottom = array.min(a_hist_bottom_mm)
f_cellpos(_top,_bottom,_rt,_rb) =>
_p0 = 10
_p100 = 50
_diff = _top-_bottom
_rtdiff = _top-_rt
_rbdiff = _top-_rb
_topp = int(10 - (_p0-_p100)*_rtdiff/_diff)
_bottomp =int(10 - (_p0-_p100)*_rbdiff/_diff)
[_topp,_bottomp]
if showMinimap
minimap = table.new(position.bottom_left,100,100,color.new(color.white,90),frame_color=color.white,frame_width=1,border_color=na,border_width=1)
if array.size(a_hist_time_mm)>0
table.cell(minimap,0,0,text="minimap from "+f_time_ddHHmm(array.last(a_hist_time_mm)-array.get(a_hist_time_mm,0))+" ago",text_color=color.white,text_size=size.small,text_halign=text.align_left)
table.merge_cells(minimap,0,0,10,0)
table.cell(minimap,0,1,text=str.tostring(hist_top),text_color=color.white,text_size=size.small,text_halign=text.align_left)
table.merge_cells(minimap,0,1,10,1)
table.cell(minimap,0,99,text=str.tostring(hist_bottom),text_color=color.white,text_size=size.small,text_halign=text.align_left)
table.merge_cells(minimap,0,99,10,99)
if array.size(a_hist_top_mm)>0
for i = 0 to array.size(a_hist_top_mm)-1
[_top,_bottom]=f_cellpos(hist_top,hist_bottom,array.get(a_hist_top_mm,i),array.get(a_hist_bottom_mm,i))
if array.get(a_hist_tf_mm,i) == tfChart
_fl = f_fibo_level(array.get(a_hist_bottom_mm,i),array.get(a_hist_top_mm,i),array.get(a_hist_close_mm,i))
table.cell(minimap,i,_top,_fl,text_color=f_fl_c(_fl),bgcolor=array.get(a_hist_cbox_mm,i),text_size=size.tiny,text_valign=f_fl_va(_fl))
table.merge_cells(minimap,i,_top,i,_bottom)
else
table.cell(minimap,i,_top-1,"โผ",text_color=array.get(a_hist_cbox_mm,i),text_size=size.tiny,bgcolor=na)
table.cell(minimap,i,_top,array.get(a_hist_tf_mm,i),text_color=color.white,bgcolor=array.get(a_hist_cbox_mm,i),text_size=size.tiny)
table.merge_cells(minimap,i,_top,i,_bottom)
table.cell(minimap,i,_bottom+1,"โฒ",text_color=array.get(a_hist_cbox_mm,i),text_size=size.tiny,bgcolor=na)
na
//*****
//end of HighLowBox
//*****
//
//RSI
//
var int RSIt =70
var int RSIb =30
s_RSI_1= show0 and showRSI?ta.rsi(srcRSI,spanRSI_1):na
s_RSI_2= show0 and showRSI?ta.rsi(srcRSI,spanRSI_2):na
b_RSI_70 = s_RSI_1>=RSIt or s_RSI_2>=RSIt
b_RSI_30 = s_RSI_1<=RSIb or s_RSI_2<=RSIb
cRSI=
s_RSI_1==s_RSI_1[1] and s_RSI_2==s_RSI_2[1]?na:
b_RSI_70? s_RSI_1>s_RSI_2? s_RSI_2<RSIt?cRSIi: cRSIt1: s_RSI_1<RSIt?cRSIt3: cRSIt2:
b_RSI_30? s_RSI_1<s_RSI_2? s_RSI_2>RSIb?cRSIi: cRSIb1: s_RSI_1>RSIb?cRSIb3: cRSIb2:na
RSIy=b_RSI_70? box.get_top(mybox): b_RSI_30?box.get_bottom(mybox):na
plotshape(RSIy,"SIG_RSI",shape.circle,location=location.absolute,color=cRSI,text=na,textcolor=na,size=size.normal)
//โโโโโโโโโโโถโทโธโนโบโปโผโฝโพโฟ
//H1
s_RSI1_1= show1 and showRSI1?f_getMtf(tf1,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI1_2= show1 and showRSI1?f_getMtf(tf1,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI1_70 = s_RSI1_1>=RSIt or s_RSI1_2>=RSIt
b_RSI1_30 = s_RSI1_1<=RSIb or s_RSI1_2<=RSIb
cRSI1=
s_RSI1_1==s_RSI1_1[1] and s_RSI1_2==s_RSI1_2[1]?na:
b_RSI1_70? s_RSI1_1>s_RSI1_2? s_RSI1_2<RSIt?cRSI1i: cRSI1t1: s_RSI1_1<RSIt?cRSI1t3: cRSI1t2:
b_RSI1_30? s_RSI1_1<s_RSI1_2? s_RSI1_2>RSIb?cRSI1i: cRSI1b1: s_RSI1_1>RSIb?cRSI1b3: cRSI1b2:na
RSI1y=b_RSI1_70? box.get_top(mybox1): b_RSI1_30?box.get_bottom(mybox1):na
plotchar(RSI1y,"SIG_RSI1",char="โ",location=location.absolute,color=cRSI1,textcolor=na,size=size.small)
//H2
s_RSI2_1= show2 and showRSI2?f_getMtf(tf2,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI2_2= show2 and showRSI2?f_getMtf(tf2,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI2_70 = s_RSI2_1>=RSIt or s_RSI2_2>=RSIt
b_RSI2_30 = s_RSI2_1<=RSIb or s_RSI2_2<=RSIb
cRSI2=
s_RSI2_1==s_RSI2_1[1] and s_RSI2_2==s_RSI2_2[1]?na:
b_RSI2_70? s_RSI2_1>s_RSI2_2? s_RSI2_2<RSIt?cRSI2i: cRSI2t1: s_RSI2_1<RSIt?cRSI2t3: cRSI2t2:
b_RSI2_30? s_RSI2_1<s_RSI2_2? s_RSI2_2>RSIb?cRSI2i: cRSI2b1: s_RSI2_1>RSIb?cRSI2b3: cRSI2b2:na
RSI2y=b_RSI2_70? box.get_top(mybox2): b_RSI2_30?box.get_bottom(mybox2):na
plotchar(RSI2y,"SIG_RSI2",char="โ",location=location.absolute,color=cRSI2,textcolor=na,size=size.small)
//H3
s_RSI3_1= show3 and showRSI3?f_getMtf(tf3,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI3_2= show3 and showRSI3?f_getMtf(tf3,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI3_70 = s_RSI3_1>=RSIt or s_RSI3_2>=RSIt
b_RSI3_30 = s_RSI3_1<=RSIb or s_RSI3_2<=RSIb
cRSI3=
s_RSI3_1==s_RSI3_1[1] and s_RSI3_2==s_RSI3_2[1]?na:
b_RSI3_70? s_RSI3_1>s_RSI3_2? s_RSI3_2<RSIt?cRSI3i: cRSI3t1: s_RSI3_1<RSIt?cRSI3t3: cRSI3t2:
b_RSI3_30? s_RSI3_1<s_RSI3_2? s_RSI3_2>RSIb?cRSI3i: cRSI3b1: s_RSI3_1>RSIb?cRSI3b3: cRSI3b2:na
RSI3y=b_RSI3_70? box.get_top(mybox3): b_RSI3_30?box.get_bottom(mybox3):na
plotchar(RSI3y,"SIG_RSI3",char="โ",location=location.absolute,color=cRSI3,textcolor=na,size=size.small)
//H4
s_RSI4_1= show4 and showRSI4?f_getMtf(tf4,ta.rsi(srcRSI,spanRSI_1)):na
s_RSI4_2= show4 and showRSI4?f_getMtf(tf4,ta.rsi(srcRSI,spanRSI_2)):na
b_RSI4_70 = s_RSI4_1>=RSIt or s_RSI4_2>=RSIt
b_RSI4_30 = s_RSI4_1<=RSIb or s_RSI4_2<=RSIb
cRSI4=
s_RSI4_1==s_RSI4_1[1] and s_RSI4_2==s_RSI4_2[1]?na:
b_RSI4_70? s_RSI4_1>s_RSI4_2? s_RSI4_2<RSIt?cRSI4i: cRSI4t1: s_RSI4_1<RSIt?cRSI4t3: cRSI4t2:
b_RSI4_30? s_RSI4_1<s_RSI4_2? s_RSI4_2>RSIb?cRSI4i: cRSI4b1: s_RSI4_1>RSIb?cRSI4b3: cRSI4b2:na
RSI4y=b_RSI4_70? box.get_top(mybox4): b_RSI4_30?box.get_bottom(mybox4):na
plotchar(RSI4y,"SIG_RSI4",char="โ",location=location.absolute,color=cRSI4,textcolor=na,size=size.small)
|
Oscillator Profile Indicator | https://www.tradingview.com/script/QmbvMD8Y-Oscillator-Profile-Indicator/ | gotbeatz26107 | https://www.tradingview.com/u/gotbeatz26107/ | 60 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ gotbeatz26107
//@version=5
indicator("Oscillator Profile Indicator", shorttitle="OPI", overlay=false)
// Input fields
src = input(close, title = "Source", inline = 'l1')
show_colors = input.bool(true, title = "Show colors?", inline = 'l1')
percentile = input(70, title = "Value Area Percentile", inline = 'l2')
lookback = input(100, title = "Lookback period", inline = 'l2')
// Profiler function
profiler(float src, simple float percentile, int lookback) =>
poc_val = 0.0
lower_boundary_val = 0.0
upper_boundary_val = 0.0
if lookback <= 100
poc_val := ta.percentile_linear_interpolation(src, lookback, 50)
lower_boundary_val := ta.percentile_linear_interpolation(src, lookback, 100 - percentile)
upper_boundary_val := ta.percentile_linear_interpolation(src, lookback, percentile)
[poc_val, lower_boundary_val, upper_boundary_val]
if lookback > 100
poc_val := ta.percentile_nearest_rank(src, lookback, 50)
lower_boundary_val := ta.percentile_nearest_rank(src, lookback, 100 - percentile)
upper_boundary_val := ta.percentile_nearest_rank(src, lookback, percentile)
//
[poc_val, lower_boundary_val, upper_boundary_val]
// Extract values from the profiler
[poc_val, lower_boundary_val, upper_boundary_val] = profiler(src, percentile, lookback)
// Colors and their conditions
fill_up = color.rgb(0, 137, 123, 80)
fill_dn = color.rgb(255, 82, 82, 80)
sig_up = color.rgb(0, 137, 123, 60)
sig_dn = color.rgb(255, 82, 82, 60)
line_up = color.teal
line_dn = color.red
line_up_clr = src > poc_val ? line_up : line_dn
line_dn_clr = src < poc_val ? line_dn : line_up
fill_up_clr = src > poc_val ? fill_up : na
fill_dn_clr = src < poc_val ? fill_dn : na
fill_up_sig = src >= upper_boundary_val and poc_val >= poc_val[1] ? sig_up : na
fill_dn_sig = src <= lower_boundary_val and poc_val <= poc_val[1] ? sig_dn : na
// Plots and fills
poc = plot(poc_val, color= show_colors ? color.white : color.red, linewidth = 1)
dn = plot(lower_boundary_val, color = show_colors ? line_dn_clr : color.blue, linewidth = 1)
up = plot(upper_boundary_val, color = show_colors ? line_up_clr : color.blue, linewidth = 1)
fill(dn, up, color = show_colors ? fill_up_clr : na)
fill(dn, up, color = show_colors ? fill_dn_clr : na)
fill(dn, up, color = show_colors ? fill_up_sig : na)
fill(dn, up, color = show_colors ? fill_dn_sig : na) |
Time Profile [QuantVue] | https://www.tradingview.com/script/WZ8Hf4X2-Time-Profile-QuantVue/ | QuantVue | https://www.tradingview.com/u/QuantVue/ | 106 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ QuantVue
//@version=5
indicator("Time Profile [QuantVue]", overlay = true, max_bars_back = 4999)
/////////////
// inputs //
lowerTF = input.timeframe('15', 'Lower Time Frame Data')
showTimeProfile = input.bool(true, 'Show Time Profile')
maxColor = input.color(color.new(color.lime,70), 'Highest', inline = '2')
mincolor = input.color(color.new(color.yellow,70), 'Lowest', inline = '2')
showVPOC = input.bool(true, 'Show Volume POC', inline = '3')
pocColor = input.color(color.fuchsia, ' ', inline = '3', tooltip = 'The close of the highest volume lower time frame bar')
showTime = input.bool(true, 'Time POC History', inline = '4')
tpocCol = input.color(color.yellow, ' ', inline = '4', tooltip = 'Plots where the most smaller time frame closes occured for that bar')
double = input.bool(true, 'Volume and Time POC Aligned', inline = '5')
doubleCol = input.color(color.lime, ' ', inline = '5', tooltip = 'Highlight when the volume and time point of controls are aligned on the real time bar')
////////////////
// variables //
timeArr = array.new<int>()
box box1 = na, box box2 = na, box box3 = na, box box4 = na, box box5 = na
box box6 = na, box box7 = na, box box8 = na, box box9 = na, box box10 = na
up = close > close[1]
down = close < close[1]
////////////////
// functions //
ltfVolData() =>
vol = not na(volume) ? volume : 0
[close, vol]
proColor(bc) =>
color.from_gradient(bc, timeArr.get(9), timeArr.get(0), mincolor, maxColor)
///////////////
// ltf Data //
[ltfClose, ltfvol] = request.security_lower_tf(syminfo.ticker, lowerTF, ltfVolData())
/////////////////
// volume POC //
maxVol = ltfClose.size() > 0 ? ltfvol.max() : na
idxofMax = ltfClose.size() > 0 ? ltfvol.indexof(maxVol) : na
maxPrice = ltfClose.size() > 0 ? ltfClose.get(idxofMax) : na
//////////////////
// Time Blocks //
blocks = (high - low) / 10
block1 = low + (blocks * 1)
block2 = low + (blocks * 2)
block3 = low + (blocks * 3)
block4 = low + (blocks * 4)
block5 = low + (blocks * 5)
block6 = low + (blocks * 6)
block7 = low + (blocks * 7)
block8 = low + (blocks * 8)
block9 = low + (blocks * 9)
block10 = low + (blocks * 10)
///////////////////
// Block Counts //
b1C = 0
b2C = 0
b3C = 0
b4C = 0
b5C = 0
b6C = 0
b7C = 0
b8C = 0
b9C = 0
b10C = 0
///////////////////////
// Count ltf Closes //
for i = 0 to ltfClose.size() > 0 ? ltfClose.size() - 1 : na
lastClose = ltfClose.get(i)
if lastClose < block1
b1C += 1
else if lastClose > block1 and lastClose <= block2
b2C += 1
else if lastClose > block2 and lastClose <= block3
b3C += 1
else if lastClose > block3 and lastClose <= block4
b4C += 1
else if lastClose > block4 and lastClose <= block5
b5C += 1
else if lastClose > block5 and lastClose <= block6
b6C += 1
else if lastClose > block6 and lastClose <= block7
b7C += 1
else if lastClose > block7 and lastClose <= block8
b8C += 1
else if lastClose > block8 and lastClose <= block9
b9C += 1
else if lastClose > block9 and lastClose <= block10
b10C += 1
///////////////////
// Store Counts //
timeArr.push(b1C)
timeArr.push(b2C)
timeArr.push(b3C)
timeArr.push(b4C)
timeArr.push(b5C)
timeArr.push(b6C)
timeArr.push(b7C)
timeArr.push(b8C)
timeArr.push(b9C)
timeArr.push(b10C)
////////////////////
// Highest Count //
timeMax = timeArr.max()
idxTime = timeArr.indexof(timeMax)
timeArr.sort(order.descending)
///////////////////////
// Color Background //
bg1 = proColor(b1C)
bg2 = proColor(b2C)
bg3 = proColor(b3C)
bg4 = proColor(b4C)
bg5 = proColor(b5C)
bg6 = proColor(b6C)
bg7 = proColor(b7C)
bg8 = proColor(b8C)
bg9 = proColor(b9C)
bg10 = proColor(b10C)
///////////////////////////////////
// Placement of Historical Plot //
priceBlock = idxTime == 0 ? block1 : idxTime == 1 ? block2 : idxTime == 2 ? block3 : idxTime == 3 ? block4 :
idxTime == 4 ? block5 : idxTime == 5 ? block6 : idxTime == 6 ? block7 : idxTime == 7 ? block8 :
idxTime == 8 ? block9 : block10
blockPos = priceBlock == block1 ? (low + block1) / 2 : priceBlock == block2 ? (block1 + block2) / 2 : priceBlock == block3 ? (block2 + block3) / 2 :
priceBlock == block4 ? (block3 + block4) / 2 : priceBlock == block5 ? (block4 + block5) / 2 : priceBlock == block6 ? (block5 + block6) / 2 :
priceBlock == block7 ? (block6 + block7) / 2 : priceBlock == block8 ? (block7 + block8) / 2 : priceBlock == block9 ? (block8 + block9) / 2 : (block9 + high) / 2
////////////
// Plots //
if barstate.islast and showTimeProfile
(box1[1]).delete(), (box2[1]).delete(), (box3[1]).delete(), (box4[1]).delete(), (box5[1]).delete()
(box6[1]).delete(), (box7[1]).delete(), (box8[1]).delete(), (box9[1]).delete(), (box10[1]).delete()
box1 := box.new(bar_index, block1, bar_index + b1C, low, bgcolor = bg1, border_color = color.black)
box2 := box.new(bar_index, block2, bar_index + b2C, block1, bgcolor = bg2, border_color = color.black)
box3 := box.new(bar_index, block3, bar_index + b3C, block2, bgcolor = bg3, border_color = color.black)
box4 := box.new(bar_index, block4, bar_index + b4C, block3, bgcolor = bg4, border_color = color.black)
box5 := box.new(bar_index, block5, bar_index + b5C, block4, bgcolor = bg5, border_color = color.black)
box6 := box.new(bar_index, block6, bar_index + b6C, block5, bgcolor = bg6, border_color = color.black)
box7 := box.new(bar_index, block7, bar_index + b7C, block6, bgcolor = bg7, border_color = color.black)
box8 := box.new(bar_index, block8, bar_index + b8C, block7, bgcolor = bg8, border_color = color.black)
box9 := box.new(bar_index, block9, bar_index + b9C, block8, bgcolor = bg9, border_color = color.black)
box10 := box.new(bar_index, block10, bar_index + b10C, block9, bgcolor = bg10, border_color = color.black)
plotshape(showVPOC ? maxPrice : na, 'vpoc', shape.circle, location.absolute, pocColor, size = size.tiny)
plotchar(showTime and barstate.ishistory ? blockPos : na, 'Time', '-', location.absolute, tpocCol, size = size.small)
if maxPrice > box1.get_bottom() and maxPrice < box1.get_top() and b1C == timeMax and double
box1.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box2.get_bottom() and maxPrice < box2.get_top() and b2C == timeMax and double
box2.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box3.get_bottom() and maxPrice < box3.get_top() and b3C == timeMax and double
box3.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box4.get_bottom() and maxPrice < box4.get_top() and b4C == timeMax and double
box4.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box5.get_bottom() and maxPrice < box5.get_top() and b5C == timeMax and double
box5.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box6.get_bottom() and maxPrice < box6.get_top() and b6C == timeMax and double
box6.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box7.get_bottom() and maxPrice < box7.get_top() and b7C == timeMax and double
box7.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box8.get_bottom() and maxPrice < box8.get_top() and b8C == timeMax and double
box8.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box9.get_bottom() and maxPrice < box9.get_top() and b9C == timeMax and double
box9.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
else if maxPrice > box10.get_bottom() and maxPrice < box10.get_top() and b10C == timeMax and double
box10.set_bgcolor(doubleCol)
alert('VPOC & TPOC Aligned', alert.freq_once_per_bar_close)
|
Hide Active Candle [SteinG] | https://www.tradingview.com/script/n19OmKLb-Hide-Active-Candle-SteinG/ | SteinG | https://www.tradingview.com/u/SteinG/ | 53 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ SteinG
//@version=5
//Hide Active Candle v1
// # ========================================================================= #
// # | Hide Active Candle Indicator |
// # ========================================================================= #
indicator(
title = "Hide Active Candle",
shorttitle = "",
overlay = true
)
// # ========================================================================= #
// # | Hide Active Candle Indicator |
// # ========================================================================= #
//----------------------- input ----------------------
secondForCandleVisible = input.int(30, "Countdown seconds left", minval=0, step=1, tooltip="Current candle will be visible N seconds before bar being closed")
bullColor = input(color.new(#2d9682, 0), "Bull candle color")
bearColor = input(color.new(#e85048, 0), "Bear candle color")
equalColor = input(color.white, "Equal candle color")
theme = input.string("Dark", "Theme", ["Dark", "Light"])
useCustomColor = input.bool(false, "Use custom hidden color", inline="custom")
customHiddenCandleColor = input(color.new(#171923, 0), "", tooltip="Custom color only applicable if 'Use custom hidden color' is set", inline="custom")
//--------------------Calculation --------------------
normalBarColor = close > open ? bullColor : close == open ? equalColor : bearColor
normalWickColor = close > open ? bullColor : close == open ? equalColor : bearColor
hiddenColor = useCustomColor ? customHiddenCandleColor : theme == "Dark" ? color.new(#171923, 0) : color.new(#ffffff, 0)
secondsLeft = barstate.isrealtime ?
(time_close - timenow) / 1000 :
na
plotcandle(open, high, low, close, "History candle", editable = false, color = normalBarColor, wickcolor = normalWickColor, bordercolor = normalWickColor)
plotcandle(open, high, low, close, editable = false,
color = secondsLeft <= secondForCandleVisible ? normalBarColor : hiddenColor,
wickcolor = secondsLeft <= secondForCandleVisible ? normalWickColor : hiddenColor,
bordercolor = secondsLeft <= secondForCandleVisible ? normalWickColor : hiddenColor, show_last = 1)
|
StdDev Channels | https://www.tradingview.com/script/REFrrmmT-StdDev-Channels/ | jjustingreyy | https://www.tradingview.com/u/jjustingreyy/ | 142 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ jjustingreyy
//@version=5
indicator("StdDev Channels" , overlay=true)
price = input(close, "Source")
deviations = input(2.0, "Deviation Count")
fullRange = input(false, "Toggle Full Range (DefVal 500)")
length = input(153, "Channel 1 Length")
length2 = input(50, "Channel 2 Length") // Length for second channel
uppercolor1 = input(color.rgb(236, 59, 59), "Channel 1 Upper Line")
middlecolor1 = input(color.rgb(228, 228, 220), "Channel 1 Mid Line")
lowercolor1 = input(color.rgb(61, 231, 97), "Channel 1 Lower Line")
uppercolor2 = input(color.rgb(150, 150, 150), "Channel 2 Upper Line")
middlecolor2 = input(color.rgb(188, 187, 187), "Channel 2 Mid Line")
lowercolor2 = input(color.rgb(150, 150, 150), "Channel 2 Lower Line")
// Additional inputs for line width and style
width1 = input(1, "Channel 1 Line Width")
width2 = input(1, "Channel 2 Line Width")
style1 = input(line.style_solid, "Channel 1 Line Style")
style2 = input(line.style_dashed, "Channel 2 Line Style")
//-- change this variable to the maximum number of bars you want to cover. must be bigger then length --//
//-- even if full range is off.
max_bars_back=500
//----------------------------------------------------------------------------//
max_bars_back(price, max_bars_back)
Sqr(x) => x*x
newlength = fullRange ? max_bars_back : length
newlength2 = fullRange ? max_bars_back : length2 // New length for second channel
InertiaAll (y, n) =>
var x = 0
x := x + 1
a = (n * math.sum(x * y, n) - math.sum(x, n) * math.sum(y, n) ) / ( n * math.sum(Sqr(x), n) - Sqr(math.sum(x, n)))
b = (math.sum(Sqr(x), n) * math.sum(y, n) - math.sum(x, n) * math.sum(x * y, n) ) / ( n * math.sum(Sqr(x), n) - Sqr(math.sum(x, n)))
InertiaTS = a * x + b
[InertiaTS, x, a, b]
[regression, x1, a1, b1] = InertiaAll(price, newlength)
stdDeviation = ta.stdev(price, newlength)
[regression2, x2, a2, b2] = InertiaAll(price, newlength2) // Regression for second channel
stdDeviation2 = ta.stdev(price, newlength2) // Standard deviation for second channel
var UpperLine = line.new(0, low, 0, low, color=uppercolor1, extend=extend.right, width=width1, style=style1)
var MiddleLine = line.new(0, low, 0, low, color=middlecolor1, extend=extend.right, width=width1, style=style1)
var LowerLine = line.new(0, low, 0, low, color=lowercolor1, extend=extend.right, width=width1, style=style1)
var UpperLine2 = line.new(0, low, 0, low, color=uppercolor2, extend=extend.right, width=width2, style=style2)
var MiddleLine2 = line.new(0, low, 0, low, color=middlecolor2, extend=extend.right, width=width2, style=style2)
var LowerLine2 = line.new(0, low, 0, low, color=lowercolor2, extend=extend.right, width=width2, style=style2)
if barstate.islast
line.set_xy1(UpperLine, last_bar_index - newlength + 1, a1*x1[newlength - 1] +b1 + deviations * stdDeviation)
line.set_xy2(UpperLine, last_bar_index, a1*x1 +b1 + deviations * stdDeviation)
line.set_xy1(MiddleLine, last_bar_index - newlength + 1, a1*x1[newlength - 1] +b1)
line.set_xy2(MiddleLine, last_bar_index, a1*x1 +b1)
line.set_xy1(LowerLine, last_bar_index - newlength + 1, a1*x1[newlength - 1] +b1 - deviations * stdDeviation)
line.set_xy2(LowerLine, last_bar_index, a1*x1 +b1 - deviations * stdDeviation)
line.set_xy1(UpperLine2, last_bar_index - newlength2 + 1, a2*x2[newlength2 - 1] +b2 + deviations * stdDeviation2) // Lines for second channel
line.set_xy2(UpperLine2, last_bar_index, a2*x2 +b2 + deviations * stdDeviation2)
line.set_xy1(MiddleLine2, last_bar_index - newlength2 + 1, a2*x2[newlength2 - 1] +b2)
line.set_xy2(MiddleLine2, last_bar_index, a2*x2 +b2)
line.set_xy1(LowerLine2, last_bar_index - newlength2 + 1, a2*x2[newlength2 - 1] +b2 - deviations * stdDeviation2)
line.set_xy2(LowerLine2, last_bar_index, a2*x2 +b2 - deviations * stdDeviation2) |
MACD Fake Filter [RH] | https://www.tradingview.com/script/X1YMOQGm-MACD-Fake-Filter-RH/ | HasanRifat | https://www.tradingview.com/u/HasanRifat/ | 783 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ HasanRifat
//@version=5
indicator("MACD Fake Filter [RH]", max_labels_count = 500)
// MACD inputs
fastLength = input(defval=12, title="Fast Length")
slowLength = input(defval=26, title="Slow Length")
src = input(defval=close, title="Source")
signalLength = input.int(defval = 9, title="Signal Smoothing", minval = 1, maxval = 50)
smaSource = input.string(defval="EMA", title="Oscillator MA Type", options=["SMA", "EMA"])
smaSignal = input.string(defval="EMA", title="Signal Line MA Type", options=["SMA", "EMA"])
// MACD calculation
fastMA = smaSource == "SMA" ? ta.sma(src, fastLength) : ta.ema(src, fastLength)
slowMA = smaSource == "SMA" ? ta.sma(src, slowLength) : ta.ema(src, slowLength)
macd = fastMA - slowMA
signal = smaSignal == "SMA" ? ta.sma(macd, signalLength) : ta.ema(macd, signalLength)
hist = macd - signal
var positiveHeightArray = array.new_float()
var poitiveHeightAvg = array.new_float()
var negativeHeightArray = array.new_float()
var negativeHeightAvg = array.new_float()
var float positiveTop = na
var float negatieTop = na
var int activeWave = na
// MACD average wave height calculation
macdZeroCrossOver = macd > 0 and macd[1] < 0
macdZeroCrossUnder = macd < 0 and macd[1] > 0
if macdZeroCrossOver
activeWave := 1
if macdZeroCrossUnder
activeWave := -1
if activeWave == 1
negatieTop := array.min(negativeHeightArray)
array.push(positiveHeightArray, macd)
array.push(negativeHeightAvg, negatieTop)
array.clear(negativeHeightArray)
if activeWave == -1
positiveTop := array.max(positiveHeightArray)
array.push(negativeHeightArray, macd)
array.push(poitiveHeightAvg, positiveTop)
array.clear(positiveHeightArray)
positiveAverageHeight = array.avg(poitiveHeightAvg)
negativeAverageHeight = array.avg(negativeHeightAvg)
bearishCrossunder = ta.crossunder(macd, signal)
bullishCrossover = ta.crossover(macd, signal)
crossunderAboveAvg = bearishCrossunder and macd > positiveAverageHeight
crossaboveBelowAvg = bullishCrossover and macd < negativeAverageHeight
// Labels and plotting
if crossunderAboveAvg
label.new(bar_index, macd[1], text = "", color = color.red)
if crossaboveBelowAvg
label.new(bar_index, macd[1], text = "", color = color.green, style = label.style_label_up)
hline(0, "Zero Line", color=color.new(#5171e6, 50))
plot(hist, title="Histogram", style=plot.style_histogram, color=(hist>=0 ? (hist[1] < hist ? #32cd32 : #008000) : (hist[1] < hist ? #800000 : #ff0000)))
mdPlot = plot(macd, title="MACD", color=#2962FF, linewidth = 2)
sgPlot = plot(signal, title="Signal", color=#FF6D00)
psHeight = plot(positiveAverageHeight, color = color.green, title = "Positive Avg Height")
ngHeight = plot(negativeAverageHeight, color = color.red, title = "Negative Avg Height")
fill(plot1 = mdPlot, plot2 = psHeight, title = "Positive Wave", color = macd > positiveAverageHeight ? (macd[3] < macd ? color.new(color.green, 60) : color.new(color.green, 80)) : na)
fill(plot1 = mdPlot, plot2 = ngHeight, title = "Negative Wave", color = macd < negativeAverageHeight ? (macd[3] < macd ? color.new(color.red, 80) : color.new(color.red, 60)) : na)
// Alerts
alertcondition(crossunderAboveAvg, title = "Crossunder Above Average", message = "Crossunder")
alertcondition(crossaboveBelowAvg, title = "Crossover Below Average", message = "Crossover")
|
Earnings Yield & Dividend Yield (vs SP500, treasury, IG) | https://www.tradingview.com/script/WADL9jxC/ | NatsukiKano | https://www.tradingview.com/u/NatsukiKano/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ NatsukiKano
//@version=5
// # What's this script?
// Plot the following yields.
// 1. Treasury constant maturity rate. default is 10Y(FRED:DGS10).
// 2. Investment grade corporate bond yields by Moody's.
// Grades from highest to lowest are represented by color bands.
// - Moody's Seasoned Aaa Corporate bond yields.(FRED:AAA)
// - Moody's Seasoned Baa Corporate bond yields.(FRED:DBAA)
// 3. Investment grade bond yields by BofA.
// Grades from highest to lowest are represented by color bands.
// - BofA AAA US Corporate Index Effective Yield.(FRED:BAMLC0A1CAAAEY)
// - BofA BBB US Corporate Index Effective Yield.(FRED:BAMLC0A4CBBBEY)
// 3. Earnings Yield of S&P500.
// Calculated using S&P 500 Earnings by Month provided by Nasdaq date link.
// (https://data.nasdaq.com/data/MULTPL/SP500_EARNINGS_MONTH-sp-500-earnings-by-month)
// 4. Dividend Yield of S&P500.
// Calculated using S&P 500 Dividend by Month provided by Nasdaq date link.
// (https://data.nasdaq.com/data/MULTPL/SP500_DIV_MONTH-sp-500-dividend-by-month)
// 5. Earnings Yield of the displayed symbol.
// 6. Dividend Yield of the displayed symbol.
// 2023/07/10 Changed from getting IG(BofA) data from Nasdaq date link to getting it from FRED ticker.
indicator(title="Earnings Yield & Dividend Yield (vs SP500, treasury, IG)",shorttitle="Yields", precision=3, overlay=false)
// ====================
// PRE
// ====================
/// <import_statements>
// --------------------
SymbolTreasury = input.symbol( "FRED:DGS10" ,"Treasury Constant Maturity Rate")
Group1 ="Line Color"
ColorTreasury = input(color.new(color.gray,10) , "Treasury" , group = Group1)
ColorMoodys = input(color.rgb( 255, 165, 35, 10) , "Investment grade Corporate bond by Moody's" , group = Group1)
ColorBofA = input(color.rgb( 98, 186, 108, 10) , "Investment grade Corporate bond by BofA" , group = Group1)
TransCorpBond = input( 75, "Transparency of color bands for investment grade corporate bond", group = Group1)
ColorSP500EY = input(color.rgb( 254, 82, 92, 10) , "S&P500 Earnings yield" , group = Group1)
ColorSP500DY = input(color.rgb( 172, 77, 187, 10) , "S&P500 Dividends yield" , group = Group1)
ColorSymbolEY = input(color.rgb( 0, 126, 244, 10) , "Symbol Earnings yeild" , group = Group1)
ColorSymbolDY = input(color.rgb( 0, 198, 218, 10) , "Symbol Dividends yeild" , group = Group1)
// <request>
// --------------------
// ##1. Treasury Constant Maturity Rate
Treasury = request.security( SymbolTreasury , timeframe.period, close)
// ##2. Investment Grade Corporate Bond Yield Rates by Moody's
Moodys_Aaa = request.security( "FRED:AAA" , timeframe.period, close)
Moodys_Baa = request.security( "FRED:DBAA" , timeframe.period, close)
// ##3. Investment Grade Corporate Bond Yield Rates by BofA
BofA_AAA = request.security( "FRED:BAMLC0A1CAAAEY" , timeframe.period, close)
BofA_BBB = request.security( "FRED:BAMLC0A4CBBBEY" , timeframe.period, close)
// ##4. S&P 500 Earnings Yield.
SP500 = request.security("SP500", timeframe.period, close)
EPS_SP500 = request.quandl("MULTPL/SP500_EARNINGS_MONTH", barmerge.gaps_off )
EarningsYield_SP500 = EPS_SP500 / SP500 * 100
// ##5. S&P 500 Dividend Yield.
DPS_SP500 = request.quandl("MULTPL/SP500_DIV_MONTH", barmerge.gaps_off )
DividendYield_SP500 = DPS_SP500 / SP500 * 100
// ##6. Symbol Earnings Yield
EPS_TTM = request.financial( syminfo.tickerid , "EARNINGS_PER_SHARE" , "TTM" , barmerge.gaps_off , false , syminfo.currency)
EPS_Y = request.financial( syminfo.tickerid , "EARNINGS_PER_SHARE" , "FY" , barmerge.gaps_off , false , syminfo.currency)
EPS_Symbol = EPS_TTM ? EPS_TTM : EPS_Y //Combine long term financial data and short term financial data
EarningsYield_Symbol = EPS_Symbol/close*100
// ##7. Symbol Dividends Yield
DPS_Symbol = request.financial( syminfo.tickerid , "DPS_COMMON_STOCK_PRIM_ISSUE" , "FY" , barmerge.gaps_off , false , syminfo.currency)
DividendYield_Symbol = DPS_Symbol/close*100
// ====================
// POST
// ====================
lineTreasury = plot( Treasury , "Treasury" , ColorTreasury , linewidth = 2)
lineMoodysAaa = plot( Moodys_Aaa ,"Moodys_Aaa",ColorMoodys, linewidth = 2)
lineMoodysBaa = plot( Moodys_Baa ,"Moodys_Baa",ColorMoodys, linewidth = 1)
lineBofA_AAA = plot( BofA_AAA,"BofA AAA",ColorBofA, linewidth = 2)
lineBofA_BBB = plot( BofA_BBB,"BofA BBB",ColorBofA, linewidth = 1)
fill( lineMoodysAaa , lineMoodysBaa , color.new( ColorMoodys , TransCorpBond ) )
fill( lineBofA_AAA , lineBofA_BBB , color.new( ColorBofA , TransCorpBond ) )
lineEarningsYield_SP500 = plot( EarningsYield_SP500 , "S&P500Earnings" , ColorSP500EY , linewidth = 2)
lineEarningsYield_Symbol = plot( EarningsYield_Symbol , "SymbolEarnings" , ColorSymbolEY , linewidth = 2)
lineDividendsYield_SP500 = plot( DividendYield_SP500 , "S&P500Dividend" , ColorSP500DY , linewidth = 2)
lineDividendsYield_Symbol = plot( DividendYield_Symbol , "SymbolDividend" , ColorSymbolDY , linewidth = 2) |
Zigzag Trend-based Color [SteinG] | https://www.tradingview.com/script/YWH7OAVH-Zigzag-Trend-based-Color-SteinG/ | SteinG | https://www.tradingview.com/u/SteinG/ | 221 | study | 5 | CC-BY-NC-SA-4.0 | // This source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// Note: This indicator is forked from Recursive Zigzag [Trendoscope] https://www.tradingview.com/script/J6mxhxdn-Recursive-Zigzag-Trendoscope/
// ยฉ SteinG
//@version=5
//Zigzag Trend-based Color [SteinG] v5
// # ========================================================================= #
// # | Zigzag Trend-based Color [SteinG] |
// # ========================================================================= #
indicator(
title = "Zigzag Trend-based Color [SteinG]",
shorttitle = "ZG Color",
overlay = true,
max_lines_count = 500,
max_labels_count = 500
)
// # ========================================================================= #
// # | Zigzag Trend-based Color [SteinG] |
// # ========================================================================= #
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import ironpark/TableBuilder/3 as tb
// @function get line style from text input and return as line.style type
// @param lineStyle (string) line style name
// @returns line.style type
getLineStyle(string lineStyle) =>
switch str.lower(lineStyle)
"solid" => line.style_solid
"dashed" => line.style_dashed
"dotted" => line.style_dotted
=> line.style_solid
// @function Convert float to string format by mintick
// @param _self float
// @returns number string
method tostring_mintick(float _self)=>
numberFormat = "0."
zeros = int(math.abs(math.log10(syminfo.mintick)))
if zeros > 0
for i = 0 to zeros-1
numberFormat += "0"
else
numberFormat := "0"
strFormat = '{0,number,'+numberFormat+'}'
strNumber = str.format(strFormat,_self)
//#region ************************ Zigzag Types ************************
type PivotCandle
float _high = high
float _low = low
int length = 5
int pHighBar
int pLowBar
float pHigh
float pLow
int index = bar_index
type Pivot
dr.Point point
int dir
int level = 0
int componentIndex = 0
int subComponents = 0
float ratio
float extendRatio
type ZigzagFlags
bool newPivot = false
bool doublePivot = false
bool updateLastPivot = false
type Zigzag
int length = 5
int numberOfPivots = 20
int offset = 0
int level = 0
array<Pivot> zigzagPivots
ZigzagFlags flags
type ZigzagObject
dr.Line zigzagLine
dr.Label zigzagLabel
type ZigzagProperties
bool useSingleLineColor = false
color lineColor = color.blue
int lineWidth = 1
string lineStyle = line.style_solid
bool showLabel = false
color textColor = color.black
int maxObjects = 300
string xloc = xloc.bar_time
type ZigzagDrawing
Zigzag zigzag
ZigzagProperties properties
array<ZigzagObject> drawings
//#endregion ************************
//#region ************************ Zigzag Methods ************************
//************************* TYPE PivotCandle *********************************************//
//calculate highest and lowest price and bars only.
method init(PivotCandle candle)=>
candle.pHighBar := ta.highestbars(candle._high, candle.length)
candle.pLowBar := ta.lowestbars(candle._low, candle.length)
candle.pHigh := ta.highest(candle._high, candle.length)
candle.pLow := ta.lowest(candle._low, candle.length)
candle
//************************* TYPE Pivot ***********************************************//
method unshift(array<Pivot> arr, Pivot val, int maxItems)=>
arr.unshift(val)
if(arr.size() > maxItems)
arr.pop()
//************************* TYPE Zigzag **********************************************//
//Prepare Pivot Object and ZigzagFlags Ojbect
method init(Zigzag this)=>
if(na(this.zigzagPivots))
this.zigzagPivots := array.new<Pivot>()
this.flags := ZigzagFlags.new()
this
method addnewpivot(Zigzag this, Pivot pivot)=>
dir = math.sign(pivot.dir)
if(this.zigzagPivots.size() >=1)
lastPivot = this.zigzagPivots.get(0)
lastValue = lastPivot.point.price
pivot.subComponents := lastPivot.componentIndex - pivot.componentIndex
if(math.sign(lastPivot.dir) == math.sign(dir))
runtime.error('Direction mismatch')
if(this.zigzagPivots.size() >=2)
llastPivot = this.zigzagPivots.get(1)
value = pivot.point.price
llastValue = llastPivot.point.price
newDir = dir * value >= dir * llastValue ? dir * 2 : dir
pivot.dir := int(newDir)
pivot.ratio := math.round(math.abs(lastValue - value)/math.abs(llastValue - lastValue), 3)
if(this.zigzagPivots.size() >=3)
lllastPivot = this.zigzagPivots.get(2)
lllastValue = lllastPivot.point.price
pivot.extendRatio := math.round(math.abs(lastValue - value)/math.abs(lllastValue - llastValue), 3)
this.zigzagPivots.unshift(pivot, this.numberOfPivots)
this
// @function Calculate zigzag based on input values and indicator values
// @param this Zigzag object
// @param ohlc Array containing OHLC values. Can also have custom values for which zigzag to be calculated
// @returns current Zigzag object
method calculate(Zigzag this, array<float> ohlc) =>
_ohlc = na(ohlc[this.offset])? ohlc : ohlc[this.offset]
this.init()
PivotCandle candle = PivotCandle.new(_ohlc.max(), _ohlc.min(), this.length)
candle.init() //init includes calculate the highest and lowest price and bars in specific length
pDir = 1
Pivot lastPivot = na
this.flags.updateLastPivot := false
this.flags.newPivot := false
this.flags.doublePivot := false
newBar = bar_index-this.offset
newbartime = time[this.offset]
var counter = 0
var lastCounterBar = 0
doublePivot = candle.pHighBar == 0 and candle.pLowBar == 0
if(this.zigzagPivots.size() > 0)
lastPivot := this.zigzagPivots.get(0)
pDir := int(math.sign(lastPivot.dir))
if(this.zigzagPivots.size() > 1)
llastPivot = this.zigzagPivots.get(1)
llastDir = int(math.sign(llastPivot.dir))
//current bar is the highest high in uptrend or lowest low in downtrend and already have Pivots data
//repaint lastest pivot
if ((pDir == 1 and candle.pHighBar == 0) or (pDir == -1 and candle.pLowBar == 0)) and this.zigzagPivots.size()>=1
value = pDir == 1 ? candle.pHigh : candle.pLow
ipivot = pDir == 1? candle.pLow : candle.pHigh
removeOld = value * lastPivot.dir > lastPivot.point.price * lastPivot.dir
if(removeOld and not doublePivot)
this.flags.updateLastPivot := true
this.flags.newPivot := true
this.zigzagPivots.shift() //delete last Pivot
newPivotObject = Pivot.new(dr.Point.new(value, newBar, newbartime), pDir) //create new Pivot as updated Pivot
this.addnewpivot(newPivotObject)
//current bar is the highest high in uptrend or lowest low in downtrend,
//but the price value not greater than the previous pivot in uptrend,
//or not smaller than the previous pivot in downtrend,
//add an inverse pivot from the current highest / lowest bar according to zigzag length
else if(not removeOld and not doublePivot)
ipivotbar = pDir == 1? newBar+candle.pLowBar : newBar+candle.pHighBar
ipivottime = time[newBar-ipivotbar+this.offset]
iCandle = candle[newBar-ipivotbar]
newPivotObject = Pivot.new(dr.Point.new(ipivot, ipivotbar, ipivottime), -pDir)
this.addnewpivot(newPivotObject)
this.flags.newPivot := true
//current bar is both the highest high and lowest low at the same time
else if (doublePivot)
if (pDir == 1 and close > open) or (pDir == -1 and close < open)
newPivotObject = Pivot.new(dr.Point.new(ipivot, newBar, newbartime), -pDir)
this.addnewpivot(newPivotObject)
newPivotObject := Pivot.new(dr.Point.new(value, newBar, newbartime), pDir)
this.addnewpivot(newPivotObject)
this.flags.doublePivot := true
this.flags.newPivot := true
else if (pDir == 1 and close < open) or (pDir == -1 and close > open)
if (removeOld)
this.flags.updateLastPivot := true
this.zigzagPivots.shift() //delete last Pivot
newPivotObject = Pivot.new(dr.Point.new(value, newBar, newbartime), pDir)
this.addnewpivot(newPivotObject)
newPivotObject := Pivot.new(dr.Point.new(ipivot, newBar, newbartime), -pDir)
this.addnewpivot(newPivotObject)
this.flags.doublePivot := true
this.flags.newPivot := true
//current bar is the lowest low in uptrend or highest high in downtrend
//directly add pviot point
//doublePivot excluded
if (not doublePivot) and ((pDir == 1 and candle.pLowBar == 0) or (pDir == -1 and candle.pHighBar == 0)) and (not this.flags.newPivot)
value = pDir == 1 ? candle.pLow : candle.pHigh
newPivotObject = Pivot.new(dr.Point.new(value, newBar, newbartime), -pDir)
this.addnewpivot(newPivotObject)
this.flags.newPivot := true
this
// @function Calculate zigzag based on properties embedded within Zigzag object
// @param this Zigzag object
// @returns current Zigzag object
method calculate(Zigzag this)=>
this.calculate(array.from(high,low))
//************************* TYPE ZigzagObject ****************************************//
method push(array<ZigzagObject> arr, val, maxItems)=>
arr.push(val)
if(arr.size() > maxItems)
ZigzagObject lastObject = arr.shift()
lastObject.zigzagLine.delete()
lastObject.zigzagLabel.delete()
method pop(array<ZigzagObject> arr)=>
ZigzagObject lastObject = arr.pop()
lastObject.zigzagLine.delete()
lastObject.zigzagLabel.delete()
//************************* TYPE ZigzagDrawing ***************************************//
method init(ZigzagDrawing this)=>
if(na(this.drawings))
this.drawings := array.new<ZigzagObject>()
if(na(this.zigzag))
this.zigzag := Zigzag.new()
this.zigzag.init()
if(na(this.properties))
this.properties := ZigzagProperties.new()
this
method clear(ZigzagDrawing this)=>
for zigzagObject in this.drawings
zigzagObject.zigzagLine.delete()
zigzagObject.zigzagLabel.delete()
this.drawings.clear()
// @function Clears zigzag drawings array
// @param this array<ZigzagDrawing>
// @returns void
method clear(array<ZigzagDrawing> this)=>
for drawing in this
drawing.clear()
this.clear()
// @function draws fresh zigzag based on properties embedded in ZigzagDrawing object without trying to calculate
// @param this ZigzagDrawing object
// @returns ZigzagDrawing object
method drawplain(ZigzagDrawing this)=>
this.init()
this.clear()
if(barstate.islast or barstate.islastconfirmedhistory)
for i=0 to this.zigzag.zigzagPivots.size()>1? this.zigzag.zigzagPivots.size()-2 : na
lastPivot = this.zigzag.zigzagPivots.get(i)
llastPivot = this.zigzag.zigzagPivots.get(i+1)
dir = lastPivot.dir
y1 = lastPivot.point.price
y2 = llastPivot.point.price
x1 = this.properties.xloc == xloc.bar_index? lastPivot.point.bar : lastPivot.point.bartime
x2 = this.properties.xloc == xloc.bar_index? llastPivot.point.bar : llastPivot.point.bartime
//Line
//Point Start
startPrice = lastPivot.point.price
startBar = lastPivot.point.bar
startBarTime = lastPivot.point.bartime
dr.Point startPoint = dr.Point.new(startPrice, startBar, startBarTime)
//Point End
endPrice = llastPivot.point.price
endBar = llastPivot.point.bar
endBarTime = llastPivot.point.bartime
dr.Point endPoint = dr.Point.new(endPrice, endBar, endBarTime)
//Line Properties
lineColor = this.properties.lineColor
if not this.properties.useSingleLineColor
lineColor := switch dir
1 => color.orange
2 => color.green
-1 => color.lime
-2 => color.red
=> color.silver
dr.LineProperties lineprops = dr.LineProperties.new(
this.properties.xloc,
extend.none,
lineColor,
this.properties.lineStyle,
this.properties.lineWidth
)
dr.Line zline = startPoint.createLine(endPoint, lineprops)
zline.draw()
level = lastPivot.level
//Label
dr.Label zlabel = dr.Label.new()
if(this.properties.showLabel)
labelText = 'Pivot : ' + lastPivot.point.price.tostring_mintick() + '\nRetraced Ratio : '+str.tostring(lastPivot.ratio) +
'\nExtend Ratio : '+str.tostring(lastPivot.extendRatio)
//Label Properties
labelColor = switch dir
1 => color.orange
2 => color.green
-1 => color.lime
-2 => color.red
=> color.silver
dr.LabelProperties labelprops = dr.LabelProperties.new(
this.properties.xloc,
yloc.price,
labelColor,
dir > 0? label.style_label_down : label.style_label_up,
this.properties.textColor,
size.small
)
zlabel := startPoint.createLabel(labelText, properties=labelprops)
zlabel.draw()
this.drawings.push(ZigzagObject.new(zline, zlabel))
this
//#endregion ************************
//#region ************************ main() ************************
zigzagLength = input.int(8, step=1, minval=2, title='Length', group='Zigzag', tooltip='Zigzag length')
depth = input.int(500, "Depth", step=25, maxval=500, group='Zigzag', tooltip='Zigzag depth refers to max number of pivots to show on chart')
useOCPrices = input.bool(false, 'Use Open Close Prices', group='Zigzag',
tooltip='Use open close prices for calculating pivots instead of high/low.')
lineWidth = input.int(3, "Line Width", group="Line Style", inline="l")
input_lineStyle = input.string("Solid", "Line Style", options=["Solid", "Dashed", "Dotted"], group="Line Style", inline="l")
useSingleLineColor = input.bool(defval = false, title = "Use Single Color", inline = "Color", group = 'Line Style')
lineColor = input.color(defval = color.blue, title='', inline = 'Color', group = 'Line Style', tooltip='Only applicable when "Use Single Color" is set to "true"')
showLabel = input.bool(true, 'Show Label', group='Label')
ZG_showStats = input.bool(true, 'Show Table', group='Info Table', inline='Info')
ZGtblPosition = input.string(position.top_right, '', group='Info Table', options=[position.top_right, position.bottom_right, position.top_center, position.top_left, position.bottom_left], inline='Info')
ZG_infotbl_textSize = input.string(size.small, '', group='Info Table', options=[size.tiny, size.small, size.normal, size.large, size.huge], inline='Info')
lineStyle = getLineStyle(input_lineStyle)
float bodyTop = math.max(open,close)
float bodyBottom = math.min(open,close)
highSource = useOCPrices? bodyTop : high
lowSource = useOCPrices? bodyBottom : low
ohlc = array.from(highSource, lowSource)
var Zigzag zigzag = Zigzag.new(zigzagLength, depth)
zigzag.calculate(ohlc)
var ZigzagProperties props = ZigzagProperties.new(useSingleLineColor, lineColor, lineWidth, lineStyle, showLabel=showLabel, maxObjects = depth)
var ZigzagDrawing drawing = ZigzagDrawing.new(zigzag, props)
if(barstate.islast)
drawing.drawplain()
//Zigzag Info Table
ZG_info_title_color = color.maroon
ZG_info_title_txt_color = color.white
ZG_info_no_color = #8BE8FF
ZG_info_id_color = #12B7E9
ZG_info_cell_txt_color = color.black
if(barstate.islast and ZG_showStats)
var tblstyle = tb.TableStyle.new(bgcolor = color.black,
frame_color = color.black,
frame_width = 1,
border_color = color.black,
border_width = 1
)
var ZG_infoTbl = tb.new(ZGtblPosition, 8, 21, tblstyle)
header = ZG_infoTbl.R(0).TextColor(ZG_info_title_txt_color).TextSize(ZG_infotbl_textSize)
header.Text("No.","BAR ID","DIST","DATETIME","PIVOT VALUE","DIRECTION","RETRACED RATIO","EXTEND RATIO").Bg(ZG_info_title_color)
if array.size(zigzag.zigzagPivots) > 0 and array.size(zigzag.zigzagPivots) <= 20
for i = 0 to array.size(zigzag.zigzagPivots) - 1
_str_no = str.tostring(i+1)
_str_barID = str.tostring(zigzag.zigzagPivots.get(i).point.bar)
_str_dist = str.tostring(bar_index - zigzag.zigzagPivots.get(i).point.bar)
_str_time = str.format_time(zigzag.zigzagPivots.get(i).point.bartime, "Y/M/d HH:mm", syminfo.timezone)
_str_pivot = zigzag.zigzagPivots.get(i).point.price.tostring_mintick()
_str_direction = switch zigzag.zigzagPivots.get(i).dir
1 => "โ (1)"
2 => "โ (2)"
-1 => "โ (-1)"
-2 => "โ (-2)"
=> "โฃ"
_str_ratio = str.format("{0,number,0.000}",zigzag.zigzagPivots.get(i).ratio)
_str_extendRatio = str.format("{0,number,0.000}",zigzag.zigzagPivots.get(i).extendRatio)
ZG_info_cell_color = switch zigzag.zigzagPivots.get(i).dir
1 => color.orange
2 => color.green
-1 => color.lime
-2 => color.red
=> color.silver
ZG_infoTbl.R(i+1).TextColor(ZG_info_cell_txt_color).TextSize(ZG_infotbl_textSize).Text(_str_no, _str_barID,
_str_dist, _str_time, _str_pivot, _str_direction, _str_ratio, _str_extendRatio).Bg(ZG_info_cell_color)
ZG_infoTbl.R(i+1).C(0).Bg(ZG_info_no_color)
ZG_infoTbl.R(i+1).C(1).Bg(ZG_info_id_color)
ZG_infoTbl.R(i+1).C(2).Bg(ZG_info_no_color)
else if array.size(zigzag.zigzagPivots) > 0
for i = 0 to array.size(zigzag.zigzagPivots) - 1
if i >= 20
break
_str_no = str.tostring(i+1)
_str_barID = str.tostring(zigzag.zigzagPivots.get(i).point.bar)
_str_dist = str.tostring(bar_index - zigzag.zigzagPivots.get(i).point.bar)
_str_time = str.format_time(zigzag.zigzagPivots.get(i).point.bartime, "Y/M/d HH:mm", syminfo.timezone)
_str_pivot = zigzag.zigzagPivots.get(i).point.price.tostring_mintick()
_str_direction = switch zigzag.zigzagPivots.get(i).dir
1 => "โ (1)"
2 => "โ (2)"
-1 => "โ (-1)"
-2 => "โ (-2)"
=> "โฃ"
_str_ratio = str.format("{0,number,0.000}",zigzag.zigzagPivots.get(i).ratio)
_str_extendRatio = str.format("{0,number,0.000}",zigzag.zigzagPivots.get(i).extendRatio)
ZG_info_cell_color = switch zigzag.zigzagPivots.get(i).dir
1 => color.orange
2 => color.green
-1 => color.lime
-2 => color.red
=> color.silver
ZG_infoTbl.R(i+1).TextColor(ZG_info_cell_txt_color).TextSize(ZG_infotbl_textSize).Text(_str_no, _str_barID,
_str_dist, _str_time, _str_pivot, _str_direction, _str_ratio, _str_extendRatio).Bg(ZG_info_cell_color)
ZG_infoTbl.R(i+1).C(0).Bg(ZG_info_no_color)
ZG_infoTbl.R(i+1).C(1).Bg(ZG_info_id_color)
ZG_infoTbl.R(i+1).C(2).Bg(ZG_info_no_color)
//#endregion ************************ |
MLExtensions | https://www.tradingview.com/script/ia5ozyMF-MLExtensions/ | jdehorty | https://www.tradingview.com/u/jdehorty/ | 528 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ jdehorty
//@version=5
// @description A set of extension methods for a novel implementation of a Approximate Nearest Neighbors (ANN) algorithm in Lorentzian space.
library("MLExtensions")
// ==========================
// ==== Helper Functions ====
// ==========================
// @function Returns the smoothed hyperbolic tangent of the input series.
// @param src <series float> The input series (i.e., the first-order derivative for price).
// @param quadraticMeanLength <int> The length of the quadratic mean (RMS).
// @returns nDeriv <series float> The normalized derivative of the input series.
export normalizeDeriv(series float src, int quadraticMeanLength) =>
// Calculate the derivative of the input series.
float deriv = src - src[2]
// Calculate the quadratic mean of the derivative.
quadraticMean = math.sqrt(nz(math.sum(math.pow(deriv, 2), quadraticMeanLength) / quadraticMeanLength))
// Return the normalized derivative.
nDeriv = deriv / quadraticMean
nDeriv
// @function Rescales a source value with an unbounded range to a target range.
// @param src <series float> The input series
// @param min <float> The minimum value of the unbounded range
// @param max <float> The maximum value of the unbounded range
// @returns <series float> The normalized series
export normalize(series float src, float min, float max) =>
var _historicMin = 10e10
var _historicMax = -10e10
_historicMin := math.min(nz(src, _historicMin), _historicMin)
_historicMax := math.max(nz(src, _historicMax), _historicMax)
min + (max - min) * (src - _historicMin) / math.max(_historicMax - _historicMin, 10e-10)
// @function Rescales a source value with a bounded range to anther bounded range
// @param src <series float> The input series
// @param oldMin <float> The minimum value of the range to rescale from
// @param oldMax <float> The maximum value of the range to rescale from
// @param newMin <float> The minimum value of the range to rescale to
// @param newMax <float> The maximum value of the range to rescale to
// @returns <series float> The rescaled series
export rescale(series float src, float oldMin, float oldMax, float newMin, float newMax) =>
newMin + (newMax - newMin) * (src - oldMin) / math.max(oldMax - oldMin, 10e-10)
// ================
// ==== Colors ====
// ================
// @function Creates an array of colors with varying shades of the input color
// @param color <color> The color to create shades of
// @returns <array color> An array of colors with varying shades of the input color
export getColorShades(color color) =>
float r = color.r(color)
float g = color.g(color)
float b = color.b(color)
int[] intensity = array.new_int(0)
array.push(intensity, 25)
array.push(intensity, 50)
array.push(intensity, 75)
array.push(intensity, 100)
color[] shades = array.new_color(0)
for i = 0 to array.size(intensity) - 1
float shadeR = r * array.get(intensity, i) / 100
float shadeG = g * array.get(intensity, i) / 100
float shadeB = b * array.get(intensity, i) / 100
color shadeColor = color.rgb(shadeR, shadeG, shadeB)
array.push(shades, shadeColor)
shades
// @function Determines the color shade based on prediction percentile
// @param prediction <float> Value of the prediction
// @param neighborsCount <int> The number of neighbors used in a nearest neighbors classification
// @param shadesArr <array color> An array of colors with varying shades of the input color
// @returns shade <color> Color shade based on prediction percentile
export getPredictionColor(float prediction, int neighborsCount, array<color> shadesArr) =>
float percentile = prediction / neighborsCount * 100
color shade = na
switch
percentile >= 75 => shade := array.get(shadesArr, 3) // most intense shade
percentile >= 50 => shade := array.get(shadesArr, 2)
percentile >= 25 => shade := array.get(shadesArr, 1)
percentile >= 0 => shade := array.get(shadesArr, 0) // least intense shade
shade
// @function Assigns varying shades of the color green based on the KNN classification
// @param prediction Value (int|float) of the prediction
// @returns color <color>
export color_green(float prediction) =>
switch
prediction >= 9 => #15FF00
prediction >= 8 => #15FF00E5
prediction >= 7 => #09FF00CC
prediction >= 6 => #09FF00B2
prediction >= 5 => #09FF0099
prediction >= 4 => #15FF007F
prediction >= 3 => #00FF0066
prediction >= 2 => #09FF004C
prediction >= 1 => #09FF0033
=> #15FF0019
// @function Assigns varying shades of the color red based on the KNN classification
// @param prediction Value of the prediction
// @returns color
export color_red(float prediction) =>
switch
prediction >= 9 => #CC3311
prediction >= 8 => #CC3311E5
prediction >= 7 => #B23111CC
prediction >= 6 => #B23111B2
prediction >= 5 => #B2311199
prediction >= 4 => #CC33117F
prediction >= 3 => #CC331166
prediction >= 2 => #CC33114C
prediction >= 1 => #CC331133
=> #CC331119
// @function Returns the the hyperbolic tangent of the input series. The sigmoid-like hyperbolic tangent function is used to compress the input to a value between -1 and 1.
// @param src <series float> The input series (i.e., the normalized derivative).
// @returns tanh <series float> The hyperbolic tangent of the input series.
export tanh(series float src) =>
tanh = -1 + 2/(1 + math.exp(-2*src))
tanh
// @function Returns the smoothed hyperbolic tangent of the input series.
//@param src <series float> The input series (i.e., the hyperbolic tangent).
//@param lookback <int> The lookback window for the smoothing.
//@returns filter <series float> The smoothed hyperbolic tangent of the input series.
export dualPoleFilter(series float src, int lookback) =>
float omega = -99 * math.pi / (70 * lookback)
float alpha = math.exp(omega)
float beta = -math.pow(alpha, 2)
float gamma = math.cos(omega) * 2 * alpha
float delta = 1 - gamma - beta
float slidingAvg = 0.5 * (src + nz(src[1], src))
float filter = na
filter := (delta*slidingAvg) + gamma*nz(filter[1]) + beta*nz(filter[2])
filter
// @function Returns the tanh transform of the input series.
// @param src <series float> The input series (i.e., the result of the tanh calculation).
// @param lookback <int> The lookback window for the smoothing.
// @returns signal <series float> The smoothed hyperbolic tangent transform of the input series.
export tanhTransform(series float src, int smoothingFrequency, int quadraticMeanLength) =>
signal = dualPoleFilter(tanh(normalizeDeriv(src, quadraticMeanLength)), smoothingFrequency)
signal
// @function Returns the normalized RSI ideal for use in ML algorithms.
// @param src <series float> The input series (i.e., the result of the RSI calculation).
// @param n1 <int> The length of the RSI.
// @param n2 <int> The smoothing length of the RSI.
// @returns signal <series float> The normalized RSI.
export n_rsi(series float src, simple int n1, simple int n2) =>
rescale(ta.ema(ta.rsi(src, n1), n2), 0, 100, 0, 1)
// @function Returns the normalized CCI ideal for use in ML algorithms.
// @param src <series float> The input series (i.e., the result of the CCI calculation).
// @param n1 <int> The length of the CCI.
// @param n2 <int> The smoothing length of the CCI.
// @returns signal <series float> The normalized CCI.
export n_cci(series float src, simple int n1, simple int n2) =>
normalize(ta.ema(ta.cci(src, n1), n2), 0, 1)
// @function Returns the normalized WaveTrend Classic series ideal for use in ML algorithms.
// @param src <series float> The input series (i.e., the result of the WaveTrend Classic calculation).
// @param paramA <int> The first smoothing length for WaveTrend Classic.
// @param paramB <int> The second smoothing length for the WaveTrend Classic.
// @param transformLength <int> The length of the transform.
// @returns signal <series float> The normalized WaveTrend Classic series.
export n_wt(series float src, simple int n1=10, simple int n2=11) =>
ema1 = ta.ema(src, n1)
ema2 = ta.ema(math.abs(src - ema1), n1)
ci = (src - ema1) / (0.015 * ema2)
wt1 = ta.ema(ci, n2) // tci
wt2 = ta.sma(wt1, 4)
normalize(wt1 - wt2, 0, 1)
// @function Returns the normalized ADX ideal for use in ML algorithms.
// @param highSrc <series float> The input series for the high price.
// @param lowSrc <series float> The input series for the low price.
// @param closeSrc <series float> The input series for the close price.
// @param n1 <int> The length of the ADX.
export n_adx(series float highSrc, series float lowSrc, series float closeSrc, simple int n1) =>
length = n1
th = 20
tr = math.max(math.max(highSrc - lowSrc, math.abs(highSrc - nz(closeSrc[1]))), math.abs(lowSrc - nz(closeSrc[1])))
directionalMovementPlus = highSrc - nz(highSrc[1]) > nz(lowSrc[1]) - lowSrc ? math.max(highSrc - nz(highSrc[1]), 0) : 0
negMovement = nz(lowSrc[1]) - lowSrc > highSrc - nz(highSrc[1]) ? math.max(nz(lowSrc[1]) - lowSrc, 0) : 0
trSmooth = 0.0
trSmooth := nz(trSmooth[1]) - nz(trSmooth[1]) / length + tr
smoothDirectionalMovementPlus = 0.0
smoothDirectionalMovementPlus := nz(smoothDirectionalMovementPlus[1]) - nz(smoothDirectionalMovementPlus[1]) / length + directionalMovementPlus
smoothnegMovement = 0.0
smoothnegMovement := nz(smoothnegMovement[1]) - nz(smoothnegMovement[1]) / length + negMovement
diPositive = smoothDirectionalMovementPlus / trSmooth * 100
diNegative = smoothnegMovement / trSmooth * 100
dx = math.abs(diPositive - diNegative) / (diPositive + diNegative) * 100
adx = ta.rma(dx, length)
rescale(adx, 0, 100, 0, 1)
// =================
// ==== Filters ====
// =================
// # @regime_filter
// # @param src <series float> The source series.
// # @param threshold <float> The threshold.
// # @param useRegimeFilter <bool> Whether to use the regime filter.
// # @returns <bool> Boolean indicating whether or not to let the signal pass through the filter.
export regime_filter(series float src=ohlc4, float threshold, bool useRegimeFilter) =>
// Calculate the slope of the curve.
value1 = 0.0
value2 = 0.0
klmf = 0.0
value1 := 0.2 * (src - src[1]) + 0.8 * nz(value1[1])
value2 := 0.1 * (high - low) + 0.8 * nz(value2[1])
omega = math.abs(value1 / value2)
alpha = (-math.pow(omega,2) + math.sqrt(math.pow(omega, 4) + 16 * math.pow(omega,2))) / 8
klmf := alpha * src + (1 - alpha) * nz(klmf[1])
absCurveSlope = math.abs(klmf - klmf[1])
exponentialAverageAbsCurveSlope = 1.0 * ta.ema(absCurveSlope, 200)
normalized_slope_decline = (absCurveSlope - exponentialAverageAbsCurveSlope) / exponentialAverageAbsCurveSlope
// Calculate the slope of the curve.
useRegimeFilter ? normalized_slope_decline >= threshold : true
// @function filter_adx
// @param src <series float> The source series.
// @param length <int> The length of the ADX.
// @param adxThreshold <int> The ADX threshold.
// @param useAdxFilter <bool> Whether to use the ADX filter.
// @returns <series float> The ADX.
export filter_adx(series float src=close, simple int length=14, int adxThreshold, bool useAdxFilter) =>
tr = math.max(math.max(high - low, math.abs(high - nz(src[1]))), math.abs(low - nz(src[1])))
directionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
negMovement = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
trSmooth = 0.0
trSmooth := nz(trSmooth[1]) - nz(trSmooth[1]) / length + tr
smoothDirectionalMovementPlus = 0.0
smoothDirectionalMovementPlus := nz(smoothDirectionalMovementPlus[1]) - nz(smoothDirectionalMovementPlus[1]) / length + directionalMovementPlus
smoothnegMovement = 0.0
smoothnegMovement := nz(smoothnegMovement[1]) - nz(smoothnegMovement[1]) / length + negMovement
diPositive = smoothDirectionalMovementPlus / trSmooth * 100
diNegative = smoothnegMovement / trSmooth * 100
dx = math.abs(diPositive - diNegative) / (diPositive + diNegative) * 100
adx = ta.rma(dx, length)
useAdxFilter ? adx > adxThreshold : true
// @function filter_volatility
// @param minLength <int> The minimum length of the ATR.
// @param maxLength <int> The maximum length of the ATR.
// @param useVolatilityFilter <bool> Whether to use the volatility filter.
// @returns <bool> Boolean indicating whether or not to let the signal pass through the filter.
export filter_volatility(simple int minLength=1, simple int maxLength=10, bool useVolatilityFilter) =>
recentAtr = ta.atr(minLength)
historicalAtr = ta.atr(maxLength)
useVolatilityFilter ? recentAtr > historicalAtr : true
// =====================
// ==== Backtesting ====
// =====================
// @function Performs a basic backtest using the specified parameters and conditions.
// @param high <series float> The input series for the high price.
// @param low <series float> The input series for the low price.
// @param open <series float> The input series for the open price.
// @param startLongTrade <series bool> The series of conditions that indicate the start of a long trade.
// @param endLongTrade <series bool> The series of conditions that indicate the end of a long trade.
// @param startShortTrade <series bool> The series of conditions that indicate the start of a short trade.
// @param endShortTrade <series bool> The series of conditions that indicate the end of a short trade.
// @param isEarlySignalFlip <bool> Whether or not the signal flip is early.
// @param maxBarsBackIndex <int> The maximum number of bars to go back in the backtest.
// @param thisBarIndex <int> The current bar index.
// @param src <series float> The source series.
// @param useWorstCase <bool> Whether to use the worst case scenario for the backtest.
// @returns <tuple strings> A tuple containing backtest values
export backtest(series float high, series float low, series float open, series bool startLongTrade, series bool endLongTrade, series bool startShortTrade, series bool endShortTrade, series bool isEarlySignalFlip, int maxBarsBackIndex, int thisBarIndex, series float src, bool useWorstCase) =>
marketPrice = useWorstCase ? src : (high + low + open + open)/4
var float start_long_trade = marketPrice
var float start_short_trade = marketPrice
var float total_short_profit = 0.
var float total_long_profit = 0.
var int wins = 0
var int losses = 0
var int trade_count = 0
var int early_signal_flip_count = 0
var bool tookProfit = false
lot_size = 1
if thisBarIndex > maxBarsBackIndex
trade_count := 0
wins := 0
losses := 0
early_signal_flip_count := 0
if startLongTrade
start_short_trade := 0.
early_signal_flip_count := isEarlySignalFlip ? 1 : 0
start_long_trade := marketPrice
trade_count := 1
if endLongTrade
delta = marketPrice - start_long_trade
wins := delta > 0 ? 1 : 0
losses := delta < 0 ? 1 : 0
total_long_profit := delta * lot_size
if startShortTrade
start_long_trade := 0.
start_short_trade := marketPrice
trade_count := 1
if endShortTrade
early_signal_flip_count := isEarlySignalFlip ? 1 : 0
delta = start_short_trade - marketPrice
wins := delta > 0 ? 1 : 0
losses := delta < 0 ? 1 : 0
total_short_profit := delta * lot_size
tradeStatsHeader = '๐ Trade Stats'
longProfit = ta.cum(total_long_profit)
shortProfit = ta.cum(total_short_profit)
longShortProfit = longProfit + shortProfit
totalEarlySignalFlips = ta.cum(early_signal_flip_count)
totalWins = ta.cum(wins)
totalLosses = ta.cum(losses)
totalTrades = ta.cum(wins+losses)
winLossRatio = totalWins / totalTrades
winRate = totalWins / (totalWins + totalLosses)
[totalWins, totalLosses, totalEarlySignalFlips, totalTrades, tradeStatsHeader, winLossRatio, winRate]
// @function init_table()
// @returns tbl <series table> The backtest results.
export init_table() =>
c_transparent = color.new(color.black, 100)
table.new(position.top_right, columns=2, rows=7, frame_color=c_transparent, frame_width=1, border_width=1, border_color=c_transparent)
// @function update_table(tbl, tradeStats)
// @param tbl <series table> The backtest results table.
// @param tradeStatsHeader <string> The trade stats header.
// @param totalTrades <float> The total number of trades.
// @param totalWins <float> The total number of wins.
// @param totalLosses <float> The total number of losses.
// @param winLossRatio <float> The win loss ratio.
// @param winrate <float> The winrate.
// @param earlySignalFlips <float> The total number of early signal flips.
// @returns <void> Updated backtest results table.
export update_table(series table tbl, string tradeStatsHeader, float totalTrades, float totalWins, float totalLosses, float winLossRatio, float winrate, float earlySignalFlips) =>
c_transparent = color.new(color.black, 100)
table.cell(tbl, 0, 0, tradeStatsHeader, text_halign=text.align_center, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 1, 'Winrate', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 1, str.tostring(winrate, '#.#') + '%', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 2, 'Trades', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 2, str.tostring(totalTrades, '#') + ' (' + str.tostring(totalWins, '#') + '|' + str.tostring(totalLosses, '#') + ')', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 5, 'WL Ratio', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 5, str.tostring(winLossRatio, '#.#'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 0, 6, 'Early Signal Flip Count', text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal)
table.cell(tbl, 1, 6, str.tostring(earlySignalFlips, '#'), text_halign=text.align_center, bgcolor=c_transparent, text_color=color.gray, text_size=size.normal) |
Wick-to-Body Ratio Trend Forecast | Flux Charts | https://www.tradingview.com/script/FGmvwby5-Wick-to-Body-Ratio-Trend-Forecast-Flux-Charts/ | fluxchart | https://www.tradingview.com/u/fluxchart/ | 253 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ fluxchart
//
//@version=5
indicator("Wick to Body Ratio Trend Forecast | Flux Charts", "WBR Forecast | Flux Charts", overlay = true, max_bars_back = 1000, max_lines_count = 500)
max_bars_back(time, 1000)
// inputs
int loopback = input.int(400, "Loop Back Period", 35, 700, 10 ,"Number of candles to look back at." , group = "Algorithm Settings")
int forecast = input.int(10, "Forcast Line Length" , 5, 32, 1, "Bar length of forcasted lines", group = "Algorithm Settings")
string ratio_type = input.string("General Ratio", "Ratio Type", [ "General Ratio", "Top Wick", "Bottom Wick","Body Ratio"], "The Type of ratio used to calculate the forcast", group = "Algorithm Settings")
bool direction_bias = input.bool(true, "Directional candles", "The algorithim will only use ratios of candles that have the same direction. ex: If the candle is bullish it will only find bullish candles with the same ratio.", group = "Algorithm Settings")
string default_acceptable_range = input.string("Medium", "Default Accuracy", [ "High", "Medium", "Low"], "Effects maximum inaccuracy that the script will allow for a ratio to be considered matched.", group = "Algorithm Settings")
// Forcast Lines
color line_color = input(color.white, "Line Color", "The color of the forcasted line.", group = "Forcast Lines")
bool pattern_lines = input.bool(false, "Previous trends", "Display the idividual trend lines", "lines" , "Forcast Lines")
bool regressed_pattern_lines = input.bool(false, "Best Fit Previous trends", "Display the idividual regressed trend lines", "lines" , "Forcast Lines")
// Past Trend
bool trend_square = input.bool(true, "Square Trends", "Display a square around the candles following the candle with a similar ratio.", group="Past Trends")
bool trend_square_labels = input.bool(true, "Label Ratios", "Display the candles ratios that are being used.", group="Past Trends")
color deviation_high = input(color.red, "High | Confidence Color", "The color of the forcasted line." , "The color to use when the indicator is high confidence.")
color deviation_low = input(color.blue, "Low | Confidence Color", "The color of the forcasted line." , "The color to use when the indicator is high confidence.")
// Other
bool display_logs = input.bool(true, "Display Warning Messages", "Display warning messages", group = "Other")
//Declarations
varip float accuracy = .02
varip bool ratio_not_findable = false
var log_table = table.new(position.top_right, 5, 2, color.green)
candle_forcast_matrix = matrix.new<float>()
length = 14
var square_labels = array.new<label>()
var trend_boxes = array.new<box>()
label ratio_label = na
int last_bar = 0
//clean up
//wick ratios
general_ratio() => ((math.abs(low - high) - math.abs(close - open)) / math.abs(close - open)) * ((close - open)/ math.abs(close - open))
top_wick() => ((math.max(close, open) - high) / math.abs(close - open)) * ((close - open)/ math.abs(close - open))
bottom_wick() => ((math.min(close, open) - low) / math.abs(close - open)) * ((close - open)/ math.abs(close - open))
body_ratio() => (math.abs(close - open) / math.abs(high - low)) * ((close - open)/ math.abs(close - open))
float ratio = ratio_type == "General Ratio" ? general_ratio() : ratio_type == "Top Wick" ? top_wick() : ratio_type == "Bottom Wick" ? bottom_wick() : body_ratio()
//regressions
linear_regression(y, price) =>
xy = 0.0
x_summation = 0.0
x_squared_summation = 0.0
array_close = array.new_float(forecast)
for i = 1 to array.size(y)
array.set(array_close, i-1, array.get(y, i-1) + price)
xy += (i * array.get(array_close, i-1))
x_summation += i
x_squared_summation += math.pow(i, 2)
x_squared_sum_mean = x_squared_summation/ array.size(y)
_x = x_summation/array.size(y)
_y = array.avg(array_close)
_xy = xy/array.size(y)
x_squared_mean = x_squared_summation/array.size(y)
m = ((_x*_y) - _xy)/(math.pow(_x,2) - x_squared_sum_mean)
b = _y - (m *_x)
[m, b]
// logic
if barstate.islast
if trend_square_labels
ratio_label := label.new(bar_index[1], na, text = "Ratio: " + str.tostring(math.round_to_mintick(ratio[1])) + "x", yloc = yloc.abovebar, color=color.blue, textcolor = color.white)
while(true)
for i = forecast + last_bar to (loopback + forecast)
float bars_difference = (math.abs(math.abs(ratio[i]) - math.abs(ratio[1])))
bool ratio_direction_match = (ratio[i] / math.abs(ratio[i])) == (ratio[1] / math.abs(ratio[1]))
if i < (forecast+last_bar)
na
else if (bars_difference <= accuracy and ratio_direction_match) or (bars_difference <= accuracy and not direction_bias)
candles = array.new_float(forecast)
highs = array.new_float(forecast)
lows = array.new_float(forecast)
for y = 0 to forecast - 1
array.set(candles,y, close[i - y - 1] - close[i])
array.set(highs, y, high[i - y])
array.set(lows, y, low[i - y])
matrix.add_row(candle_forcast_matrix, matrix.rows(candle_forcast_matrix), candles)
top = highs.max()
bottom = lows.min()
trend_color = ratio
if(trend_square_labels)
color direction_color = ratio[i] > 0 ? color.green : color.red
//square_labels.push(label.new(bar_index[i], na, text = "Match: " + str.tostring(math.round_to_mintick(ratio[i])) + "x" , yloc = yloc.abovebar, color=direction_color, textcolor=color.white))
square_label = label.new(bar_index[i], na, text = "Match: " + str.tostring(math.round_to_mintick(ratio[i])) + "x" , yloc = yloc.abovebar, color=direction_color, textcolor=color.white)
array.push(square_labels, square_label)
if(trend_square)
trend_box = box.new(bar_index[i], top, bar_index[i - forecast], bottom, border_color = color.gray, bgcolor = color.new(color.silver, 60))
array.push(trend_boxes, trend_box)
// box.delete(trend_box[1])
last_bar := i
int matrix_rows = matrix.rows(candle_forcast_matrix)
if accuracy > .05 and matrix_rows == 0
if display_logs
table.cell(log_table, 0, 0, "Warning")
table.cell(log_table, 0, 1, "No bars with acceptable range raise loopback")
ratio_not_findable := true
break
else if accuracy > .05 and matrix_rows < 5
if display_logs
table.cell(log_table, 0, 0, "Warning")
table.cell(log_table, 0, 1, "Too Few refrences raise loopback")
break
else if accuracy <= 0 and matrix_rows > 15
if display_logs
table.cell(log_table, 0, 0, "Warning")
table.cell(log_table, 0, 1, "Too much data lower loopback")
ratio_not_findable := true
break
else if matrix_rows < 5
accuracy := accuracy + .01
else if matrix_rows > 15
accuracy := accuracy - .005
else
ratio_not_findable := false
break
if ratio_not_findable == false
if regressed_pattern_lines or pattern_lines
for i = 0 to (matrix.rows(candle_forcast_matrix) -1)
[m, b] = linear_regression(matrix.row(candle_forcast_matrix, i), close[1])
if regressed_pattern_lines
line.new(bar_index, b, bar_index + forecast, close + (m * (forecast)))
if pattern_lines
for y = 0 to (matrix.columns(candle_forcast_matrix) - 2)
line.new(bar_index + y , close + matrix.get(candle_forcast_matrix, i, y), bar_index + y + 1 , close + matrix.get(candle_forcast_matrix, i, y +1), color=line_color)
for i = 0 to (matrix.columns(candle_forcast_matrix) -2)
matrix.col(candle_forcast_matrix, i)
deviation = (matrix.max(candle_forcast_matrix) - matrix.min(candle_forcast_matrix))/2
color avg_line_color = color.from_gradient(array.stdev(matrix.col(candle_forcast_matrix, i)), 0, deviation, deviation_high, deviation_low)
line.new(bar_index + i + 1, close + array.avg(matrix.col(candle_forcast_matrix, i)), bar_index + i + 2, close + array.avg(matrix.col(candle_forcast_matrix, i + 1)), color = avg_line_color, style = line.style_arrow_right, width = 2)
int array_size = array.size(square_labels)
if array_size[1] > 0
//label.new(bar_index, na, str.tostring(array_size[1]), yloc = yloc.belowbar)
for i = 0 to array_size[1] - 1
label.delete(array.get(square_labels, i))
box.delete(array.get(trend_boxes, i))
label.delete(ratio_label[1])
|
DrNon_NASDAQ10 | https://www.tradingview.com/script/Gmu0jss6-DrNon-NASDAQ10/ | DrNon | https://www.tradingview.com/u/DrNon/ | 4 | study | 4 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ DrNon
//@version=4
study("DrNon_NASDAQ10", shorttitle="NASDAQ10", overlay=false)
// Define the individual securities in the index
security1 = security("NASDAQ:AAPL", timeframe.period, close)
security2 = security("NASDAQ:MSFT", timeframe.period, close)
security3 = security("NASDAQ:GOOG", timeframe.period, close)
security4 = security("NASDAQ:AMZN", timeframe.period, close)
security5 = security("NASDAQ:NVDA", timeframe.period, close)
security6 = security("NASDAQ:TSLA", timeframe.period, close)
security7 = security("NASDAQ:META", timeframe.period, close)
security8 = security("NASDAQ:AVGO", timeframe.period, close)
security9 = security("NASDAQ:PEP", timeframe.period, close)
security10 = security("NASDAQ:COST", timeframe.period, close)
// Calculate the index value
indexValue = security1 + security2 + security3 + security4 + security5 + security6 + security7 + security8 + security9 + security10
// Plotting the index value
plot(indexValue, title="Custom Index", color=color.blue, linewidth=2)
|
Candle Range Widget | https://www.tradingview.com/script/e6w9muJl-Candle-Range-Widget/ | caasimdas | https://www.tradingview.com/u/caasimdas/ | 3 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ caasimdas
//@version=5
indicator("Candle Range Widget", overlay=true)
prevdiff = high[1]- low[1]
diff = high-low
var srtable = table.new(position = position.top_right, columns = 2, rows= 3, frame_width = 1, frame_color = color.gray, border_width = 1, border_color = color.gray)
table.cell(srtable, column = 0, row =0, text ="High Low Difference", text_color = color.rgb(0, 0, 0), bgcolor = color.yellow)
table.merge_cells(srtable, 0, 0,1,0)
table.cell(srtable, column = 0, row =1, text = "Last Candle" , text_color = color.rgb(0, 0, 0), bgcolor = color.rgb(248, 248, 245))
table.cell(srtable, column = 0, row =2, text = "Previous Candle" , text_color = color.rgb(0, 0, 0), bgcolor = color.rgb(248, 248, 245))
table.cell(srtable, column = 1, row =1, text = str.tostring(diff) , text_color = color.rgb(0, 0, 0), bgcolor = color.rgb(248, 248, 245))
table.cell(srtable, column = 1, row =2, text = str.tostring(prevdiff) , text_color = color.rgb(0, 0, 0), bgcolor = color.rgb(248, 248, 245))
|
Market Smith Indicators | https://www.tradingview.com/script/em5aMqKQ-Market-Smith-Indicators/ | adaml735 | https://www.tradingview.com/u/adaml735/ | 320 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ adaml735
//@version=5
// This script's goal is to closely replicate the tools utilized in market smith
// Included in this script is:
// 21, 50, 200 day moving averages
// RS line and indicator
// High and Low pivot indicators
// An inportant note is that the moving averages and RS Line will only be visible in the day view
// Huge thank you to the following coders who I took inspiration from their open source code
// Fred6724, RaviYendru
// -----------------------------------------------------------------------------------------------------
// Global variables and indicators
indicator("Market Smith Indicators", overlay=true, max_labels_count=500, max_bars_back = 253)
isDaily = timeframe.isdaily
// -----------------------------------------------------------------------------------------------------
// High and low pivot point indicators
lengthGroupTitle = "LENGTH LEFT / RIGHT"
colorGroupTitle = "Text Color / Label Color"
leftLenH = 10
rightLenH = 10
textColorH = color.rgb(103, 255, 154)
leftLenL = 10
rightLenL = 10
textColorL = color.rgb(255, 153, 153)
ph = ta.pivothigh(leftLenH, rightLenH)
pl = ta.pivotlow(leftLenL, rightLenL)
drawLabel(_offset, _pivot, _style, _color, _textColor) =>
if not na(_pivot)
label.new(bar_index[_offset], _pivot, str.tostring(_pivot, format.mintick), style=_style, color=_color, textcolor=_textColor)
drawLabel(rightLenH, ph, label.style_label_down, color.rgb(0,0,0,100), textColorH)
drawLabel(rightLenL, pl, label.style_label_up, color.rgb(0,0,0,100), textColorL)
// -----------------------------------------------------------------------------------------------------
// 21, 50, 200 moving day averages
// Define variables
ma1 = ta.sma(close, 21)
ma2 = ta.sma(close, 50)
ma3 = ta.sma(close, 200)
sym1 = "21 Day MA"
sym2 = "50 Day MA"
sym3 = "200 Day MA"
color1 = color.new(color.fuchsia, 0)
color2 = color.new(color.orange, 0)
color3 = color.new(color.green, 0)
// Plot moving averages
maPlot1 = plot(ma1, color=color1, title=sym1)
maPlot2 = plot(ma2, color=color2, title=sym2)
maPlot3 = plot(ma3, color=color3, title=sym3)
// Plot labels to the right of the moving averages
var l1 = isDaily ? label.new(bar_index, ma1, sym1, color = color.rgb(0,0,0,100), size=size.normal, textcolor=color1, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
var l2 = isDaily ? label.new(bar_index, ma2, sym2, color = color.rgb(0,0,0,100), size=size.normal, textcolor=color2, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
var l3 = isDaily ? label.new(bar_index, ma3, sym3, color = color.rgb(0,0,0,100), size=size.normal, textcolor=color3, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
// set up new xy params to labels on new bar
label.set_xy(l1, bar_index, ma1)
label.set_xy(l2, bar_index, ma2)
label.set_xy(l3, bar_index, ma3)
// -----------------------------------------------------------------------------------------------------
// Simplified RS Line and RS Rating
// Thank you to ยฉFred6724
// Inputs
hideRSRat = false
// seedetail = input(false, title="Display the 3 results", group = "Parameters", inline="0")
src = close
comparativeTickerId = "SP:SPX"
SpxValue = 3900//input(4140, title="Value of Comparative Symbol", group = "RS Line", tooltip = "Used to display the RS Line under the price. If you modify the ticker, please report its value in this box.")
colorRS = color.rgb(120, 150, 255,0)
offset = 80
plotNewHigh = false
rsNewHigh = "RS New Highs"
blueDotCol = color.rgb(38, 198, 218,60)
lookback = 40
plotNewLow = false
rsNewLow = "RS New Lows"
redDotCol = color.rgb(255, 82, 82, 60)
lookback2 = 40
// Constants for calculation of RS Rating
// SMA method
W1Ma = 40
W2Ma = 20
W3Ma = 20
W4Ma = 20
//Classic perf method
W1P = 40
W2P = 20
W3P = 20
W4P = 20
//Spx
spxW1Ma = 40
spxW2Ma = 20
spxW3Ma = 20
spxW4Ma = 20
// Final
w1 = 2
w2 = 1
w3 = 1
// Using bar index in case of IPO for avoiding NaN results
// Added max_bars_max = 253 to improve display speed
n63 = bar_index < 63 ? bar_index:63
n126 = bar_index < 126 ? bar_index:126
n189 = bar_index < 189 ? bar_index:189
n252 = bar_index < 252 ? bar_index:252
// Comparative Ticker for RS Line
comparativeSymbol = request.security(comparativeTickerId, timeframe.period, close)
// RS Line but multiplied by a little bit less than the constant value of the comparative ticker for correct display
rsCurve = (src/comparativeSymbol)
rsRatio = timeframe.isweekly ? SpxValue*(offset-10)/100:SpxValue*offset/100 // 70 We - 80 Da
rs = rsCurve*rsRatio
prevlookback = lookback
prevlookback2 = lookback2 // for new low
lookback := math.min(lookback - 1, bar_index)
rsPlot = plot(rs, title="RS Line", style=plot.style_line, linewidth=1, color=colorRS)
// Historical New Highs & New Highs Before Price
histNH = ta.highest(rs , prevlookback)
histCl = ta.highest(high, prevlookback)
// Historical RS New High
if(rsNewHigh == "Historical RS New Highs" and plotNewHigh and rs == histNH)
label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = size.tiny)
// Historical RS New High Before Price
if(rsNewHigh == "Historical RS New Highs Before Price" and plotNewHigh and rs == histNH and high < histCl)
label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = size.tiny)
// RS New High
if(barstate.islast and rsNewHigh == "RS New Highs" and plotNewHigh and rs == histNH)
label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = size.tiny)
// RS New High Before Price
if(barstate.islast and rsNewHigh == "RS New Highs Before Price" and plotNewHigh and rs == histNH and high < histCl)
label.new(x = bar_index, y = rs, color = blueDotCol, style = label.style_circle, size = size.tiny)
// Historical New Lows & New Lows Before Price
histNL = ta.lowest(rs , prevlookback2)
histClL = ta.lowest(low, prevlookback2)
// Historical RS New Low
if(rsNewLow == "Historical RS New Lows" and plotNewLow and rs == histNL)
label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = size.tiny)
// Historical RS New Low Before Price
if(rsNewLow == "Historical RS New Lows Before Price" and plotNewLow and rs == histNL and low > histClL)
label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = size.tiny)
// RS New Low
if(barstate.islast and rsNewLow == "RS New Lows" and plotNewLow and rs == histNL)
labelNL = label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = size.tiny)
// RS New Low Before Price
if(barstate.islast and rsNewLow == "RS New Lows Before Price" and plotNewLow and rs == histNL and low > histClL)
labelNLBP = label.new(x = bar_index, y = rs, color = redDotCol, style = label.style_circle, size = size.tiny)
// 1ST METHOD
// Tickers I will use
// MMTH - %Stock > 200 Da SMA
// MMOF - %Stock > 150 Da SMA
// MMOH - %Stock > 100 Da SMA
// MMFI - %Stock > 50 Da SMA
// MMTW - %Stock > 20 Da SMA
// MMFD - %Stock > 5 Da SMA (more or less only noise, I won't use the 5 Daily SMA)
// |Formula | Here I use this code to limite 75% up and 25% down regarding number of stock above SMA X
limitDown = 25 // | This limitation will allow me to calculate a theorical max & min to limit the result to 99 & 1
limitUp = 75
perStockAbove200 = request.security("MMTH", 'D', close) > limitUp ? limitUp:request.security("MMTH", 'D', close) < limitDown ? limitDown:request.security("MMTH", 'D', close)
perStockAbove150 = request.security("MMOF", 'D', close) > limitUp ? limitUp:request.security("MMOF", 'D', close) < limitDown ? limitDown:request.security("MMOF", 'D', close)
perStockAbove100 = request.security("MMOH", 'D', close) > limitUp ? limitUp:request.security("MMOH", 'D', close) < limitDown ? limitDown:request.security("MMOH", 'D', close)
perStockAbove50 = request.security("MMFI", 'D', close) > limitUp ? limitUp:request.security("MMFI", 'D', close) < limitDown ? limitDown:request.security("MMFI", 'D', close)
perStockAbove20 = request.security("MMTW", 'D', close) > limitUp ? limitUp:request.security("MMTW", 'D', close) < limitDown ? limitDown:request.security("MMTW", 'D', close)
// The goal is to gather as much data as possible as we can't compare the score relatively to every other ticker. We do an approximation based on SMA and % of stock above them at X moment.
closeDa = request.security(syminfo.tickerid, 'D', close)
// SMA Declaration based on SMA Daily on the ticker we're watching
sma200 = request.security(syminfo.tickerid, 'D', ta.sma(closeDa,200))
sma150 = request.security(syminfo.tickerid, 'D', ta.sma(closeDa,150))
sma100 = request.security(syminfo.tickerid, 'D', ta.sma(closeDa,100))
sma50 = request.security(syminfo.tickerid, 'D', ta.sma(closeDa,50))
sma20 = request.security(syminfo.tickerid, 'D', ta.sma(closeDa,20))
// Daily Close SPX500
spxCloseDa = request.security(comparativeTickerId, 'D', close)
// We save if we were above dedicated moving averages in a boolean variable
// Reference point ticker
bCloseAbove200 = closeDa > sma200 ? 1:0
bCloseAbove150 = closeDa > sma150 ? 1:0
bCloseAbove100 = closeDa > sma100 ? 1:0
bCloseAbove50 = closeDa > sma50 ? 1:0
bCloseAbove20 = closeDa > sma20 ? 1:0
// Refence 63 days back (3 months)
bClose63Above200 = closeDa[n63] > sma200[n63] ? 1:0
bClose63Above150 = closeDa[n63] > sma150[n63] ? 1:0
bClose63Above100 = closeDa[n63] > sma100[n63] ? 1:0
bClose63Above50 = closeDa[n63] > sma50[n63] ? 1:0
bClose63Above20 = closeDa[n63] > sma20[n63] ? 1:0
// Refence 126 days back (6 months)
bClose126Above200 = closeDa[n126] > sma200[n126] ? 1:0
bClose126Above150 = closeDa[n126] > sma150[n126] ? 1:0
bClose126Above100 = closeDa[n126] > sma100[n126] ? 1:0
bClose126Above50 = closeDa[n126] > sma50[n126] ? 1:0
bClose126Above20 = closeDa[n126] > sma20[n126] ? 1:0
// Refence 189 days back (9 months)
bClose189Above200 = closeDa[n189] > sma200[n189] ? 1:0
bClose189Above150 = closeDa[n189] > sma150[n189] ? 1:0
bClose189Above100 = closeDa[n189] > sma100[n189] ? 1:0
bClose189Above50 = closeDa[n189] > sma50[n189] ? 1:0
bClose189Above20 = closeDa[n189] > sma20[n189] ? 1:0
// Refence 252 days back (12 months)
bClose252Above200 = closeDa[n252] > sma200[n252] ? 1:0
bClose252Above150 = closeDa[n252] > sma150[n252] ? 1:0
bClose252Above100 = closeDa[n252] > sma100[n252] ? 1:0
bClose252Above50 = closeDa[n252] > sma50[n252] ? 1:0
bClose252Above20 = closeDa[n252] > sma20[n252] ? 1:0
// Calculation based on the formula: RS Score = 40% * P3 + 20% * P6 + 20% * P9 + 20% * P12
// I choosed to calculate like this: if we were above this moving average when only 20% of stock were above, we get 1/0.20 = higher score because it is more noticeable.
// The same when we are below the moving average whereas 80% of stocks are above, we loose the same amont with the formula 1/(1-0.8)
// 0 MONTHS RS
zeroMonthSma200Weight = bCloseAbove200 ? 100/(perStockAbove200):-100/(100-perStockAbove200)
zeroMonthSma150Weight = bCloseAbove150 ? 100/(perStockAbove150):-100/(100-perStockAbove150)
zeroMonthSma100Weight = bCloseAbove100 ? 100/(perStockAbove100):-100/(100-perStockAbove100)
zeroMonthSma50Weight = bCloseAbove50 ? 100/(perStockAbove50 ):-100/(100-perStockAbove50 )
zeroMonthSma20Weight = bCloseAbove20 ? 100/(perStockAbove20 ):-100/(100-perStockAbove20 )
zeroMonthWeight = zeroMonthSma200Weight + zeroMonthSma150Weight + zeroMonthSma100Weight + zeroMonthSma50Weight + zeroMonthSma20Weight
// 3 MONTHS RS
threeMonthSma200Weight = bClose63Above200 ? 100/(perStockAbove200[n63]):-100/(100-perStockAbove200[n63])
threeMonthSma150Weight = bClose63Above150 ? 100/(perStockAbove150[n63]):-100/(100-perStockAbove150[n63])
threeMonthSma100Weight = bClose63Above100 ? 100/(perStockAbove100[n63]):-100/(100-perStockAbove100[n63])
threeMonthSma50Weight = bClose63Above50 ? 100/(perStockAbove50[n63] ):-100/(100-perStockAbove50[n63] )
threeMonthSma20Weight = bClose63Above20 ? 100/(perStockAbove20[n63] ):-100/(100-perStockAbove20[n63] )
threeMonthWeight = threeMonthSma200Weight + threeMonthSma150Weight + threeMonthSma100Weight + threeMonthSma50Weight + threeMonthSma20Weight
// 6 MONTHS RS
sixMonthSma200Weight = bClose126Above200 ? 100/(perStockAbove200[n126]):-100/(100-perStockAbove200[n126])
sixMonthSma150Weight = bClose126Above150 ? 100/(perStockAbove150[n126]):-100/(100-perStockAbove150[n126])
sixMonthSma100Weight = bClose126Above100 ? 100/(perStockAbove100[n126]):-100/(100-perStockAbove100[n126])
sixMonthSma50Weight = bClose126Above50 ? 100/(perStockAbove50[n126] ):-100/(100-perStockAbove50[n126] )
sixMonthSma20Weight = bClose126Above20 ? 100/(perStockAbove20[n126] ):-100/(100-perStockAbove20[n126] )
sixMonthWeight = sixMonthSma200Weight + sixMonthSma150Weight + sixMonthSma100Weight + sixMonthSma50Weight + sixMonthSma20Weight
// 9 MONTH RS
nineMonthSma200Weight = bClose189Above200 ? 100/(perStockAbove200[n189]):-100/(100-perStockAbove200[n189])
nineMonthSma150Weight = bClose189Above150 ? 100/(perStockAbove150[n189]):-100/(100-perStockAbove150[n189])
nineMonthSma100Weight = bClose189Above100 ? 100/(perStockAbove100[n189]):-100/(100-perStockAbove100[n189])
nineMonthSma50Weight = bClose189Above50 ? 100/(perStockAbove50[n189] ):-100/(100-perStockAbove50[n189] )
nineMonthSma20Weight = bClose189Above20 ? 100/(perStockAbove20[n189] ):-100/(100-perStockAbove20[n189] )
nineMonthWeight = nineMonthSma200Weight + nineMonthSma150Weight + nineMonthSma100Weight + nineMonthSma50Weight + nineMonthSma20Weight
// 12 MONTH RS
twelveMonthSma200Weight = bClose252Above200 ? 100/(perStockAbove200[n252]):-100/(100-perStockAbove200[n252])
twelveMonthSma150Weight = bClose252Above150 ? 100/(perStockAbove150[n252]):-100/(100-perStockAbove150[n252])
twelveMonthSma100Weight = bClose252Above100 ? 100/(perStockAbove100[n252]):-100/(100-perStockAbove100[n252])
twelveMonthSma50Weight = bClose252Above50 ? 100/(perStockAbove50[n252] ):-100/(100-perStockAbove50[n252] )
twelveMonthSma20Weight = bClose252Above20 ? 100/(perStockAbove20[n252] ):-100/(100-perStockAbove20[n252] )
twelveMonthWeight = twelveMonthSma200Weight + twelveMonthSma150Weight + twelveMonthSma100Weight + twelveMonthSma50Weight + twelveMonthSma20Weight
// IBD's Formula for score without border (used to apply the cross product)
scoreWithoutBorder = W1Ma * (zeroMonthWeight + threeMonthWeight) + W2Ma * sixMonthWeight + W3Ma * nineMonthWeight + W4Ma * twelveMonthWeight
// Calculation of theorical max and min scores (Truncated because results are very very arround 50-60 otherwise)
// (The real formula of maxScore should be maxScore = W1Ma * (5*2*100/limitDown) + P2ma * (5*3*100/limitDown) )
maxScore = W1Ma * (2*100/limitDown) + W2Ma * (100/limitDown) + W3Ma * (100/limitDown) + W4Ma * (100/limitDown)
minScore = -(W1Ma * (2*100/(100-limitUp)) + W2Ma * (100/(100-limitUp)) + W3Ma * (100/(100-limitUp)) + W4Ma * (100/(100-limitUp)) )
// Formula for score without border adjusted (for the min value to be equals 1)
adjustedScoreWithoutBorder = scoreWithoutBorder - minScore + 1
adjustedMaxScore = maxScore - minScore +1
adjustedMinScore = minScore - minScore +1
// Formula for score with border (cross product) - Result should not be greater than 99 and lower than 1 to this point
rsRating1 = math.round((adjustedScoreWithoutBorder)*99/(adjustedMaxScore-adjustedMinScore))
// Rendering the result (results are mainly distributed at the middle so to get a better result I try to get a wider range by adding to good and removing to bad one)
// Again results are distributed arround 1 to 75 so to get something linear I add to the score proportionally with their distance with 50 (only for better scores)
if(rsRating1>=50)
truncate = (rsRating1-50)/2
rsRating1 := math.round(rsRating1 + truncate)
if(rsRating1>99)
rsRating1 := 99
if(rsRating1<1)
rsRating1 := 1
// 2nd METHOD - No modification except limitation to 100% to master the limit and fix it further to 99 and 1 (and also because -100 is the max)
// Relative strength IBD style -> Initial Calculation against itslef
limitPerf = 2 // +/- 100% limitation
ThreeMthRS = (closeDa/closeDa[n63])
if(closeDa < closeDa[n63])
ThreeMthRS := -(1/ThreeMthRS) // to remove the same score than if this is a positive move
if(ThreeMthRS > limitPerf)
ThreeMthRS := limitPerf
if(ThreeMthRS < -limitPerf)
ThreeMthRS := -limitPerf
SixMthRS = (closeDa/closeDa[n126])
if(closeDa < closeDa[n126])
SixMthRS := -(1/SixMthRS)
if(SixMthRS > limitPerf)
SixMthRS := limitPerf
if(SixMthRS < -limitPerf)
SixMthRS := -limitPerf
NineMthRS = (closeDa/closeDa[n189])
if(closeDa < closeDa[n189])
NineMthRS := -(1/NineMthRS)
if(NineMthRS > limitPerf)
NineMthRS := limitPerf
if(NineMthRS < -limitPerf)
NineMthRS := -limitPerf
TwelveMthRS = (closeDa/closeDa[n252])
if(closeDa < closeDa[n252])
TwelveMthRS := -(1/TwelveMthRS)
if(TwelveMthRS > limitPerf)
TwelveMthRS := limitPerf
if(TwelveMthRS < -limitPerf)
TwelveMthRS := -limitPerf
// Calculation of theorical max and min scores
maxScore2 = limitPerf*W1P + limitPerf*W2P + limitPerf*W3P + limitPerf*W4P
minScore2 = -limitPerf*W1P - limitPerf*W2P - limitPerf*W3P - limitPerf*W4P
// Calulation of Score
RSraw = W1P * ThreeMthRS + W2P * SixMthRS + W3P * NineMthRS + W4P * TwelveMthRS
// Adjustment (used to apply the cross product)
adjustedPerfScoreWithoutBorder = RSraw - minScore2 + 1
adjustedPerfMaxScore = maxScore2 - minScore2 + 1
adjustedPerfMinScore = minScore2 - minScore2 + 1
// Formula for score with border (cross product)
rsRating2 = math.round((adjustedPerfScoreWithoutBorder)*99/(adjustedPerfMaxScore-adjustedPerfMinScore))
// Rendering the result
if(rsRating2>=50)
truncate = (rsRating2-50)/2
rsRating2 := math.round(rsRating2 + truncate)
if(rsRating2>99)
rsRating2 := 99
if(rsRating2<1)
rsRating2 := 1
// 3RD METHOD
// I was running the average of both precedent results and... I found it was actually not that bad!
// But something was missing, a score for relative strenght against the SPX500.
// Let's do it
// Here I wanted to compare perf of ticker vs perf of spx500
// Limited at 100% of original calculation (I use a limit to determine maxscore and minscore and not go above 99 or under 1)
perfTicker63 = closeDa/closeDa[n63]
perfComp63 = spxCloseDa/spxCloseDa[n63]
perfTicker126 = closeDa/closeDa[n126]
perfComp126 = spxCloseDa/spxCloseDa[n126]
perfTicker189 = closeDa/closeDa[n189]
perfComp189 = spxCloseDa/spxCloseDa[n189]
perfTicker252 = closeDa/closeDa[n252]
perfComp252 = spxCloseDa/spxCloseDa[n252]
// Calculation of relative/comparative performance
limiteComp = 2 // +/- 100% limitation
spxThreeMthRS = ( perfTicker63/perfComp63 )
if(perfTicker63 < perfComp63)
spxThreeMthRS := -(1/spxThreeMthRS)
if(spxThreeMthRS > limiteComp)
spxThreeMthRS := limiteComp
if(spxThreeMthRS < -limiteComp)
spxThreeMthRS := -limiteComp
spxSixMthRS = ( perfTicker126/perfComp126 )
if(perfTicker126 < perfComp126)
spxSixMthRS := -(1/spxSixMthRS)
if(spxSixMthRS > limiteComp)
spxSixMthRS := limiteComp
if(spxSixMthRS < -limiteComp)
spxSixMthRS := -limiteComp
spxNineMthRS = (perfTicker189/perfComp189)
if(perfTicker189 < perfComp189)
spxNineMthRS := -(1/spxNineMthRS)
if(spxNineMthRS > limiteComp)
spxNineMthRS := limiteComp
if(spxNineMthRS < -limiteComp)
spxNineMthRS := -limiteComp
spxTwelveMthRS = ( perfTicker252/perfComp252 )
if(perfTicker252 < perfComp252)
spxTwelveMthRS := -(1/spxTwelveMthRS)
if(spxTwelveMthRS > limiteComp)
spxTwelveMthRS := limiteComp
if(spxTwelveMthRS < -limiteComp)
spxTwelveMthRS := -limiteComp
// Calculation of theorical max and min scores
spxMaxScore2 = limiteComp*spxW1Ma + limiteComp*spxW2Ma + limiteComp*spxW3Ma + limiteComp*spxW4Ma
spxMinScore2 = -limiteComp*spxW1Ma - limiteComp*spxW2Ma - limiteComp*spxW3Ma - limiteComp*spxW4Ma
// Calulation of Score
spxRSraw = spxW1Ma * spxThreeMthRS + spxW2Ma * spxSixMthRS + spxW3Ma * spxNineMthRS + spxW4Ma * spxTwelveMthRS
// Adjustment (used to apply the cross product)
spxAdjustedPerfScoreWithoutBorder = spxRSraw - spxMinScore2 + 1
spxAdjustedPerfMaxScore = spxMaxScore2 - spxMinScore2 + 1
spxAdjustedPerfMinScore = spxMinScore2 - spxMinScore2 + 1
// Formula for score with border (cross product)
rsRating3 = math.round((spxAdjustedPerfScoreWithoutBorder)*99/(spxAdjustedPerfMaxScore-spxAdjustedPerfMinScore))
// Rendering the result
if(rsRating3>99)
rsRating3 := 99
if(rsRating3<1)
rsRating3 := 1
// Combination of both systems (w1, w2, are weight to give to the 3 methods)
float totalRsRating = math.round((w1 * rsRating1 + w2 * rsRating2 + w3 * rsRating3) / (w1 + w2 + w3)) // Combining the 3 methods
// Score adjustment based on observation among vast amount of examples against IBD's ranking
// This is handiwork, if you want to work on improving the code you should remove this part
if(rsRating3<45 and rsRating3<rsRating1 and rsRating3<rsRating2) // When we have a great historic score, a great performance but a poor relative strenght, most of the time the rating decrease
totalRsRating := math.round((w2 * rsRating2 + w3 * rsRating3) / (w2 + w3))
if(rsRating2>80 and rsRating1<70 and rsRating3>=68)// Many time when the stock is beaten down but have a huge momentum, this rating is down 20-30 points.
totalRsRating := rsRating2-1 // so we modify the score in this case to take into consideration only the RS Score which is usually not that bad alone at this moment
if(rsRating2>=59 and rsRating1<=30 and rsRating3>=50)// Many time when the stock is beaten down but have a huge/correct momentum, this rating is down 20-30 points.
totalRsRating := rsRating2-1 // And very often the RsRating is the closer to the final result
if(rsRating1>=80 and rsRating2>=49 and rsRating2<=65 and rsRating3<=45 and rsRating3>=33 and rsRating2-rsRating3>=6) // Sometimes when rsRating 2 & 3 are in between a given range, results seems OK. Exception here
totalRsRating := math.round((w1 * rsRating1 + w2 * rsRating2 + w3 * rsRating3) / (w1 + w2 + w3)) // due to the first adjustment but still the first enhances and the second too
if(rsRating1 <= 5)
totalRsRating := math.round((w2 * rsRating2 + w3 * rsRating3) / (w2 + w3))
// Display the RS Rating
// Results are only acceptable in Daily TimeFrame
labelText1 = "RS Rating"
if(isDaily == false)
labelText1 := ""
labelText2 = "\n\n"+str.tostring(totalRsRating,"#0")
if(isDaily)
labelText2 := "\n\n"+str.tostring(totalRsRating,"#0")
else
labelText2 := ""
label1 = (hideRSRat == false) and barstate.islast ? label.new(bar_index, rs, text=labelText1 , color = color.rgb(0,0,0,100), size=size.normal, textcolor=colorRS, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
label2 = (hideRSRat == false) and barstate.islast ? label.new(bar_index, rs, text=labelText2 , color = color.rgb(0,0,0,100), size=size.large, textcolor=colorRS, style=label.style_label_left, textalign=text.align_left, yloc=yloc.price) : na
// Delete previous Labels (When new candle opens or when replay mode, the labels were piling on)
label.delete(label1[1])
label.delete(label2[1])
|
MyLibrary | https://www.tradingview.com/script/Ftmnn1el-MyLibrary/ | Rthompson2548 | https://www.tradingview.com/u/Rthompson2548/ | 2 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Rthompson2548
//@version=5
// @description: Library that contains my functions for using within strategies and indicators
library("MyLibrary")
// @function isHammer: Checks if current bar is hammer doji
// @param float fib: Fibonacci retracement value
// @returns boolean: True if current bar is a hammer doji, and false if it is not
export isHammer(float fib=0.382) =>
//TODO : add function body and return value here
bullishFib = (low - high) * fib + high
lowestBody = close < open ? close : open
lowestBody >= bullishFib and (close > open)
// @function isShootingStar: Checks if current bar is shooting star doji
// @param float fib: Fibonacci retracement value
// @returns boolean: True if current bar is a shooting star doji, and false if it is not
export isShootingStar(float fib=0.382) =>
bearishFib = (high - low) * fib + low
highestBody = close > open ? close : open
highestBody <= bearishFib and (close < open)
// @function isBullishEngulfing: Checks if bullish engulfing candle pattern is present
// @returns boolean: True if previous candle is red, current candle is green, candle closes above previous open, and opens at/lower than previous close
export isBullishEngulfing() =>
prevCandleRed = close[1] < open[1]
greenCandle = close > open
openAtBelowPrevClose = open <= close[1]
closeAbovePrevOpen = close > open[1]
prevCandleRed and greenCandle and openAtBelowPrevClose and closeAbovePrevOpen
// @function isBearishEngulfing: Checks if bearish engulfing candle pattern is present
// @returns boolean: True if previous candle is green, current candle is red, candle closes below previous open, and opens at/above previous close
export isBearishEngulfing() =>
prevCandleGreen = close[1] > open[1]
redCandle = close < open
openAtAbovePrevClose = open >= close[1]
closeBelowPrevOpen = close < open[1]
prevCandleGreen and redCandle and openAtAbovePrevClose and closeBelowPrevOpen
// VWAP data variables
[vwap, upperSD1, lowerSD1] = ta.vwap(open, timeframe.change("1D"), 1)
[vwap2, upperSD2, lowerSD2] = ta.vwap(open, timeframe.change("1D"), 2)
[vwap3, upperSD3, lowerSD3] = ta.vwap(open, timeframe.change("1D"), 3)
// @function isAtUpperVWAPSD: Checks if current candle is touching the 2nd or 3rd upper VWAP standard deviation lines
// @returns boolean: True if current candle is touching the 2nd or 3rd upper VWAP standard deviation lines
export isAtUpperVWAPSD() =>
isAtUpperSD2 = high >= upperSD2 and low <= upperSD2
isAtUpperSD3 = high >= upperSD3 and low <= upperSD3
isAtUpperSD2 or isAtUpperSD3
// @function isAtLowerVWAPSD: Checks if current candle is touching the 2nd or 3rd lower VWAP standard deviation lines
// @returns boolean: True if current candle is touching the 2nd or 3rd lower VWAP standard deviation lines
export isAtLowerVWAPSD() =>
isAtLowerSD2 = high >= lowerSD2 and low <= lowerSD2
isAtLowerSD3 = high >= lowerSD3 and low <= lowerSD3
isAtLowerSD2 or isAtLowerSD3
// @function isAtVWAP: Checks if current candle is touching the VWAP
// @returns boolean: True if current candle is touching the VWAP
export isAtVWAP() =>
isAtVWAP = high >= vwap and low <= vwap
isAtVWAP
// RSI variables
rsi = ta.rsi(close, 14)
export rsiOversold() =>
rsi < 30
export rsiOverbought() =>
rsi > 70
|
RAINBOW AVERAGES - INDICATOR - (AS) - 1/3 | https://www.tradingview.com/script/gV0PSWkf-RAINBOW-AVERAGES-INDICATOR-AS-1-3/ | Adam-Szafranski | https://www.tradingview.com/u/Adam-Szafranski/ | 55 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Adam-Szafranski
//@version=5
indicator("RAINBOW AVERAGES - INDICATOR - (AS) - 1/3", overlay = true ,shorttitle = 'RB_AVGs-(AS)-INDICATOR')
///////////////FUNCTIONS AND TOOLTIPS///////////////////////////FUNCTIONS AND TOOLTIPS/////////////////////////////{
TT_00 = 'INFORMATION: \n-RAINBOW moving averages can be used in many different ways, this script is mainly destinded for trend analysis. \n -Indicator is build to be used on chart not below. but if you would like you can turn this off and change code from "overlay=true" to false. This will cause it to show below chart and will let user see how BG color variants are calculated(also turn of this switch if you prefer below chart). \n-This is First of 3 scripts i will publish using RAINBOW indicators. This one shows the averages on chart, second will utilize RAINBOW BANDS and OSCILLATOR. Third one will be a strategy combining everything'
TT_01 = '-Here we choose SOURCE that is mainly used for calculation of first MA and Type of BGcolor we want to use. \n-BGCOLORS: there are 4 different types of bgc that can be used. \n1-CHANGE: Sums change of all 10 MAs and if its positive and not falling BG=green. If value is negative and not rising BG=red. \n2-RAINBW: simply gives green when all averages are in thier order(so MA1>MA2>MA3>MA4 etc...).Red is exactly the other way so MA1<MA2<MA3....<MA9.\n3-TSHOLD: This one calculates difference beetwen MA0 and MA9 then divided by MA9 and multiplies by 100, So = (100*((MA0-MA9)/MA0)).This way we get width of rainbow averages. We get green if width>treshold or red if width<-treshold.\n4-DIRECT: Checks how many MAs are blw/abv SOURCE and adds 1 or subtracts -1. If value (will be set later) is crossed it gives green when positive and red when negative.\nAnd ofc 0-NONE for no BGC at all '
TT_02 = '-Now we choose type and period of MA0 (it says MA1 but its MA0). From this MA all others will be calculated - meaning MA0 will have source that you choosed above but src of MA1 will be MA0 and MA1 will be source of MA2 and so on'
TT_03 = '-smooth MA0? and length of this smoothing. \nfew things:\n-This will only smooth MA0 but as others are calculated based on it will be smthed as well.\n-To smooth script uses 3-pole super smoother.'
TT_04 = '-We move to "MA2" i called it like that but this settings affect all MAs except MA0 (so M1-M9). \nLike previously we define type and length of MAs.\n MA1-9 use same type and length. but keep in mind that these values should be lower as for exaple if we set 55 this will mean that MA1 is average of picked type from 55periods of MA0. MA2 will be 55 periods of MA1 and so on.\n-(Check out RMA)'
TT_05 = '-Moving on to defing some of the inputs for BG color: \nTSH=value of treshold when using 3-TSHOLD-BGC.Its a good idea to change chart to pane below so it will be easier to adjust. Defualt values are from EURUSD-5M.\nFinally we set value that must be crossed if using 4-DIRECT-BGC. There are 10 MAs so max is also 10. if u set for example 9 this will mean that at least 9 Mas must be below/above price for the script to detect trend. (higher values adviced as most of the time this indicator oscillates either around max or min ) '
TT_06 = '-Hope this will be usefull, if you have any ideas/feedback or maybe spotted error in the code - LET ME KNOW \n-Iam looking for ideas for intresting indicators and strategies that i could code, so if you do not know pinescript just message me and i would be glad to write it for you:)....for free obviously. \n-Stay tuned for two remaining scripts using skittles indicators and check out my other scripts \n----Until we meet again!'
SSF3(SRC, LEN) =>
P = 2 * math.asin(1)
X = P / LEN
a = math.exp(-X)
b = 2 * a * math.cos(1.738 * X)
c = math.pow(a, 2)
cf4 = math.pow(c, 2)
cf3 = -(c + b * c)
cf2 = b+c
cf1 = 1-cf2-cf3-cf4
src1 = nz(SRC[1], SRC)
src2 = nz(SRC[2], src1)
src3 = nz(SRC[3], src2)
SSF = 0.0
SSF := cf1 * SRC + cf2 * nz(SSF[1], src1) + cf3 * nz(SSF[2], src2) + cf4 * nz(SSF[3], src3)
sinmov(SRC,LEN) =>
float result = 0.0
Pi = 2 * math.asin(1)
sum = 0.0
weigS = 0.0
for i = 0 to LEN - 1 by 1
weig = math.sin((i + 1) * Pi / (LEN + 1))
sum += nz(SRC[i]) * weig
weigS += weig
weigS
result := sum / weigS
MA(MA_SRC,MA_LEN,MA_TYP) =>
switch MA_TYP
"EMA" => ta.ema (MA_SRC, MA_LEN)
"SMA" => ta.sma (MA_SRC, MA_LEN)
"RMA" => ta.rma (MA_SRC, MA_LEN)
"WMA" => ta.wma (MA_SRC, MA_LEN)
'SIN' => sinmov (MA_SRC, MA_LEN)
CHANGE (MA,LEN) => ta.change(MA,LEN)
DIRECT (MA,SRC) => MA<SRC?1:MA>SRC?-1:0
///////////////FUNCTIONS AND TOOLTIPS///////////////////////////FUNCTIONS AND TOOLTIPS/////////////////////////////}
///////////////////////INPUTS///////////////////////INPUTS///////////////////////INPUTS///////////////////////INPUTS{
MA_PLT = input.bool (true ,inline='1', tooltip = TT_00,title = 'PLOT RAINBOW AVERAGE ? / !READ ME!-:)')
BG_COL = input.string ('0-NONE','BGC?/SOURCE' ,inline='2', options = ['0-NONE','1-CHANGE','2-RAINBW','3-TSHOLD','4-DIRECT'])
MA_SRC = input (hlcc4 ,'/' ,inline='2', tooltip = TT_01)
MA1TYP = input.string ('EMA' ,'MA1: TYP/LEN' ,inline='3', options = ['EMA','SIN','RMA','SMA','WMA'])
MA1LEN = input.int (120 ,'/' ,inline='3', tooltip = TT_02)
MA1SMT = input.bool (false ,'SMT RBW MA1?/SMTHLEN' ,inline='4')
SM1LEN = input.int (55 ,'/' ,inline='4', tooltip = TT_03)
MA2TYP = input.string ('SMA' ,'MA2: TYP/LEN' ,inline='5', options = ['EMA','SIN','RMA','SMA','WMA'])
MA2LEN = input.int (31 ,'/' ,inline='5', tooltip = TT_04)
TSHOLD = input.float (0.1 ,'BG:TSH/CH/DR' ,inline='6', step = 0.05)
BG_DIR = input.int (7 ,'/' ,inline='6', tooltip = TT_05)
BYEBYE = input.bool (true ,'Last thing....' ,inline='7', tooltip = TT_06)
//////////////INPUTS///////////////////////INPUTS///////////////////////INPUTS///////////////////////INPUTS//////////////}
/////////////////////CALC////////////////////CALC////////////////////CALC////////////////////CALC////////////////////CALC{
SSF = SSF3 (MA_SRC,SM1LEN) ,MA0 = MA1SMT?MA(SSF,MA1LEN,MA1TYP) : MA(MA_SRC,MA1LEN,MA1TYP)
MA1 = MA (MA0,MA2LEN,MA2TYP) ,MA2 = MA (MA1,MA2LEN,MA2TYP) ,MA3 = MA (MA2,MA2LEN,MA2TYP)
MA4 = MA (MA3,MA2LEN,MA2TYP) ,MA5 = MA (MA4,MA2LEN,MA2TYP) ,MA6 = MA (MA5,MA2LEN,MA2TYP)
MA7 = MA (MA6,MA2LEN,MA2TYP) ,MA8 = MA (MA7,MA2LEN,MA2TYP) ,MA9 = MA (MA8,MA2LEN,MA2TYP)
c_MA0 = CHANGE(MA0,2) ,d_MA0 = DIRECT (MA0,MA_SRC)
c_MA1 = CHANGE(MA1,2) ,d_MA1 = DIRECT (MA1,MA_SRC)
c_MA2 = CHANGE(MA2,2) ,d_MA2 = DIRECT (MA2,MA_SRC)
c_MA3 = CHANGE(MA3,2) ,d_MA3 = DIRECT (MA3,MA_SRC)
c_MA4 = CHANGE(MA4,2) ,d_MA4 = DIRECT (MA4,MA_SRC)
c_MA5 = CHANGE(MA5,2) ,d_MA5 = DIRECT (MA5,MA_SRC)
c_MA6 = CHANGE(MA6,2) ,d_MA6 = DIRECT (MA6,MA_SRC)
c_MA7 = CHANGE(MA7,2) ,d_MA7 = DIRECT (MA7,MA_SRC)
c_MA8 = CHANGE(MA8,2) ,d_MA8 = DIRECT (MA8,MA_SRC)
c_MA9 = CHANGE(MA9,2) ,d_MA9 = DIRECT (MA9,MA_SRC)
DIRECT_RAINBW = (d_MA0+d_MA1+d_MA2+d_MA3+d_MA4+d_MA5+d_MA6+d_MA7+d_MA8+d_MA9)
CHANGE_RAINBW = (c_MA0+c_MA1+c_MA2+c_MA3+c_MA4+c_MA5+c_MA6+c_MA7+c_MA8+c_MA9)
RBW_UPP_ORDER = MA1>MA2 and MA2>MA3 and MA3>MA4 and MA4>MA5 and MA5>MA6 and MA7>MA8 and MA8>MA9
RBW_DWN_ORDER = MA1<MA2 and MA2<MA3 and MA3<MA4 and MA4<MA5 and MA5<MA6 and MA7<MA8 and MA8<MA9
RAINBOW_WIDTH = (100*((MA0-MA9)/MA0))
ZERO_OVF_LINE = 0
DIR_UP = DIRECT_RAINBW >= BG_DIR
DIR_DN = DIRECT_RAINBW <=-BG_DIR
TSH_UP = RAINBOW_WIDTH > TSHOLD and ta.rising (RAINBOW_WIDTH,3)
TSH_DN = RAINBOW_WIDTH <-TSHOLD and ta.falling (RAINBOW_WIDTH,3)
CHA_UP = CHANGE_RAINBW > 0 and not ta.falling (CHANGE_RAINBW,3)
CHA_DN = CHANGE_RAINBW < 0 and not ta.rising (CHANGE_RAINBW,3)
RBW_UP = RBW_UPP_ORDER
RBW_DN = RBW_DWN_ORDER
//////////////CALC////////////////////CALC////////////////////CALC////////////////////CALC////////////////////CALC////////////////////CALC}
//////////////////////PLOTS//////////////////////PLOTS//////////////////////PLOTS//////////////////////PLOTS//////////////////////PLOTS{
p_MA0 = plot (MA_PLT ? MA0 : na , 'MA0' , color.rgb (255, 0 , 0 ),display = display.all )
p_MA1 = plot (MA_PLT ? MA1 : na , 'MA1' , color.rgb (255, 94 , 0 ),display = display.pane)
p_MA2 = plot (MA_PLT ? MA2 : na , 'MA2' , color.rgb (255, 230, 0 ),display = display.pane)
p_MA3 = plot (MA_PLT ? MA3 : na , 'MA3' , color.rgb (145, 255, 49 ),display = display.pane)
p_MA4 = plot (MA_PLT ? MA4 : na , 'MA4' , color.rgb (59 , 211, 51 ),display = display.pane)
p_MA5 = plot (MA_PLT ? MA5 : na , 'MA5' , color.rgb (28 , 120, 55 ),display = display.pane)
p_MA6 = plot (MA_PLT ? MA6 : na , 'MA6' , color.rgb (58 , 252, 255 ),display = display.pane)
p_MA7 = plot (MA_PLT ? MA7 : na , 'MA7' , color.rgb (54 , 90 , 237 ),display = display.pane)
p_MA8 = plot (MA_PLT ? MA8 : na , 'MA8' , color.rgb (31 , 37 , 139 ),display = display.pane)
p_MA9 = plot (MA_PLT ? MA9 : na , 'MA9' , color.rgb (151, 0 , 182 ),display = display.all )
CLR_LIN_GR = color.rgb(167, 170, 182, 18) ,CLR_FIL_MA = color.rgb(80, 136, 240 , 89)
CLR_IND_UP = color.rgb(61, 202, 66 , 13) ,CLR_IND_DN = color.rgb(235 , 65, 13 , 9)
CLR_BGC_UP = color.rgb(44, 216, 107 , 80) ,CLR_BGC_DN = color.rgb(205 , 24, 72 , 80)
CLR_IND_DR = DIR_UP?CLR_IND_UP:DIR_DN?CLR_IND_DN:CLR_LIN_GR
CLR_IND_TH = TSH_UP?CLR_IND_UP:TSH_DN?CLR_IND_DN:CLR_LIN_GR
CLR_IND_CH = CHA_UP?CLR_IND_UP:CHA_DN?CLR_IND_DN:CLR_LIN_GR
BGCLR1_CHA = CHA_UP?CLR_BGC_UP:CHA_DN?CLR_BGC_DN:na
BGCLR2_RBW = RBW_UP?CLR_BGC_UP:RBW_DN?CLR_BGC_DN:na
BGCLR3_TSH = TSH_UP?CLR_BGC_UP:TSH_DN?CLR_BGC_DN:na
BGCLR4_DIR = DIR_UP?CLR_BGC_UP:DIR_DN?CLR_BGC_DN:na
plot(not MA_PLT and BG_COL=='1-CHANGE'?CHANGE_RAINBW:na,'CHANGE_RBW' ,CLR_IND_CH,1,plot.style_area )
plot(not MA_PLT and BG_COL=='1-CHANGE'?ZERO_OVF_LINE:na,'ZERO_HLINE' ,CLR_LIN_GR,1,plot.style_linebr )
plot(not MA_PLT and BG_COL=='3-TSHOLD'?RAINBOW_WIDTH:na,'RAINBW_WID' ,CLR_IND_TH,1,plot.style_area )
plot(not MA_PLT and BG_COL=='3-TSHOLD'?TSHOLD :na,'TSHOLD_POS' ,CLR_LIN_GR,1,plot.style_linebr )
plot(not MA_PLT and BG_COL=='3-TSHOLD'?-TSHOLD :na,'TSHOLD_NEG' ,CLR_LIN_GR,1,plot.style_linebr )
plot(not MA_PLT and BG_COL=='4-DIRECT'?DIRECT_RAINBW:na,'DIRECT_RBW' ,CLR_IND_DR,1,plot.style_columns)
BACKGROUND_COLOR = switch BG_COL
'0-NOCOLR' => na
'1-CHANGE' => BGCLR1_CHA
'2-RAINBW' => BGCLR2_RBW
'3-TSHOLD' => BGCLR3_TSH
'4-DIRECT' => BGCLR4_DIR
bgcolor(BACKGROUND_COLOR ,title = 'RAINBOW BGC TREND')
fill(p_MA0,p_MA9,CLR_FIL_MA,title = 'Gentle fill for MAs')
//////////////PLOTS//////////////////////PLOTS//////////////////////PLOTS//////////////////////PLOTS//////////////////////PLOTS}
|
theme_engine | https://www.tradingview.com/script/525Zi7V5-theme-engine/ | kaigouthro | https://www.tradingview.com/u/kaigouthro/ | 12 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ kaigouthro
//@version=5
//@description Theme Builder and Structure for live generative themes
library("theme_engine",true)
import kaigouthro/hsvColor/15 as h
//=======================================================
//#region Type declarations
//=======================================================
// @type Settings for a theme
// @field h1 (float) Hue #1 for Template
// @field h2 (float) Hue #2 for Template
// @field h3 (float) Hue #3 for Template
// @field h4 (float) Hue #4 for Template
// @field sat (float) Saturation of theme
// @field lum (float) Luminosity (light/dark)
// @field vib (float) Vibrance (Contrast)
// @field r (float) Hue of Red
// @field o (float) Hue of Orange
// @field y (float) Hue of Yellow
// @field g (float) Hue of Green
// @field a (float) Hue of Aqua
// @field b (float) Hue of Blue
// @field i (float) Hue of Indigo
// @field v (float) Hue of Violet
// @field satvals (settings) Array for use if desired to customize Saturation per color
// @field lumvals (settings) Array for use if desired to customize Luminancce per color
export type settings
float h1 = 0
float h2 = 0
float h3 = 0
float h4 = 0
float sat = 1
float lum = 1
float vib = 1
float r = 0
float o = 30
float y = 60
float g = 120
float a = 210
float b = 240
float i = 270
float v = 330
settings satvals
settings lumvals
// @type Modifiers Item for Use if desired
// @field val (float)
// @field size (float)
// @field depth (float)
// @field hue (float)
// @field sat (float)
// @field alpha (float)
// @field mix (float)
// @field emit (float)
// @field ch (float)
// @field step (int)
// @field dist (int)
// @field holds (mods)
// @field isin (mods)
// @field track (color)
export type mods
float val = 1
float size = 1
float depth = 1
float hue = 0
float sat = 1
float alpha = 1
float mix = 1
float emit = 0
float ch = 0
int step = 1
int dist = 1
mods holds
mods isin
color track
// @type Light/Dark/Custom Theme Varients
// @field bg (color) Bacckground Color
// @field fg (color) Foreground Color
// @field accent (color) Accccent Color
// @field secondary (color) Secondary Color
// @field txt (color) Text Color
export type varient
color bg = na
color fg = na
color accent = na
color secondary = na
color txt = na
// @type Theme Object
// @field name (string) Theme name
// @field dark (varient) Theme dark Varient
// @field light (varient) Theme light Varient
// @field red (color) Color for red
// @field orange (color) Color for orange
// @field yellow (color) Color for yellow
// @field green (color) Color for green
// @field aqua (color) Color for aqua
// @field blue (color) Color for blue
// @field purple (color) Color for purple
// @field pink (color) Color for pink
// @field tweaks (mods) Modifiers UDT to use for adjusters
export type theme
string name = ''
varient dark = na
varient light = na
color red = color.red
color orange = color.orange
color yellow = color.yellow
color green = color.green
color aqua = color.aqua
color blue = color.blue
color purple = color.purple
color pink = color.fuchsia
mods tweaks
// @type Multiple theme Container
// @field names (string[]) Names of themes
// @field themes (theme[]) Theme Items
// @type
export type themedict
string[] names
theme[] themes
//#endregion ============================================
//#region Functions for themes
//=======================================================
//@function New theme object.
//@param _name (string) opptional name
//@returns a VAR theme (holds it's vals when updated if not overwritten)
export init(string _name = 'New Theme') =>
var _red = color.red
var _orange = color.orange
var _yellow = color.yellow
var _green = color.green
var _aqua = color.aqua
var _blue = color.blue
var _purple = color.purple
var _fuchsia = color.fuchsia
var dark_bg = color(na), var dark_accent = color(na)
var dark_fg = color(na), var dark_comment = color(na)
var light_bg = color(na), var light_accent = color(na)
var light_fg = color(na), var light_comment = color(na)
var light_ttl = color(na), var dark_ttl = color(na)
var dark = varient.new(dark_bg ,dark_fg, dark_accent, dark_comment,dark_ttl )
var light = varient.new(light_bg,light_fg,light_accent,light_comment,light_ttl)
var theme = theme.new(_name ,
dark = dark ,
light = light ,
red = _red ,
orange = _orange ,
yellow = _yellow ,
green = _green ,
aqua = _aqua ,
blue = _blue ,
purple = _purple ,
pink = _fuchsia ,
tweaks = mods.new())
theme
// @function helper to do brihgtness of globals
brightness(n,c)=> math.pow(1 + c/2, 10 * (n/2) - 10)
// @function Create light/dark theme globals
// @param theme (theme) Theme to add theses to
// @param _h1 (float) Hue #1 for Template
// @param _h2 (float) Hue #2 for Template
// @param _h3 (float) Hue #3 for Template
// @param _h4 (float) Hue #4 for Template
// @param _s (float) Saturation of theme
// @param _val (float) Luminosity (light/dark)
// @param _contrast (float) Contrast to apply
// @returns Theme wwith adjusted colors
export globals(theme theme,float _h1,float _h2,float _h3,float _h4,float _s,float _val,float _contrast)=>
_v = math.max(0,math.min(1,_val ))
_c = math.max(0,math.min(1,_contrast ))
theme.dark.bg := h.hsv(_h1,_s/3 , brightness(_v , 1 -_c /10 ) , 1 ) , theme.light.bg := h.hsv(_h1,_s/13 , brightness(_v , _c /10 ) ,1)
theme.dark.accent := h.hsv(_h2,_s/3 , brightness(_v , 1 -_c / 3 ) , 1 ) , theme.light.accent := h.hsv(_h2,_s/5 , brightness(_v , _c / 3 ) ,1)
theme.dark.secondary := h.hsv(_h3,_s/5 , brightness(_v , _c / 3 ) , 1 ) , theme.light.secondary := h.hsv(_h3,_s/3 , brightness(_v , 1 -_c / 3 ) ,1)
theme.dark.fg := h.hsv(_h4,_s/13 , brightness(_v , _c /10 ) , 1 ) , theme.light.fg := h.hsv(_h4,_s/3 , brightness(_v , 1 -_c /10 ) ,1)
theme.dark.txt := h.hsv(0 , 0 , 0.9 , 1 ) , theme.light.txt := h.hsv( 0, 0 , _v + _c ,1)
theme
// @function Apply a Settings object to a theme
// @param theme Theme object to apply settings to.
// @param setting settings to apply
// @returns theme
export setConfig (theme theme , settings setting) =>
_sat = setting.sat
_bright = setting.vib
bg = #000000
acc = #3f3f3f
cmm = #7f7f7f
fg = #bfbfbf
ttl = #ffffff
theme.red := h.hsv ( setting.r ,_sat, _bright , 1)
theme.orange := h.hsv ( setting.o ,_sat, _bright , 1)
theme.yellow := h.hsv ( setting.y ,_sat, _bright , 1)
theme.green := h.hsv ( setting.g ,_sat, _bright , 1)
theme.aqua := h.hsv ( setting.a ,_sat, _bright , 1)
theme.blue := h.hsv ( setting.b ,_sat, _bright , 1)
theme.purple := h.hsv ( setting.i ,_sat, _bright , 1)
theme.pink := h.hsv ( setting.v ,_sat, _bright , 1)
theme.dark := varient.new ( bg ,acc , cmm ,fg)
theme.light := varient.new ( fg ,cmm , acc ,bg)
globals(theme, setting.h1 , setting.h2, setting.h3 , setting.h4,setting.sat , setting.lum, setting.vib )
//#endregion ============================================
//// demo
// //demo testing inputs for settings obj
// _count = input(10,'demo generate count')
// g1 = input(1, 'Global hue 1', inline='gcol', group='Globals')
// g2 = input(1, 'Global hue 2', inline='gcol', group='Globals')
// g3 = input(1, 'Global hue 3', inline='gcol', group='Globals')
// g4 = input(1, 'Global hue 4', inline='gcol', group='Globals')
// gs = input.float(1,'sat' ,step=0.1, inline='hsv', group='Globals')
// gv = input.float(1,'bright' ,step=0.1, inline='hsv', group='Globals')
// gc = input.float(1,'contrast' ,step=0.1, inline='hsv', group='Globals')
// _rBase = input( 0 ,'r',inline='sh',group='per-color')
// _oBase = input( 30 ,'o',inline='sh',group='per-color')
// _yBase = input( 60 ,'y',inline='sh',group='per-color')
// _gBase = input( 120 ,'g',inline='sh',group='per-color')
// _aBase = input( 210 ,'a',inline='sh',group='per-color')
// _bBase = input( 240 ,'b',inline='sh',group='per-color')
// _iBase = input( 270 ,'i',inline='sh',group='per-color')
// _vBase = input( 330 ,'v',inline='sh',group='per-color')
// // helpers for demo
// addSomeRandom() => math.random(-5,5)
// spc(x)=>
// s = ''
// for i = 0 to x
// s+= font.space(6)
// // create a multitheme dictionary to hold more than one theme
// var dict = themedict.new(array.new<string>(_count,''),array.new<theme>(_count))
// // local function just to generate multiple themes
// addshortcut(i,_count)=>
// array.set(dict.names ,i,str.tostring(i))
// var _mult = 0.
// _mult := i/_count
// // theme = theme.copy(array.get(dict.themes,i))
// var theme = init()
// theme := setConfig(theme,
// settings.new (
// _mult * 360 + g1 ,
// _mult * 360 + g2 ,
// _mult * 360 + g3 ,
// _mult * 360 + g4 ,
// _mult * gs ,
// _mult + gv ,
// _mult + gc ,
// addSomeRandom() + _rBase ,
// addSomeRandom() + _oBase ,
// addSomeRandom() + _yBase ,
// addSomeRandom() + _gBase ,
// addSomeRandom() + _aBase ,
// addSomeRandom() + _bBase ,
// addSomeRandom() + _iBase ,
// addSomeRandom() + _vBase ))
// theme
// // for display purposes, local items
// import kaigouthro/matrixautotable/14 as mtb
// import kaigouthro/calc/5
// import kaigouthro/font/4
// // just to randomly shift the color values
// shift(c,r)=>
// [h,s,v,a] = h.rgbhsv(c)
// h+= r
// s+= r/50
// v-= r/50
// h.hsv(h,s,v,a)
// testshift(theme)=>
// theme.red := shift(theme.red ,addSomeRandom())
// theme.orange := shift(theme.orange ,addSomeRandom())
// theme.yellow := shift(theme.yellow ,addSomeRandom())
// theme.green := shift(theme.green ,addSomeRandom())
// theme.aqua := shift(theme.aqua ,addSomeRandom())
// theme.blue := shift(theme.blue ,addSomeRandom())
// theme.purple := shift(theme.purple ,addSomeRandom())
// theme.pink := shift(theme.pink ,addSomeRandom())
// theme
// //////////////////////////////////////////////////////////////////////////////////////////
// /////////////////
// ///////////////// HERE
// /////////////////
// // when creating and adding to an array, this is a pine limitation..
// if barstate.isfirst
// for i = 0 to array.size(dict.themes) -1
// switch input.int(0,'three ways',0,2)
// 0 => // creates a new theme for each, then copies it, places copy
// theme = addshortcut(i,array.size(dict.themes))
// array.set(dict.themes,i, theme.copy(theme))
// 1 => // only first makes it
// var theme = addshortcut(i,array.size(dict.themes))
// array.set(dict.themes,i, theme)
// 2 => // only last makes it
// theme = addshortcut(i,array.size(dict.themes))
// array.set(dict.themes,i, theme)
// /////////////////
// ///////////////// HERE
// /////////////////
// //////////////////////////////////////////////////////////////////////////////////////////
// if barstate.islast
// _out = matrix.new<color> ( 0,16 )
// _st = array.copy ( dict.names )
// _fm = matrix.new <float> ( _count,16,float(na) )
// _in = matrix.new<color> ( _count,16 )
// _txin = matrix.new<color> ( _count,16 )
// _smtx = matrix.new <string> ( _count,16 )
// _tmtx = matrix.new <string> ( _count,16 )
// for [_n,theme] in dict.themes
// // adjuust colors without creating new theme
// testshift(array.get(dict.themes,_n))
// matrix.fill(_tmtx,theme.name,_n,_n+1,0,16)
// matrix.set(_in , _n , 00 , theme.dark.bg )
// matrix.set(_in , _n , 01 , theme.dark.accent )
// matrix.set(_in , _n , 02 , theme.dark.secondary )
// matrix.set(_in , _n , 03 , theme.dark.fg )
// matrix.set(_in , _n , 04 , theme.light.bg )
// matrix.set(_in , _n , 05 , theme.light.accent )
// matrix.set(_in , _n , 06 , theme.light.secondary )
// matrix.set(_in , _n , 07 , theme.light.fg )
// matrix.set(_in , _n , 08 , theme.red )
// matrix.set(_in , _n , 09 , theme.orange )
// matrix.set(_in , _n , 10 , theme.yellow )
// matrix.set(_in , _n , 11 , theme.green )
// matrix.set(_in , _n , 12 , theme.aqua )
// matrix.set(_in , _n , 13 , theme.blue )
// matrix.set(_in , _n , 14 , theme.purple )
// matrix.set(_in , _n , 15 , theme.pink )
// //testt that updating master updates theme
// matrix.set(_txin,_n,00, theme.dark.fg )
// matrix.set(_txin,_n,01, theme.dark.txt )
// matrix.set(_txin,_n,02, theme.dark.txt )
// matrix.set(_txin,_n,03, theme.dark.bg )
// matrix.set(_txin,_n,04, theme.light.fg )
// matrix.set(_txin,_n,05, theme.light.txt )
// matrix.set(_txin,_n,06, theme.light.txt )
// matrix.set(_txin,_n,07, theme.light.bg )
// matrix.set(_txin,_n,08, h.tripswitch(theme.red , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,09, h.tripswitch(theme.orange , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,10, h.tripswitch(theme.yellow , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,11, h.tripswitch(theme.green , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,12, h.tripswitch(theme.aqua , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,13, h.tripswitch(theme.blue , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,14, h.tripswitch(theme.purple , 0.8, #ffffff,#000000 ))
// matrix.set(_txin,_n,15, h.tripswitch(theme.pink , 0.8, #ffffff,#000000 ))
// if input.bool(false,'show text')
// matrix.set(_smtx,_n,00, font.uni((_n == _count-1?'dark bg \n text - fg' : 'text') ,15))
// matrix.set(_smtx,_n,01, font.uni((_n == _count-1?'dark accent \n text - txt' : 'text') ,15))
// matrix.set(_smtx,_n,02, font.uni((_n == _count-1?'dark secondary \n text - txt' : 'text') ,15))
// matrix.set(_smtx,_n,03, font.uni((_n == _count-1?'dark fg \n text - bg' : 'text') ,15))
// matrix.set(_smtx,_n,04, font.uni((_n == _count-1?'light bg \n text - fg' : 'text') ,15))
// matrix.set(_smtx,_n,05, font.uni((_n == _count-1?'light accent \n text - txt' : 'text') ,15))
// matrix.set(_smtx,_n,06, font.uni((_n == _count-1?'light secondary \n text - txt' : 'text') ,15))
// matrix.set(_smtx,_n,07, font.uni((_n == _count-1?'light fg \n text - bg' : 'text') ,15))
// matrix.set(_smtx,_n,08, font.uni(_n==_count-1?'red' : '' ,15))
// matrix.set(_smtx,_n,09, font.uni(_n==_count-1?'orange' : '' ,15))
// matrix.set(_smtx,_n,10, font.uni(_n==_count-1?'yellow' : '' ,15))
// matrix.set(_smtx,_n,11, font.uni(_n==_count-1?'green' : '' ,15))
// matrix.set(_smtx,_n,12, font.uni(_n==_count-1?'aqua' : '' ,15))
// matrix.set(_smtx,_n,13, font.uni(_n==_count-1?'blue' : '' ,15))
// matrix.set(_smtx,_n,14, font.uni(_n==_count-1?'purple' : '' ,15))
// matrix.set(_smtx,_n,15, font.uni(_n==_count-1?'pink' : '' ,15))
// // show the table
// if input(false,'Rotate table 90 degrees')
// _fm := matrix.transpose(_fm)
// _txin := matrix.transpose(_txin)
// _smtx := matrix.transpose(_smtx)
// _in := matrix.transpose(_in)
// _tbl = mtb.matrixtable(_fm, _smtx,_in,_txin,input(2,'textsize'), _fit=true)
// mtb.border(_tbl,#00000000,input(true,'Borders')?1:0)
|
RSI Multi Timeframe Based on Moving Average By Alireza Phoenix | https://www.tradingview.com/script/tqySeDFc-RSI-Multi-Timeframe-Based-on-Moving-Average-By-Alireza-Phoenix/ | AlirezaPhoenix | https://www.tradingview.com/u/AlirezaPhoenix/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
// ยฉ AlirezaPhoenix
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ //
//# * โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
//# *
//# * Study : Relative Strength Index Multi Timeframe Based on Moving Average By Alireza Phoenix
//# * Author : Alireza Phoenix
//# *
//# * Version : 1.1
indicator(title="Relative Strength Index Multi Timeframe Based on Moving Average By Alireza Phoenix", shorttitle="RSI Multi Timeframe Based on Moving Average By Alireza Phoenix", format=format.price, precision=2 )
len = input(14, title="Length")
src = input(close, "Source")
up = ta.rma(math.max(ta.change(src), 0), len)
down = ta.rma(-math.min(ta.change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
offset = input(0 , "RSI Offset")
offset1 = input(0 , "RSI Time1 Offset")
offset2 = input(0 , "RSI Time2 Offset")
plot(rsi, "RSI", color=#7E57C2 , offset = offset)
band1 = hline(70, "Upper Band", color=#787B86)
bandm = hline(50, "Middle Band", color=color.new(#787B86, 50))
band0 = hline(30, "Lower Band", color=#787B86)
fill(band1, band0, color=color.rgb(126, 87, 194, 90), title="Background")
i_res = input.timeframe('120', "Time 1 Resolution" )
s = request.security(syminfo.tickerid , i_res, rsi)
plot(s , 'RSI Time 1', color = color.blue , offset = offset1)
i_res2 = input.timeframe('240', "Time 2 Resolution" )
s2 = request.security(syminfo.tickerid , i_res2, rsi)
plot(s2 , 'RSI Time 2', color=color.red , offset = offset2)
//RSI MA Setup
length1 = input.int(98, 'Fast SMA Length', minval=1)
length2 = input.int(112, 'Slow SMA Length', minval=1)
offset3 = input.int(3, 'Offset Fast SMA', minval=-500, maxval=500)
offset4 = input.int(0, 'Offset Slow SMA', minval=-500, maxval=500)
RSIma1 = ta.wma(2 * ta.wma(s, length1 / 2) - ta.wma(s, length1), math.round(math.sqrt(length1)))
RSIma2 = ta.wma(2 * ta.wma(s2, length2 / 2) - ta.wma(s2, length2), math.round(math.sqrt(length2)))
plot(RSIma1, 'RSI SMA Fast', offset=offset3, color=color.new(#21f3de, 0))
plot(RSIma2, 'RSI SMA Slow', offset=offset4, color=color.new(#ffdf41, 0), display=display.none) |
PitchforkMethods | https://www.tradingview.com/script/eUSeK6kz-PitchforkMethods/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 30 | library | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ Trendoscope Pty Ltd
// โโ
// โโโ โโ
// โโโโโ โโ
// โโโโโโโโ โ โโ
// โโโโโโ โ โโ
// โโโโ โ โโโโโโโโโโโ
// โโโโโโโโโโโ โ โโโโโโโโโโโโโโโโโโโโ
// โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโโโโโโโ โโ
// โโโโโ โโโโโโโ
// โโโโโโโโโ
// โโโโโ โโโโโ
// โโโโโ โโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโ โโโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโ โโโโโโโโ
// โโโโโ โโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// โโโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโ โโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโโโโโโโโ
// โโโโโ โโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโ โโโโโโโโโโโโโโ โโโ โโโโโโโโโโ โโโโโโ
// โโโโโ โโโโโ โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโ
// โโ โ
//@version=5
// @description Methods associated with Pitchfork and Pitchfork Drawing. Depends on the library PitchforkTypes for Pitchfork/PitchforkDrawing objects which in turn use DrawingTypes for basic objects Point/Line/LineProperties. Also depends on DrawingMethods for related methods
library("PitchforkMethods", overlay = true)
import HeWhoMustNotBeNamed/DrawingTypes/2 as dr
import HeWhoMustNotBeNamed/DrawingMethods/2
import HeWhoMustNotBeNamed/PitchforkTypes/2 as p
method get(p.Fork this, string key)=>key== "ratio"? str.tostring(this.ratio) : key == "include"? str.tostring(this.include) : na
// @function Converts PitchforkTypes/Fork object to string representation
// @param this PitchforkTypes/Fork object
// @returns string representation of PitchforkTypes/Fork
export method tostring(p.Fork this)=>
str = ''
if(not na(this))
keys = array.from("ratio", "include")
keyValues = array.new<string>()
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
// @function Converts Array of PitchforkTypes/Fork object to string representation
// @param this Array of PitchforkTypes/Fork object
// @returns string representation of PitchforkTypes/Fork array
export method tostring(array<p.Fork> this)=>
str = ''
if(not na(this))
values = array.new<string>()
for fork in this
values.push(fork.tostring())
str := '['+array.join(values, ",")+']'
str
method get(p.PitchforkProperties this, string key)=>key == "forks"? str.tostring(this.forks.tostring()) : key == "type"? this.type : key == "inside"? (this.inside? 'true': 'false'): na
// @function Converts PitchforkTypes/PitchforkProperties object to string representation
// @param this PitchforkTypes/PitchforkProperties object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @returns string representation of PitchforkTypes/PitchforkProperties
export method tostring(p.PitchforkProperties this, bool sortKeys = false, int sortOrder = 1)=>
str = ''
if(not na(this))
keys = array.from("ratios", "type", "inside")
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(p.PitchforkDrawingProperties this, string key)=>key == "extend"? (this.extend?'true':'false') :
key == "fillTransparency"? str.tostring(this.fillTransparency) :
key == "fill"? (this.fill? 'true': 'false'): na
// @function Converts PitchforkTypes/PitchforkDrawingProperties object to string representation
// @param this PitchforkTypes/PitchforkDrawingProperties object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @returns string representation of PitchforkTypes/PitchforkDrawingProperties
export method tostring(p.PitchforkDrawingProperties this, bool sortKeys = false, int sortOrder = 1)=>
str = ''
if(not na(this))
keys = array.from("extend", "fill", "fillTransparency")
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
method get(p.Pitchfork this, string key)=>key == "a"? this.a.tostring() : key == "b"? this.b.tostring() : key == "c"? this.c.tostring() :
key == "properties"? this.properties.tostring(): key == "dProperties"? this.dProperties.tostring() : na
// @function Converts PitchforkTypes/Pitchfork object to string representation
// @param this PitchforkTypes/Pitchfork object
// @param sortKeys If set to true, string output is sorted by keys.
// @param sortOrder Applicable only if sortKeys is set to true. Positive number will sort them in ascending order whreas negative numer will sort them in descending order. Passing 0 will not sort the keys
// @returns string representation of PitchforkTypes/Pitchfork
export method tostring(p.Pitchfork this, bool sortKeys = false, int sortOrder = 1)=>
str = ''
if(not na(this))
keys = array.from("a", "b", "c", "properties", "dProperties")
keyValues = array.new<string>()
if(sortKeys and not na(sortOrder) and sortOrder!=0)
keys.sort(sortOrder>0? order.ascending : order.descending)
for key in keys
keyValues.push('"'+key+'":'+'"'+this.get(key)+'"')
str := '{'+array.join(keyValues, ",")+'}'
str
getParrallelPoint(p1Start, p1End, p2Start)=>
priceDiff = p1Start.price-p2Start.price
barDiff = p1Start.bar - p2Start.bar
barTimeDiff = p1Start.bartime - p2Start.bartime
dr.Point.new(p1End.price-priceDiff, p1End.bar-barDiff, p1End.bartime - barTimeDiff)
// @function Creates PitchforkTypes/PitchforkDrawing from PitchforkTypes/Pitchfork object
// @param this PitchforkTypes/Pitchfork object
// @returns PitchforkTypes/PitchforkDrawing object created
export method createDrawing(p.Pitchfork this)=>
this.lProperties := na(this.lProperties)? dr.LineProperties.new() : this.lProperties
this.properties := na(this.properties)? p.PitchforkProperties.new() : this.properties
this.dProperties := na(this.dProperties)? p.PitchforkDrawingProperties.new(commonColor = this.lProperties.color) : this.dProperties
if(na(this.properties.forks))
this.properties.forks := array.new<p.Fork>()
if(this.properties.forks.size()==0)
this.properties.forks.push(p.Fork.new(0.5, this.lProperties.color, true))
this.properties.forks.push(p.Fork.new(1.0, this.lProperties.color, true))
if(na(this.dProperties.commonColor))
this.dProperties.commonColor := this.lProperties.color
dr.Point p1 = this.properties.type == "schiff"? dr.Point.new((this.a.price+this.b.price)/2, this.a.bar, this.a.bartime) :
this.properties.type == "mschiff"? dr.Point.new((this.a.price+this.b.price)/2, int((this.a.bar+this.b.bar)/2), int((this.a.bartime+this.b.bartime)/2)):
this.a
dr.Point p2 = this.properties.inside? this.c : dr.Point.new((this.b.price+this.c.price)/2, int((this.b.bar+this.c.bar)/2), int((this.a.bartime+this.b.bartime)/2))
dr.Point p3 = dr.Point.new(2*p2.price-p1.price, 2*p2.bar-p1.bar, 2*p2.bartime-p1.bartime)
baseLineProperties = dr.LineProperties.copy(this.lProperties)
baseLineProperties.extend := this.dProperties.extend? extend.right : extend.none
medianLine = dr.Line.new(p1, p2, this.lProperties)
array<dr.Line> forkLines = array.new<dr.Line>()
array<dr.Linefill> fills = array.new<dr.Linefill>()
forkLines.push(dr.Line.new(p2, p3, baseLineProperties))
array<color> fillColors = array.new<color>()
for [i, fork] in this.properties.forks
if(fork.include)
forkColor = na(fork.forkColor) or fork.forkColor == color(na) or this.dProperties.forceCommonColor? this.dProperties.commonColor : fork.forkColor
diffPriceB = (this.b.price-p2.price)*fork.ratio
diffBarB = int((this.b.bar-p2.bar)*fork.ratio)
diffBarTimeB = int((this.b.bartime-p2.bar)*fork.ratio)
forkLineProperties = dr.LineProperties.copy(baseLineProperties)
forkLineProperties.color := forkColor
dr.Point p1Edgeb = dr.Point.new(p2.price+diffPriceB, p2.bar+diffBarB, p2.bartime+diffBarTimeB)
dr.Point p2Edgeb = getParrallelPoint(p2, p3, p1Edgeb)
dr.Line forkLineEdgeB = dr.Line.new(p1Edgeb, p2Edgeb, forkLineProperties)
forkLines.push(forkLineEdgeB)
fillColors.push(forkColor)
if(not this.properties.inside)
dr.Point p1Edgec = dr.Point.new(p2.price-diffPriceB, p2.bar-diffBarB, p2.bartime-diffBarTimeB)
dr.Point p2Edgec = getParrallelPoint(p2, p3, p1Edgec)
dr.Line forkLineEdgeC = dr.Line.new(p1Edgec, p2Edgec, forkLineProperties)
forkLines.unshift(forkLineEdgeC)
fillColors.unshift(forkColor)
if(this.dProperties.fill)
for [index, forkColor] in fillColors
fills.push(dr.Linefill.new(forkLines.get(index), forkLines.get(index+1), forkColor, this.dProperties.fillTransparency))
baseLine = dr.Line.new(array.first(forkLines).start, array.last(forkLines).start, this.lProperties)
this.drawing := p.PitchforkDrawing.new(medianLine, baseLine, forkLines, fills)
this.drawing
// @function Creates PitchforkTypes/PitchforkDrawing array from PitchforkTypes/Pitchfork array of objects
// @param this array of PitchforkTypes/Pitchfork object
// @returns array of PitchforkTypes/PitchforkDrawing object created
export method createDrawing(array<p.Pitchfork> this)=>
array<p.PitchforkDrawing> drawings = array.new<p.PitchforkDrawing>()
if(not na(this))
for pitchfork in this
drawings.push(pitchfork.createDrawing())
drawings
// @function draws from PitchforkTypes/PitchforkDrawing object
// @param this PitchforkTypes/PitchforkDrawing object
// @returns PitchforkTypes/PitchforkDrawing object drawn
export method draw(p.PitchforkDrawing this)=>
this.medianLine.draw()
this.baseLine.draw()
this.forkLines.draw()
this.linefills.draw()
this
// @function deletes PitchforkTypes/PitchforkDrawing object
// @param this PitchforkTypes/PitchforkDrawing object
// @returns PitchforkTypes/PitchforkDrawing object deleted
export method delete(p.PitchforkDrawing this)=>
this.medianLine.delete()
this.baseLine.delete()
this.linefills.delete()
this.forkLines.delete()
this
// @function deletes underlying drawing of PitchforkTypes/Pitchfork object
// @param this PitchforkTypes/Pitchfork object
// @returns PitchforkTypes/Pitchfork object deleted
export method delete(p.Pitchfork this)=>
if(not na(this))
this.drawing.delete()
this
// @function deletes array of PitchforkTypes/PitchforkDrawing objects
// @param this Array of PitchforkTypes/PitchforkDrawing object
// @returns Array of PitchforkTypes/PitchforkDrawing object deleted
export method delete(array<p.PitchforkDrawing> this)=>
if not na(this)
for drawing in this
drawing.delete()
this
// @function deletes underlying drawing in array of PitchforkTypes/Pitchfork objects
// @param this Array of PitchforkTypes/Pitchfork object
// @returns Array of PitchforkTypes/Pitchfork object deleted
export method delete(array<p.Pitchfork> this)=>
if not na(this)
for pitchfork in this
pitchfork.delete()
this
// @function deletes array of PitchforkTypes/PitchforkDrawing objects and clears the array
// @param this Array of PitchforkTypes/PitchforkDrawing object
// @returns void
export method clear(array<p.PitchforkDrawing> this)=>
if not na(this)
while(this.size()!=0)
this.pop().delete()
// @function deletes array of PitchforkTypes/Pitchfork objects and clears the array
// @param this Array of Pitchfork/Pitchfork object
// @returns void
export method clear(array<p.Pitchfork> this)=>
if(not na(this))
while(this.size()!=0)
this.pop().delete()
// ###################################################################### Tests #############################################################
// import HeWhoMustNotBeNamed/ZigzagTypes/1 as zg
// import HeWhoMustNotBeNamed/ZigzagMethods/1
// import HeWhoMustNotBeNamed/utils/1 as ut
// import HeWhoMustNotBeNamed/Logger/1 as l
// var logger = l.Logger.new(minimumLevel = 'DEBUG')
// logger.init()
// theme = input.string('Dark', title='Theme', options=['Light', 'Dark'], group='Generic Settings',
// tooltip='Chart theme settings. Line and label colors are generted based on the theme settings. If dark theme is selected, '+
// 'lighter colors are used and if light theme is selected, darker colors are used.')
// zigzagLength = input.int(13, step=5, minval=3, title='Length', group='Zigzag', tooltip='Zigzag length for level 0 zigzag')
// depth = input.int(50, "Depth", step=25, maxval=500, group='Zigzag', tooltip='Zigzag depth refers to max number of pivots to show on chart')
// useRealTimeBars = input.bool(true, 'Use Real Time Bars', group='Zigzag', tooltip = 'If enabled real time bars are used for calculation. Otherwise, only confirmed bars are used')
// typeTooltip = 'Handle Type' +
// '\n\tregular - Pivot A' +
// '\n\tschiff - X of Pivot A and y from median of Pivot A and B' +
// '\n\tmschiff - X and Y are median of Pivot A and Pivot B' +
// '\n\nNeck Type' +
// '\n\tmedian - median of Pivot B and Pivot C' +
// '\n\tinside - Pivot C'
// pitchforkType = input.string("regular", "Type", ["regular", "schiff", "mschiff"], group="Pitchfork", inline="t")
// neckType = input.string('median', '', ['median', 'inside'], group="Pitchfork", inline="t", tooltip=typeTooltip)
// inside = neckType == 'inside'
// ratioFrom = input.float(0.25, 'Ratio', minval=0.0, maxval=0.5, group='Pitchfork', inline='r')
// ratioTo = input.float(1, '', minval=0.5, maxval=1.618, group='Pitchfork', inline='r', tooltip='Range of ratio for which drawing pitchfork is allowed')
// useConfirmedPivot = input.bool(true, 'Use Confirmed Pivots', group="Pitchfork", tooltip="If set to true, uses last confirmed pivot and ignores the current moving pivot")
// includeRatio1 = input.bool(false, '', inline='r1', group='Forks')
// ratio1 = input.float(0.236, '', inline='r1', group='Forks')
// color1 = input.color(#f77c80, '', inline='r1', group='Forks')
// includeRatio2 = input.bool(false, '', inline='r1', group='Forks')
// ratio2 = input.float(0.382, '', inline='r1', group='Forks')
// color2 = input.color(#ffb74d, '', inline='r1', group='Forks')
// includeRatio3 = input.bool(true, '', inline='r2', group='Forks')
// ratio3 = input.float(0.500, '', inline='r2', group='Forks')
// color3 = input.color(#fff176, '', inline='r2', group='Forks')
// includeRatio4 = input.bool(false, '', inline='r2', group='Forks')
// ratio4 = input.float(0.618, '', inline='r2', group='Forks')
// color4 = input.color(#81c784, '', inline='r2', group='Forks')
// includeRatio5 = input.bool(false, '', inline='r3', group='Forks')
// ratio5 = input.float(0.786, '', inline='r3', group='Forks')
// color5 = input.color(#42bda8, '', inline='r3', group='Forks')
// includeRatio6 = input.bool(false, '', inline='r3', group='Forks')
// ratio6 = input.float(0.886, '', inline='r3', group='Forks')
// color6 = input.color(#4dd0e1, '', inline='r3', group='Forks')
// includeRatio7 = input.bool(true, '', inline='r4', group='Forks')
// ratio7 = input.float(1.000, '', inline='r4', group='Forks')
// color7 = input.color(#5b9cf6, '', inline='r4', group='Forks')
// includeRatio8 = input.bool(false, '', inline='r4', group='Forks')
// ratio8 = input.float(1.130, '', inline='r4', group='Forks')
// color8 = input.color(#9575cd, '', inline='r4', group='Forks')
// includeRatio9 = input.bool(false, '', inline='r5', group='Forks')
// ratio9 = input.float(1.272, '', inline='r5', group='Forks')
// color9 = input.color(#ba68c8, '', inline='r5', group='Forks')
// includeRatio10 = input.bool(false, '', inline='r5', group='Forks')
// ratio10 = input.float(1.382, '', inline='r5', group='Forks')
// color10 = input.color(#f06292, '', inline='r5', group='Forks')
// includeRatio11 = input.bool(false, '', inline='r6', group='Forks')
// ratio11 = input.float(1.618, '', inline='r6', group='Forks')
// color11 = input.color(#faa1a4, '', inline='r6', group='Forks')
// includeRatio12 = input.bool(false, '', inline='r6', group='Forks')
// ratio12 = input.float(2.000, '', inline='r6', group='Forks')
// color12 = input.color(#4caf50, '', inline='r6', group='Forks')
// extend = input.bool(true, "Extend", group="Display", tooltip = "Extend fork lines to right")
// fill = input.bool(true, "Fill", group="Display", inline='f')
// transparency = input.int(95, "Transparency", group="Display", inline='f', tooltip = "Fill Forkline with background color")
// offset = useRealTimeBars? 0 : 1
// indicators = matrix.new<float>()
// indicatorNames = array.new<string>()
// themeColors = ut.getColors(theme)
// var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, depth, offset)
// zigzag.calculate(array.from(high, low), indicators, indicatorNames)
// startIndex = useConfirmedPivot? 1:0
// includes = array.from(includeRatio1, includeRatio2, includeRatio3, includeRatio4, includeRatio5, includeRatio6,
// includeRatio7, includeRatio8, includeRatio9, includeRatio10, includeRatio11, includeRatio12)
// ratios = array.from(ratio1, ratio2, ratio3, ratio4, ratio5, ratio6, ratio7, ratio8, ratio9, ratio10, ratio11, ratio12)
// colors = array.from(color1, color2, color3, color4, color5, color6, color7, color8, color9, color10, color11, color12)
// array<p.Fork> forks = array.new<p.Fork>()
// for [i, include] in includes
// if(include)
// forks.push(p.Fork.new(ratios.get(i), colors.get(i), include))
// p.PitchforkProperties properties = p.PitchforkProperties.new(forks, pitchforkType, inside)
// p.PitchforkDrawingProperties dProperties = p.PitchforkDrawingProperties.new(extend, fill, transparency)
// if(barstate.islast)
// var array<p.Pitchfork> pitchforks = array.new<p.Pitchfork>()
// pitchforks.clear()
// mlzigzag = zigzag
// while(array.size(mlzigzag.zigzagPivots) >= 3+startIndex)
// lineColor = themeColors.pop()
// themeColors.unshift(lineColor)
// p3 = array.get(mlzigzag.zigzagPivots, startIndex)
// p3Point = p3.point
// p2Point = array.get(mlzigzag.zigzagPivots, startIndex+1).point
// p1Point = array.get(mlzigzag.zigzagPivots, startIndex+2).point
// if (p3.ratio >= ratioFrom and p3.ratio <= ratioTo and p3Point.bar - p1Point.bar <500)
// dr.LineProperties lProperties = dr.LineProperties.new(color=lineColor)
// p.Pitchfork pitchFork = p.Pitchfork.new(p1Point, p2Point, p3Point, properties, dProperties, lProperties)
// drawing = pitchFork.createDrawing()
// drawing.draw()
// pitchforks.push(pitchFork)
// mlzigzag := mlzigzag.nextlevel() |
OI Volume Oscillator Cross Dynamics | https://www.tradingview.com/script/58lGqRsC-OI-Volume-Oscillator-Cross-Dynamics/ | Crypto_Moses | https://www.tradingview.com/u/Crypto_Moses/ | 20 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Crypto_Moses
//@version=5
indicator(title="Custom Open Interest and Volume Oscillator", shorttitle="OI_VO", overlay=false)
// Open Interest Code
Coin = input("BTC", title = "Coin")
Margin = input("Tether", title = 'Margin')
Exchange = 'BINANCE:'
SelectCoin = Coin
Code = (Margin == 'Tether') ? 'USDTPERP_OI' : 'PERP_OI'
Altcoin = Exchange + SelectCoin + Code
OpenInterest = request.security(Altcoin, timeframe.period, close)
plot(OpenInterest, color=color.red, title="Open Interest", linewidth=2)
// Volume Oscillator Code
shortPeriod = input.int(5, title="Short Period")
longPeriod = input.int(20, title="Long Period")
volMultiplier = input.float(1000, title="Volume Oscillator Multiplier")
shortMA = ta.sma(volume, shortPeriod)
longMA = ta.sma(volume, longPeriod)
volOsc = (shortMA - longMA) * volMultiplier
plot(volOsc, color=color.blue, title="Volume Oscillator")
// Crossover/Crossunder Conditions
bullishCross = ta.crossover(volOsc, OpenInterest)
bearishCross = ta.crossunder(volOsc, OpenInterest)
// Plotting Shapes for Crossovers
plotshape(series=bullishCross, color=color.green, style=shape.triangleup, location=location.belowbar, size=size.small, title="Bullish Cross")
plotshape(series=bearishCross, color=color.red, style=shape.triangledown, location=location.abovebar, size=size.small, title="Bearish Cross") |
Harmonic Pattern Table Inputs | https://www.tradingview.com/script/LWIBxRtf-Harmonic-Pattern-Table-Inputs/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 18 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ RozaniGhani-RG
//@version=5
indicator('Harmonic Pattern Table Inputs', 'HPTI', overlay = true)
// 0. Initialize
// 1. Inputs
// 2. Variable
// 3. Methods
// 4. Constructs
//#region โโโโโโโโโโโโโโโโโโโโ 0. Initialize
// @type rng
// @field min float value
// @field max float value
type rng
float min = na
float max = na
// @type ratio
// @field BXA rng value
// @field CAB rng value
// @field DBC rng value
// @field DXA float value
// @field SL float value
type ratio
rng BXA = na
rng CAB = na
rng DBC = na
float DXA = na
float SL = na
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 1. Inputs
TT = 'Small font size recommended for mobile app or multiple layout'
GT0 = 'TABLE SETTINGS'
i_s_font = input.string('normal', 'Font size', group = GT0, options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = TT)
i_s_Y = input.string('bottom', 'Position', group = GT0, inline = 'Table2', options = ['top', 'middle', 'bottom'])
i_s_X = input.string( 'right', '', group = GT0, inline = 'Table2', options = ['left', 'center', 'right'])
GT1 = 'SHOW / HIDE TITLE'
i_b_title = input.bool( true, 'TITLE', group = GT1)
i_b_NO = input.bool( true, 'NO', group = GT1)
i_b_BXA = input.bool( true, 'POINT B', group = GT1)
i_b_CAB = input.bool( true, 'POINT C', group = GT1)
i_b_DBC = input.bool( true, 'LAYERING', group = GT1)
i_b_DXA = input.bool( true, 'PRZ', group = GT1)
i_b_SL = input.bool( true, 'STOP LOSS', group = GT1)
GP = 'SHOW / HIDE PATTERN'
i_b_aBat = input.bool( true, 'ALT BAT', group = GP)
i_b_bat = input.bool( true, 'BAT', group = GP)
i_b_crab = input.bool( true, 'CRAB', group = GP)
i_b_gart = input.bool( true, 'GARTLEY', group = GP)
i_b_bfly = input.bool( true, 'BUTTERFLY', group = GP)
i_b_dCrab = input.bool( true, 'DEEP CRAB', group = GP)
i_b_shark = input.bool( true, 'SHARK', group = GP)
G0 = 'C = AB'
cRet = rng.new(input.float(0.382, 'Retracement', group = G0, inline = 'R'), input.float(0.886, '', group = G0, inline = 'R'))
cExt = rng.new(input.float(1.130, 'Extension', group = G0, inline = 'E'), input.float(1.618, '', group = G0, inline = 'E', tooltip = 'Shark only'))
P0 = 'ALT BAT'
aBat = ratio.new(
rng.new(input.float(0.371, 'B = XA', group = P0, inline = 'B'), input.float(0.382, '', group = P0, inline = 'B')),
cRet,
rng.new(input.float(2.000, 'D = BC', group = P0, inline = 'D'), input.float(3.618, '', group = P0, inline = 'D')),
input.float(1.130, 'D = XA', group = P0),
input.float(1.270, 'SL', group = P0))
P1 = 'BAT'
bat = ratio.new(
rng.new(input.float(0.382, 'B = XA', group = P1, inline = 'B'), input.float(0.500, '', group = P1, inline = 'B')),
cRet,
rng.new(input.float(1.618, 'D = BC', group = P1, inline = 'D'), input.float(2.618, '', group = P1, inline = 'D')),
input.float(0.886, 'D = XA', group = P1),
input.float(1.130, 'SL', group = P1))
P2 = 'CRAB'
crab = ratio.new(
rng.new(input.float(0.382, 'B = XA', group = P2, inline = 'B'), input.float(0.618, '', group = P2, inline = 'B')),
cRet,
rng.new(input.float(2.618, 'D = BC', group = P2, inline = 'D'), input.float(3.618, '', group = P2, inline = 'D')),
input.float(1.618, 'D = XA', group = P2),
input.float(2.000, 'SL', group = P2))
P3 = 'GARTLEY'
gart = ratio.new(
rng.new(input.float(0.599, 'B = XA', group = P3, inline = 'B'), input.float(0.637, '', group = P3, inline = 'B')),
cRet,
rng.new(input.float(1.130, 'D = BC', group = P3, inline = 'D'), input.float(1.618, '', group = P3, inline = 'D')),
input.float(0.786, 'D = XA', group = P3),
input.float(1.000, 'SL', group = P3))
P4 = 'BUTTERFLY'
bfly = ratio.new(
rng.new(input.float(0.762, 'B = XA', group = P4, inline = 'B'), input.float(0.810, '', group = P4, inline = 'B')),
cRet,
rng.new(input.float(1.618, 'D = BC', group = P4, inline = 'D'), input.float(2.240, '', group = P4, inline = 'D')),
input.float(1.270, 'D = XA', group = P4),
input.float(1.414, 'SL', group = P4))
P5 = 'DEEP CRAB'
dCrab = ratio.new(
rng.new(input.float(0.886, 'B = XA', group = P5, inline = 'B'), input.float(0.930, '', group = P5, inline = 'B')),
cRet,
rng.new(input.float(2.000, 'D = BC', group = P5, inline = 'D'), input.float(3.618, '', group = P5, inline = 'D')),
input.float(1.618, 'D = XA', group = P5),
input.float(2.000, 'SL', group = P5))
P6 = 'SHARK'
shark = ratio.new(
rng.new(input.float(0.382, 'B = XA', group = P6, inline = 'B'), input.float(0.618, '', group = P6, inline = 'B')),
cExt,
rng.new(input.float(1.618, 'D = BC', group = P6, inline = 'D'), input.float(2.240, '', group = P6, inline = 'D')),
input.float(0.886, 'D = XA', group = P6),
input.float(1.270, 'SL', group = P6))
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 2. Variable
var tbl = table.new(i_s_Y + '_' + i_s_X, 7, 9, color.new(color.blue, 100), chart.fg_color, 1, chart.fg_color, 1)
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 3. Methods
// @function createTitle
// @param table_id table id
// @param fontSize string value
// @returns table.cell
method createTitle(table table_id = na, string fontSize = na) =>
if i_b_title
if i_b_NO
table_id.cell(0, 0, 'NO', text_color = chart.fg_color, text_size = fontSize)
table_id.cell( 1, 0, 'HARMONIC\nPATTERN', text_color = chart.fg_color, text_size = fontSize)
if i_b_BXA
table_id.cell(2, 0, 'B = XA', text_color = chart.fg_color, text_size = fontSize)
if i_b_CAB
table_id.cell(3, 0, 'C = AB\n(POINT C)', text_color = chart.fg_color, text_size = fontSize)
if i_b_DBC
table_id.cell(4, 0, 'D = BC\n(LAYERING)', text_color = chart.fg_color, text_size = fontSize)
if i_b_DXA
table_id.cell(5, 0, 'D = XA\n(PRZ)', text_color = chart.fg_color, text_size = fontSize)
if i_b_SL
table_id.cell(6, 0, 'SL = XA\n(STOP LOSS)', text_color = chart.fg_color, text_size = fontSize)
// @function createRow
// @param table_id table id
// @param row int value
// @param enable bool value
// @param string str value
// @param id ratio value
// @param fontSize string value
// @returns table.cell
method createRow(table table_id = na, int row = na, bool enable = na, string str = na, ratio id = na, string fontSize = na) =>
if enable
if i_b_NO
table_id.cell(0, row, str.tostring(row), text_size = fontSize, text_color = id.DXA >= 1. ? color.blue : color.red)
table_id.cell( 1, row, str, text_size = fontSize, text_color = id.DXA >= 1. ? color.blue : color.red)
if i_b_BXA
table_id.cell(2, row, str.tostring(id.BXA.min, '0.000') + ' ; ' + str.tostring(id.BXA.max, '0.000'), text_size = fontSize, text_color = id.BXA.min >= 1. ? color.blue : color.red)
if i_b_CAB
table_id.cell(3, row, str.tostring(id.CAB.min, '0.000') + ' ; ' + str.tostring(id.CAB.max, '0.000'), text_size = fontSize, text_color = id.CAB.min >= 1. ? color.blue : color.red)
if i_b_DBC
table_id.cell(4, row, str.tostring(id.DBC.min, '0.000') + ' ; ' + str.tostring(id.DBC.max, '0.000'), text_size = fontSize, text_color = id.DBC.min >= 1. ? color.blue : color.red)
if i_b_DXA
table_id.cell(5, row, str.tostring(id.DXA, '0.000'), text_size = fontSize, text_color = id.DXA >= 1. ? color.blue : color.red)
if i_b_SL
table_id.cell(6, row, str.tostring(id.SL, '0.000'), text_size = fontSize, text_color = id.SL >= 1. ? color.blue : color.red)
//#endregion
//#region โโโโโโโโโโโโโโโโโโโโ 4. Constructs
if barstate.islast
tbl.createTitle(i_s_font)
tbl.createRow(1, i_b_aBat, 'ALT BAT', aBat, i_s_font)
tbl.createRow(2, i_b_bat, 'BAT', bat, i_s_font)
tbl.createRow(3, i_b_crab, 'CRAB', crab, i_s_font)
tbl.createRow(4, i_b_gart, 'GARTLEY', gart, i_s_font)
tbl.createRow(5, i_b_bfly, 'BUTTERFLY', bfly, i_s_font)
tbl.createRow(6, i_b_dCrab,'DEEP CRAB', dCrab, i_s_font)
tbl.createRow(7, i_b_shark, 'SHARK', shark, i_s_font)
//#endregion |
Market Performance Table | https://www.tradingview.com/script/OqHgkQSi-Market-Performance-Table/ | fyntrade | https://www.tradingview.com/u/fyntrade/ | 29 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ fyntrade
// Version 1.0 - 6 Oct 2023
//@version=5
indicator(title="Market Performance", shorttitle = "MP", overlay=true)
useT1 = input(true,"", inline = "1", group="Tickers")
t1 = input.symbol("AMEX:SPY","", inline = "1", group="Tickers")
useT2 = input(true,"", inline = "2", group="Tickers")
t2 = input.symbol("NASDAQ:QQQ" , "", inline = "2", group="Tickers")
useT3 = input(true,"", inline = "3", group="Tickers")
t3 = input.symbol("AMEX:IWM", "", inline = "3", group="Tickers")
useT4 = input(true,"", inline = "4", group="Tickers")
t4 = input.symbol("AMEX:IWO", "", inline = "4", group="Tickers")
useT5 = input(true,"", inline = "5", group="Tickers")
t5 = input.symbol("AMEX:IWC", "", inline = "5", group="Tickers")
dash_loc = input.string(defval = "Bottom Left", title = "Dashboard Location", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group='Style Settings')
text_size = input.string(defval = "Small", title = "Dashboard Size", options=["Tiny", "Small", "Normal", "Large"], group='Style Settings')
var table_position = switch dash_loc
"Top Left" => position.top_left
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
var table_text_size = switch text_size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
cell_up = input(#4caf50,'Bullish Cell Color' ,group='Style Settings')
cell_dn = input(#FF5252,'Bearish Cell Color' ,group='Style Settings')
cell_neutral = input(#5d606b,'Neutral Cell Color' ,group='Style Settings')
txt_col = input(color.silver,'Text/Frame Color' ,group='Style Settings')
cell_transp = input.int(25,'Transparency' ,minval=0 ,maxval=100 ,group='Style Settings')
f_calc(ticker) =>
a_close = request.security(ticker,'1D',close)
a_text = array.get(str.split(ticker, ':'),1)
roc = ta.roc(a_close,1)/100
sma200 = ta.sma(a_close,200)
sma50 = ta.sma(a_close,50)
sma20 = ta.sma(a_close,20)
sma10 = ta.sma(a_close,10)
ext50 = (a_close - sma50) / sma50
[a_text, a_close, roc, a_close > sma50, a_close > sma20, a_close > sma10, sma10 > sma20, sma20 > sma50, sma50 > sma200, ext50]
var t = table.new(table_position,11,6,
frame_color=txt_col,
frame_width=1,
border_color=txt_col,
border_width=1)
[t1text, t1close, t1roc, t1sma50, t1sma20, t1sma10, t1sma10_20, t1sma20_50, t1sma50_200, t1ext50] = f_calc(t1)
[t2text, t2close, t2roc, t2sma50, t2sma20, t2sma10, t2sma10_20, t2sma20_50, t2sma50_200, t2ext50] = f_calc(t2)
[t3text, t3close, t3roc, t3sma50, t3sma20, t3sma10, t3sma10_20, t3sma20_50, t3sma50_200, t3ext50] = f_calc(t3)
[t4text, t4close, t4roc, t4sma50, t4sma20, t4sma10, t4sma10_20, t4sma20_50, t4sma50_200, t4ext50] = f_calc(t4)
[t5text, t5close, t5roc, t5sma50, t5sma20, t5sma10, t5sma10_20, t5sma20_50, t5sma50_200, t5ext50] = f_calc(t5)
if barstate.islast
table.cell(t,1,0, 'Symbol' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,2,0, 'Price ($)' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,3,0, '1D change (%)' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,4,0, '>50SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,5,0, '>20SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,6,0, '>10SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,7,0, '10>20SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,8,0, '20>50SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,9,0, '50>200SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,10,0, 'Ext 50SMA' ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
if useT1
table.cell(t,1,1, str.tostring(t1text) ,text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,2,1, str.tostring(t1close, '#.##'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,3,1, str.tostring(t1roc, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,4,1, str.tostring(t1sma50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t1sma50 ? cell_up : cell_dn,cell_transp))
table.cell(t,5,1, str.tostring(t1sma20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t1sma20 ? cell_up : cell_dn,cell_transp))
table.cell(t,6,1, str.tostring(t1sma10),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t1sma10 ? cell_up : cell_dn,cell_transp))
table.cell(t,7,1, str.tostring(t1sma10_20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t1sma10_20 ? cell_up : cell_dn,cell_transp))
table.cell(t,8,1, str.tostring(t1sma20_50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t1sma20_50 ? cell_up : cell_dn,cell_transp))
table.cell(t,9,1, str.tostring(t1sma50_200),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t1sma50_200 ? cell_up : cell_dn,cell_transp))
table.cell(t,10,1, str.tostring(t1ext50, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
if useT2
table.cell(t,1,2, str.tostring(t2text),text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,2,2, str.tostring(t2close, '#.##'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,3,2, str.tostring(t2roc, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,4,2, str.tostring(t2sma50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t2sma50 ? cell_up : cell_dn,cell_transp))
table.cell(t,5,2, str.tostring(t2sma20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t2sma20 ? cell_up : cell_dn,cell_transp))
table.cell(t,6,2, str.tostring(t2sma10),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t2sma10 ? cell_up : cell_dn,cell_transp))
table.cell(t,7,2, str.tostring(t2sma10_20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t2sma10_20 ? cell_up : cell_dn,cell_transp))
table.cell(t,8,2, str.tostring(t2sma20_50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t2sma20_50 ? cell_up : cell_dn,cell_transp))
table.cell(t,9,2, str.tostring(t2sma50_200),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t2sma50_200 ? cell_up : cell_dn,cell_transp))
table.cell(t,10,2, str.tostring(t2ext50, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
if useT3
table.cell(t,1,3, str.tostring(t3text),text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,2,3, str.tostring(t3close, '#.##'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,3,3, str.tostring(t3roc, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,4,3, str.tostring(t3sma50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t3sma50 ? cell_up : cell_dn,cell_transp))
table.cell(t,5,3, str.tostring(t3sma20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t3sma20 ? cell_up : cell_dn,cell_transp))
table.cell(t,6,3, str.tostring(t3sma10),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t3sma10 ? cell_up : cell_dn,cell_transp))
table.cell(t,7,3, str.tostring(t3sma10_20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t3sma10_20 ? cell_up : cell_dn,cell_transp))
table.cell(t,8,3, str.tostring(t3sma20_50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t3sma20_50 ? cell_up : cell_dn,cell_transp))
table.cell(t,9,3, str.tostring(t3sma50_200),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t3sma50_200 ? cell_up : cell_dn,cell_transp))
table.cell(t,10,3, str.tostring(t3ext50, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
if useT4
table.cell(t,1,4, str.tostring(t4text),text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,2,4, str.tostring(t4close, '#.##'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,3,4, str.tostring(t4roc, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,4,4, str.tostring(t4sma50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t4sma50 ? cell_up : cell_dn,cell_transp))
table.cell(t,5,4, str.tostring(t4sma20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t4sma20 ? cell_up : cell_dn,cell_transp))
table.cell(t,6,4, str.tostring(t4sma10),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t4sma10 ? cell_up : cell_dn,cell_transp))
table.cell(t,7,4, str.tostring(t4sma10_20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t4sma10_20 ? cell_up : cell_dn,cell_transp))
table.cell(t,8,4, str.tostring(t4sma20_50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t4sma20_50 ? cell_up : cell_dn,cell_transp))
table.cell(t,9,4, str.tostring(t4sma50_200),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t4sma50_200 ? cell_up : cell_dn,cell_transp))
table.cell(t,10,4, str.tostring(t4ext50, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
if useT5
table.cell(t,1,5, str.tostring(t5text),text_color=color.white,text_size=table_text_size,bgcolor=color.black)
table.cell(t,2,5, str.tostring(t5close, '#.##'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,3,5, str.tostring(t5roc, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
table.cell(t,4,5, str.tostring(t5sma50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t5sma50 ? cell_up : cell_dn,cell_transp))
table.cell(t,5,5, str.tostring(t5sma20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t5sma20 ? cell_up : cell_dn,cell_transp))
table.cell(t,6,5, str.tostring(t5sma10),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t5sma10 ? cell_up : cell_dn,cell_transp))
table.cell(t,7,5, str.tostring(t5sma10_20),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t5sma10_20 ? cell_up : cell_dn,cell_transp))
table.cell(t,8,5, str.tostring(t5sma20_50),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t5sma20_50 ? cell_up : cell_dn,cell_transp))
table.cell(t,9,5, str.tostring(t5sma50_200),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(t5sma50_200 ? cell_up : cell_dn,cell_transp))
table.cell(t,10,5, str.tostring(t5ext50, '#.##%'),text_color=txt_col,text_size=table_text_size, bgcolor=color.new(cell_neutral,cell_transp))
|
SML Suite | https://www.tradingview.com/script/J0HupBnn-SML-Suite/ | kikfraben | https://www.tradingview.com/u/kikfraben/ | 16 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ kikfraben
// Updated last on 25. Oct, 2023
//@version=5
indicator("SML Suite", overlay = false)
// Define Moving Average Lengths
len_ma1 = input(9, "Moving Average 1", group = "User Inputs")
len_ma2 = input(22, "Moving Average 2", group = "User Inputs")
len_ma3 = input(52, "Moving Average 3", group = "User Inputs")
// Source
src = input(close, "Moving Average Source", group = "User Inputs")
// Define Standard Deviation Multiplier
mult = input.float(1.0, "Standard Deviation Multiplier", group = "User Inputs")
// Get Moving Averages
val_ma1 = ta.sma(src, len_ma1)
val_ma2 = ta.sma(src, len_ma2)
val_ma3 = ta.sma(src, len_ma3)
// Get Standard Deviations
stdev_ma1 = ta.stdev(src, len_ma1)
stdev_ma2 = ta.stdev(src, len_ma2)
stdev_ma3 = ta.stdev(src, len_ma3)
// Get Upper and Lower Bands
u1 = val_ma1 + mult * stdev_ma1
l1 = val_ma1 - mult * stdev_ma1
u2 = val_ma2 + mult * stdev_ma2
l2 = val_ma2 - mult * stdev_ma2
u3 = val_ma3 + mult * stdev_ma3
l3 = val_ma3 - mult * stdev_ma3
// Get Binary Results
b1 = (close > u1) ? 1 : (close < l1) ? -1 : 1
b2 = (close > u2) ? 1 : (close < l2) ? -1 : 1
b3 = (close > u3) ? 1 : (close < l3) ? -1 : 1
// SML Calculation
sml = math.avg(b1, b2, b3)
// Color Inputs
col_up1 = #3fa8c9
col_up2 = color.new(#3fa8c9, 55)
col_down1 = #c93f3f
col_down2 = color.new(#c93f3f, 55)
// Determine the Color of the Bars
hist_col = sml >= 0 ? (sml > sml[1] ? col_up1 : col_up2) : (sml < sml[1] ? col_down1 : col_down2)
// Plot SML as Histogram
plot(sml, style = plot.style_histogram, color = hist_col, linewidth = 3)
// Table with Binary Results
var bTable = table.new(position = position.top_right, columns = 5, rows = 5, bgcolor = color.new(color.white, 95), border_width = 1, frame_color = color.new(color.white, 50), frame_width = 1, border_color = color.new(color.white, 70))
table.merge_cells(bTable, 0, 0, 1, 0)
table.cell(bTable, 0, 0, "SML Suite", text_color = color.new(color.white, 50))
table.cell(bTable, 0, 1, "S", text_color = color.new(color.white, 50))
table.cell(bTable, 0, 2, "M", text_color = color.new(color.white, 50))
table.cell(bTable, 0, 3, "L", text_color = color.new(color.white, 50))
table.cell(bTable, 0, 4, "SML", text_color = color.new(color.white, 50))
table.cell(bTable, 1, 1, str.tostring(b1), text_color = b1 >= 0 ? col_up1 : col_down1)
table.cell(bTable, 1, 2, str.tostring(b2), text_color = b2 >= 0 ? col_up1 : col_down1)
table.cell(bTable, 1, 3, str.tostring(b3), text_color = b3 >= 0 ? col_up1 : col_down1)
table.cell(bTable, 1, 4, str.tostring(sml), text_color = sml >= 0 ? col_up1 : col_down1) |
@tk ยท spectral | https://www.tradingview.com/script/LFTbUfY9-tk-spectral/ | gabrielrtakeda | https://www.tradingview.com/u/gabrielrtakeda/ | 39 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ gabrielrtakeda
//@version=5
// <declaration_statement>
indicator("@tk ยท spectral", overlay=true)
// <import_statements>
import gabrielrtakeda/tk/1 as tk
// <constant_declarations>
string DEFAULT_TEXT_SIZE = size.normal
string DEFAULT_POSITION = position.bottom_right
string DEFAULT_PAIR_OPERATOR = 'USDT'
color DEFAULT_SPECTRUM_COLOR = #434651
// hints
string HINT_PAIR_QUOTE = 'e.g. BTCUSDT. Which BTC is the "base" and USDT is the "quote".'
// <inputs>
string GROUP_GENERAL = 'General'
string textSizeInput = input.string(DEFAULT_TEXT_SIZE, 'Text Size', [size.tiny, size.small, size.normal, size.large], group=GROUP_GENERAL)
string positionInput = input.string(DEFAULT_POSITION, 'Position', [position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right], group=GROUP_GENERAL)
string pairQuoteInput = input.string(DEFAULT_PAIR_OPERATOR, 'Pair Quote', tooltip=HINT_PAIR_QUOTE, group=GROUP_GENERAL)
color spectrumColorInput = input.color(DEFAULT_SPECTRUM_COLOR, 'Spectrum Color', group=GROUP_GENERAL)
note = input.bool(true, 'v0.1.37')
// <function_declarations>
stripStarts(src, str) =>
strRegex = str.format('^{0}', str)
strMatch = str.match(src, strRegex)
strStripped = str.replace(src, strMatch, '')
strStripped
// <calculations>
isCrypto = syminfo.type == 'crypto'
hasPerpRoot = str.length(str.match(syminfo.root, '^[\\w]+\.[P|PERP]$')) > 0
hasPerpDesc = str.contains(syminfo.description, 'Perpetual')
isFutures = hasPerpRoot or hasPerpDesc
posUsdtPair = str.pos(syminfo.ticker, pairQuoteInput) // e.g. BTC(USDT.P)
posInstrumentSep = str.pos(syminfo.ticker, ":") // e.g. (BINANCE:)BTCUSDT.P
symbolSubstr = str.substring(syminfo.ticker, posInstrumentSep+1, posUsdtPair)
symbolStripped = stripStarts(stripStarts(stripStarts(symbolSubstr, '100000'), '10000'), '1000')
symbol = symbolStripped
ticker = str.format('{0}{1}{2}', symbol, pairQuoteInput, isFutures ? '' : '.P')
is100kMult = str.startswith(symbolSubstr, '100000')
is10kMult = str.startswith(symbolSubstr, '10000')
is1kMult = str.startswith(symbolSubstr, '1000')
multplier = is100kMult ? 100000 : is10kMult ? 10000 : is1kMult ? 1000 : 1
otherMarketClose = request.security(ticker, timeframe.period, close, gaps=barmerge.gaps_off)
higherClose = math.max(close, otherMarketClose)
priceDiff = (close - otherMarketClose) * -1
priceDiffNeg = priceDiff < 0
priceDiffPerc = math.abs(priceDiff) / higherClose * 100 / multplier
priceDiffPercStr = str.format('{1}{0,number,0.00}%', priceDiffPerc, priceDiffNeg ? '-' : '+')
//
// plot spectrum bars
//
// TODO: refactor
// Use gaps to only return data when the 1D timeframe completes, `na` otherwise.
[o, h, l, c] = request.security(ticker, timeframe.period, [open, high, low, close], gaps = barmerge.gaps_on)
// Only plot candles on intraday timeframes,
// and when non `na` values are returned by `request.security()` because a HTF has completed.
plotcandle(timeframe.isintraday ? o : na, h, l, c, "Spectrum Candles", color=spectrumColorInput, wickcolor=spectrumColorInput, bordercolor=spectrumColorInput, display=display.pane)
var line1 = line.new(bar_index, c, bar_index, c, extend=extend.both, color=spectrumColorInput, style=line.style_dotted, width=1)
line.set_y1(line1, c)
line.set_y2(line1, c)
line.set_x1(line1, bar_index)
line.set_x2(line1, bar_index+1)
// line.set_xloc(line1, time, time + 60 * 60 * 24, xloc.bar_time)
// <strategy_calls>
// <visuals>
hudInstance = tk.hudInit(positionInput, columns=2, bgcolor=chart.bg_color, textSize=textSizeInput, textColor=chart.fg_color)
if tk.isHudReady() and barstate.isrealtime
tk.hud(hudInstance, array.from(isFutures ? 'spot' : 'futures', str.tostring(priceDiffPercStr)))
// <alerts> |
Machine Learning: Support and Resistance [YinYangAlgorithms] | https://www.tradingview.com/script/hurudMoT-Machine-Learning-Support-and-Resistance-YinYangAlgorithms/ | YinYangAlgorithms | https://www.tradingview.com/u/YinYangAlgorithms/ | 135 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ .@@@@@@@@@@@@@@@ @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *@@@@@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@. @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@, @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@@@ @
// @@@@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@@ @@
// @@@@@@@@@@@@@@@@@@@@@@ @@@
// @@@@@@@@@@@@@@@@@@@@@* @@@@@ @@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@
// @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@% @@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@ %@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// ยฉ YinYangAlgorithms
//@version=5
indicator("Machine Learning Support and Resistance [YinYangAlgorithms]", overlay=true)
// ~~~~~~~~~~~ INPUTS ~~~~~~~~~~~ //
source = input.source(close, "Source", tooltip="This source is the base for all our calculations")
mlLength = input.int(100, "Machine Learning Length", minval=2, tooltip="How much projection data are we storing and using to make calculations")
smoothingLength = input.int(14, "Smoothing Length", minval=1, tooltip="We need to smooth calculations such as RSI, EMA and VWMA. What length are we smoothing it with.")
vwmaProjectionLength = input.int(1, "VWMA ML Projection Length", minval=1, tooltip="How far into our Machine Learning data should we average for our VWMA. Please note the 'Smoothing Length' is still applied here after getting the Projection Average.")
showLongTermMemory = input.string("Hard Line", "Long Term Memory", options=["Average", "Hard Line", "None"], tooltip="Long term memory has the same storage length but is only updated once per Machine Learning Length. For instance, if Machine Learning Length is 100, it will save the Average of our data once every 100 bars. This means its memory is an average of 10,000 bars of Machine Learning. 'Average' connects its values diagonally whereas 'Hard Line' holds its value until it changes.")
useAverageLastDistance = input.bool(false, "Use Average Last Distance In Potential Movement", tooltip="This can help accuracy but generally also displaces the Support and Resistance by projecting it further")
showCurrentProjection = input.bool(false, "Show Current Projection", tooltip="Projections occur for each bar, and our Machine Learning utilizes these projections by storing and evaluating them. This toggle will display the Current Projection Line which is used to create all our Projections.")
// ~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~ //
//Calculate the current bars projection
getCurrentProjection(_src, _rsi, _ma) =>
//Difference between source and MA
dif = _src - _ma
//Difference between last source and MA
prev = _src[1] - _ma[1]
//We need to know the direction the RSI is currently moving
prevRSI = _rsi - _rsi[1]
//The average over the last MM length so we know our relationship to it
avg = 0.
for i = 0 to mlLength - 1
avg += _src[i] - _ma[i]
avg := avg / mlLength
//get the absolute difference between our current values and the averages
avgDif = math.abs(dif) - math.abs(avg)
//calculate the average distance between our last 2 bars
avgLastDistance = math.avg(dif, prev)
//calculate our potential movement
potentialMovement = useAverageLastDistance ? avgDif + math.avg(avg, avgLastDistance) : avgDif + avg
//calculate our projection direction
projDir = 1.
if prev > 0
projDir += 0.05
else
projDir -= 0.05
if dif > avgDif
projDir += 0.05
else
projDir -= 0.05
if prevRSI > 0
projDir += 0.05
else
projDir -= 0.05
if (_rsi > 30 and _rsi[1] <= 30)
projDir += 0.1
else if (_rsi < 70 and _rsi[1] >= 70)
projDir -= 0.1
//calculate our projection mult
projMult = 1.
if (_rsi > 30 and _rsi[1] <= 30) or (_rsi < 70 and _rsi[1] >= 70)
projMult += 0.1
if dif > prev
projMult += 0.05
//apply mult to potential movement and create projection
projection = 0.
if projDir >= 1
projection := _src + (potentialMovement * projMult)
else
projection := _src - (potentialMovement * projMult)
//return projection
projection
//Calculate the Machine Learning projection over a given length with possible sorting
getProjection(_data, _length, _sorting) =>
//If specified, sort the data accordingly
if _sorting == "Ascending"
_data.sort(order.ascending)
else if _sorting == "Descending"
_data.sort(order.descending)
//Compute the average of the KNN (if sorted) or most recent data over a specified length
//If using sorting this allows it to compute its KNN over X length rather than a fixed KNN length
avg = 0.
for i = 0 to _length - 1
avg += array.get(_data, i)
avg / _length
// ~~~~~~~~~~~ CALCULATIONS ~~~~~~~~~~~ //
//our current values used to create projections
src = source[1]
rsi = ta.rsi(src, smoothingLength)
ma = ta.ema(src, smoothingLength)
//our projection of this bar
float projection = 0.
projection := getCurrentProjection(src, rsi, ma)
//save what the previous projections were
data = array.new_float(mlLength)
for i = 0 to mlLength - 1
data.set(i, projection[i])
//save long term memory
longTermMemory = array.new_float(mlLength)
if bar_index % mlLength == 0
longTermMemory.push(data.avg())
else if barstate.islast and showLongTermMemory == "Average"
longTermMemory.set(longTermMemory.size() - 1, data.avg())
//calculate projections with varying lengths
ltm = showLongTermMemory == "Average" ? longTermMemory.avg() : ta.sma(longTermMemory.avg(), 1)
avg = data.avg()
vwma = ta.vwma(getProjection(data, math.min(vwmaProjectionLength, mlLength), ""), smoothingLength)
strongSupport = getProjection(data, 2, "Ascending")
strongResistance = getProjection(data, 2, "Descending")
support = getProjection(data, math.max(mlLength / 10, 2), "Ascending")
resistance = getProjection(data, math.max(mlLength / 10, 2), "Descending")
// ~~~~~~~~~~~ PLOTS ~~~~~~~~~~~ //
plot(showCurrentProjection ? projection : na, color=color.white)
ss = plot(strongSupport, color=color.green)
sr = plot(strongResistance, color=color.red)
s = plot(support, color=color.new(color.green, 50))
r = plot(resistance, color=color.new(color.red, 50))
a = plot(avg, color=color.purple)
v = plot(vwma, color=color.blue)
plot(showLongTermMemory != "None" ? ltm : na, color=color.maroon)
fill(ss, s, color=color.new(color.green, 95))
fill(sr, r, color=color.new(color.red, 95))
midColor = vwma > avg ? color.green : color.red
fill(v, a, color=color.new(midColor, 95))
// ~~~~~~~~~~~ END ~~~~~~~~~~~ // |
Old Tradability by Kiersten & Haji | https://www.tradingview.com/script/X7UqfJBy-Old-Tradability-by-Kiersten-Haji/ | elicruz2380 | https://www.tradingview.com/u/elicruz2380/ | 15 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ hajjiplays
//This code is now available to the public. People may now copy and reuse the code in bigger projects.
//However this script property of NoGoodLuck LLC, and may not be copied or redistributed without credit to Elhadji Ouedrago or NoGoodLuck.
//@version=5
//VERY BEGINNING -------------------------------------------------------------------------------------------------------VERY BEGINNING//
//VERY BEGINNING -------------------------------------------------------------------------------------------------------VERY BEGINNING//
indicator("Old Tradability by Kiersten & Haji", overlay = false)
//SETTINGS ------------------------------------------------------------------------------------------------------------- SETTINGS//
//SETTINGS ------------------------------------------------------------------------------------------------------------- SETTINGS//
device = input.string("Computer", "Device", ["Computer", "Mobile"], group = "Basic Settings")
source = input.string("High / Low", "Source", ["High / Low", "Close"], group = "Basic Settings")
areanumber = input.int(8, "True Area Lookback Number", group = "Basic Settings")
lookback = 100
timeframes=input.timeframe("15","Normalization Timeframe", group = "Basic Settings")
takeprofit = input.string("Normalized Take Profit", "Take Profit Levels", ["Normalized Take Profit", "Kiersten Take Profit"], group = "Structure Settings")
stoploss = input.string("Normalized Stop Loss", "Stop Loss Levels", ["Normalized Stop Loss", "Kiersten Stop Loss"], group = "Structure Settings")
kierstenamount = input.int(1, title = "Kiersten Dynamic Bar Amount", group = "Structure Settings")
bias = input.string("Automatic", "Trend Direction", options = ["Automatic", "Bullish", "Bearish"], group = "Structure Settings")
UsePatterns = input.bool(false, "Use Patterns In Alerts", group = "Patterns")
patterns_short = input.timeframe('60', "Patterns Short Timeframe", group = "Patterns")
patterns_long = input.timeframe('240', "Patterns Long Timeframe", group = "Patterns")
useLongHeikinAshi = input.bool(true, "Use 4 Hour Heikin Ashi", group = "Considerations")
useWilliamAlligator = input.bool(true, "Use William Alligator", group = "Considerations")
useChandelierExit = input.bool(true, "Use Chandelier Exit", group = "Considerations")
useShortHeikinAshi = input.bool(true, "Use 1 Hour Heikin Ashi", group = "Considerations")
useMFI = input.bool(true, "Use MFI", group = "Considerations")
useMACD = input.bool(true, "Use MacD", group = "Considerations")
useEverything = input.bool(true, "Show Everything Crosses", group = "Considerations")
trueareaalertvalue = input.int(0, title = "True Area Score Alert Value", group = "Alerts")
normalizedvalue = input.int(50, "Normalization (Enter)", group = "Alerts")
normalizedmode = input.string("Automatic", "Normalization Mode", ["Automatic", "Manual"])
normalizedvaluetakeprofit = input.float(50, "Normalization (Take Profit)", group = "Alerts")
normalizedvaluestoploss = input.float(50, "Normalization (Stop Loss)", group = "Alerts")
positionSize = input.int(title="Position Size", defval=5, group = "Risk Management")
maxrisk = input.int(10000, "Maximum Risk", group = "Risk Management")
minreward = input.int(0, "Minmum Reward", group = "Risk Management")
minRRR = input.int(0, "Minmum Risk Reward Ratio", group = "Risk Management")
//END OF SETTINGS ------------------------------------------------------------------------------------------------------END OF SETTINGS//
//END OF SETTINGS ------------------------------------------------------------------------------------------------------END OF SETTINGS//
//SPEED CALCULATIONS ---------------------------------------------------------------------------------------------------SPEED CALCULATIONS//
//SPEED CALCULATIONS ---------------------------------------------------------------------------------------------------SPEED CALCULATIONS//
// Calculate the duration of a bar in seconds
// Calculate the difference in price between the current and previous bar
price1 = request.security(syminfo.tickerid, "1", close[2])
price2 = request.security(syminfo.tickerid, "1", close[1])
priceChange = math.abs(price1 - price2)
// Convert the price change to pips
priceChangeInPips = priceChange / syminfo.mintick
// Calculate the speed of the stock in pips per second
speed = priceChangeInPips
//END SPEED CALCULATIONS -----------------------------------------------------------------------------------------------END SPEED CALCULATIONS//
//END SPEED CALCULATIONS -----------------------------------------------------------------------------------------------END SPEED CALCULATIONS//
//HEIKIN ASHI CALCULATIONS ---------------------------------------------------------------------------------------------HEIKIN ASHI CALCULATIONS//
//HEIKIN ASHI CALCULATIONS ---------------------------------------------------------------------------------------------HEIKIN ASHI CALCULATIONS//
ha_t = ticker.heikinashi(syminfo.tickerid)
normal = ticker.new(syminfo.prefix, syminfo.tickerid)
resS = 'S'
ha_openS = request.security(ha_t, resS, open)
ha_closeS = request.security(ha_t, resS, close)
ha_difS = ha_openS - ha_closeS
iff_S = ha_difS < 0 ? 2 : 3
ha_diffS = ha_difS > 0 ? 1 : iff_S
res1 = '1'
ha_open1 = request.security(ha_t, res1, open)
ha_close1 = request.security(ha_t, res1, close)
ha_dif1 = ha_open1 - ha_close1
iff_1 = ha_dif1 < 0 ? 2 : 3
ha_diff1 = ha_dif1 > 0 ? 1 : iff_1
res3 = '3'
ha_open3 = request.security(ha_t, res3, open)
ha_close3 = request.security(ha_t, res3, close)
ha_dif3 = ha_open3 - ha_close3
iff_3 = ha_dif3 < 0 ? 2 : 3
ha_diff3 = ha_dif3 > 0 ? 1 : iff_3
res5 = '5'
ha_open5 = request.security(ha_t, res5, open)
ha_close5 = request.security(ha_t, res5, close)
ha_dif5 = ha_open5 - ha_close5
iff_5 = ha_dif5 < 0 ? 2 : 3
ha_diff5 = ha_dif5 > 0 ? 1 : iff_5
res15 = '15'
ha_open15 = request.security(ha_t, res15, open)
ha_close15 = request.security(ha_t, res15, close)
ha_dif15 = ha_open15 - ha_close15
iff_15 = ha_dif15 < 0 ? 2 : 3
ha_diff15 = ha_dif15 > 0 ? 1 : iff_15
res30 = '30'
ha_open30 = request.security(ha_t, res30, open)
ha_close30 = request.security(ha_t, res30, close)
ha_dif30 = ha_open30 - ha_close30
iff_30 = ha_dif30 < 0 ? 2 : 3
ha_diff30 = ha_dif30 > 0 ? 1 : iff_30
res60 = '60'
ha_open60 = request.security(ha_t, res60, open)
ha_close60 = request.security(ha_t, res60, close)
ha_dif60 = ha_open60 - ha_close60
iff_60 = ha_dif60 < 0 ? 2 : 3
ha_diff60 = ha_dif60 > 0 ? 1 : iff_60
res120 = '120'
ha_open120 = request.security(ha_t, res120, open)
ha_close120 = request.security(ha_t, res120, close)
ha_dif120 = ha_open120 - ha_close120
iff_120 = ha_dif120 < 0 ? 2 : 3
ha_diff120 = ha_dif120 > 0 ? 1 : iff_120
res180 = '180'
ha_open180 = request.security(ha_t, res180, open)
ha_close180 = request.security(ha_t, res180, close)
ha_dif180 = ha_open180 - ha_close180
iff_180 = ha_dif180 < 0 ? 2 : 3
ha_diff180 = ha_dif180 > 0 ? 1 : iff_180
res240 = '240'
ha_open240 = request.security(ha_t, res240, open)
ha_close240 = request.security(ha_t, res240, close)
ha_dif240 = ha_open240 - ha_close240
iff_240 = ha_dif240 < 0 ? 2 : 3
ha_diff240 = ha_dif240 > 0 ? 1 : iff_240
resD = 'D'
ha_openD = request.security(ha_t, resD, open)
ha_closeD = request.security(ha_t, resD, close)
ha_difD = ha_openD - ha_closeD
iff_D = ha_difD < 0 ? 2 : 3
ha_diffD = ha_difD > 0 ? 1 : iff_D
resshort = patterns_short
ha_openshort = request.security(ha_t, resshort, open)
ha_closeshort = request.security(ha_t, resshort, close)
ha_difshort = ha_openshort - ha_closeshort
iff_short = ha_difshort < 0 ? 2 : 3
ha_diffshort = ha_difshort > 0 ? 1 : iff_short
reslong = patterns_long
ha_openlong = request.security(ha_t, reslong, open)
ha_closelong = request.security(ha_t, reslong, close)
ha_diflong = ha_openlong - ha_closelong
iff_long = ha_diflong < 0 ? 2 : 3
ha_difflong = ha_diflong > 0 ? 1 : iff_long
//END OF HEIKIN ASHI CALCULATIONS --------------------------------------------------------------------------------------END OF HEIKIN ASHI CALCULATIONS//
//END OF HEIKIN ASHI CALCULATIONS --------------------------------------------------------------------------------------END OF HEIKIN ASHI CALCULATIONS//
//PATTERN DETECTION ----------------------------------------------------------------------------------------------------PATTERN DETECTION//
//PATTERN DETECTION ----------------------------------------------------------------------------------------------------PATTERN DETECTION//
trend = 'Consolidation'
if ha_diffshort == 2 and ha_difflong == 2
trend := 'Bullish'
if ha_diffshort == 1 and ha_difflong == 1
trend := 'Bearish'
if ha_diffshort[2] == 1 and ha_diffshort[1] == 1 and ha_diffshort == 1 and ha_difflong[2] == 2 and ha_difflong[1] == 2 and ha_difflong == 2
trend := 'Consolidation'
if ha_diffshort[2] == 2 and ha_diffshort[1] == 2 and ha_diffshort == 2 and ha_difflong[2] == 1 and ha_difflong[1] == 1 and ha_difflong == 1
trend := 'Consolidation'
if ha_diffshort[1] == 1 and ha_diffshort == 2 and ha_difflong[1] == 1 and ha_difflong == 2
trend := 'Double Up'
if ha_diffshort[2] == 1 and ha_diffshort[1] == 2 and ha_difflong[2] == 1 and ha_difflong[1] == 2 and ha_diffshort == 2 and ha_difflong == 2
trend := 'Double Up Confirmed'
if ha_diffshort[2] == 1 and ha_diffshort[1] == 2 and ha_difflong[2] == 1 and ha_difflong[1] == 2 and ha_diffshort == 1 and ha_difflong == 1
trend := 'Double Up Declined'
if ha_diffshort[1] == 2 and ha_diffshort == 1 and ha_difflong[1] == 2 and ha_difflong == 1
trend := 'Double Down'
if ha_diffshort[2] == 2 and ha_diffshort[1] == 1 and ha_difflong[2] == 2 and ha_difflong[1] == 1 and ha_diffshort == 1 and ha_difflong == 1
trend := 'Double Down Confirmed'
if ha_diffshort[2] == 2 and ha_diffshort[1] == 1 and ha_difflong[2] == 2 and ha_difflong[1] == 1 and ha_diffshort == 2 and ha_difflong == 2
trend := 'Double Down Declined'
if ha_diffshort[1] == 1 and ha_diffshort == 2 and ha_difflong[1] == 2 and ha_difflong == 2
trend := 'Bullish Continuation'
if ha_diffshort[2] == 1 and ha_diffshort[1] == 2 and ha_difflong[2] == 2 and ha_difflong[1] == 2 and ha_diffshort == 2 and ha_difflong == 2
trend := 'Bullish Continuation Confirmed'
if ha_diffshort[2] == 1 and ha_diffshort[1] == 2 and ha_difflong[2] == 2 and ha_difflong[1] == 2 and ha_diffshort == 1 and ha_difflong == 2
trend := 'Bullish Continuation Declined'
if ha_diffshort[1] == 2 and ha_diffshort == 1 and ha_difflong[1] == 1 and ha_difflong == 1
trend := 'Bearish Continuation'
if ha_diffshort[2] == 2 and ha_diffshort[1] == 1 and ha_difflong[2] == 1 and ha_difflong[1] == 1 and ha_diffshort == 1 and ha_difflong == 1
trend := 'Bearish Continuation Confirmed'
if ha_diffshort[2] == 2 and ha_diffshort[1] == 1 and ha_difflong[2] == 1 and ha_difflong[1] == 1 and ha_diffshort == 2 and ha_difflong == 1
trend := 'Bearish Continuation Declined'
if ha_difflong[1] == 1 and ha_difflong == 2 and ha_diffshort[1] == 2 and ha_diffshort == 2
trend := 'Bullish Break'
if ha_difflong[2] == 1 and ha_difflong[1] == 2 and ha_diffshort[2] == 2 and ha_diffshort[1] == 2 and ha_diffshort == 2 and ha_difflong == 2
trend := 'Bullish Break Confirmed'
if ha_difflong[2] == 1 and ha_difflong[1] == 2 and ha_diffshort[2] == 2 and ha_diffshort[1] == 2 and ha_diffshort == 1 and ha_difflong == 2
trend := 'Bullish Break Declined'
if ha_difflong[2] == 1 and ha_difflong[1] == 2 and ha_diffshort[2] == 2 and ha_diffshort[1] == 2 and ha_diffshort == 2 and ha_difflong == 1
trend := 'Bullish Break Declined'
if ha_difflong[1] == 2 and ha_difflong == 1 and ha_diffshort[1] == 1 and ha_diffshort == 1
trend := 'Bearish Break'
if ha_difflong[2] == 2 and ha_difflong[1] == 1 and ha_diffshort[2] == 1 and ha_diffshort[1] == 1 and ha_diffshort == 1 and ha_difflong == 1
trend := 'Bearish Break Confirmed'
if ha_difflong[2] == 2 and ha_difflong[1] == 1 and ha_diffshort[2] == 1 and ha_diffshort[1] == 1 and ha_diffshort == 2 and ha_difflong == 1
trend := 'Bearish Break Declined'
if ha_difflong[2] == 2 and ha_difflong[1] == 1 and ha_diffshort[2] == 1 and ha_diffshort[1] == 1 and ha_diffshort == 1 and ha_difflong == 2
trend := 'Bearish Break Declined'
if ha_diffshort == 2 and ha_difflong[1] == 2 and ha_difflong == 1 or ha_diffshort == 2 and ha_difflong[2] == 2 and ha_difflong == 1
trend := 'Bullish Trend Swapping'
if ha_diffshort[1] == 2 and ha_difflong[2] == 2 and ha_difflong[1] == 1 or ha_diffshort[1] == 2 and ha_difflong[3] == 2 and ha_difflong[1] == 1 and ha_diffshort == 2 and ha_difflong == 2
trend := 'Bullish Trend Swapping Confirmed'
if ha_diffshort[1] == 2 and ha_difflong[2] == 2 and ha_difflong[1] == 1 or ha_diffshort[1] == 2 and ha_difflong[3] == 2 and ha_difflong[1] == 1 and ha_diffshort == 1 and ha_difflong == 1
trend := 'Bullish Trend Swapping Declined'
if ha_diffshort == 1 and ha_difflong[1] == 1 and ha_difflong == 2 or ha_diffshort == 1 and ha_difflong[2] == 1 and ha_difflong == 2
trend := 'Bearish Trend Swapping'
if ha_diffshort[1] == 1 and ha_difflong[2] == 1 and ha_difflong[1] == 2 or ha_diffshort[1] == 1 and ha_difflong[3] == 1 and ha_difflong[1] == 2 and ha_diffshort == 1 and ha_difflong == 1
trend := 'Bearish Trend Swapping Confirmed'
if ha_diffshort[1] == 1 and ha_difflong[2] == 1 and ha_difflong[1] == 2 or ha_diffshort[1] == 1 and ha_difflong[3] == 1 and ha_difflong[1] == 2 and ha_diffshort == 2 and ha_difflong == 2
trend := 'Bearish Trend Swapping Declined'
trendcolor = color.rgb(224, 224, 224)
if ha_diffshort == 2 and ha_difflong == 2
trendcolor := color.green
if ha_diffshort == 1 and ha_difflong == 1
trendcolor := color.red
if trend == 'Double Up Declined' or trend == 'Bullish Continuation Declined' or trend == 'Bullish Break Declined' or trend == 'Bullish Trend Swapping Declined'
trendcolor := color.red
if trend == 'Double Down Declined' or trend == 'Bearish Continuation Declined' or trend == 'Bearish Break Declined' or trend == 'Bearish Trend Swapping Declined'
trendcolor := color.green
if trend == 'Bullish Trend Swapping'
trendcolor := color.green
if trend == 'Bearish Trend Swapping'
trendcolor := color.red
//END OF PATTERN DETECTION ---------------------------------------------------------------------------------------------END OF PATTERN DETECTION//
//END OF PATTERN DETECTION ---------------------------------------------------------------------------------------------END OFPATTERN DETECTION//
//PATTERN WIN RATE CALCULATION -----------------------------------------------------------------------------------------PATTERN WIN RATE CALCULATION//
//PATTERN WIN RATE CALCULATION -----------------------------------------------------------------------------------------PATTERN WIN RATE CALCULATION//
currentConversion = 0.0
backtracknumber = 3
arrownumber = 2
DoubleUpSuccess = 0.0
DoubleUpFail = 0.0
if trend == 'Double Up'
for i = arrownumber to backtracknumber
if trend[i] == 'Double Up'
if close[i - arrownumber] < close[i]
DoubleUpSuccess := DoubleUpSuccess + 1
else
DoubleUpFail := DoubleUpFail + 1
DoubleUpConversion = DoubleUpSuccess / (DoubleUpSuccess + DoubleUpFail)
DoubleUpConfirmedSuccess = 0.0
DoubleUpConfirmedFail = 0.0
if trend == 'Double Up Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Double Up Confirmed'
if close[i - arrownumber] < close[i]
DoubleUpConfirmedSuccess := DoubleUpConfirmedSuccess + 1
else
DoubleUpConfirmedFail := DoubleUpConfirmedFail + 1
DoubleUpConfirmedConversion = DoubleUpConfirmedSuccess / (DoubleUpConfirmedSuccess + DoubleUpConfirmedFail)
DoubleDownDeclinedSuccess = 0.0
DoubleDownDeclinedFail = 0.0
if trend == 'Double Down Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Double Down Declined'
if close[i - arrownumber] < close[i]
DoubleDownDeclinedSuccess := DoubleDownDeclinedSuccess + 1
else
DoubleDownDeclinedFail := DoubleDownDeclinedFail + 1
DoubleDownDeclinedConversion = DoubleDownDeclinedSuccess / (DoubleDownDeclinedSuccess + DoubleDownDeclinedFail)
BullishContinuationSuccess = 0.0
BullishContinuationFail = 0.0
if trend == 'Bullish Continuation'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Continuation'
if close[i - arrownumber] < close[i]
BullishContinuationSuccess := BullishContinuationSuccess + 1
else
BullishContinuationFail := BullishContinuationFail + 1
BullishContinuationConversion = BullishContinuationSuccess / (BullishContinuationSuccess + BullishContinuationFail)
BullishContinuationConfirmedSuccess = 0.0
BullishContinuationConfirmedFail = 0.0
if trend == 'Bullish Continuation Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Continuation Confirmed'
if close[i - arrownumber] < close[i]
BullishContinuationConfirmedSuccess := BullishContinuationConfirmedSuccess + 1
else
BullishContinuationConfirmedFail := BullishContinuationConfirmedFail + 1
BullishContinuationConfirmedConversion = BullishContinuationConfirmedSuccess / (BullishContinuationConfirmedSuccess + BullishContinuationConfirmedFail)
BearishContinuationDeclinedSuccess = 0.0
BearishContinuationDeclinedFail = 0.0
if trend == 'Bearish Continuation Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Continuation Declined'
if close[i - arrownumber] < close[i]
BearishContinuationDeclinedSuccess := BearishContinuationDeclinedSuccess + 1
else
BearishContinuationDeclinedFail := BearishContinuationDeclinedFail + 1
BearishContinuationDeclinedConversion = BearishContinuationDeclinedSuccess / (BearishContinuationDeclinedSuccess + BearishContinuationDeclinedFail)
BullishBreakSuccess = 0.0
BullishBreakFail = 0.0
if trend == 'Bullish Break'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Break'
if close[i - arrownumber] < close[i]
BullishBreakSuccess := BullishBreakSuccess + 1
else
BullishBreakFail := BullishBreakFail + 1
BullishBreakConversion = BullishBreakSuccess / (BullishBreakSuccess + BullishBreakFail)
BullishBreakConfirmedSuccess = 0.0
BullishBreakConfirmedFail = 0.0
if trend == 'Bullish Break Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Break Confirmed'
if close[i - arrownumber] < close[i]
BullishBreakConfirmedSuccess := BullishBreakConfirmedSuccess + 1
else
BullishBreakConfirmedFail := BullishBreakConfirmedFail + 1
BullishBreakConfirmedConversion = BullishBreakConfirmedSuccess / (BullishBreakConfirmedSuccess + BullishBreakConfirmedFail)
BearishBreakDeclinedSuccess = 0.0
BearishBreakDeclinedFail = 0.0
if trend == 'Bearish Break Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Break Declined'
if close[i - arrownumber] < close[i]
BearishBreakDeclinedSuccess := BearishBreakDeclinedSuccess + 1
else
BearishBreakDeclinedFail := BearishBreakDeclinedFail + 1
BearishBreakDeclinedConversion = BearishBreakDeclinedSuccess / (BearishBreakDeclinedSuccess + BearishBreakDeclinedFail)
BullishTrendSwappingSuccess = 0.0
BullishTrendSwappingFail = 0.0
if trend == 'Bullish Trend Swapping'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Trend Swapping'
if close[i - arrownumber] < close[i]
BullishTrendSwappingSuccess := BullishTrendSwappingSuccess + 1
else
BullishTrendSwappingFail := BullishTrendSwappingFail + 1
BullishTrendSwappingConversion = BullishTrendSwappingSuccess / (BullishTrendSwappingSuccess + BullishTrendSwappingFail)
BullishTrendSwappingConfirmedSuccess = 0.0
BullishTrendSwappingConfirmedFail = 0.0
if trend == 'Bullish Trend Swapping Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Trend Swapping Confirmed'
if close[i - arrownumber] < close[i]
BullishTrendSwappingConfirmedSuccess := BullishTrendSwappingConfirmedSuccess + 1
else
BullishTrendSwappingConfirmedFail := BullishTrendSwappingConfirmedFail + 1
BullishTrendSwappingConfirmedConversion = BullishTrendSwappingConfirmedSuccess / (BullishTrendSwappingConfirmedSuccess + BullishTrendSwappingConfirmedFail)
BearishTrendSwappingDeclinedSuccess = 0.0
BearishTrendSwappingDeclinedFail = 0.0
if trend == 'Bearish Trend Swapping Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Trend Swapping Declined'
if close[i - arrownumber] < close[i]
BearishTrendSwappingDeclinedSuccess := BearishTrendSwappingDeclinedSuccess + 1
else
BearishTrendSwappingDeclinedFail := BearishTrendSwappingDeclinedFail + 1
BearishTrendSwappingDeclinedConversion = BearishTrendSwappingDeclinedSuccess / (BearishTrendSwappingDeclinedSuccess + BearishTrendSwappingDeclinedFail)
DoubleDownSuccess = 0.0
DoubleDownFail = 0.0
if trend == 'Double Down'
for i = arrownumber to backtracknumber
if trend[i] == 'Double Down'
if close[i - arrownumber] > close[i]
DoubleDownSuccess := DoubleDownSuccess + 1
else
DoubleDownFail := DoubleDownFail + 1
DoubleDownConversion = DoubleDownSuccess / (DoubleDownSuccess + DoubleDownFail)
DoubleUpDeclinedSuccess = 0.0
DoubleUpDeclinedFail = 0.0
if trend == 'Double Up Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Double Up Declined'
if close[i - arrownumber] < close[i]
DoubleUpDeclinedSuccess := DoubleUpDeclinedSuccess + 1
else
DoubleUpDeclinedFail := DoubleUpDeclinedFail + 1
DoubleUpDeclinedConversion = DoubleUpDeclinedSuccess / (DoubleUpDeclinedSuccess + DoubleUpDeclinedFail)
DoubleDownConfirmedSuccess = 0.0
DoubleDownConfirmedFail = 0.0
if trend == 'Double Down Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Double Down Confirmed'
if close[i - arrownumber] > close[i]
DoubleDownConfirmedSuccess := DoubleDownConfirmedSuccess + 1
else
DoubleDownConfirmedFail := DoubleDownConfirmedFail + 1
DoubleDownConfirmedConversion = DoubleDownConfirmedSuccess / (DoubleDownConfirmedSuccess + DoubleDownConfirmedFail)
BearishContinuationSuccess = 0.0
BearishContinuationFail = 0.0
if trend == 'Bearish Continuation'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Continuation'
if close[i - arrownumber] > close[i]
BearishContinuationSuccess := BearishContinuationSuccess + 1
else
BearishContinuationFail := BearishContinuationFail + 1
BearishContinuationConversion = BearishContinuationSuccess / (BearishContinuationSuccess + BearishContinuationFail)
BearishContinuationConfirmedSuccess = 0.0
BearishContinuationConfirmedFail = 0.0
if trend == 'Bearish Continuation Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Continuation Confirmed'
if close[i - arrownumber] > close[i]
BearishContinuationConfirmedSuccess := BearishContinuationConfirmedSuccess + 1
else
BearishContinuationConfirmedFail := BearishContinuationConfirmedFail + 1
BearishContinuationConfirmedConversion = BearishContinuationConfirmedSuccess / (BearishContinuationConfirmedSuccess + BearishContinuationConfirmedFail)
BullishContinuationDeclinedSuccess = 0.0
BullishContinuationDeclinedFail = 0.0
if trend == 'Bullish Continuation Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Continuation Declined'
if close[i - arrownumber] > close[i]
BullishContinuationDeclinedSuccess := BullishContinuationDeclinedSuccess + 1
else
BullishContinuationDeclinedFail := BullishContinuationDeclinedFail + 1
BullishContinuationDeclinedConversion = BullishContinuationDeclinedSuccess / (BullishContinuationDeclinedSuccess + BullishContinuationDeclinedFail)
BearishBreakSuccess = 0.0
BearishBreakFail = 0.0
if trend == 'Bearish Break'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Break'
if close[i - arrownumber] > close[i]
BearishBreakSuccess := BearishBreakSuccess + 1
else
BearishBreakFail := BearishBreakFail + 1
BearishBreakConversion = BearishBreakSuccess / (BearishBreakSuccess + BearishBreakFail)
BearishBreakConfirmedSuccess = 0.0
BearishBreakConfirmedFail = 0.0
if trend == 'Bearish Break Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Break Confirmed'
if close[i - arrownumber] > close[i]
BearishBreakConfirmedSuccess := BearishBreakConfirmedSuccess + 1
else
BearishBreakConfirmedFail := BearishBreakConfirmedFail + 1
BearishBreakConfirmedConversion = BearishBreakConfirmedSuccess / (BearishBreakConfirmedSuccess + BearishBreakConfirmedFail)
BullishBreakDeclinedSuccess = 0.0
BullishBreakDeclinedFail = 0.0
if trend == 'Bullish Break Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Break Declined'
if close[i - arrownumber] > close[i]
BullishBreakDeclinedSuccess := BullishBreakDeclinedSuccess + 1
else
BullishBreakDeclinedFail := BullishBreakDeclinedFail + 1
BullishBreakDeclinedConversion = BullishBreakDeclinedSuccess / (BullishBreakDeclinedSuccess + BullishBreakDeclinedFail)
BearishTrendSwappingSuccess = 0.0
BearishTrendSwappingFail = 0.0
if trend == 'Bearish Trend Swapping'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Trend Swapping'
if close[i - arrownumber] > close[i]
BearishTrendSwappingSuccess := BearishTrendSwappingSuccess + 1
else
BearishTrendSwappingFail := BearishTrendSwappingFail + 1
BearishTrendSwappingConversion = BearishTrendSwappingSuccess / (BearishTrendSwappingSuccess + BearishTrendSwappingFail)
BearishTrendSwappingConfirmedSuccess = 0.0
BearishTrendSwappingConfirmedFail = 0.0
if trend == 'Bearish Trend Swapping Confirmed'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish Trend Swapping Confirmed'
if close[i - arrownumber] > close[i]
BearishTrendSwappingConfirmedSuccess := BearishTrendSwappingConfirmedSuccess + 1
else
BearishTrendSwappingConfirmedFail := BearishTrendSwappingConfirmedFail + 1
BearishTrendSwappingConfirmedConversion = BearishTrendSwappingConfirmedSuccess / (BearishTrendSwappingConfirmedSuccess + BearishTrendSwappingConfirmedFail)
BullishTrendSwappingDeclinedSuccess = 0.0
BullishTrendSwappingDeclinedFail = 0.0
if trend == 'Bullish Trend Swapping Declined'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish Trend Swapping Declined'
if close[i - arrownumber] > close[i]
BullishTrendSwappingDeclinedSuccess := BullishTrendSwappingDeclinedSuccess + 1
else
BullishTrendSwappingDeclinedFail := BullishTrendSwappingDeclinedFail + 1
BullishTrendSwappingDeclinedConversion = BullishTrendSwappingDeclinedSuccess / (BullishTrendSwappingDeclinedSuccess + BullishTrendSwappingDeclinedFail)
BullishSuccess = 0.0
BullishFail = 0.0
if trend == 'Bullish'
for i = arrownumber to backtracknumber
if trend[i] == 'Bullish'
if close[i - arrownumber] > close[i]
BullishSuccess := BullishSuccess + 1
else
BullishFail := BullishFail + 1
BullishConversion = BullishSuccess / (BullishSuccess + BullishFail)
BearishSuccess = 0.0
BearishFail = 0.0
if trend == 'Bearish'
for i = arrownumber to backtracknumber
if trend[i] == 'Bearish'
if close[i - arrownumber] > close[i]
BearishSuccess := BearishSuccess + 1
else
BearishFail := BearishFail + 1
BearishConversion = BearishSuccess / (BearishSuccess + BearishFail)
if trend == "Double Up"
currentConversion := DoubleUpConversion
if trend == "Double Up Confirmed"
currentConversion := DoubleUpConfirmedConversion
if trend == "Double Up Declined"
currentConversion := DoubleUpDeclinedConversion
if trend == "Double Down"
currentConversion := DoubleDownConversion
if trend == "Double Down Confirmed"
currentConversion := DoubleDownConfirmedConversion
if trend == "Double Down Declined"
currentConversion := DoubleDownDeclinedConversion
if trend == "Bullish Continuation"
currentConversion := BullishContinuationConversion
if trend == "Bullish Continuation Confirmed"
currentConversion := BullishContinuationConfirmedConversion
if trend == "Bullish Continuation Declined"
currentConversion := BullishContinuationDeclinedConversion
if trend == "Bearish Continuation"
currentConversion := BearishContinuationConversion
if trend == "Bearish Continuation Confirmed"
currentConversion := BearishContinuationConfirmedConversion
if trend == "Bearish Continuation Declined"
currentConversion := BearishContinuationDeclinedConversion
if trend == "Bullish Break"
currentConversion := BullishBreakConversion
if trend == "Bullish Break Confirmed"
currentConversion := BullishBreakConfirmedConversion
if trend == "Bullish Break Declined"
currentConversion := BullishBreakDeclinedConversion
if trend == "Bearish Break"
currentConversion := BearishBreakConversion
if trend == "Bearish Break Confirmed"
currentConversion := BearishBreakConfirmedConversion
if trend == "Bearish Break Declined"
currentConversion := BearishBreakDeclinedConversion
if trend == "Bullish Trend Swapping"
currentConversion := BullishTrendSwappingConversion
if trend == "Bullish Trend Swapping Confirmed"
currentConversion := BullishBreakConfirmedConversion
if trend == "Bullish Trend Swapping Declined"
currentConversion := BullishBreakDeclinedConversion
if trend == "Bearish Trend Swapping"
currentConversion := BearishTrendSwappingConversion
if trend == "Bearish Trend Swapping Confirmed"
currentConversion := BearishBreakConfirmedConversion
if trend == "Bearish Trend Swapping Declined"
currentConversion := BearishBreakDeclinedConversion
if trend == "Bullish"
currentConversion := BullishConversion
if trend == "Bearish"
currentConversion := BearishConversion
patterwinrate = (currentConversion * 1.5) * 100
//WILLIAMS ALLIGATOR CALCULATIONS --------------------------------------------------------------------------------------WILLIAMS ALLIGATOR CALCULATIONS//
//WILLIAMS ALLIGATOR CALCULATIONS --------------------------------------------------------------------------------------WILLIAMS ALLIGATOR CALCULATIONS//
smma(src, length) =>
smma = 0.0
smma := na(smma[1]) ? ta.sma(src, length) : (smma[1] * (length - 1) + src) / length
smma
jawLength = 13
teethLength = 8
lipsLength = 5
jawOffset = 8
teethOffset = 5
lipsOffset = 3
jaw = smma(request.security(syminfo.tickerid, '15', hl2), jawLength)
teeth = smma(request.security(syminfo.tickerid, '15', hl2), teethLength)
lips = smma(request.security(syminfo.tickerid, '15', hl2), lipsLength)
williamsalligator = " Williams Alligator is Mixed"
if lips > teeth and lips > jaw and jaw < teeth
williamsalligator := "Williams Alligator is Bullish โ"
if lips < teeth and lips < jaw and jaw > teeth
williamsalligator := "Williams Alligator is Bearish โ"
//END OF WILLIAMS ALLIGATOR CALCULATIONS -------------------------------------------------------------------------------END OF WILLIAMS ALLIGATOR CALCULATIONS//
//END OF WILLIAMS ALLIGATOR CALCULATIONS --------------------------------------------------------------------------------END OF WILLIAMS ALLIGATOR CALCULATIONS//
////QUALITY CALCULATION ------------------------------------------------------------------------------------------------//QUALITY CALCULATION//
////QUALITY CALCULATION ------------------------------------------------------------------------------------------------//QUALITY CALCULATION//
fifteenclose200 = (request.security(syminfo.tickerid, timeframes, ta.sma(request.security(syminfo.tickerid, timeframes, close), 200)))
fifteenclose50 = (request.security(syminfo.tickerid, timeframes, ta.sma(request.security(syminfo.tickerid, timeframes, close), 50)))
fifteenclose9 = (request.security(syminfo.tickerid, timeframes, ta.sma(request.security(syminfo.tickerid, timeframes, close), 9)))
purequality = (((math.abs(close - fifteenclose200) * 8) + (math.abs(close - fifteenclose50) * 4) + (math.abs(close - fifteenclose9) * 2)))
currentquality = purequality[0]
rankedquality = 1
for i = 1 to 10
if purequality[i] > currentquality
rankedquality := rankedquality + 1
quality = ((rankedquality - 1) * 100) / 1000
//END OF QUALITY CALCULATION -------------------------------------------------------------------------------------------//END OF QUALITY CALCULATION//
//END OF QUALITY CALCULATION -------------------------------------------------------------------------------------------//END OF QUALITY CALCULATION//
//CHANDLIERS EXIT CALCULATION ------------------------------------------------------------------------------------------//CHANDLIERS EXIT CALCULATION//
//CHANDLIERS EXIT CALCULATION ------------------------------------------------------------------------------------------//CHANDLIERS EXIT CALCULATION//
lengthce = 4
multce = 2.0
showLabels = true
useClose = true
highlightState = true
atr = multce * ta.atr(lengthce)
longStop = (useClose ? ta.highest(close, lengthce) : ta.highest(lengthce)) - atr
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = (useClose ? ta.lowest(close, lengthce) : ta.lowest(lengthce)) + atr
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
var int dir = 1
dir := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dir
//END OF CHANDLIERS EXIT CALCULATION -----------------------------------------------------------------------------------//END OF CHANDLIERS EXIT CALCULATION//
//END OF CHANDLIERS EXIT CALCULATION -----------------------------------------------------------------------------------//END OF CHANDLIERS EXIT CALCULATION//
//CUSTOM MACD CALCULATION ----------------------------------------------------------------------------------------------//CUSTOM MACD CALCULATION//
//CUSTOM MACD CALCULATION ----------------------------------------------------------------------------------------------//CUSTOM MACD CALCULATION//
[macd, signal, histo] = ta.macd(close, 12, 26, 9)
bigtime = ''
mediumtime = ''
smalltime = ''
if histo > 0
bigtime := 'โฌ'
if histo < 0
bigtime := 'โฌ'
[macdm, signalm, histom] = request.security(syminfo.tickerid, '15', ta.macd(close, 12, 26, 9))
if histom > 0
mediumtime := 'โฌ'
if histom < 0
mediumtime := 'โฌ'
[macds, signals, histos] = request.security(syminfo.tickerid, '5', ta.macd(close, 12, 26, 9))
if histos > 0
smalltime := 'โฌ'
if histos < 0
smalltime := 'โฌ'
//END OF CUSTOM MACD CALCULATION ---------------------------------------------------------------------------------------//END OF CUSTOM MACD CALCULATION//
//END OF CUSTOM MACD CALCULATION ---------------------------------------------------------------------------------------//END OF CUSTOM MACD CALCULATION//
//CUSTOM MFI CALCULATION -----------------------------------------------------------------------------------------------//CUSTOM MFI CALCULATION//
//CUSTOM MFI CALCULATION -----------------------------------------------------------------------------------------------//CUSTOM MFI CALCULATION//
five_minute_MFI = request.security(syminfo.tickerid, '5', ta.mfi(hlc3, 14))
fifteen_minute_MFI = request.security(syminfo.tickerid, '5', ta.mfi(hlc3, 14))
one_hour_MFI = request.security(syminfo.tickerid, '60', ta.mfi(hlc3, 14))
if five_minute_MFI > 80
smalltime := 'โฌ'
if five_minute_MFI < 20
smalltime := 'โฌ'
if fifteen_minute_MFI > 80
mediumtime := 'โฌ'
if fifteen_minute_MFI < 20
mediumtime := 'โฌ'
if one_hour_MFI > 80
bigtime := 'โฌ'
if one_hour_MFI < 20
bigtime := 'โฌ'
//END OF CUSTOM MFI CALCULATION ----------------------------------------------------------------------------------------//END OF CUSTOM MFI CALCULATION//
//END OF CUSTOM MFI CALCULATION ----------------------------------------------------------------------------------------//END OF CUSTOM MFI CALCULATION//
//TRUE AREA CALCULATION -----------------------------------------------------------------------------------------------//TRUE AREA CALCULATION//
//TRUE AREA CALCULATION -----------------------------------------------------------------------------------------------//TRUE AREA CALCULATION//
MACDTRADEBUY = smalltime == 'โฌ' and bigtime == 'โฌ' and mediumtime == 'โฌ' and (useMACD)
MACDTRADESELL = smalltime == 'โฌ' and bigtime == 'โฌ' and mediumtime == 'โฌ' and (useMACD)
fourhourHeikinAshibuy = ha_diff240 == 2 and (useLongHeikinAshi)
fourhourHeikinAshisell = ha_diff240 == 1 and (useLongHeikinAshi)
WilliamsAlligatorBuy = williamsalligator == "Williams Alligator is Bullish โ" and (useWilliamAlligator)
WilliamsAlligatorSell = williamsalligator == "Williams Alligator is Bearish โ" and (useWilliamAlligator)
ChandelierBuy = dir == 1 and (useChandelierExit)
ChandelierSell = dir == -1 and (useChandelierExit)
onehourHeikinAshiBuy = ha_diff60 == 2 and (useShortHeikinAshi)
onehourHeikinAshiSell = ha_diff60 == 1 and (useShortHeikinAshi)
MFIbuy = ta.mfi(close, 14)[2] <= 30 and (useMFI)
MFIsell = ta.mfi(close, 14)[2] >= 70 and (useMFI)
buyarea = 0.0
sellarea = 0.0
for i = 0 to areanumber
if fourhourHeikinAshibuy[i]
buyarea += 1
if fourhourHeikinAshisell[i]
sellarea += 1
if WilliamsAlligatorBuy[i]
buyarea += 1
if WilliamsAlligatorSell[i]
sellarea += 1
if ChandelierBuy[i]
buyarea += 1
if ChandelierSell[i]
sellarea += 1
if onehourHeikinAshiBuy[i]
buyarea += 1
if onehourHeikinAshiSell[i]
sellarea += 1
if MFIbuy[i]
buyarea += 1
if MFIsell[i]
sellarea += 1
if MACDTRADEBUY[i]
buyarea += 1
if MACDTRADESELL[i]
sellarea += 1
truearea = (buyarea / ((areanumber + 1) * 6)) * 100
areatrend = 'โโโ'
if sellarea > buyarea
truearea := (sellarea / ((areanumber + 1) * 6)) * 100
areatrend := 'โโโ'
//END OF TRUE AREA CALCULATION -----------------------------------------------------------------------------------------//END OF TRUE AREA CALCULATION//
//END OF TRUE AREA CALCULATION -----------------------------------------------------------------------------------------//END OF TRUE AREA CALCULATION//
//TREND AREA BAR -------------------------------------------------------------------------------------------------------//TREND AREA BAR//
//TREND AREA BAR -------------------------------------------------------------------------------------------------------//TREND AREA BAR//
BUY = buyarea > sellarea
SELL = buyarea < sellarea
if bias == "Bullish"
BUY := true
SELL := false
if bias == "Bearish"
SELL := true
BUY := false
barinnercolor_trueareabar = color.gray
if buyarea > sellarea
barinnercolor_trueareabar := color.rgb(76, 175, 79, 20)
if buyarea < sellarea
barinnercolor_trueareabar := color.rgb(255, 82, 82, 20)
baroutercolor_trueareabar = color.gray
if buyarea > sellarea
baroutercolor_trueareabar := color.green
if buyarea < sellarea
baroutercolor_trueareabar := color.red
defaultcolor = color.rgb(255, 255, 255, 100)
trueareacolor1 = defaultcolor
trueareacolor2 = defaultcolor
trueareacolor3 = defaultcolor
trueareacolor4 = defaultcolor
trueareacolor5 = defaultcolor
trueareacolor6 = defaultcolor
trueareacolor7 = defaultcolor
trueareacolor8 = defaultcolor
trueareacolor9 = defaultcolor
trueareacolor10 = defaultcolor
trueareacolor11 = defaultcolor
trueareacolor12 = defaultcolor
trueareacolor13 = defaultcolor
trueareacolor14 = defaultcolor
trueareacolor15 = defaultcolor
trueareacolor16 = defaultcolor
trueareacolor17 = defaultcolor
trueareacolor18 = defaultcolor
trueareacolor19 = defaultcolor
trueareacolor20 = defaultcolor
trueareacolor21 = defaultcolor
trueareacolor22 = defaultcolor
trueareacolor23 = defaultcolor
trueareacolor24 = defaultcolor
trueareacolor25 = defaultcolor
trueareacolor26 = defaultcolor
trueareacolor27 = defaultcolor
trueareacolor28 = defaultcolor
trueareacolor29 = defaultcolor
trueareacolor30 = defaultcolor
trueareacolor31 = defaultcolor
trueareacolor32 = defaultcolor
trueareacolor33 = defaultcolor
trueareacolor34 = defaultcolor
trueareacolor35 = defaultcolor
trueareacolor36 = defaultcolor
trueareacolor37 = defaultcolor
trueareacolor38 = defaultcolor
trueareacolor39 = defaultcolor
trueareacolor40 = defaultcolor
trueareacolor41 = defaultcolor
trueareacolor42 = defaultcolor
trueareacolor43 = defaultcolor
trueareacolor44 = defaultcolor
trueareacolor45 = defaultcolor
trueareacolor46 = defaultcolor
trueareacolor47 = defaultcolor
trueareacolor48 = defaultcolor
trueareacolor49 = defaultcolor
trueareacolor50 = defaultcolor
trueareacolor51 = defaultcolor
trueareacolor52 = defaultcolor
trueareacolor53 = defaultcolor
trueareacolor54 = defaultcolor
trueareacolor55 = defaultcolor
trueareacolor56 = defaultcolor
trueareacolor57 = defaultcolor
trueareacolor58 = defaultcolor
trueareacolor59 = defaultcolor
trueareacolor60 = defaultcolor
trueareacolor61 = defaultcolor
trueareacolor62 = defaultcolor
trueareacolor63 = defaultcolor
trueareacolor64 = defaultcolor
trueareacolor65 = defaultcolor
trueareacolor66 = defaultcolor
trueareacolor67 = defaultcolor
trueareacolor68 = defaultcolor
trueareacolor69 = defaultcolor
trueareacolor70 = defaultcolor
trueareacolor71 = defaultcolor
trueareacolor72 = defaultcolor
trueareacolor73 = defaultcolor
trueareacolor74 = defaultcolor
trueareacolor75 = defaultcolor
trueareacolor76 = defaultcolor
trueareacolor77 = defaultcolor
trueareacolor78 = defaultcolor
trueareacolor79 = defaultcolor
trueareacolor80 = defaultcolor
trueareacolor81 = defaultcolor
trueareacolor82 = defaultcolor
trueareacolor83 = defaultcolor
trueareacolor84 = defaultcolor
trueareacolor85 = defaultcolor
trueareacolor86 = defaultcolor
trueareacolor87 = defaultcolor
trueareacolor88 = defaultcolor
trueareacolor89 = defaultcolor
trueareacolor90 = defaultcolor
trueareacolor91 = defaultcolor
trueareacolor92 = defaultcolor
trueareacolor93 = defaultcolor
trueareacolor94 = defaultcolor
trueareacolor95 = defaultcolor
trueareacolor96 = defaultcolor
trueareacolor97 = defaultcolor
trueareacolor98 = defaultcolor
trueareacolor99 = defaultcolor
if truearea > 0
trueareacolor1 := barinnercolor_trueareabar
if truearea > 1
trueareacolor2 := barinnercolor_trueareabar
if truearea > 2
trueareacolor3 := barinnercolor_trueareabar
if truearea > 3
trueareacolor4 := barinnercolor_trueareabar
if truearea > 4
trueareacolor5 := barinnercolor_trueareabar
if truearea > 5
trueareacolor6 := barinnercolor_trueareabar
if truearea > 6
trueareacolor7 := barinnercolor_trueareabar
if truearea > 7
trueareacolor8 := barinnercolor_trueareabar
if truearea > 8
trueareacolor9 := barinnercolor_trueareabar
if truearea > 9
trueareacolor10 := barinnercolor_trueareabar
if truearea > 10
trueareacolor11 := barinnercolor_trueareabar
if truearea > 11
trueareacolor12 := barinnercolor_trueareabar
if truearea > 12
trueareacolor13 := barinnercolor_trueareabar
if truearea > 13
trueareacolor14 := barinnercolor_trueareabar
if truearea > 14
trueareacolor15 := barinnercolor_trueareabar
if truearea > 15
trueareacolor16 := barinnercolor_trueareabar
if truearea > 16
trueareacolor17 := barinnercolor_trueareabar
if truearea > 17
trueareacolor18 := barinnercolor_trueareabar
if truearea > 18
trueareacolor19 := barinnercolor_trueareabar
if truearea > 19
trueareacolor20 := barinnercolor_trueareabar
if truearea > 20
trueareacolor21 := barinnercolor_trueareabar
if truearea > 21
trueareacolor22 := barinnercolor_trueareabar
if truearea > 22
trueareacolor23 := barinnercolor_trueareabar
if truearea > 23
trueareacolor24 := barinnercolor_trueareabar
if truearea > 24
trueareacolor25 := barinnercolor_trueareabar
if truearea > 25
trueareacolor26 := barinnercolor_trueareabar
if truearea > 26
trueareacolor27 := barinnercolor_trueareabar
if truearea > 27
trueareacolor28 := barinnercolor_trueareabar
if truearea > 28
trueareacolor29 := barinnercolor_trueareabar
if truearea > 29
trueareacolor30 := barinnercolor_trueareabar
if truearea > 30
trueareacolor31 := barinnercolor_trueareabar
if truearea > 31
trueareacolor32 := barinnercolor_trueareabar
if truearea > 32
trueareacolor33 := barinnercolor_trueareabar
if truearea > 33
trueareacolor34 := barinnercolor_trueareabar
if truearea > 34
trueareacolor35 := barinnercolor_trueareabar
if truearea > 35
trueareacolor36 := barinnercolor_trueareabar
if truearea > 36
trueareacolor37 := barinnercolor_trueareabar
if truearea > 37
trueareacolor38 := barinnercolor_trueareabar
if truearea > 38
trueareacolor39 := barinnercolor_trueareabar
if truearea > 39
trueareacolor40 := barinnercolor_trueareabar
if truearea > 40
trueareacolor41 := barinnercolor_trueareabar
if truearea > 41
trueareacolor42 := barinnercolor_trueareabar
if truearea > 42
trueareacolor43 := barinnercolor_trueareabar
if truearea > 43
trueareacolor44 := barinnercolor_trueareabar
if truearea > 44
trueareacolor45 := barinnercolor_trueareabar
if truearea > 45
trueareacolor46 := barinnercolor_trueareabar
if truearea > 46
trueareacolor47 := barinnercolor_trueareabar
if truearea > 47
trueareacolor48 := barinnercolor_trueareabar
if truearea > 48
trueareacolor49 := barinnercolor_trueareabar
if truearea > 49
trueareacolor50 := barinnercolor_trueareabar
if truearea > 50
trueareacolor51 := barinnercolor_trueareabar
if truearea > 51
trueareacolor52 := barinnercolor_trueareabar
if truearea > 52
trueareacolor53 := barinnercolor_trueareabar
if truearea > 53
trueareacolor54 := barinnercolor_trueareabar
if truearea > 54
trueareacolor54 := barinnercolor_trueareabar
if truearea > 54
trueareacolor55 := barinnercolor_trueareabar
if truearea > 55
trueareacolor56 := barinnercolor_trueareabar
if truearea > 56
trueareacolor57 := barinnercolor_trueareabar
if truearea > 57
trueareacolor58 := barinnercolor_trueareabar
if truearea > 58
trueareacolor59 := barinnercolor_trueareabar
if truearea > 59
trueareacolor60 := barinnercolor_trueareabar
if truearea > 60
trueareacolor61 := barinnercolor_trueareabar
if truearea > 61
trueareacolor62 := barinnercolor_trueareabar
if truearea > 62
trueareacolor63 := barinnercolor_trueareabar
if truearea > 63
trueareacolor64 := barinnercolor_trueareabar
if truearea > 64
trueareacolor65 := barinnercolor_trueareabar
if truearea > 65
trueareacolor66 := barinnercolor_trueareabar
if truearea > 66
trueareacolor67 := barinnercolor_trueareabar
if truearea > 67
trueareacolor68 := barinnercolor_trueareabar
if truearea > 68
trueareacolor69 := barinnercolor_trueareabar
if truearea > 69
trueareacolor70 := barinnercolor_trueareabar
if truearea > 70
trueareacolor71 := barinnercolor_trueareabar
if truearea > 71
trueareacolor72 := barinnercolor_trueareabar
if truearea > 72
trueareacolor73 := barinnercolor_trueareabar
if truearea > 73
trueareacolor74 := barinnercolor_trueareabar
if truearea > 74
trueareacolor75 := barinnercolor_trueareabar
if truearea > 75
trueareacolor76 := barinnercolor_trueareabar
if truearea > 76
trueareacolor77 := barinnercolor_trueareabar
if truearea > 77
trueareacolor78 := barinnercolor_trueareabar
if truearea > 78
trueareacolor79 := barinnercolor_trueareabar
if truearea > 79
trueareacolor80 := barinnercolor_trueareabar
if truearea > 80
trueareacolor81 := barinnercolor_trueareabar
if truearea > 81
trueareacolor82 := barinnercolor_trueareabar
if truearea > 82
trueareacolor83 := barinnercolor_trueareabar
if truearea > 83
trueareacolor84 := barinnercolor_trueareabar
if truearea > 84
trueareacolor85 := barinnercolor_trueareabar
if truearea > 85
trueareacolor86 := barinnercolor_trueareabar
if truearea > 86
trueareacolor87 := barinnercolor_trueareabar
if truearea > 87
trueareacolor88 := barinnercolor_trueareabar
if truearea > 88
trueareacolor89 := barinnercolor_trueareabar
if truearea > 89
trueareacolor90 := barinnercolor_trueareabar
if truearea > 90
trueareacolor91 := barinnercolor_trueareabar
if truearea > 91
trueareacolor92 := barinnercolor_trueareabar
if truearea > 92
trueareacolor93 := barinnercolor_trueareabar
if truearea > 93
trueareacolor94 := barinnercolor_trueareabar
if truearea > 94
trueareacolor95 := barinnercolor_trueareabar
if truearea > 95
trueareacolor96 := barinnercolor_trueareabar
if truearea > 96
trueareacolor97 := barinnercolor_trueareabar
if truearea > 97
trueareacolor98 := barinnercolor_trueareabar
if truearea > 98
trueareacolor99 := barinnercolor_trueareabar
var trueareatable = table.new(position.top_center, 101, 2, border_width = 0, border_color = baroutercolor_trueareabar, frame_color = baroutercolor_trueareabar, frame_width = 3)
hi = 5
why = 0.5
if device == "Computer"
table.cell(trueareatable, 20, 0, ' ', bgcolor=trueareacolor20, height=hi, width=why)
table.cell(trueareatable, 21, 0, ' ', bgcolor=trueareacolor21, height=hi, width=why)
table.cell(trueareatable, 22, 0, ' ', bgcolor=trueareacolor22, height=hi, width=why)
table.cell(trueareatable, 22, 0, ' ', bgcolor=trueareacolor22, height=hi, width=why)
table.cell(trueareatable, 24, 0, ' ', bgcolor=trueareacolor24, height=hi, width=why)
table.cell(trueareatable, 25, 0, ' ', bgcolor=trueareacolor25, height=hi, width=why)
table.cell(trueareatable, 26, 0, ' ', bgcolor=trueareacolor26, height=hi, width=why)
table.cell(trueareatable, 27, 0, ' ', bgcolor=trueareacolor27, height=hi, width=why)
table.cell(trueareatable, 28, 0, ' ', bgcolor=trueareacolor28, height=hi, width=why)
table.cell(trueareatable, 29, 0, ' ', bgcolor=trueareacolor29, height=hi, width=why)
table.cell(trueareatable, 30, 0, ' ', bgcolor=trueareacolor40, height=hi, width=why)
table.cell(trueareatable, 30, 0, ' ', bgcolor=trueareacolor30, height=hi, width=why)
table.cell(trueareatable, 31, 0, ' ', bgcolor=trueareacolor31, height=hi, width=why)
table.cell(trueareatable, 32, 0, ' ', bgcolor=trueareacolor32, height=hi, width=why)
table.cell(trueareatable, 33, 0, ' ', bgcolor=trueareacolor33, height=hi, width=why)
table.cell(trueareatable, 34, 0, ' ', bgcolor=trueareacolor34, height=hi, width=why)
table.cell(trueareatable, 35, 0, ' ', bgcolor=trueareacolor35, height=hi, width=why)
table.cell(trueareatable, 36, 0, ' ', bgcolor=trueareacolor36, height=hi, width=why)
table.cell(trueareatable, 37, 0, ' ', bgcolor=trueareacolor37, height=hi, width=why)
table.cell(trueareatable, 38, 0, ' ', bgcolor=trueareacolor38, height=hi, width=why)
table.cell(trueareatable, 39, 0, ' ', bgcolor=trueareacolor39, height=hi, width=why)
table.cell(trueareatable, 40, 0, ' ', bgcolor=trueareacolor40, height=hi, width=why)
table.cell(trueareatable, 41, 0, ' ', bgcolor=trueareacolor41, height=hi, width=why)
table.cell(trueareatable, 42, 0, ' ', bgcolor=trueareacolor42, height=hi, width=why)
table.cell(trueareatable, 43, 0, ' ', bgcolor=trueareacolor43, height=hi, width=why)
table.cell(trueareatable, 44, 0, ' ', bgcolor=trueareacolor44, height=hi, width=why)
table.cell(trueareatable, 45, 0, ' ', bgcolor=trueareacolor45, height=hi, width=why)
table.cell(trueareatable, 46, 0, ' ', bgcolor=trueareacolor46, height=hi, width=why)
table.cell(trueareatable, 47, 0, ' ', bgcolor=trueareacolor47, height=hi, width=why)
table.cell(trueareatable, 48, 0, ' ', bgcolor=trueareacolor48, height=hi, width=why)
table.cell(trueareatable, 49, 0, ' ', bgcolor=trueareacolor49, height=hi, width=why)
table.cell(trueareatable, 50, 0, ' ', bgcolor=trueareacolor50, height=hi, width=why)
table.cell(trueareatable, 51, 0, ' ', bgcolor=trueareacolor51, height=hi, width=why)
table.cell(trueareatable, 52, 0, ' ', bgcolor=trueareacolor52, height=hi, width=why)
table.cell(trueareatable, 53, 0, ' ', bgcolor=trueareacolor53, height=hi, width=why)
table.cell(trueareatable, 54, 0, ' ', bgcolor=trueareacolor54, height=hi, width=why)
table.cell(trueareatable, 55, 0, ' ', bgcolor=trueareacolor55, height=hi, width=why)
table.cell(trueareatable, 56, 0, ' ', bgcolor=trueareacolor56, height=hi, width=why)
table.cell(trueareatable, 57, 0, ' ', bgcolor=trueareacolor57, height=hi, width=why)
table.cell(trueareatable, 58, 0, ' ', bgcolor=trueareacolor58, height=hi, width=why)
table.cell(trueareatable, 59, 0, ' ', bgcolor=trueareacolor59, height=hi, width=why)
table.cell(trueareatable, 60, 0, str.tostring(truearea, "#") + ' %', bgcolor=trueareacolor60, height=hi, width=why, text_color = color.white)
table.cell(trueareatable, 61, 0, ' ', bgcolor=trueareacolor61, height=hi, width=why)
table.cell(trueareatable, 62, 0, ' ', bgcolor=trueareacolor62, height=hi, width=why)
table.cell(trueareatable, 63, 0, ' ', bgcolor=trueareacolor63, height=hi, width=why)
table.cell(trueareatable, 64, 0, ' ', bgcolor=trueareacolor64, height=hi, width=why)
table.cell(trueareatable, 65, 0, ' ', bgcolor=trueareacolor65, height=hi, width=why)
table.cell(trueareatable, 66, 0, ' ', bgcolor=trueareacolor66, height=hi, width=why)
table.cell(trueareatable, 67, 0, ' ', bgcolor=trueareacolor67, height=hi, width=why)
table.cell(trueareatable, 68, 0, ' ', bgcolor=trueareacolor68, height=hi, width=why)
table.cell(trueareatable, 69, 0, ' ', bgcolor=trueareacolor69, height=hi, width=why)
table.cell(trueareatable, 70, 0, ' ', bgcolor=trueareacolor70, height=hi, width=why)
table.cell(trueareatable, 71, 0, ' ', bgcolor=trueareacolor71, height=hi, width=why)
table.cell(trueareatable, 72, 0, ' ', bgcolor=trueareacolor72, height=hi, width=why)
table.cell(trueareatable, 73, 0, ' ', bgcolor=trueareacolor73, height=hi, width=why)
table.cell(trueareatable, 74, 0, ' ', bgcolor=trueareacolor74, height=hi, width=why)
table.cell(trueareatable, 75, 0, ' ', bgcolor=trueareacolor75, height=hi, width=why)
table.cell(trueareatable, 76, 0, ' ', bgcolor=trueareacolor76, height=hi, width=why)
table.cell(trueareatable, 77, 0, ' ', bgcolor=trueareacolor77, height=hi, width=why)
table.cell(trueareatable, 78, 0, ' ', bgcolor=trueareacolor78, height=hi, width=why)
table.cell(trueareatable, 79, 0, ' ', bgcolor=trueareacolor79, height=hi, width=why)
table.cell(trueareatable, 80, 0, ' ', bgcolor=trueareacolor80, height=hi, width=why)
table.cell(trueareatable, 81, 0, ' ', bgcolor=trueareacolor81, height=hi, width=why)
table.cell(trueareatable, 82, 0, ' ', bgcolor=trueareacolor82, height=hi, width=why)
table.cell(trueareatable, 83, 0, ' ', bgcolor=trueareacolor83, height=hi, width=why)
table.cell(trueareatable, 84, 0, ' ', bgcolor=trueareacolor84, height=hi, width=why)
table.cell(trueareatable, 85, 0, ' ', bgcolor=trueareacolor85, height=hi, width=why)
table.cell(trueareatable, 86, 0, ' ', bgcolor=trueareacolor86, height=hi, width=why)
table.cell(trueareatable, 87, 0, ' ', bgcolor=trueareacolor87, height=hi, width=why)
table.cell(trueareatable, 89, 0, ' ', bgcolor=trueareacolor89, height=hi, width=why)
table.cell(trueareatable, 90, 0, ' ', bgcolor=trueareacolor90, height=hi, width=why)
table.cell(trueareatable, 91, 0, ' ', bgcolor=trueareacolor91, height=hi, width=why)
table.cell(trueareatable, 92, 0, ' ', bgcolor=trueareacolor92, height=hi, width=why)
table.cell(trueareatable, 93, 0, ' ', bgcolor=trueareacolor93, height=hi, width=why)
table.cell(trueareatable, 94, 0, ' ', bgcolor=trueareacolor94, height=hi, width=why)
table.cell(trueareatable, 95, 0, ' ', bgcolor=trueareacolor95, height=hi, width=why)
table.cell(trueareatable, 96, 0, ' ', bgcolor=trueareacolor96, height=hi, width=why)
table.cell(trueareatable, 97, 0, ' ', bgcolor=trueareacolor97, height=hi, width=why)
table.cell(trueareatable, 98, 0, ' ', bgcolor=trueareacolor98, height=hi, width=why)
table.cell(trueareatable, 99, 0, ' ', bgcolor=trueareacolor99, height=hi, width=why)
table.merge_cells(trueareatable, 60, 0, 61, 0)
table.set_frame_color(trueareatable, baroutercolor_trueareabar)
//END OF TREND AREA BAR ------------------------------------------------------------------------------------------------//END OF TREND AREA BAR//
//END OF TREND AREA BAR ------------------------------------------------------------------------------------------------//END OF TREND AREA BAR//
//MIN MAX NORMALIZATION ------------------------------------------------------------------------------------------------//MIN MAX NORMALIZATION//
//MIN MAX NORMALIZATION ------------------------------------------------------------------------------------------------//MIN MAX NORMALIZATION//
min_price = source == "High / Low" ? request.security(syminfo.tickerid, timeframes, ta.lowest(low, lookback)) : request.security(syminfo.tickerid, timeframes, ta.lowest(close, lookback))
max_price = source == "High / Low" ? request.security(syminfo.tickerid, timeframes, ta.highest(high, lookback)) : request.security(syminfo.tickerid, timeframes, ta.highest(close, lookback))
min_price_long = source == "High / Low" ? request.security(syminfo.tickerid, "", ta.lowest(low, lookback)) : request.security(syminfo.tickerid, "", ta.lowest(close, lookback))
max_price_long = source == "High / Low" ? request.security(syminfo.tickerid, "", ta.highest(high, lookback)) : request.security(syminfo.tickerid, "", ta.highest(close, lookback))
normalized_price = (close - min_price) / (max_price - min_price)
minmax = (normalized_price * 100)
space = request.security(syminfo.tickerid, timeframes, ta.atr(5))
spacelong = request.security(syminfo.tickerid, "", ta.atr(5))
takeprofitm = 0.0
stoplossm = 0.0
if BUY and (stoploss == "Kiersten Stop Loss")
stoplossm := close - (space * kierstenamount)
if SELL and (stoploss == "Kiersten Stop Loss")
stoplossm := close + (space * kierstenamount)
if BUY and (takeprofit == "Kiersten Take Profit")
takeprofitm:= close + (space * kierstenamount)
if SELL and (takeprofit == "Kiersten Take Profit")
takeprofitm := close - (space * kierstenamount)
if (takeprofit == "Normalized Take Profit") and normalizedmode == "Automatic" and BUY
normalizedvaluetakeprofit := 90
if (takeprofit == "Normalized Take Profit") and normalizedmode == "Automatic" and SELL
normalizedvaluetakeprofit := 10
if (stoploss == "Normalized Stop Loss") and normalizedmode == "Automatic" and BUY
normalizedvaluestoploss := -10
if (stoploss == "Normalized Stop Loss") and normalizedmode == "Automatic" and SELL
normalizedvaluestoploss := 110
if (takeprofit == "Normalized Take Profit")
takeprofitm := ((normalizedvaluetakeprofit/100) * (max_price - min_price)) + min_price
if (stoploss == "Normalized Stop Loss")
stoplossm := ((normalizedvaluestoploss/100) * (max_price - min_price)) + min_price
if stoploss == "Kiersten Stop Loss"
normalizedvaluestoploss := ((stoplossm - min_price) / (max_price - min_price)) * 100
if takeprofit == "Kiersten Take Profit"
normalizedvaluetakeprofit := ((takeprofitm - min_price) / (max_price - min_price)) * 100
minmaxbordercolor = color.gray
if takeprofitm > stoplossm
minmaxbordercolor := color.green
if takeprofitm < stoplossm
minmaxbordercolor := color.red
barinnercolor_minmaxbar = color.rgb(51, 153, 255, 50)
barinnercolor_minmaxbartakeprofit = color.rgb(76, 175, 79, 50)
barinnercolor_minmaxbarstoploss = color.rgb(255, 82, 82, 50)
defaultcolorminmax = color.rgb(120, 123, 134, 70)
var minmax_table = table.new(position.middle_right, 1, 12, border_color = minmaxbordercolor, border_width = 1, frame_color = minmaxbordercolor, frame_width = 2)
minmaxcolor00frequency = 0
minmaxcolor0frequency = 0
minmaxcolor1frequency = 0
minmaxcolor2frequency = 0
minmaxcolor3frequency = 0
minmaxcolor4frequency = 0
minmaxcolor5frequency = 0
minmaxcolor6frequency = 0
minmaxcolor7frequency = 0
minmaxcolor8frequency = 0
minmaxcolor9frequency = 0
minmaxcolor10frequency = 0
minmaxcolor11frequency = 0
minmaxcolor12frequency = 0
for i = 1 to 100
if minmax[i] <= 0
minmaxcolor0frequency += 1
if minmax[i] > 0 and minmax[i] < 10
minmaxcolor1frequency += 1
if minmax[i] >= 10 and minmax[i] < 20
minmaxcolor2frequency += 1
if minmax[i] >= 20 and minmax[i] < 30
minmaxcolor3frequency += 1
if minmax[i] >= 30 and minmax[i] < 40
minmaxcolor4frequency += 1
if minmax[i] >= 40 and minmax[i] < 50
minmaxcolor5frequency += 1
if minmax[i] >= 50 and minmax[i] < 60
minmaxcolor6frequency += 1
if minmax[i] >= 60 and minmax[i] < 70
minmaxcolor7frequency += 1
if minmax[i] >= 70 and minmax[i] < 80
minmaxcolor8frequency += 1
if minmax[i] >= 80 and minmax[i] < 90
minmaxcolor9frequency += 1
if minmax[i] >= 90 and minmax[i] < 100
minmaxcolor10frequency += 1
if minmax[i] >= 100
minmaxcolor11frequency += 1
minmaxcolor00 = defaultcolorminmax
minmaxcolor0 = defaultcolorminmax
minmaxcolor1 = defaultcolorminmax
minmaxcolor2 = defaultcolorminmax
minmaxcolor3 = defaultcolorminmax
minmaxcolor4 = defaultcolorminmax
minmaxcolor5 = defaultcolorminmax
minmaxcolor6 = defaultcolorminmax
minmaxcolor7 = defaultcolorminmax
minmaxcolor8 = defaultcolorminmax
minmaxcolor9 = defaultcolorminmax
minmaxcolor10 = defaultcolorminmax
minmaxcolor11 = defaultcolorminmax
minmaxcolor12 = defaultcolorminmax
if normalizedvaluetakeprofit <= 0
minmaxcolor0 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit > 0 and normalizedvaluetakeprofit <= 10
minmaxcolor1 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit > 10 and normalizedvaluetakeprofit <= 20
minmaxcolor2 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit > 20 and normalizedvaluetakeprofit <= 30
minmaxcolor3 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit > 30 and normalizedvaluetakeprofit <= 40
minmaxcolor4 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit > 40 and normalizedvaluetakeprofit <= 50
minmaxcolor5 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit > 50 and normalizedvaluetakeprofit < 60
minmaxcolor6 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit >= 60 and normalizedvaluetakeprofit < 70
minmaxcolor7 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit >= 70 and normalizedvaluetakeprofit < 80
minmaxcolor8 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit >= 80 and normalizedvaluetakeprofit < 90
minmaxcolor9 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit >= 90 and normalizedvaluetakeprofit < 100
minmaxcolor10 := barinnercolor_minmaxbartakeprofit
if normalizedvaluetakeprofit >= 100
minmaxcolor11 := barinnercolor_minmaxbartakeprofit
if normalizedvaluestoploss <= 0
minmaxcolor0 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss > 0 and normalizedvaluestoploss <= 10
minmaxcolor1 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss > 10 and normalizedvaluestoploss <= 20
minmaxcolor2 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss > 20 and normalizedvaluestoploss <= 30
minmaxcolor3 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss > 30 and normalizedvaluestoploss <= 40
minmaxcolor4 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss > 40 and normalizedvaluestoploss <= 50
minmaxcolor5 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss > 50 and normalizedvaluestoploss < 60
minmaxcolor6 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss >= 60 and normalizedvaluestoploss < 70
minmaxcolor7 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss >= 70 and normalizedvaluestoploss < 80
minmaxcolor8 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss >= 80 and normalizedvaluestoploss < 90
minmaxcolor9 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss >= 90 and normalizedvaluestoploss < 100
minmaxcolor10 := barinnercolor_minmaxbarstoploss
if normalizedvaluestoploss >= 100
minmaxcolor11 := barinnercolor_minmaxbarstoploss
if minmax <= 0
minmaxcolor0 := barinnercolor_minmaxbar
if minmax > 0 and minmax <= 10
minmaxcolor1 := barinnercolor_minmaxbar
if minmax > 10 and minmax <= 20
minmaxcolor2 := barinnercolor_minmaxbar
if minmax > 20 and minmax <= 30
minmaxcolor3 := barinnercolor_minmaxbar
if minmax > 30 and minmax <= 40
minmaxcolor4 := barinnercolor_minmaxbar
if minmax > 40 and minmax <= 50
minmaxcolor5 := barinnercolor_minmaxbar
if minmax > 50 and minmax < 60
minmaxcolor6 := barinnercolor_minmaxbar
if minmax >= 60 and minmax < 70
minmaxcolor7 := barinnercolor_minmaxbar
if minmax >= 70 and minmax < 80
minmaxcolor8 := barinnercolor_minmaxbar
if minmax >= 80 and minmax < 90
minmaxcolor9 := barinnercolor_minmaxbar
if minmax >= 90 and minmax < 100
minmaxcolor10 := barinnercolor_minmaxbar
if minmax >= 100
minmaxcolor11 := barinnercolor_minmaxbar
minmax_height = 5
minmax_width = 7.5
if device == "Computer"
table.cell(minmax_table, 0, 0, ((minmax > 100 or normalizedvaluestoploss > 100 or normalizedvaluetakeprofit > 100) ? str.tostring(normalizedvaluetakeprofit > 100 ? normalizedvaluetakeprofit : normalizedvaluestoploss > 100 ? normalizedvaluestoploss : minmax > 100 ? minmax : na, "#.##") + " %" + "\n" +' โฌ ' : ' โฌ '), bgcolor=minmaxcolor11, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 1, 'Top 10%' + " ~ (" + str.tostring(minmaxcolor10frequency) + "%)", bgcolor=minmaxcolor10, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 2, 'Top 20%' + " ~ (" + str.tostring(minmaxcolor9frequency) + "%)", bgcolor=minmaxcolor9, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 3, 'Top 30%' + " ~ (" + str.tostring(minmaxcolor8frequency) + "%)", bgcolor=minmaxcolor8, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 4, 'Top 40%' + " ~ (" + str.tostring(minmaxcolor7frequency) + "%)", bgcolor=minmaxcolor7, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 5, 'Top 50%'+ " ~ (" + str.tostring(minmaxcolor6frequency) + "%)", bgcolor=minmaxcolor6, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 6, 'Bottom 50%'+ " ~ (" +str.tostring(minmaxcolor5frequency) + "%)", bgcolor=minmaxcolor5, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 7, 'Bottom 40%'+ " ~ (" + str.tostring(minmaxcolor4frequency) + "%)", bgcolor=minmaxcolor4, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 8, 'Bottom 30%'+ " ~ (" + str.tostring(minmaxcolor3frequency) + "%)", bgcolor=minmaxcolor3, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 9, 'Bottom 20%'+ " ~ (" + str.tostring(minmaxcolor2frequency) + "%)", bgcolor=minmaxcolor2, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 10, 'Bottom 10%'+ " ~ (" + str.tostring(minmaxcolor1frequency) + "%)", bgcolor=minmaxcolor1, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.cell(minmax_table, 0, 11, ((minmax < 0 or normalizedvaluestoploss < 0 or normalizedvaluetakeprofit < 0) ? ' โฌ ' + "\n" + str.tostring(normalizedvaluetakeprofit < 0 ? normalizedvaluetakeprofit : normalizedvaluestoploss < 0 ? normalizedvaluestoploss : minmax < 0 ? minmax : na, "#.##") + " %" : ' โฌ '), bgcolor=minmaxcolor0, height=minmax_height, width=minmax_width, text_color = color.white, text_size = size.tiny)
table.set_frame_color(minmax_table, minmaxbordercolor)
table.set_border_color(minmax_table, minmaxbordercolor)
//END OF MIN MAX NORMALIZATION -----------------------------------------------------------------------------------------//END OF MIN MAX NORMALIZATION//
//END OF MIN MAX NORMALIZATION -----------------------------------------------------------------------------------------//END OF MIN MAX NORMALIZATION//
//PATTERNS TABLE -------------------------------------------------------------------------------------------------------//PATTERNS TABLE//
//PATTERNS TABLE -------------------------------------------------------------------------------------------------------//PATTERNS TABLE// ' โฌ '
PatternTable = table.new(position.middle_center,2,22)
if device == "Computer"
for i = 2 to 13
table.cell(PatternTable, 1, i)
table.cell(PatternTable,1, 1,bgcolor = color.new(trendcolor[1], 80) ,height = 12, width =110, text = trend[1] + " ------- > " + trend,text_size = size.small,text_color = color.new(trendcolor[1], 20))
//PATTERNS TABLE END ---------------------------------------------------------------------------------------------------//PATTERNS TABLE END//
//PATTERNS TABLE END ---------------------------------------------------------------------------------------------------//PATTERNS TABLE END//
max = 100
min = 1
overbought = 65
oversold = 35
src = close
N = max-min+1
diff = nz(src - src[1])
var num = array.new_float(N,0)
var den = array.new_float(N,0)
//----
k = 0
overbuy = 0
oversell = 0
avg = 0.
for i = min to max
alpha = 1/i
num_rma = alpha*diff + (1-alpha)*array.get(num,k)
den_rma = alpha*math.abs(diff) + (1-alpha)*array.get(den,k)
rsi = 50*num_rma/den_rma + 50
avg += rsi
overbuy := rsi > overbought ? overbuy + 1 : overbuy
oversell := rsi < oversold ? oversell + 1 : oversell
array.set(num,k,num_rma)
array.set(den,k,den_rma)
k += 1
//----
//TRADABILITY BAR ------------------------------------------------------------------------------------------------------//TRADABILITY BAR//
//TRADABILITY BAR ------------------------------------------------------------------------------------------------------//TRADABILITY BAR//
barinnercolor = color.from_gradient(quality, 0, 100, color.rgb(58, 33, 243, 20), color.rgb(255, 235, 59, 20))
baroutercolor = color.from_gradient(quality, 0, 100, color.blue, color.yellow)
NormalizedBuy = false
NormalizedSell = false
if minmax <= normalizedvalue
NormalizedBuy := true
if minmax >= (100 - normalizedvalue)
NormalizedSell := true
hi_ = 10
why_ = 20
reversalprobability = 0
reversalprobabilitybgcolor = color.rgb(120, 123, 134, 70)
reversalprobabilitycolor = color.gray
if BUY
reversalprobability := (overbuy/N*100)
reversalprobabilitybgcolor := color.rgb(255, 82, 82, 70)
reversalprobabilitycolor := color.red
if SELL
reversalprobability := (oversell/N*100)
reversalprobabilitybgcolor := color.rgb(76, 175, 79, 70)
reversalprobabilitycolor := color.green
// Define inputs
entryPrice = close
takeProfitPrice = takeprofitm
stopLossPrice = stoplossm
reward = BUY ? (positionSize * (takeProfitPrice - entryPrice) / syminfo.mintick) : (positionSize * (takeProfitPrice - entryPrice) / syminfo.mintick) * -1
risk = BUY ? (positionSize * (entryPrice - stopLossPrice) / syminfo.mintick) : (positionSize * (entryPrice - stopLossPrice) / syminfo.mintick) * -1
RRR = reward/risk
BuySetting = (truearea >= trueareaalertvalue) and (BUY) and (NormalizedBuy) and (((UsePatterns == true and (trendcolor[1] == color.green)) or (UsePatterns == false))) and (maxrisk >= risk) and (minreward <= reward) and (minRRR <= RRR)
SellSetting = (truearea >= trueareaalertvalue) and (SELL) and (NormalizedSell) and (((UsePatterns == true and (trendcolor[1] == color.red)) or (UsePatterns == false))) and (maxrisk >= risk) and (minreward <= reward) and (minRRR <= RRR)
reversalprobabilitycolor := color.from_gradient(RRR, 0, 10, color.rgb(33, 149, 243, 50), color.rgb(255, 235, 59, 50))
mobilecolor = color.rgb(255, 255, 255, 50)
framewide = 1
if BuySetting
mobilecolor := color.green
framewide := 4
if SellSetting
mobilecolor := color.red
framewide := 4
var statstable = table.new(position.bottom_center, 6, 1, border_width = 1, border_color = color.new(mobilecolor, 90), frame_color = baroutercolor_trueareabar, frame_width = 2)
table.set_border_color(statstable, mobilecolor)
table.set_frame_color(statstable, mobilecolor)
if device == "Computer"
table.cell(statstable , 1, 0, "Take Profit: " + str.tostring(takeprofitm, "#.#####") + "$" + " (Reward " + str.tostring(reward, "#") + " $)", bgcolor= color.rgb(76, 175, 79, 70), height=hi_, width=why_, text_color = color.green, text_size = size.small)
table.cell(statstable , 2, 0, "Stop Loss: " + str.tostring(stoplossm, "#.#####") + "$" + " (Risk " + str.tostring(risk, "#") + " $)", bgcolor= color.rgb(255, 82, 82, 70), height=hi_, width=why_, text_color = color.red, text_size = size.small)
table.cell(statstable , 3, 0, "Risk Reward Ratio: " + str.tostring(RRR, "#.##") + "x", bgcolor= color.from_gradient(reward/risk, 0.1, 10, color.rgb(33, 149, 243, 50), color.rgb(255, 235, 59, 50)), height=hi_, width=why_, text_color = color.white, text_size = size.small)
table.cell(statstable , 4, 0, "Likelihood of Reversal: " + str.tostring(reversalprobability, "#.##") + " %", bgcolor= reversalprobabilitybgcolor, height=hi_, width=why_, text_color = color.white, text_size = size.small)
table.cell(statstable, 5, 0, text = (str.tostring(speed, '#.##') + ' Pips Per Minute'), bgcolor = color.from_gradient(speed, ta.lowest(speed, lookback),ta.highest(speed, lookback), color.rgb(33, 149, 243, 70), color.rgb(255, 235, 59, 70)), text_color = color.from_gradient(speed, ta.lowest(speed, lookback),ta.highest(speed, lookback), color.blue, color.yellow), width = why_, height = hi_, text_size = size.small)
//END OF TRADABILITY BAR -----------------------------------------------------------------------------------------------//END OF TRADABILITY BAR//
//END OF TRADABILITY BAR -----------------------------------------------------------------------------------------------//END OF TRADABILITY BAR//
//PLOT COLORFUL LINES ---------------------------------------------------------------------------------------------------//PLOT COLORFUL LINES//
//PLOT COLORFUL LINES ---------------------------------------------------------------------------------------------------//PLOT COLORFUL LINES//
plot(0, color = useLongHeikinAshi ? color.gray : na, style = plot.style_line, linewidth = 3)
plot(0, color = useLongHeikinAshi and fourhourHeikinAshibuy ? color.green : na, style = plot.style_line, linewidth = 3)
plot(0, color = useLongHeikinAshi and fourhourHeikinAshisell ? color.red : na, style = plot.style_line, linewidth = 3)
plot(1, color = useWilliamAlligator ? color.gray : na, style = plot.style_line, linewidth = 3)
plot(1, color = useWilliamAlligator and WilliamsAlligatorBuy ? color.green : na, style = plot.style_line, linewidth = 3)
plot(1, color = useWilliamAlligator and WilliamsAlligatorSell ? color.red : na, style = plot.style_line, linewidth = 3)
plot(2, color = useChandelierExit ? color.gray : na, style = plot.style_line, linewidth = 3)
plot(2, color = useChandelierExit and ChandelierBuy ? color.green : na, style = plot.style_line)
plot(2, color = useChandelierExit and ChandelierSell ? color.red : na, style = plot.style_line)
plot(3, color = useShortHeikinAshi ? color.gray : na, style = plot.style_line, linewidth = 3)
plot(3, color = useShortHeikinAshi and onehourHeikinAshiBuy ? color.green : na, style = plot.style_line)
plot(3, color = useShortHeikinAshi and onehourHeikinAshiSell ? color.red : na, style = plot.style_line)
plot(4, color = useMFI ? color.gray : na, style = plot.style_cross)
plot(4, color = useMFI and MFIbuy ? color.green : na, style = plot.style_cross)
plot(4, color = useMFI and MFIsell ? color.red : na, style = plot.style_cross)
plot(5, color = useMACD ? color.gray : na, style = plot.style_line, linewidth = 3)
plot(5, color = useMACD and MACDTRADEBUY ? color.green : na, style = plot.style_line, linewidth = 3)
plot(5, color = useMACD and MACDTRADESELL ? color.red : na, style = plot.style_line, linewidth = 3)
plot(8.5, color = color.rgb(255, 255, 255, 100))
plot(-2, color = color.rgb(255, 255, 255, 100))
EVRYTHINGBUY = williamsalligator != "Williams Alligator is Bearish โ" and dir == 1 and ha_diff60 == 2 and ta.mfi(close, 14)[2] <= 70 and MACDTRADESELL == false
EVRYTHINGSELL = williamsalligator != "Williams Alligator is Bullish โ" and dir == -1 and ha_diff60 == 1 and ta.mfi(close, 14)[2] >= 30 and MACDTRADEBUY == false
EVERYTHINGBUY = EVRYTHINGBUY[1] == false and EVRYTHINGBUY
EVERYTHINGSELL = EVRYTHINGSELL[1] == false and EVRYTHINGSELL
plot(5, color = useEverything and EVERYTHINGBUY == true ? color.rgb(36, 255, 43, 90) : na, style = plot.style_area, linewidth = 4)
plot(6, color = useEverything and EVERYTHINGBUY == true ? color.rgb(45, 255, 52) : na, style = plot.style_cross, linewidth = 2)
plot(5, color = useEverything and EVERYTHINGSELL == true ? color.rgb(175, 76, 76, 90) : na, style = plot.style_area, linewidth = 4)
plot(6, color = useEverything and EVRYTHINGSELL == true ? color.rgb(175, 76, 76) : na, style = plot.style_cross, linewidth = 2)
//END PLOT COLORFUL LINES ----------------------------------------------------------------------------------------------//END PLOT COLORFUL LINES//
//END PLOT COLORFUL LINES ----------------------------------------------------------------------------------------------/END PLOT COLORFUL LINES//
//MOBILE VERSION -------------------------------------------------------------------------------------------------------//MOBILE VERSION//
//MOBILE VERSION -------------------------------------------------------------------------------------------------------//MOBILE VERSION//
plot(device == "Mobile" ? 100000 : na, color = color.rgb(255, 255, 255, 90))
var mobiletable = table.new(position.middle_left, 6, 13, border_width = 1, border_color = baroutercolor_trueareabar, frame_color = baroutercolor_trueareabar, frame_width = framewide)
table.set_border_color(mobiletable, color.new(mobilecolor, 99))
table.set_frame_color(mobiletable, mobilecolor)
table.set_frame_width(mobiletable, framewide)
hi__ = 12
why__ = 16.5
speedcolor = color.from_gradient(speed, ta.lowest(speed, lookback),ta.highest(speed, lookback) / 2, color.rgb(33, 149, 243, 70), color.rgb(255, 235, 59, 70))
if device == "Mobile"
table.cell(mobiletable, 0, 0, text = "Price: " + (str.tostring(close, '#.#####')) + " $", bgcolor = color.rgb(0, 0, 0), text_color = open > close ? color.red : color.green, width = why__ / 2, height = hi__ / 2, text_size = size.small)
for i = 2 to 5
table.cell(mobiletable, 0, i)
table.merge_cells(mobiletable, 0, 0, 5, 0)
table.cell(mobiletable , 0, 1, bgcolor = color.new(barinnercolor_trueareabar, 80) ,height = hi__, width =why__, text = str.tostring(truearea[areanumber], "#") + " %" + "\n" + "\n" + " โ " + "\n" + "\n" + str.tostring(truearea, "#") + " %",text_size = size.small,text_color = baroutercolor_trueareabar)
for i = 2 to 5
table.cell(mobiletable, 2, i)
table.merge_cells(mobiletable, 0, 1, 2, 1)
table.cell(mobiletable , 3, 1, bgcolor = color.new(trendcolor[1], 80) ,height = hi__, width =why__, text = trend[1] + "\n" + "\n" + " โ " + "\n" + "\n" + trend,text_size = size.small,text_color = color.new(trendcolor[1], 20))
table.merge_cells(mobiletable, 3, 1, 5, 1)
table.cell(mobiletable, 0, 2, ((minmax > 100 or normalizedvaluestoploss > 100 or normalizedvaluetakeprofit > 100) ? str.tostring(normalizedvaluetakeprofit > 100 ? normalizedvaluetakeprofit : normalizedvaluestoploss > 100 ? normalizedvaluestoploss : minmax > 100 ? minmax : na, "#.##") + " %" + "\n" + "\n" +' < ' : ' < '), bgcolor=minmaxcolor11, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 1, 2, 'Top 10%' + "\n" + "( Frq " + str.tostring(minmaxcolor10frequency) + "% )", bgcolor=minmaxcolor10, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 2, 2, 'Top 20%' + "\n" + "( Frq " + str.tostring(minmaxcolor9frequency) + "% )", bgcolor=minmaxcolor9, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 3, 2, 'Top 30%' + "\n" + "( Frq " + str.tostring(minmaxcolor8frequency) + "% )", bgcolor=minmaxcolor8, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 4, 2, 'Top 40%' + "\n" + "( Frq " + str.tostring(minmaxcolor7frequency) + "% )", bgcolor=minmaxcolor7, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 5, 2, 'Top 50%' + "\n" + "( Frq " + str.tostring(minmaxcolor6frequency) + "% )", bgcolor=minmaxcolor6, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 0, 3, 'Bottom 50%' + "\n" + "( Frq " + str.tostring(minmaxcolor5frequency) + "% )", bgcolor=minmaxcolor5, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 1, 3, 'Bottom 40%'+ "\n" + "( Frq " + str.tostring(minmaxcolor4frequency) + "% )", bgcolor=minmaxcolor4, height=hi__, width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 2, 3, 'Bottom 30%' + "\n" + "( Frq " + str.tostring(minmaxcolor3frequency) + "% )", bgcolor=minmaxcolor3, height=hi__ , width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 3, 3, 'Bottom 20%' + "\n" + "( Frq " + str.tostring(minmaxcolor2frequency) + "% )", bgcolor=minmaxcolor2, height=hi__ , width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 4, 3, 'Bottom 10%'+ "\n" + "( Frq " + str.tostring(minmaxcolor1frequency) + "% )", bgcolor=minmaxcolor1, height=hi__ , width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable, 5, 3, ((minmax < 0 or normalizedvaluestoploss < 0 or normalizedvaluetakeprofit < 0) ? str.tostring(normalizedvaluetakeprofit < 0 ? normalizedvaluetakeprofit : normalizedvaluestoploss < 0 ? normalizedvaluestoploss : minmax < 0 ? minmax : na, "#.##") + " %" + "\n" + "\n" +' < ' : ' < '), bgcolor=minmaxcolor0, height=hi__ , width=why__, text_color = color.white, text_size = size.tiny)
table.cell(mobiletable , 0, 4, "Top Frequency: " + str.tostring(minmaxcolor11frequency + minmaxcolor10frequency + minmaxcolor9frequency + minmaxcolor8frequency + minmaxcolor7frequency) + " %", bgcolor= color.rgb(76, 175, 79, 70), height=hi__ / 2, width=why__, text_color = color.green, text_size = size.small)
table.cell(mobiletable , 2, 4, "Middle Frequency: " + str.tostring(minmaxcolor5frequency + minmaxcolor6frequency) + " %", bgcolor= color.rgb(120, 123, 134, 70), height=hi__ / 2, width=why__, text_color = color.rgb(255, 255, 255), text_size = size.small)
table.cell(mobiletable , 4, 4, "Bottom Frequency: " + str.tostring(minmaxcolor4frequency + minmaxcolor3frequency + minmaxcolor2frequency + minmaxcolor1frequency + minmaxcolor0frequency)+ " %", bgcolor= color.rgb(255, 82, 82, 70), height=hi__ / 2, width=why__, text_color = color.red, text_size = size.small)
table.merge_cells(mobiletable, 0, 4, 1, 4)
table.merge_cells(mobiletable, 2, 4, 3, 4)
table.merge_cells(mobiletable, 4, 4, 5, 4)
table.cell(mobiletable , 0, 5, "Stop Loss: " + str.tostring(stoplossm, "#.#####") + " $" + "\n" + "\n" + " (Risk " + str.tostring(risk, "#") + " $)", bgcolor= color.rgb(255, 82, 82, 70), height=hi__, width=why__, text_color = color.red, text_size = size.small)
for i = 2 to 5
table.cell(mobiletable, i, 5)
table.merge_cells(mobiletable, 0, 5, 2, 5)
table.cell(mobiletable , 3, 5, "Take Profit: " + str.tostring(takeprofitm, "#.#####") + " $" + "\n" + "\n" + " (Reward " + str.tostring(reward, "#") + " $)", bgcolor= color.rgb(76, 175, 79, 70), height=hi__, width=why__, text_color = color.green, text_size = size.small)
table.merge_cells(mobiletable, 3, 5, 5, 5)
table.cell(mobiletable , 0, 6, "Risk to Reward Ratio: " + str.tostring(RRR, "#.##") + " x" + "\n" + "\n" + "โ", bgcolor= reversalprobabilitycolor, height=hi__, width=why__, text_color = reversalprobabilitycolor, text_size = size.small)
table.merge_cells(mobiletable, 0, 6, 5, 6)
table.cell(mobiletable , 0, 7, "////////////////////////////////////////////", bgcolor= RRR > 0 ? color.new(reversalprobabilitycolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = RRR > 0 ? color.new(reversalprobabilitycolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 1, 7, "////////////////////////////////////////////", bgcolor= RRR > 2 ? color.new(reversalprobabilitycolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = RRR > 2 ? color.new(reversalprobabilitycolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 2, 7, "////////////////////////////////////////////", bgcolor= RRR > 4 ? color.new(reversalprobabilitycolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = RRR > 4 ? color.new(reversalprobabilitycolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 3, 7, "////////////////////////////////////////////", bgcolor= RRR > 6 ? color.new(reversalprobabilitycolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = RRR > 6 ? color.new(reversalprobabilitycolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 4, 7, "////////////////////////////////////////////", bgcolor= RRR > 8 ? color.new(reversalprobabilitycolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = RRR > 8 ? color.new(reversalprobabilitycolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 5, 7, "////////////////////////////////////////////", bgcolor= RRR > 10 ? color.new(reversalprobabilitycolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = RRR > 10 ? color.new(reversalprobabilitycolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable, 0, 8, text = "Speed: " + (str.tostring(speed, '#.##') + ' PPM') + "\n" + "\n" + (speed > 20 ? "๐" : "๐ข"), bgcolor = color.from_gradient(speed, ta.lowest(speed, lookback),ta.highest(speed, lookback) / 2, color.rgb(33, 149, 243, 70), color.rgb(255, 235, 59, 70)), text_color = color.from_gradient(speed, ta.lowest(speed, lookback),ta.highest(speed, lookback), color.rgb(34, 108, 255), color.rgb(251, 255, 0)), width = why__, height = hi__ * 1.5, text_size = size.normal)
table.merge_cells(mobiletable, 0, 8, 5, 8)
table.cell(mobiletable , 0, 9, "////////////////////////////////////////////", bgcolor= speed > 1 ? color.new(speedcolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = speed > 1 ? color.new(speedcolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 1, 9, "////////////////////////////////////////////", bgcolor= speed > 20 ? color.new(speedcolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = speed > 20 ? color.new(speedcolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 2, 9, "////////////////////////////////////////////", bgcolor= speed > 30 ? color.new(speedcolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = speed > 30 ? color.new(speedcolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 3, 9, "////////////////////////////////////////////", bgcolor= speed > 40 ? color.new(speedcolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = speed > 40 ? color.new(speedcolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 4, 9, "////////////////////////////////////////////", bgcolor= speed > 50 ? color.new(speedcolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = speed > 50 ? color.new(speedcolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable , 5, 9, "////////////////////////////////////////////", bgcolor= speed > 60 ? color.new(speedcolor, 60) : defaultcolor, height=hi__ / 4, width=why__, text_color = speed > 60 ? color.new(speedcolor, 80) : defaultcolor, text_size = size.huge)
table.cell(mobiletable, 0, 10, text = "By Kiersten and Haji", bgcolor = color.rgb(0, 0, 0), text_color = color.rgb(255, 38, 150, 10), width = why__ / 6, height = hi__ / 6, text_size = size.tiny)
table.merge_cells(mobiletable, 0, 10, 5, 10)
hline(device == "Mobile" ? 8 : na, color = color.silver, linestyle = hline.style_solid, linewidth = device == "Mobile" ? 5 : 1)
//ALERTS ---------------------------------------------------------------------------------------------------------------//ALERTS//
//ALERTS ---------------------------------------------------------------------------------------------------------------//ALERTS//
CloseBuy = false
CloseSell = false
if minmax <= normalizedvaluetakeprofit
CloseSell := true
if minmax >= normalizedvaluetakeprofit
CloseBuy := true
alertcondition(BuySetting or SellSetting, ".Trade", "TRADE {{ticker}}")
alertcondition(CloseBuy, "I JUST BOUGHT", "GET OUT {{ticker}}")
alertcondition(CloseSell, "I JUST SOLD", "GET OUT {{ticker}}")
//END OF ALERTS --------------------------------------------------------------------------------------------------------//END OF ALERTS//
//END OF ALERTS --------------------------------------------------------------------------------------------------------//END OF ALERTS//
//VERY END -------------------------------------------------------------------------------------------------------------VERY END//
//VERY END -------------------------------------------------------------------------------------------------------------VERY END// |
PerformanceTable | https://www.tradingview.com/script/sKNYzycd-PerformanceTable/ | Cube_Lee | https://www.tradingview.com/u/Cube_Lee/ | 12 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Cube_Lee
//@version=5
// @description TODO: add library description here
library("PerformanceTable")
// Global Function
tableTextSize = size.small
truncate(number, decimals) =>
factor = math.pow(10, decimals)
int(number * factor) / factor
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=tableTextSize)
// Performance Table
export PerformanceTable() =>
var bgcolor = color.new(color.black,0)
// Keep track of Wins/Losses streaks
newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])
varip int winRow = 0
varip int lossRow = 0
varip int maxWinRow = 0
varip int maxLossRow = 0
if newWin
lossRow := 0
winRow := winRow + 1
if winRow > maxWinRow
maxWinRow := winRow
if newLoss
winRow := 0
lossRow := lossRow + 1
if lossRow > maxLossRow
maxLossRow := lossRow
// Prepare stats table
var table dashTable = table.new(position.top_right, 2, 15, border_width=1)
if barstate.islastconfirmedhistory
// Update table
_positionsize = truncate(strategy.position_size, 5)
_coinvalue = truncate(math.abs(strategy.position_size*close), 2)
_pnl = truncate(strategy.openprofit, 2)
_ROE = truncate(strategy.openprofit / math.abs(strategy.position_size) / strategy.position_avg_price * 100, 2)
_equity = truncate(strategy.equity, 2)
_leverage = truncate(math.abs(strategy.position_size*open/strategy.equity), 2)
dollarReturn = strategy.netprofit
_end = strategy.position_size == 0 ? strategy.closedtrades.exit_time(strategy.closedtrades-1) : time
_profit = (strategy.netprofit / strategy.initial_capital) * 100
_numOfDaysInStrategy = truncate((strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24),2)
_winRate = (strategy.wintrades / strategy.closedtrades ) * 100
_profitFactor = strategy.grossprofit / strategy.grossloss
_maxdd = (strategy.max_drawdown / strategy.equity) * 100
f_fillCell(dashTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
f_fillCell(dashTable, 0, 1, "Max.Win / Max.Loss", str.tostring(maxWinRow) + " / " + str.tostring(maxLossRow) , bgcolor, color.white)
f_fillCell(dashTable, 0, 2, "Equity:", str.tostring(_equity) , bgcolor, color.white)
f_fillCell(dashTable, 0, 3, "Leverage:", str.tostring(_leverage) +"x", bgcolor, color.white)
f_fillCell(dashTable, 0, 4, "Coin Value:", str.tostring(_coinvalue), bgcolor, color.white)
f_fillCell(dashTable, 0, 5, "PnL: "+ str.tostring(_pnl), "(" + str.tostring(_ROE) + "%)" , _pnl > 0 ? color.rgb(56, 173, 59) : _pnl < 0 ? color.red : bgcolor, color.white)
f_fillCell(dashTable, 0, 6, "Position Size:", str.tostring(_positionsize) , _positionsize > 0 ? color.rgb(56, 173, 59) : _positionsize < 0 ? color.red : bgcolor, color.white)
f_fillCell(dashTable, 1, 0, "Start:", str.format("{0,date,y-MM-dd}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0))
f_fillCell(dashTable, 1, 1, "End:", str.format("{0,date,y-MM-dd}", _end) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0))
f_fillCell(dashTable, 1, 2, "Net Profit %:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.teal : color.maroon, color.white)
f_fillCell(dashTable, 1, 3, "% Per Day", str.tostring(_profit / _numOfDaysInStrategy, '################.##')+"%", _profit > 0 ? color.teal : color.maroon, color.white)
f_fillCell(dashTable, 1, 4, "% Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.maroon : _winRate < 75 ? #999900 : color.teal, color.white)
f_fillCell(dashTable, 1, 5, "Profit Factor:", str.tostring(_profitFactor, '##.##'), strategy.grossprofit > strategy.grossloss ? color.teal : color.maroon, color.white)
f_fillCell(dashTable, 1, 6, "MaxDD:", str.tostring(_maxdd, '###.##') + "%", color.red, color.white)
// Monthly Table
export MonthlyTable() =>
new_month = month(time) != month(time[1])
new_year = year(time) != year(time[1])
eq = strategy.equity
bar_pnl = eq / eq[1] - 1
cur_month_pnl = 0.0
cur_year_pnl = 0.0
// Current Monthly P&L
cur_month_pnl := new_month ? 0.0 :
(1 + cur_month_pnl[1]) * (1 + bar_pnl) - 1
// Current Yearly P&L
cur_year_pnl := new_year ? 0.0 :
(1 + cur_year_pnl[1]) * (1 + bar_pnl) - 1
// Arrays to store Yearly and Monthly P&Ls
var month_pnl = array.new_float(0)
var month_time = array.new_int(0)
var year_pnl = array.new_float(0)
var year_time = array.new_int(0)
last_computed = false
if (not na(cur_month_pnl[1]) and (new_month or barstate.islastconfirmedhistory))
if (last_computed[1])
array.pop(month_pnl)
array.pop(month_time)
array.push(month_pnl , cur_month_pnl[1])
array.push(month_time, time[1])
if (not na(cur_year_pnl[1]) and (new_year or barstate.islastconfirmedhistory))
if (last_computed[1])
array.pop(year_pnl)
array.pop(year_time)
array.push(year_pnl , cur_year_pnl[1])
array.push(year_time, time[1])
last_computed := barstate.islastconfirmedhistory ? true : nz(last_computed[1])
// Monthly P&L Table
var monthly_table = table(na)
if (barstate.islastconfirmedhistory)
monthly_table := table.new(position.bottom_right, columns = 14, rows = array.size(year_pnl) + 1, border_width = 1)
table.cell(monthly_table, 0, 0, "", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 1, 0, "Jan", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 2, 0, "Feb", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 3, 0, "Mar", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 4, 0, "Apr", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 5, 0, "May", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 6, 0, "Jun", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 7, 0, "Jul", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 8, 0, "Aug", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 9, 0, "Sep", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 10, 0, "Oct", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 11, 0, "Nov", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 12, 0, "Dec", bgcolor = #cccccc, text_size=tableTextSize)
table.cell(monthly_table, 13, 0, "Year", bgcolor = #999999, text_size=tableTextSize)
for yi = 0 to array.size(year_pnl) - 1
table.cell(monthly_table, 0, yi + 1, str.tostring(year(array.get(year_time, yi))), bgcolor = #cccccc, text_size=tableTextSize)
y_color = array.get(year_pnl, yi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.gray, transp = 40)
table.cell(monthly_table, 13, yi + 1, str.tostring(math.round(array.get(year_pnl, yi) * 100, 2)), bgcolor = y_color, text_color=color.new(color.white, 0),text_size=tableTextSize)
for mi = 0 to array.size(month_time) - 1
m_row = year(array.get(month_time, mi)) - year(array.get(year_time, 0)) + 1
m_col = month(array.get(month_time, mi))
m_color = array.get(month_pnl, mi) > 0 ? color.new(color.teal, transp = 40) : color.new(color.maroon, transp = 40)
table.cell(monthly_table, m_col, m_row, str.tostring(math.round(array.get(month_pnl, mi) * 100, 2)), bgcolor = m_color, text_color=color.new(color.white, 0), text_size=tableTextSize)
|
How To Input And Offset CSV Data | https://www.tradingview.com/script/3K2yD4aY-How-To-Input-And-Offset-CSV-Data/ | allanster | https://www.tradingview.com/u/allanster/ | 36 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ allanster
//@version=5
indicator("How To Input And Offset CSV Data")
bump = input(true, '', inline = '1') // Enable/Disable offset of origin bar.
date = input.time(timestamp("19 Feb 2022 00:00 +0000"), "Shift Origin To", tooltip = 'When enabled use this offset for origin bar of data range.', inline = '1')
// Example CSV ๐ Normalized Data From Yahoo Finance BTCUSD Daily Close From February 19th, 2022 Thru January 1st, 2023.
feed = input.text_area(
'40122.15625, 38431.37891, 37075.28125, 38286.02734, 37296.57031, 38332.60938, 39214.21875, 39105.14844, 37709.78516, 43193.23438, 44354.63672, 43924.11719, 42451.78906,' +
'39137.60547, 39400.58594, 38419.98438, 38062.03906, 38737.26953, 41982.92578, 39437.46094, 38794.97266, 38904.01172, 37849.66406, 39666.75391, 39338.78516, 41143.92969,' +
'40951.37891, 41801.15625, 42190.65234, 41247.82422, 41077.99609, 42358.80859, 42892.95703, 43960.93359, 44348.73047, 44500.82813, 46820.49219, 47128.00391, 47465.73047,' +
'47062.66406, 45538.67578, 46281.64453, 45868.94922, 46453.56641, 46622.67578, 45555.99219, 43206.73828, 43503.84766, 42287.66406, 42782.13672, 42207.67188, 39521.90234,' +
'40127.18359, 41166.73047, 39935.51563, 40553.46484, 40424.48438, 39716.95313, 40826.21484, 41502.75000, 41374.37891, 40527.36328, 39740.32031, 39486.73047, 39469.29297,' +
'40458.30859, 38117.46094, 39241.12109, 39773.82813, 38609.82422, 37714.87500, 38469.09375, 38529.32813, 37750.45313, 39698.37109, 36575.14063, 36040.92188, 35501.95313,' +
'34059.26563, 30296.95313, 31022.90625, 28936.35547, 29047.75195, 29283.10352, 30101.26563, 31305.11328, 29862.91797, 30425.85742, 28720.27148, 30314.33398, 29200.74023,' +
'29432.22656, 30323.72266, 29098.91016, 29655.58594, 29562.36133, 29267.22461, 28627.57422, 28814.90039, 29445.95703, 31726.39063, 31792.31055, 29799.08008, 30467.48828,' +
'29704.39063, 29832.91406, 29906.66211, 31370.67188, 31155.47852, 30214.35547, 30111.99805, 29083.80469, 28360.81055, 26762.64844, 22487.38867, 22206.79297, 22572.83984,' +
'20381.65039, 20471.48242, 19017.64258, 20553.27148, 20599.53711, 20710.59766, 19987.02930, 21085.87695, 21231.65625, 21502.33789, 21027.29492, 20735.47852, 20280.63477,' +
'20104.02344, 19784.72656, 19269.36719, 19242.25586, 19297.07617, 20231.26172, 20190.11523, 20548.24609, 21637.58789, 21731.11719, 21592.20703, 20860.44922, 19970.55664,' +
'19323.91406, 20212.07422, 20569.91992, 20836.32813, 21190.31641, 20779.34375, 22485.68945, 23389.43359, 23231.73242, 23164.62891, 22714.97852, 22465.47852, 22609.16406,' +
'21361.70117, 21239.75391, 22930.54883, 23843.88672, 23804.63281, 23656.20703, 23336.89648, 23314.19922, 22978.11719, 22846.50781, 22630.95703, 23289.31445, 22961.27930,' +
'23175.89063, 23809.48633, 23164.31836, 23947.64258, 23957.52930, 24402.81836, 24424.06836, 24319.33398, 24136.97266, 23883.29102, 23335.99805, 23212.73828, 20877.55273,' +
'21166.06055, 21534.12109, 21398.90820, 21528.08789, 21395.01953, 21600.90430, 20260.01953, 20041.73828, 19616.81445, 20297.99414, 19796.80859, 20049.76367, 20127.14063,' +
'19969.77148, 19832.08789, 19986.71289, 19812.37109, 18837.66797, 19290.32422, 19329.83398, 21381.15234, 21680.53906, 21769.25586, 22370.44922, 20296.70703, 20241.08984,' +
'19701.21094, 19772.58398, 20127.57617, 19419.50586, 19544.12891, 18890.78906, 18547.40039, 19413.55078, 19297.63867, 18937.01172, 18802.09766, 19222.67188, 19110.54688,' +
'19426.72070, 19573.05078, 19431.78906, 19312.09570, 19044.10742, 19623.58008, 20336.84375, 20160.71680, 19955.44336, 19546.84961, 19416.56836, 19446.42578, 19141.48438,' +
'19051.41797, 19157.44531, 19382.90430, 19185.65625, 19067.63477, 19268.09375, 19550.75781, 19334.41602, 19139.53516, 19053.74023, 19172.46875, 19208.18945, 19567.00781,' +
'19345.57227, 20095.85742, 20770.44141, 20285.83594, 20595.35156, 20818.47656, 20635.60352, 20495.77344, 20485.27344, 20159.50391, 20209.98828, 21147.23047, 21282.69141,' +
'20926.48633, 20602.81641, 18541.27148, 15880.78027, 17586.77148, 17034.29297, 16799.18555, 16353.36523, 16618.19922, 16884.61328, 16669.43945, 16687.51758, 16697.77734,' +
'16711.54688, 16291.83203, 15787.28418, 16189.76953, 16610.70703, 16604.46484, 16521.84180, 16464.28125, 16444.62695, 16217.32227, 16444.98242, 17168.56641, 16967.13281,' +
'17088.66016, 16908.23633, 17130.48633, 16974.82617, 17089.50391, 16848.12695, 17233.47461, 17133.15234, 17128.72461, 17104.19336, 17206.43750, 17781.31836, 17815.65039,' +
'17364.86523, 16647.48438, 16795.09180, 16757.97656, 16439.67969, 16906.30469, 16817.53516, 16830.34180, 16796.95313, 16847.75586, 16841.98633, 16919.80469, 16717.17383,' +
'16552.57227, 16642.34180, 16602.58594, 16547.49609, 16625.08008', 'Feed', tooltip = 'Total characters cannot exceed 4096.')
subs = str.split(feed, ',') // Split input text into an array of individual substrings.
var data = array.new_float() // Create data array.
indx = not bump ? 0 : ta.valuewhen(time == date, bar_index, 0) // Origin bar index.
if bar_index == indx // If current bar is origin of data range populate the array.
for i = 0 to array.size(subs) - 1 // Loop through individual substrings.
array.push(data, str.tonumber(array.get(subs, i))) // Push float number equivalents of substrings into data array.
array.reverse(data) // Reverse index the data so that pop may be used instead of shift.
plot(array.size(data) < 1 ? na : array.pop(data), 'csv', #ffff00) // Plot and shrink dataset for bars within data range. |
EMA 08:00 | https://www.tradingview.com/script/YDBNlPFz-EMA-08-00/ | schroederjoa | https://www.tradingview.com/u/schroederjoa/ | 10 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ schroederjoa
// Some traders prefer to start the charts at 8am in the morning.
// This chart setting is not possible as of today, but the following script lets you calculate ema for a defined time range.
// Right now it is set to include bars from 08:00 to 1959, meaning thatlate post market and early pre market 04:00 to 07:59 is left out.
//@version=5
indicator("EMA 08:00", overlay=true)
// input definitions for period and timeframe
period = input.int(20, minval = 1)
timeframe = input.timeframe("5", "Timeframe")
// define time range that should be used to calculate indicators
t = time(timeframe.period, "0800-1959")
// disregard close values outside of time range
close_filtered = not na(t) ? close : na
// define indicator function, feed filtered values
// USE ALTERNATIVE FUNCTION HERE TO APPLY FOR DIFFERENT INDICATORS
func = ta.ema(close_filtered, period)
// create higher timeframe function and plot
func_htf = request.security(syminfo.tickerid, timeframe, func)
plot(func_htf) |
Flag Finder | https://www.tradingview.com/script/DU228Vjm-Flag-Finder/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 1,630 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Amphibiantrading
//@version=5
indicator("Flag Finder", overlay = true, max_lines_count = 500)
//inputs
//user controlled settings for the indicator, separated into 4 different groups
var g1 = 'Bull Flag Criteria'
max_depth = input.float(7.5, 'Max Flag Depth', step = .25, minval = .25, group = g1, tooltip = 'Maximum pullback allowed from flag high to flag low')
max_flag = input.int(10, 'Max Flag Length', group = g1, tooltip = 'The maximum number of bars the flag can last')
min_flag = input.int(4, 'Min Flag Length', group = g1, tooltip = 'The minimum number of bars required for the flag')
poleMin = input.float(20.0, 'Prior Uptrend Minimum', step = .50, minval = .25, group = g1, tooltip = 'The minimum percentage gain required before a flag forms')
poleMaxLen = input.int(15, 'Max Flag Pole Length', minval = 1, group = g1, tooltip = 'The maximum number of bars the flagpole can be')
poleMinLen = input.int(5, 'Min Flag Pole Length', minval = 1, group = g1, tooltip = 'The minimum number of bars required for the flag pole')
var g2 = 'Bear Flag Criteria'
max_rally = input.float(10, 'Max Flag Rally', step = .25, minval = .25, group = g2, tooltip = 'Maximum rally allowed from flag low to flag low')
max_flagBear = input.int(10, 'Max Flag Length', group = g2, tooltip = 'The maximum number of bars the flag can last')
min_flagBear = input.int(4, 'Min Flag Length', group = g2, tooltip = 'The minimum number of bars required for the flag')
poleMinBear = input.float(15.0, 'Prior Downtrend Minimum', step = .50, minval = .25, group = g2, tooltip = 'The minimum percentage loss required before a flag forms')
poleMaxLenBear = input.int(15, 'Max Flag Pole Length', minval = 1, group = g2, tooltip = 'The maximum number of bars the flagpole can be')
poleMinLenBear = input.int(3, 'Min Flag Pole Length', minval = 1, group = g2, tooltip = 'The minimum number of bars required for the flag pole')
var g3 = 'Bull Flag Display Options'
showF = input.bool(true, 'Show Bull Flags', group = g3)
showBO = input.bool(true,'Show Bull Flag Breakouts', group = g3)
lineColor = input.color(color.green, 'Bull Line Color', group = g3)
lineWidth = input.int(2, 'Bull Line Width', minval = 1, maxval = 5, group = g3)
var g4 = 'Bear Flag Display Options'
showBF = input.bool(true, 'Show Bear Flags', group = g4)
showBD = input.bool(true,'Show Bear Flag Breakdowns', group = g4)
lineColorBear = input.color(color.red, 'Bear Flag Line Color', group = g4)
lineWidthBear = input.int(2, 'Bear Flag Line Width', minval = 1, maxval = 5, group = g4)
//variables
//declare starting variables used for identfying flags
var baseHigh = high, var startIndex = 0, var flagLength = 0, var baseLow = low
var lowIndex = 0, var flagBool = false, var poleLow = 0.0, var poleLowIndex = 0
var line flagHLine = na, var line flagLLine = na, var line flagPLine = na
// bear flag variables
var flagLowBear = high, var startIndexBear = 0, var flagLengthBear = 0, var flagHigh = low
var highIndex = 0, var flagBoolBear = false, var poleHigh = 0.0, var polehighIndex = 0
var line flagBearHLine = na, var line flagBearLLine = na, var line flagBearPLine = na
//find bull flag highs
// check to see if the current bars price is higher than the previous base high or na and then sets the variables needed for flag detection
if high > baseHigh or na(baseHigh)
baseHigh := high
startIndex := bar_index
flagLength := 0
baseLow := low
lowIndex := bar_index
// check to see if the low of the current bar is lower than the base low, if it is set the base low to the low
if high <= baseHigh and low < baseLow
baseLow := low
lowIndex := bar_index
// moves the base low from the base high bar_index to prevent the high and low being the same bar
if high <= baseHigh and lowIndex == startIndex
baseLow := low
lowIndex := bar_index
//find bear flag lows
// check to see if the current bars price is lower than the previous flag low or na and then sets the variables needed for flag detection
if low < flagLowBear or na(flagLowBear)
flagLowBear := low
startIndexBear := bar_index
flagLengthBear := 0
flagHigh := high
highIndex := bar_index
// check to see if the high of the current bar is higher than the flag high, if it is set the flag high to the high
if low >= flagLowBear and high > flagHigh
flagHigh := high
highIndex := bar_index
// moves the flag high from the flag low bar_index to prevent the high and low being the same bar
if low >= flagLowBear and highIndex == startIndexBear
flagHigh := high
highIndex := bar_index
//calulations bullish
findDepth = math.abs(((baseLow / baseHigh) - 1) * 100) //calculate the depth of the flag
poleDepth = ((baseHigh / poleLow)- 1) * 100 // calculate the low of the flag pole to the base high
lower_close = close < close[1] // defines a lower close
//calculations bearish
findRally = math.abs(((flagHigh / flagLowBear) - 1) * 100) //calculate the rally of the flag
poleDepthBear = ((flagLowBear / poleHigh)- 1) * 100 // calculate the high of the flag pole to the low high
higher_close = close > close[1] // defines a higher close
//start the counters
// begins starting bars once a high is less than the flag high
if high < baseHigh and findDepth <= max_depth or (high == baseHigh and lower_close)
flagLength += 1
else
flagLength := 0
// begins starting bars once a low is higher than the flag low
if low > flagLowBear and findRally <= max_rally or (low == flagLowBear and higher_close)
flagLengthBear += 1
else
flagLengthBear := 0
// check for prior uptrend / downtrend to meet requirements
// loops through all the bars from the minimum pole length to the maximum pole length to check if the prior uptrend requirements are met and sets the variables to their new values
if high == baseHigh
for i = poleMinLen to poleMaxLen
if ((high / low[i]) - 1) * 100 >= poleMin
flagBool := true
poleLow := low[i]
poleLowIndex := bar_index[i]
break
// loops through all the bars from the minimum pole length to the maximum pole length to check if the prior downtrend requirements are met and sets the variables to their new values
if low == flagLowBear
for i = poleMinLenBear to poleMaxLenBear
if math.abs(((low / high[i]) - 1) * 100) >= poleMinBear
flagBoolBear := true
poleHigh := high[i]
polehighIndex := bar_index[i]
break
// reset variables if criteria for a flag is broken
// if the depth of the bull flag is greater than the maximum depth limit or the flag lasts longer than the maximum length everything is reset to beging looking for a new flag
if findDepth >= max_depth or flagLength > max_flag
flagBool := false
flagLength := 0
baseHigh := na
startIndex := na
lowIndex := na
baseLow := na
// if the rally of the bear flag is greater than the maximum rally limit or the flag lasts longer than the maximum length everything is reset to beging looking for a new flag
if findRally >= max_rally or flagLengthBear > max_flagBear
flagBoolBear := false
flagLengthBear := 0
flagLowBear := na
startIndexBear := na
highIndex := na
flagHigh := na
// reset the variables and begin looking for a new bull flag if price continues higher before the minimum flag length requirement is met
if high > baseHigh[1] and flagLength < min_flag
baseHigh := high
flagLength := 0
startIndex := bar_index
lowIndex := bar_index
baseLow := low
// reset the variables and begin looking for a new bear flag if price continues lower before the minimum bear flag length requirement is met
if low < flagLowBear[1] and flagLengthBear < min_flagBear
flagLowBear := low
flagLengthBear := 0
startIndexBear := bar_index
highIndex := bar_index
flagHigh := high
//define the flags
// if all requirements are met a bull flag is true, flagBool is true, flag length is less than maximum set length and more than miminum required. The prior run up also meets the requirements for length and price
flag = flagBool == true and flagLength < max_flag and findDepth < max_depth and flagLength >= min_flag and startIndex - poleLowIndex <= poleMaxLen
// if all requirements are met a bear flag is true, flagBoolBear is true, flag length is less than maximum set length and more than miminum required. The prior downtrend also meets the requirements for length and price
bearFlag = flagBoolBear == true and flagLengthBear < max_flagBear and findRally < max_rally and flagLengthBear >= min_flagBear and startIndexBear - polehighIndex <= poleMaxLen
//define flags, breakouts, breadowns
// a breakout is defined as the high going above the flag high and the length of the flag is greater than the minimum requirement. The flag boolean must also be true
breakout = high > baseHigh[1] and flagLength >= min_flag and flagBool == true
//a breakdown is defined as the depth of the flag being larger than user set parameter or the length of the flag exceeded the maximum flag length
breakdown = findDepth >= max_depth or flagLength > max_flag
// a separate variable to have breakouts only plot once using a plotshape
plotBO = flag[1] and high > baseHigh[1] and flagLength[1] >= min_flag and flagBool == true
// a bear flag breakout is defined as the low going below the flag low and the length of the flag is greater than the minimum requirement. The flag boolean must also be true
breakoutBear = low < flagLowBear[1] and flagLengthBear >= min_flagBear and flagBoolBear == true
//a breakdown is defined as the rally of the flag being larger than user set parameter or the length of the flag exceeded the maximum flag length
breakdownBear = findRally >= max_rally or flagLengthBear > max_flagBear
// a separate variable to have breakouts only plot once using a plotshape
plotBD = bearFlag[1] and low < flagLowBear[1] and flagLengthBear[1] >= min_flagBear and flagBoolBear == true
// if a bul flag is detected and the user has bull flags selected from the settings menu draw it on the chart
if flag and showF
//if a flag was detected on the previous bar, delete those lines and allow for new lines to be drawn
if flag[1]
line.delete(flagHLine[1]), line.delete(flagLLine[1]), line.delete(flagPLine[1])
//draw new lines
flagHLine := line.new(startIndex, baseHigh, bar_index, baseHigh, color=lineColor, width = lineWidth)
flagLLine := line.new(startIndex, baseLow, bar_index, baseLow, color=lineColor, width = lineWidth)
flagPLine := line.new(poleLowIndex +1, poleLow, startIndex , baseLow, color=lineColor, width = lineWidth)
// if a bear flag is detected and the user has bear flags selected from the settings menu draw it on the chart
if bearFlag and showBF
//if a bear flag was detected on the previous bar, delete those lines and allow for new lines to be drawn
if bearFlag[1]
line.delete(flagBearHLine[1]), line.delete(flagBearLLine[1]), line.delete(flagBearPLine[1])
//draw new lines
flagBearHLine := line.new(startIndexBear, flagHigh, bar_index, flagHigh, color=lineColorBear, width = lineWidthBear)
flagBearLLine := line.new(startIndexBear, flagLowBear, bar_index, flagLowBear, color=lineColorBear, width = lineWidthBear)
flagBearPLine := line.new(polehighIndex + 1, poleHigh, startIndexBear , flagHigh, color=lineColorBear, width = lineWidthBear)
//reset variables if a breakout occurs
if breakout // bull flag - high gets above flag high
flagLength := 0
baseHigh := high
startIndex := bar_index
lowIndex := bar_index
baseLow := low
if breakoutBear // bear flag - low gets below flag low
flagLengthBear := 0
flagLowBear := low
startIndexBear := bar_index
highIndex := bar_index
flagHigh := high
//reset the variables and highs from a failed bull flag. This allows stocks below previous highs to find new flags
highest = ta.highest(high, 10) // built in variable that finds the highest high lookingback the past 10 bars
if breakdown or flagLength == max_flag
flagBool := false
baseHigh := highest
startIndex := bar_index
lowIndex := bar_index
baseLow := low
//reset the variables and lows from a failed bear flag. This allows stocks above previous lows to find new flags
lowest = ta.lowest(low, 10) // built in variable that finds the lowest low lookingback the past 10 bars
if breakdownBear or flagLengthBear == max_flagBear
flagBoolBear := false
flagLowBear := lowest
startIndexBear := bar_index
highIndex := bar_index
flagHigh := high
// if a flag breakdowns remove the lines from the chart
if (breakdown and flag[1])
line.delete(flagHLine)
line.delete(flagLLine)
line.delete(flagPLine)
if (breakdownBear and bearFlag[1])
line.delete(flagBearHLine)
line.delete(flagBearLLine)
line.delete(flagBearPLine)
//plot breakouts
// use a plotshape to check if there is a breakout and the show breakout option is selected. If both requirements are met plot a shape at the breakout bar
plotshape(plotBO and showBO and showF, 'Breakout', shape.triangleup, location.belowbar, color.green, display = display.pane)
// use a plotshape to check if there is a breakout and the show breakout option is selected. If both requirements are met plot a shape at the breakout bar
plotshape(plotBD and showBD and showBF, 'Breakout', shape.triangledown, location.abovebar, color.red, display = display.pane)
//alerts
// add alerts for two conditions, a breakout and when a new flag is formed meeting all requirements.
alertcondition(plotBO, 'Bull Flag Breakout', '{{ticker}} Breaking Out from Bull Flag')
alertcondition(flag, 'New Bull Flag', '{{ticker}} has formed a bull flag')
alertcondition(plotBD, 'Bear Flag Breakout', '{{ticker}} Breaking Out from Bear Flag')
alertcondition(bearFlag, 'New Bear Flag', '{{ticker}} has formed a bear flag') |
Global Yield Spread | https://www.tradingview.com/script/sp8D6btR-Global-Yield-Spread/ | Celestial-Eye | https://www.tradingview.com/u/Celestial-Eye/ | 61 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Celestial-Eye
//@version=5
indicator("Global Yield Spread", overlay=true, scale = scale.left)
// Define the bond yields for each country
china_3my = request.security("CN01Y", "D", close)
china_2y = request.security("CN02Y", "D", close)
china_10y = request.security("CN10Y", "D", close)
china_30y = request.security("CN30Y", "D", close)
japan_3my = request.security("JP03MY", "D", close)
japan_2y = request.security("JP02Y", "D", close)
japan_10y = request.security("JP10Y", "D", close)
japan_30y = request.security("JP30Y", "D", close)
germany_3my = request.security("DE03MY", "D", close)
germany_2y = request.security("DE02Y", "D", close)
germany_10y = request.security("DE10Y", "D", close)
germany_30y = request.security("DE30Y", "D", close)
italy_3my = request.security("IT03MY", "D", close)
italy_2y = request.security("IT02Y", "D", close)
italy_10y = request.security("IT10Y", "D", close)
italy_30y = request.security("IT30Y", "D", close)
canada_3my = request.security("CA03MY", "D", close)
canada_2y = request.security("CA02Y", "D", close)
canada_10y = request.security("CA10Y", "D", close)
canada_30y = request.security("CA30Y", "D", close)
russia_3my = request.security("RU03MY", "D", close)
russia_2y = request.security("RU02Y", "D", close)
russia_10y = request.security("RU10Y", "D", close)
russia_30y = request.security("RU20Y", "D", close)
france_3my = request.security("FR03MY", "D", close)
france_2y = request.security("FR02Y", "D", close)
france_10y = request.security("FR10Y", "D", close)
france_30y = request.security("FR30Y", "D", close)
uk_3my = request.security("GB03MY", "D", close)
uk_2y = request.security("GB02Y", "D", close)
uk_10y = request.security("GB10Y", "D", close)
uk_30y = request.security("GB30Y", "D", close)
india_3my = request.security("IN03MY", "D", close)
india_2y = request.security("IN02Y", "D", close)
india_10y = request.security("IN10Y", "D", close)
india_30y = request.security("IN30Y", "D", close)
us_3my = request.security("US03MY", "D", close)
us_2y = request.security("US02Y", "D", close)
us_10y = request.security("US10Y", "D", close)
us_30y = request.security("US30Y", "D", close)
// Calculate yield spread
china_yield_spread10to3m = china_10y - china_3my
japan_yield_spread10to3m = japan_10y - japan_3my
germany_yield_spread10to3m = germany_10y - germany_3my
italy_yield_spread10to3m = italy_10y - italy_3my
canada_yield_spread10to3m = canada_10y - canada_3my
russia_yield_spread10to3m = russia_10y - russia_3my
france_yield_spread10to3m = france_10y - france_3my
uk_yield_spread10to3m = uk_10y - uk_3my
india_yield_spread10to3m = india_10y - india_3my
us_yield_spread10to3m = us_10y - us_3my
china_yield_spread10to02 = china_10y - china_2y
japan_yield_spread10to02 = japan_10y - japan_2y
germany_yield_spread10to02 = germany_10y - germany_2y
italy_yield_spread10to02 = italy_10y - italy_2y
canada_yield_spread10to02 = canada_10y - canada_2y
russia_yield_spread10to02 = russia_10y - russia_2y
france_yield_spread10to02 = france_10y - france_2y
uk_yield_spread10to02 = uk_10y - uk_2y
india_yield_spread10to02 = india_10y - india_2y
us_yield_spread10to02 = us_10y - us_2y
china_yield_spread30to10 = china_30y - china_10y
japan_yield_spread30to10 = japan_30y - japan_10y
germany_yield_spread30to10 = germany_30y - germany_10y
italy_yield_spread30to10 = italy_30y - italy_10y
canada_yield_spread30to10 = canada_30y - canada_10y
russia_yield_spread30to10 = russia_30y - russia_10y
france_yield_spread30to10 = france_30y - france_10y
uk_yield_spread30to10 = uk_30y - uk_10y
india_yield_spread30to10 = india_30y - india_10y
us_yield_spread30to10 = us_30y - us_10y
showCN = input.bool(false, "Show CN Yield Spread")
showJP = input.bool(false, "Show JP Yield Spread")
showGE = input.bool(false, "Show GE Yield Spread")
showIT = input.bool(false, "Show IT Yield Spread")
showCA = input.bool(false, "Show CA Yield Spread")
showRU = input.bool(false, "Show RU Yield Spread")
showFR = input.bool(false, "Show FR Yield Spread")
showGB = input.bool(false, "Show GB Yield Spread")
showIN = input.bool(false, "Show IN Yield Spread")
showUS = input.bool(false, "Show US Yield Spread")
// Plot yield spread
plot( showCN?china_yield_spread10to3m:na, color=color.blue, linewidth=2, title="China 10Y - 3M Yield Spread")
plot( showJP?japan_yield_spread10to3m:na, color= color.red, linewidth=2, title="Japan 10Y - 3M Yield Spread")
plot( showGE?germany_yield_spread10to3m:na, color= color.green, linewidth=2, title="Germany 10Y - 3M Yield Spread")
plot( showIT?italy_yield_spread10to3m:na, color= color.orange, linewidth=2, title="Italy 10Y - 3M Yield Spread")
plot( showCA?canada_yield_spread10to3m:na, color= color.purple, linewidth=2, title="Canada 10Y - 3M Yield Spread")
plot( showRU?russia_yield_spread10to3m:na, color= color.yellow, linewidth=2, title="Russia 10Y - 3M Yield Spread")
plot( showFR?france_yield_spread10to3m:na, color= color.teal, linewidth=2, title="France 10Y - 3M Yield Spread")
plot( showGB?uk_yield_spread10to3m:na, color= color.gray, linewidth=2, title="UK 10Y - 3M Yield Spread")
plot( showIN?india_yield_spread10to3m:na, color= color.maroon, linewidth=2, title="India 10Y - 3M Yield Spread")
plot( showUS?us_yield_spread10to3m:na, color= color.black, linewidth=2, title="US 10Y - 3M Yield Spread")
plot( showCN?china_yield_spread10to02:na, color=color.blue, linewidth=2, title="China 10Y - 2Y Yield Spread")
plot( showJP?japan_yield_spread10to02:na, color= color.red, linewidth=2, title="Japan 10Y - 2Y Yield Spread")
plot( showGE?germany_yield_spread10to02:na, color= color.green, linewidth=2, title="Germany 10Y - 2Y Yield Spread")
plot( showIT?italy_yield_spread10to02:na, color= color.orange, linewidth=2, title="Italy 10Y - 2Y Yield Spread")
plot( showCA?canada_yield_spread10to02:na, color= color.purple, linewidth=2, title="Canada 10Y - 2Y Yield Spread")
plot( showRU?russia_yield_spread10to02:na, color= color.yellow, linewidth=2, title="Russia 10Y - 2Y Yield Spread")
plot( showFR?france_yield_spread10to02:na, color= color.teal, linewidth=2, title="France 10Y - 2Y Yield Spread")
plot( showGB?uk_yield_spread10to02:na, color= color.gray, linewidth=2, title="UK 10Y - 2Y Yield Spread")
plot( showIN?india_yield_spread10to02:na, color= color.maroon, linewidth=2, title="India 10Y - 2Y Yield Spread")
plot( showUS?us_yield_spread10to02:na, color= color.black, linewidth=2, title="US 10Y - 2Y Yield Spread")
plot( showCN?china_yield_spread30to10:na, color=color.blue, linewidth=2, title="China 30Y - 10Y Yield Spread")
plot( showJP?japan_yield_spread30to10:na, color= color.red, linewidth=2, title="Japan 30Y - 10Y Yield Spread")
plot( showGE?germany_yield_spread30to10:na, color= color.green, linewidth=2, title="Germany 30Y - 10Y Yield Spread")
plot( showIT?italy_yield_spread30to10:na, color= color.orange, linewidth=2, title="Italy 30Y - 10Y Yield Spread")
plot( showCA?canada_yield_spread30to10:na, color= color.purple, linewidth=2, title="Canada 30Y - 10Y Yield Spread")
plot( showRU?russia_yield_spread30to10:na, color= color.yellow, linewidth=2, title="Russia 30Y - 10Y Yield Spread")
plot( showFR?france_yield_spread30to10:na, color= color.teal, linewidth=2, title="France 30Y - 10Y Yield Spread")
plot( showGB?uk_yield_spread30to10:na, color= color.gray, linewidth=2, title="UK 30Y - 10Y Yield Spread")
plot( showIN?india_yield_spread30to10:na, color= color.maroon, linewidth=2, title="India 30Y - 10Y Yield Spread")
plot( showUS?us_yield_spread30to10:na, color= color.black, linewidth=2, title="US 30Y - 10Y Yield Spread")
// Calculate global yield spread
global_yield_spread10to3m = (china_yield_spread10to3m + germany_yield_spread10to3m + canada_yield_spread10to3m + france_yield_spread10to3m + uk_yield_spread10to3m + india_yield_spread10to3m) / 6
global_yield_spread10to02 = (china_yield_spread10to02 + japan_yield_spread10to02+ germany_yield_spread10to02 + italy_yield_spread10to02 + canada_yield_spread10to02 + france_yield_spread10to02 + uk_yield_spread10to02 + india_yield_spread10to02) / 8
global_yield_spread30to10 = (china_yield_spread30to10 + japan_yield_spread30to10 + germany_yield_spread30to10 + italy_yield_spread30to10 + canada_yield_spread30to10 + france_yield_spread30to10 + uk_yield_spread30to10 + india_yield_spread30to10 + us_yield_spread30to10) / 9
avgGlobalYield = math.avg(global_yield_spread10to3m,global_yield_spread10to02,global_yield_spread30to10)
show10to3m = input.bool(false, "Show Global 10Y - 3M Yield Spread")
show10to02 = input.bool(false, "Show Global 10Y - 2Y Yield Spread")
show30to10 = input.bool(false, "Show Global 30Y - 10Y Yield Spread")
showavg = input.bool(false, "Show Average Global Yield Spread")
GlobalYieldFill = input.bool(true, "Fill Yield Spread")
// Plot yield spread
plot(show10to3m?global_yield_spread10to3m:na, color=color.purple, linewidth=3, title="Global 10Y - 3M Yield Spread")
plot(show10to02?global_yield_spread10to02:na, color=color.purple, linewidth=3, title="Global 10Y - 2Y Yield Spread")
plot(show30to10?global_yield_spread30to10:na, color=color.purple, linewidth=3, title="Global 30Y - 10Y Yield Spread")
plot(showavg?avgGlobalYield:na, color=color.purple, linewidth=3, title="Average Global Yield Spread")
fill(plot(show10to3m?global_yield_spread10to3m:na,"", color= color.new(color.black,100)),plot(show10to3m?0:na,"", color= color.new(color.black,100)), color = GlobalYieldFill? global_yield_spread10to3m < 0? color.new(color.red,40): color.new(color.green,60):na)
fill(plot(show10to02?global_yield_spread10to02:na,"", color= color.new(color.black,100)),plot(show10to02?0:na,"", color= color.new(color.black,100)), color = GlobalYieldFill? global_yield_spread10to02 < 0? color.new(color.red,40): color.new(color.green,60):na)
fill(plot(show30to10?global_yield_spread30to10:na,"", color= color.new(color.black,100)),plot(show30to10?0:na,"", color= color.new(color.black,100)), color = GlobalYieldFill? global_yield_spread30to10 < 0? color.new(color.red,40): color.new(color.green,60):na)
fill(plot(showavg?avgGlobalYield:na,"", color= color.new(color.black,100)),plot(showavg?0:na,"", color= color.new(color.black,100)), color = GlobalYieldFill? avgGlobalYield < 0? color.new(color.red,40): color.new(color.green,60):na)
hline(0)
|
Volume accumulation on past range [TCS] | VTA | https://www.tradingview.com/script/9t8NXwgi-Volume-accumulation-on-past-range-TCS-VTA/ | zendrer | https://www.tradingview.com/u/zendrer/ | 45 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ zendrer
//@version=5
indicator(shorttitle='TCSโขVOL ACC FIXED', title='TCS โข VOLUME ACCUMULATION FIXED RANGE', precision=0, overlay =true, max_boxes_count = 500)
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//INPUT
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//----------------------------------------------------------------
//TIME PERIOD
//----------------------------------------------------------------
endPeriodTime = input.time(timestamp('30 Jun 2023'), '', group = 'DATE RANGE', tooltip = "! It calculate from one bar after the dat7time choosed")
x1 = input.int(100, minval = 2, maxval = 100, step = 1, title = "VOLUME BARS LOOK-BACK", group = 'DATE RANGE', tooltip = "min : 2 - max : 100, From the date choosed")
//----------------------------------------------------------------
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//FUNCTION
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//VOL BUY-SELL
//----------------------------------------------------------------
buyVol = high[1] == low[1] ? 0 : volume[1] * (close[1] - low[1]) / (high[1] - low[1])
sellVol = high[1] == low[1] ? 0 : volume[1] * (high[1] - close[1]) / (high[1] - low[1])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol2 = high[2] == low[2] ? 0 : volume[2] * (close[2] - low[2]) / (high[2] - low[2])
sellVol2 = high[2] == low[2] ? 0 : volume[2] * (high[2] - close[2]) / (high[2] - low[2])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol3 = high[3] == low[3] ? 0 : volume[3] * (close[3] - low[3]) / (high[3] - low[3])
sellVol3 = high[3] == low[3] ? 0 : volume[3] * (high[3] - close[3]) / (high[3] - low[3])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol4 = high[4] == low[4] ? 0 : volume[4] * (close[4] - low[4]) / (high[4] - low[4])
sellVol4 = high[4] == low[4] ? 0 : volume[4] * (high[4] - close[4]) / (high[4] - low[4])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol5 = high[5] == low[5] ? 0 : volume[5] * (close[5] - low[5]) / (high[5] - low[5])
sellVol5 = high[5] == low[5] ? 0 : volume[5] * (high[5] - close[5]) / (high[5] - low[5])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol6 = high[6] == low[6] ? 0 : volume[6] * (close[6] - low[6]) / (high[6] - low[6])
sellVol6 = high[6] == low[6] ? 0 : volume[6] * (high[6] - close[6]) / (high[6] - low[6])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol7 = high[7] == low[7] ? 0 : volume[7] * (close[7] - low[7]) / (high[7] - low[7])
sellVol7 = high[7] == low[7] ? 0 : volume[7] * (high[7] - close[7]) / (high[7] - low[7])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol8 = high[8] == low[8] ? 0 : volume[8] * (close[8] - low[8]) / (high[8] - low[8])
sellVol8 = high[8] == low[8] ? 0 : volume[8] * (high[8] - close[8]) / (high[8] - low[8])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol9 = high[9] == low[9] ? 0 : volume[9] * (close[9] - low[9]) / (high[9] - low[9])
sellVol9 = high[9] == low[9] ? 0 : volume[9] * (high[9] - close[9]) / (high[9] - low[9])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol10 = high[10] == low[10] ? 0 : volume[10] * (close[10] - low[10]) / (high[10] - low[10])
sellVol10 = high[10] == low[10] ? 0 : volume[10] * (high[10] - close[10]) / (high[10] - low[10])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol11 = high[11] == low[11] ? 0 : volume[11] * (close[11] - low[11]) / (high[11] - low[11])
sellVol11 = high[11] == low[11] ? 0 : volume[11] * (high[11] - close[11]) / (high[11] - low[11])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol12 = high[12] == low[12] ? 0 : volume[12] * (close[12] - low[12]) / (high[12] - low[12])
sellVol12 = high[12] == low[12] ? 0 : volume[12] * (high[12] - close[12]) / (high[12] - low[12])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol13 = high[13] == low[13] ? 0 : volume[13] * (close[13] - low[13]) / (high[13] - low[13])
sellVol13 = high[13] == low[13] ? 0 : volume[13] * (high[13] - close[13]) / (high[13] - low[13])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol14 = high[14] == low[14] ? 0 : volume[14] * (close[14] - low[14]) / (high[14] - low[14])
sellVol14 = high[14] == low[14] ? 0 : volume[14] * (high[14] - close[14]) / (high[14] - low[14])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol15 = high[15] == low[15] ? 0 : volume[15] * (close[15] - low[15]) / (high[15] - low[15])
sellVol15 = high[15] == low[15] ? 0 : volume[15] * (high[15] - close[15]) / (high[15] - low[15])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol16 = high[16] == low[16] ? 0 : volume[16] * (close[16] - low[16]) / (high[16] - low[16])
sellVol16 = high[16] == low[16] ? 0 : volume[16] * (high[16] - close[16]) / (high[16] - low[16])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol17 = high[17] == low[17] ? 0 : volume[17] * (close[17] - low[17]) / (high[17] - low[17])
sellVol17 = high[17] == low[17] ? 0 : volume[17] * (high[17] - close[17]) / (high[17] - low[17])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol18 = high[18] == low[18] ? 0 : volume[18] * (close[18] - low[18]) / (high[18] - low[18])
sellVol18 = high[18] == low[18] ? 0 : volume[18] * (high[18] - close[18]) / (high[18] - low[18])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol19 = high[19] == low[19] ? 0 : volume[19] * (close[19] - low[19]) / (high[19] - low[19])
sellVol19 = high[19] == low[19] ? 0 : volume[19] * (high[19] - close[19]) / (high[19] - low[19])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol20 = high[20] == low[20] ? 0 : volume[20] * (close[20] - low[20]) / (high[20] - low[20])
sellVol20 = high[20] == low[20] ? 0 : volume[20] * (high[20] - close[20]) / (high[20] - low[20])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol21 = high[21] == low[21] ? 0 : volume[21] * (close[21] - low[21]) / (high[21] - low[21])
sellVol21 = high[21] == low[21] ? 0 : volume[21] * (high[21] - close[21]) / (high[21] - low[21])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol22 = high[22] == low[22] ? 0 : volume[22] * (close[22] - low[22]) / (high[22] - low[22])
sellVol22 = high[22] == low[22] ? 0 : volume[22] * (high[22] - close[22]) / (high[22] - low[22])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol23 = high[23] == low[23] ? 0 : volume[23] * (close[23] - low[23]) / (high[23] - low[23])
sellVol23 = high[23] == low[23] ? 0 : volume[23] * (high[23] - close[23]) / (high[23] - low[23])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol24 = high[24] == low[24] ? 0 : volume[24] * (close[24] - low[24]) / (high[24] - low[24])
sellVol24 = high[24] == low[24] ? 0 : volume[24] * (high[24] - close[24]) / (high[24] - low[24])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol25 = high[25] == low[25] ? 0 : volume[25] * (close[25] - low[25]) / (high[25] - low[25])
sellVol25 = high[25] == low[25] ? 0 : volume[25] * (high[25] - close[25]) / (high[25] - low[25])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol26 = high[26] == low[26] ? 0 : volume[26] * (close[26] - low[26]) / (high[26] - low[26])
sellVol26 = high[26] == low[26] ? 0 : volume[26] * (high[26] - close[26]) / (high[26] - low[26])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol27 = high[27] == low[27] ? 0 : volume[27] * (close[27] - low[27]) / (high[27] - low[27])
sellVol27 = high[27] == low[27] ? 0 : volume[27] * (high[27] - close[27]) / (high[27] - low[27])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol28 = high[28] == low[28] ? 0 : volume[28] * (close[28] - low[28]) / (high[28] - low[28])
sellVol28 = high[28] == low[28] ? 0 : volume[28] * (high[28] - close[28]) / (high[28] - low[28])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol29 = high[29] == low[29] ? 0 : volume[29] * (close[29] - low[29]) / (high[29] - low[29])
sellVol29 = high[29] == low[29] ? 0 : volume[29] * (high[29] - close[29]) / (high[29] - low[29])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol30 = high[30] == low[30] ? 0 : volume[30] * (close[30] - low[30]) / (high[30] - low[30])
sellVol30 = high[30] == low[30] ? 0 : volume[30] * (high[30] - close[30]) / (high[30] - low[30])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol31 = high[31] == low[31] ? 0 : volume[31] * (close[31] - low[31]) / (high[31] - low[31])
sellVol31 = high[31] == low[31] ? 0 : volume[31] * (high[31] - close[31]) / (high[31] - low[31])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol32 = high[32] == low[32] ? 0 : volume[32] * (close[32] - low[32]) / (high[32] - low[32])
sellVol32 = high[32] == low[32] ? 0 : volume[32] * (high[32] - close[32]) / (high[32] - low[32])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol33 = high[33] == low[33] ? 0 : volume[33] * (close[33] - low[33]) / (high[33] - low[33])
sellVol33 = high[33] == low[33] ? 0 : volume[33] * (high[33] - close[33]) / (high[33] - low[33])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol34 = high[34] == low[34] ? 0 : volume[34] * (close[34] - low[34]) / (high[34] - low[34])
sellVol34 = high[34] == low[34] ? 0 : volume[34] * (high[34] - close[34]) / (high[34] - low[34])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol35 = high[35] == low[35] ? 0 : volume[35] * (close[35] - low[35]) / (high[35] - low[35])
sellVol35 = high[35] == low[35] ? 0 : volume[35] * (high[35] - close[35]) / (high[35] - low[35])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol36 = high[36] == low[36] ? 0 : volume[36] * (close[36] - low[36]) / (high[36] - low[36])
sellVol36 = high[36] == low[36] ? 0 : volume[36] * (high[36] - close[36]) / (high[36] - low[36])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol37 = high[37] == low[37] ? 0 : volume[37] * (close[37] - low[37]) / (high[37] - low[37])
sellVol37 = high[37] == low[37] ? 0 : volume[37] * (high[37] - close[37]) / (high[37] - low[37])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol38 = high[38] == low[38] ? 0 : volume[38] * (close[38] - low[38]) / (high[38] - low[38])
sellVol38 = high[38] == low[38] ? 0 : volume[38] * (high[38] - close[38]) / (high[38] - low[38])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol39 = high[39] == low[39] ? 0 : volume[39] * (close[39] - low[39]) / (high[39] - low[39])
sellVol39 = high[39] == low[39] ? 0 : volume[39] * (high[39] - close[39]) / (high[39] - low[39])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol40 = high[40] == low[40] ? 0 : volume[40] * (close[40] - low[40]) / (high[40] - low[40])
sellVol40 = high[40] == low[40] ? 0 : volume[40] * (high[40] - close[40]) / (high[40] - low[40])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol41 = high[41] == low[41] ? 0 : volume[41] * (close[41] - low[41]) / (high[41] - low[41])
sellVol41 = high[41] == low[41] ? 0 : volume[41] * (high[41] - close[41]) / (high[41] - low[41])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol42 = high[42] == low[42] ? 0 : volume[42] * (close[42] - low[42]) / (high[42] - low[42])
sellVol42 = high[42] == low[42] ? 0 : volume[42] * (high[42] - close[42]) / (high[42] - low[42])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol43 = high[43] == low[43] ? 0 : volume[43] * (close[43] - low[43]) / (high[43] - low[43])
sellVol43 = high[43] == low[43] ? 0 : volume[43] * (high[43] - close[43]) / (high[43] - low[43])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol44 = high[44] == low[44] ? 0 : volume[44] * (close[44] - low[44]) / (high[44] - low[44])
sellVol44 = high[44] == low[44] ? 0 : volume[44] * (high[44] - close[44]) / (high[44] - low[44])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol45 = high[45] == low[45] ? 0 : volume[45] * (close[45] - low[45]) / (high[45] - low[45])
sellVol45 = high[45] == low[45] ? 0 : volume[45] * (high[45] - close[45]) / (high[45] - low[45])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol46 = high[46] == low[46] ? 0 : volume[46] * (close[46] - low[46]) / (high[46] - low[46])
sellVol46 = high[46] == low[46] ? 0 : volume[46] * (high[46] - close[46]) / (high[46] - low[46])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol47 = high[47] == low[47] ? 0 : volume[47] * (close[47] - low[47]) / (high[47] - low[47])
sellVol47 = high[47] == low[47] ? 0 : volume[47] * (high[47] - close[47]) / (high[47] - low[47])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol48 = high[48] == low[48] ? 0 : volume[48] * (close[48] - low[48]) / (high[48] - low[48])
sellVol48 = high[48] == low[48] ? 0 : volume[48] * (high[48] - close[48]) / (high[48] - low[48])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol49 = high[49] == low[49] ? 0 : volume[49] * (close[49] - low[49]) / (high[49] - low[49])
sellVol49 = high[49] == low[49] ? 0 : volume[49] * (high[49] - close[49]) / (high[49] - low[49])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol50 = high[50] == low[50] ? 0 : volume[50] * (close[50] - low[50]) / (high[50] - low[50])
sellVol50 = high[50] == low[50] ? 0 : volume[50] * (high[50] - close[50]) / (high[50] - low[50])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol51 = high[51] == low[51] ? 0 : volume[51] * (close[51] - low[51]) / (high[51] - low[51])
sellVol51 = high[51] == low[51] ? 0 : volume[51] * (high[51] - close[51]) / (high[51] - low[51])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol52 = high[52] == low[52] ? 0 : volume[52] * (close[52] - low[52]) / (high[52] - low[52])
sellVol52 = high[52] == low[52] ? 0 : volume[52] * (high[52] - close[52]) / (high[52] - low[52])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol53 = high[53] == low[53] ? 0 : volume[53] * (close[53] - low[53]) / (high[53] - low[53])
sellVol53 = high[53] == low[53] ? 0 : volume[53] * (high[53] - close[53]) / (high[53] - low[53])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol54 = high[54] == low[54] ? 0 : volume[54] * (close[54] - low[54]) / (high[54] - low[54])
sellVol54 = high[54] == low[54] ? 0 : volume[54] * (high[54] - close[54]) / (high[54] - low[54])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol55 = high[55] == low[55] ? 0 : volume[55] * (close[55] - low[55]) / (high[55] - low[55])
sellVol55 = high[55] == low[55] ? 0 : volume[55] * (high[55] - close[55]) / (high[55] - low[55])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol56 = high[56] == low[56] ? 0 : volume[56] * (close[56] - low[56]) / (high[56] - low[56])
sellVol56 = high[56] == low[56] ? 0 : volume[56] * (high[56] - close[56]) / (high[56] - low[56])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol57 = high[57] == low[57] ? 0 : volume[57] * (close[57] - low[57]) / (high[57] - low[57])
sellVol57 = high[57] == low[57] ? 0 : volume[57] * (high[57] - close[57]) / (high[57] - low[57])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol58 = high[58] == low[58] ? 0 : volume[58] * (close[58] - low[58]) / (high[58] - low[58])
sellVol58 = high[58] == low[58] ? 0 : volume[58] * (high[58] - close[58]) / (high[58] - low[58])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol59 = high[59] == low[59] ? 0 : volume[59] * (close[59] - low[59]) / (high[59] - low[59])
sellVol59 = high[59] == low[59] ? 0 : volume[59] * (high[59] - close[59]) / (high[59] - low[59])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol60 = high[60] == low[60] ? 0 : volume[60] * (close[60] - low[60]) / (high[60] - low[60])
sellVol60 = high[60] == low[60] ? 0 : volume[60] * (high[60] - close[60]) / (high[60] - low[60])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol61 = high[61] == low[61] ? 0 : volume[61] * (close[61] - low[61]) / (high[61] - low[61])
sellVol61 = high[61] == low[61] ? 0 : volume[61] * (high[61] - close[61]) / (high[61] - low[61])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol62 = high[62] == low[62] ? 0 : volume[62] * (close[62] - low[62]) / (high[62] - low[62])
sellVol62 = high[62] == low[62] ? 0 : volume[62] * (high[62] - close[62]) / (high[62] - low[62])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol63 = high[63] == low[63] ? 0 : volume[63] * (close[63] - low[63]) / (high[63] - low[63])
sellVol63 = high[63] == low[63] ? 0 : volume[63] * (high[63] - close[63]) / (high[63] - low[63])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol64 = high[64] == low[64] ? 0 : volume[64] * (close[64] - low[64]) / (high[64] - low[64])
sellVol64 = high[64] == low[64] ? 0 : volume[64] * (high[64] - close[64]) / (high[64] - low[64])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol65 = high[65] == low[65] ? 0 : volume[65] * (close[65] - low[65]) / (high[65] - low[65])
sellVol65 = high[65] == low[65] ? 0 : volume[65] * (high[65] - close[65]) / (high[65] - low[65])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol66 = high[66] == low[66] ? 0 : volume[66] * (close[66] - low[66]) / (high[66] - low[66])
sellVol66 = high[66] == low[66] ? 0 : volume[66] * (high[66] - close[66]) / (high[66] - low[66])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol67 = high[67] == low[67] ? 0 : volume[67] * (close[67] - low[67]) / (high[67] - low[67])
sellVol67 = high[67] == low[67] ? 0 : volume[67] * (high[67] - close[67]) / (high[67] - low[67])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol68 = high[68] == low[68] ? 0 : volume[68] * (close[68] - low[68]) / (high[68] - low[68])
sellVol68 = high[68] == low[68] ? 0 : volume[68] * (high[68] - close[68]) / (high[68] - low[68])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol69 = high[69] == low[69] ? 0 : volume[69] * (close[69] - low[69]) / (high[69] - low[69])
sellVol69 = high[69] == low[69] ? 0 : volume[69] * (high[69] - close[69]) / (high[69] - low[69])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol70 = high[70] == low[70] ? 0 : volume[70] * (close[70] - low[70]) / (high[70] - low[70])
sellVol70 = high[70] == low[70] ? 0 : volume[70] * (high[70] - close[70]) / (high[70] - low[70])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol71 = high[71] == low[71] ? 0 : volume[71] * (close[71] - low[71]) / (high[71] - low[71])
sellVol71 = high[71] == low[71] ? 0 : volume[71] * (high[71] - close[71]) / (high[71] - low[71])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol72 = high[72] == low[72] ? 0 : volume[72] * (close[72] - low[72]) / (high[72] - low[72])
sellVol72 = high[72] == low[72] ? 0 : volume[72] * (high[72] - close[72]) / (high[72] - low[72])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol73 = high[73] == low[73] ? 0 : volume[73] * (close[73] - low[73]) / (high[73] - low[73])
sellVol73 = high[73] == low[73] ? 0 : volume[73] * (high[73] - close[73]) / (high[73] - low[73])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol74 = high[74] == low[74] ? 0 : volume[74] * (close[74] - low[74]) / (high[74] - low[74])
sellVol74 = high[74] == low[74] ? 0 : volume[74] * (high[74] - close[74]) / (high[74] - low[74])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol75 = high[75] == low[75] ? 0 : volume[75] * (close[75] - low[75]) / (high[75] - low[75])
sellVol75 = high[75] == low[75] ? 0 : volume[75] * (high[75] - close[75]) / (high[75] - low[75])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol76 = high[76] == low[76] ? 0 : volume[76] * (close[76] - low[76]) / (high[76] - low[76])
sellVol76 = high[76] == low[76] ? 0 : volume[76] * (high[76] - close[76]) / (high[76] - low[76])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol77 = high[77] == low[77] ? 0 : volume[77] * (close[77] - low[77]) / (high[77] - low[77])
sellVol77 = high[77] == low[77] ? 0 : volume[77] * (high[77] - close[77]) / (high[77] - low[77])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol78 = high[78] == low[78] ? 0 : volume[78] * (close[78] - low[78]) / (high[78] - low[78])
sellVol78 = high[78] == low[78] ? 0 : volume[78] * (high[78] - close[78]) / (high[78] - low[78])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol79 = high[79] == low[79] ? 0 : volume[79] * (close[79] - low[79]) / (high[79] - low[79])
sellVol79 = high[79] == low[79] ? 0 : volume[79] * (high[79] - close[79]) / (high[79] - low[79])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol80 = high[80] == low[80] ? 0 : volume[80] * (close[80] - low[80]) / (high[80] - low[80])
sellVol80 = high[80] == low[80] ? 0 : volume[80] * (high[80] - close[80]) / (high[80] - low[80])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol81 = high[81] == low[81] ? 0 : volume[81] * (close[81] - low[81]) / (high[81] - low[81])
sellVol81 = high[81] == low[81] ? 0 : volume[81] * (high[81] - close[81]) / (high[81] - low[81])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol82 = high[82] == low[82] ? 0 : volume[82] * (close[82] - low[82]) / (high[82] - low[82])
sellVol82 = high[82] == low[82] ? 0 : volume[82] * (high[82] - close[82]) / (high[82] - low[82])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol83 = high[83] == low[83] ? 0 : volume[83] * (close[83] - low[83]) / (high[83] - low[83])
sellVol83 = high[83] == low[83] ? 0 : volume[83] * (high[83] - close[83]) / (high[83] - low[83])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol84 = high[84] == low[84] ? 0 : volume[84] * (close[84] - low[84]) / (high[84] - low[84])
sellVol84 = high[84] == low[84] ? 0 : volume[84] * (high[84] - close[84]) / (high[84] - low[84])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol85 = high[85] == low[85] ? 0 : volume[85] * (close[85] - low[85]) / (high[85] - low[85])
sellVol85 = high[85] == low[85] ? 0 : volume[85] * (high[85] - close[85]) / (high[85] - low[85])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol86 = high[86] == low[86] ? 0 : volume[86] * (close[86] - low[86]) / (high[86] - low[86])
sellVol86 = high[86] == low[86] ? 0 : volume[86] * (high[86] - close[86]) / (high[86] - low[86])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol87 = high[87] == low[87] ? 0 : volume[87] * (close[87] - low[87]) / (high[87] - low[87])
sellVol87 = high[87] == low[87] ? 0 : volume[87] * (high[87] - close[87]) / (high[87] - low[87])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol88 = high[88] == low[88] ? 0 : volume[88] * (close[88] - low[88]) / (high[88] - low[88])
sellVol88 = high[88] == low[88] ? 0 : volume[88] * (high[88] - close[88]) / (high[88] - low[88])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol89 = high[89] == low[89] ? 0 : volume[89] * (close[89] - low[89]) / (high[89] - low[89])
sellVol89 = high[89] == low[89] ? 0 : volume[89] * (high[89] - close[89]) / (high[89] - low[89])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol90 = high[90] == low[90] ? 0 : volume[90] * (close[90] - low[90]) / (high[90] - low[90])
sellVol90 = high[90] == low[90] ? 0 : volume[90] * (high[90] - close[90]) / (high[90] - low[90])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol91 = high[91] == low[91] ? 0 : volume[91] * (close[91] - low[91]) / (high[91] - low[91])
sellVol91 = high[91] == low[91] ? 0 : volume[91] * (high[91] - close[91]) / (high[91] - low[91])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol92 = high[92] == low[92] ? 0 : volume[92] * (close[92] - low[92]) / (high[92] - low[92])
sellVol92 = high[92] == low[92] ? 0 : volume[92] * (high[92] - close[92]) / (high[92] - low[92])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol93 = high[93] == low[93] ? 0 : volume[93] * (close[93] - low[93]) / (high[93] - low[93])
sellVol93 = high[93] == low[93] ? 0 : volume[93] * (high[93] - close[93]) / (high[93] - low[93])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol94 = high[94] == low[94] ? 0 : volume[94] * (close[94] - low[94]) / (high[94] - low[94])
sellVol94 = high[94] == low[94] ? 0 : volume[94] * (high[94] - close[94]) / (high[94] - low[94])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol95 = high[95] == low[95] ? 0 : volume[95] * (close[95] - low[95]) / (high[95] - low[95])
sellVol95 = high[95] == low[95] ? 0 : volume[95] * (high[95] - close[95]) / (high[95] - low[95])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol96 = high[96] == low[96] ? 0 : volume[96] * (close[96] - low[96]) / (high[96] - low[96])
sellVol96 = high[96] == low[96] ? 0 : volume[96] * (high[96] - close[96]) / (high[96] - low[96])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol97 = high[97] == low[97] ? 0 : volume[97] * (close[97] - low[97]) / (high[97] - low[97])
sellVol97 = high[97] == low[97] ? 0 : volume[97] * (high[97] - close[97]) / (high[97] - low[97])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol98 = high[98] == low[98] ? 0 : volume[98] * (close[98] - low[98]) / (high[98] - low[98])
sellVol98 = high[98] == low[98] ? 0 : volume[98] * (high[98] - close[98]) / (high[98] - low[98])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol99 = high[99] == low[99] ? 0 : volume[99] * (close[99] - low[99]) / (high[99] - low[99])
sellVol99 = high[99] == low[99] ? 0 : volume[99] * (high[99] - close[99]) / (high[99] - low[99])
//----------------------------------------------------------------
//----------------------------------------------------------------
buyVol100 = high[100] == low[100] ? 0 : volume[100] * (close[100] - low[100]) / (high[100] - low[100])
sellVol100 = high[100] == low[100] ? 0 : volume[100] * (high[100] - close[100]) / (high[100] - low[100])
//----------------------------------------------------------------
//VOLUME LOOKBACK
//----------------------------------------------------------------
vol1 = buyVol
volm1 = sellVol
vol2 = vol1 + buyVol2
volm2 = volm1 + sellVol2
vol3 = vol2 + buyVol3
volm3 = volm2 + sellVol3
vol4 = vol3 + buyVol4
volm4 = volm3 + sellVol4
vol5 = vol4 + buyVol5
volm5 = volm4 + sellVol5
vol6 = vol5 + buyVol6
volm6 = volm5 + sellVol6
vol7 = vol6 + buyVol7
volm7 = volm6 + sellVol7
vol8 = vol7 + buyVol8
volm8 = volm7 + sellVol8
vol9 = vol8 + buyVol9
volm9 = volm8 + sellVol9
vol10 = vol9 + buyVol10
volm10 = volm9 + sellVol10
vol11 = vol10 + buyVol11
volm11 = volm10 + sellVol11
vol12 = vol11+ buyVol12
volm12 = volm11 + sellVol12
vol13 = vol12+ buyVol13
volm13 = volm12 + sellVol13
vol14 = vol13 + buyVol14
volm14 = volm13 + sellVol14
vol15 = vol14 + buyVol15
volm15 = volm14 + sellVol15
vol16 = vol15 + buyVol16
volm16 = volm15 + sellVol16
vol17 = vol16 + buyVol17
volm17 = volm16 + sellVol17
vol18 = vol17 + buyVol18
volm18 = volm17 + sellVol18
vol19 = vol18 + buyVol19
volm19 = volm18 + sellVol19
vol20 = vol19 + buyVol20
volm20 = volm19 + sellVol20
vol21 = vol20 + buyVol21
volm21 = volm20 + sellVol21
vol22 = vol21 + buyVol22
volm22 = volm21 + sellVol22
vol23 = vol22 + buyVol23
volm23 = volm22 + sellVol23
vol24 = vol23 + buyVol24
volm24 = volm23 + sellVol24
vol25 = vol24 + buyVol25
volm25 = volm24 + sellVol25
vol26 = vol25 + buyVol26
volm26 = volm25 + sellVol26
vol27 = vol26 + buyVol27
volm27 = volm26 + sellVol27
vol28 = vol27 + buyVol28
volm28 = volm27 + sellVol28
vol29 = vol28 + buyVol29
volm29 = volm28 + sellVol29
vol30 = vol29 + buyVol30
volm30 = volm29 + sellVol30
vol31 = vol30 + buyVol31
volm31 = volm30 + sellVol31
vol32 = vol31 + buyVol32
volm32 = volm31 + sellVol32
vol33 = vol32 + buyVol33
volm33 = volm32 + sellVol33
vol34 = vol33 + buyVol34
volm34 = volm33 + sellVol34
vol35 = vol34 + buyVol35
volm35 = volm34 + sellVol35
vol36 = vol35 + buyVol36
volm36 = volm35 + sellVol36
vol37 = vol36 + buyVol37
volm37 = volm36 + sellVol37
vol38 = vol37 + buyVol38
volm38 = volm37 + sellVol38
vol39 = vol38 + buyVol39
volm39 = volm38 + sellVol39
vol40 = vol39 + buyVol40
volm40 = volm39 + sellVol40
vol41 = vol40+ buyVol41
volm41 = volm40 + sellVol41
vol42 = vol41 + buyVol42
volm42 = volm41 + sellVol42
vol43 = vol42 + buyVol43
volm43 = volm42 + sellVol43
vol44 = vol43 + buyVol44
volm44 = volm43 + sellVol44
vol45 = vol44 + buyVol45
volm45 = volm44 + sellVol45
vol46 = vol45 + buyVol46
volm46 = volm45 + sellVol46
vol47 = vol46 + buyVol47
volm47 = volm46 + sellVol47
vol48 = vol47 + buyVol48
volm48 = volm47 + sellVol48
vol49 = vol48 + buyVol49
volm49 = volm48 + sellVol49
vol50 = vol49 + buyVol50
volm50 = volm49 + sellVol50
vol51 = vol50 + buyVol51
volm51 = volm50 + sellVol51
vol52 = vol51 + buyVol52
volm52 = volm51 + sellVol52
vol53 = vol52 + buyVol53
volm53 = volm52 + sellVol53
vol54 = vol53 + buyVol54
volm54 = volm53 + sellVol54
vol55 = vol54 + buyVol55
volm55 = volm54 + sellVol55
vol56 = vol55 + buyVol56
volm56 = volm55 + sellVol56
vol57 = vol56 + buyVol57
volm57 = volm56 + sellVol57
vol58 = vol57 + buyVol58
volm58 = volm57 + sellVol58
vol59 = vol58 + buyVol59
volm59 = volm58 + sellVol59
vol60 = vol59 + buyVol60
volm60 = volm59 + sellVol60
vol61 = vol60 + buyVol61
volm61 = volm60 + sellVol61
vol62 = vol61 + buyVol62
volm62 = volm61 + sellVol62
vol63 = vol62 + buyVol63
volm63 = volm62 + sellVol63
vol64 = vol63 + buyVol64
volm64 = volm63 + sellVol64
vol65 = vol64 + buyVol65
volm65 = volm64 + sellVol65
vol66 = vol65 + buyVol66
volm66 = volm65 + sellVol66
vol67 = vol66 + buyVol67
volm67 = volm66 + sellVol67
vol68 = vol67 + buyVol68
volm68 = volm67 + sellVol68
vol69 = vol68 + buyVol69
volm69 = volm68 + sellVol69
vol70 = vol69 + buyVol70
volm70 = volm69 + sellVol70
vol71 = vol70 + buyVol71
volm71 = volm70 + sellVol71
vol72 = vol71 + buyVol72
volm72 = volm71 + sellVol72
vol73 = vol72 + buyVol73
volm73 = volm72 + sellVol73
vol74 = vol73 + buyVol74
volm74 = volm73 + sellVol74
vol75 = vol74 + buyVol75
volm75 = volm74 + sellVol75
vol76 = vol75 + buyVol76
volm76 = volm75 + sellVol76
vol77 = vol76 + buyVol77
volm77 = volm76 + sellVol77
vol78 = vol77 + buyVol78
volm78 = volm77 + sellVol78
vol79 = vol78 + buyVol79
volm79 = volm78 + sellVol79
vol80 = vol79 + buyVol80
volm80 = volm79 + sellVol80
vol81 = vol80 + buyVol81
volm81 = volm80 + sellVol81
vol82 = vol81 + buyVol82
volm82 = volm81 + sellVol82
vol83 = vol82 + buyVol83
volm83 = volm82 + sellVol83
vol84 = vol83 + buyVol84
volm84 = volm83 + sellVol84
vol85 = vol84 + buyVol85
volm85 = volm84 + sellVol85
vol86 = vol85 + buyVol86
volm86 = volm85 + sellVol86
vol87 = vol86 + buyVol87
volm87 = volm86 + sellVol87
vol88 = vol87 + buyVol88
volm88 = volm87 + sellVol88
vol89 = vol88 + buyVol89
volm89 = volm88 + sellVol89
vol90 = vol89 + buyVol90
volm90 = volm89 + sellVol90
vol91 = vol90 + buyVol91
volm91 = volm90 + sellVol91
vol92 = vol91 + buyVol92
volm92 = volm91 + sellVol92
vol93 = vol92 + buyVol93
volm93 = volm92 + sellVol93
vol94 = vol93 + buyVol94
volm94 = volm93 + sellVol94
vol95 = vol94 + buyVol95
volm95 = volm94 + sellVol95
vol96 = vol95 + buyVol96
volm96 = volm95 + sellVol96
vol97 = vol96 + buyVol97
volm97 = volm96 + sellVol97
vol98 = vol97 + buyVol98
volm98 = volm97 + sellVol98
vol99 = vol98 + buyVol99
volm99 = volm98 + sellVol99
vol100 = vol99 + buyVol100
volm100 = volm99 + sellVol100
//----------------------------------------------------------------
//VOLUME DEFINTION
//----------------------------------------------------------------
voldefbull = (x1 == 1) ? vol1 :
(x1 == 2) ? vol2 :
(x1 == 3) ? vol3 :
(x1 == 4) ? vol4 :
(x1 == 5) ? vol5 :
(x1 == 6) ? vol6 :
(x1 == 7) ? vol7 :
(x1 == 8) ? vol8 :
(x1 == 9) ? vol9 :
(x1 == 10) ? vol10 :
(x1 == 11) ? vol11 :
(x1 == 12) ? vol12 :
(x1 == 13) ? vol13 :
(x1 == 14) ? vol14 :
(x1 == 15) ? vol15 :
(x1 == 16) ? vol16 :
(x1 == 17) ? vol17 :
(x1 == 18) ? vol18 :
(x1 == 19) ? vol19 :
(x1 == 20) ? vol20 :
(x1 == 21) ? vol21 :
(x1 == 22) ? vol22 :
(x1 == 23) ? vol23 :
(x1 == 24) ? vol24 :
(x1 == 25) ? vol25 :
(x1 == 26) ? vol26 :
(x1 == 27) ? vol27 :
(x1 == 28) ? vol28 :
(x1 == 29) ? vol29 :
(x1 == 30) ? vol30 :
(x1 == 31) ? vol31 :
(x1 == 32) ? vol32 :
(x1 == 33) ? vol33 :
(x1 == 34) ? vol34 :
(x1 == 35) ? vol35 :
(x1 == 36) ? vol36 :
(x1 == 37) ? vol37 :
(x1 == 38) ? vol38 :
(x1 == 39) ? vol39 :
(x1 == 40) ? vol40 :
(x1 == 41) ? vol41 :
(x1 == 42) ? vol42 :
(x1 == 43) ? vol43 :
(x1 == 44) ? vol44 :
(x1 == 45) ? vol45 :
(x1 == 46) ? vol46 :
(x1 == 47) ? vol47 :
(x1 == 48) ? vol48 :
(x1 == 49) ? vol49 :
(x1 == 50) ? vol50 :
(x1 == 51) ? vol51 :
(x1 == 52) ? vol52 :
(x1 == 53) ? vol53 :
(x1 == 54) ? vol54 :
(x1 == 55) ? vol55 :
(x1 == 56) ? vol56 :
(x1 == 57) ? vol57 :
(x1 == 58) ? vol58 :
(x1 == 59) ? vol59 :
(x1 == 60) ? vol60 :
(x1 == 61) ? vol61 :
(x1 == 62) ? vol62 :
(x1 == 63) ? vol63 :
(x1 == 64) ? vol64 :
(x1 == 65) ? vol65 :
(x1 == 66) ? vol66 :
(x1 == 67) ? vol67 :
(x1 == 68) ? vol68 :
(x1 == 69) ? vol69 :
(x1 == 70) ? vol70 :
(x1 == 71) ? vol71 :
(x1 == 72) ? vol72 :
(x1 == 73) ? vol73 :
(x1 == 74) ? vol74 :
(x1 == 75) ? vol75 :
(x1 == 76) ? vol76 :
(x1 == 77) ? vol77 :
(x1 == 78) ? vol78 :
(x1 == 79) ? vol79 :
(x1 == 80) ? vol80 :
(x1 == 81) ? vol81 :
(x1 == 82) ? vol82 :
(x1 == 83) ? vol83 :
(x1 == 84) ? vol84 :
(x1 == 85) ? vol85 :
(x1 == 86) ? vol86 :
(x1 == 87) ? vol87 :
(x1 == 88) ? vol88 :
(x1 == 89) ? vol89 :
(x1 == 90) ? vol90 :
(x1 == 91) ? vol91 :
(x1 == 92) ? vol92 :
(x1 == 93) ? vol93 :
(x1 == 94) ? vol94 :
(x1 == 95) ? vol95 :
(x1 == 96) ? vol96 :
(x1 == 97) ? vol97 :
(x1 == 98) ? vol98 :
(x1 == 99) ? vol99 :
(x1 == 100) ? vol100 : na
voldefbear = (x1 == 1) ? volm1 :
(x1 == 2) ? volm2 :
(x1 == 3) ? volm3 :
(x1 == 4) ? volm4 :
(x1 == 5) ? volm5 :
(x1 == 6) ? volm6 :
(x1 == 7) ? volm7 :
(x1 == 8) ? volm8 :
(x1 == 9) ? volm9 :
(x1 == 10) ? volm10 :
(x1 == 11) ? volm11 :
(x1 == 12) ? volm12 :
(x1 == 13) ? volm13 :
(x1 == 14) ? volm14 :
(x1 == 15) ? volm15 :
(x1 == 16) ? volm16 :
(x1 == 17) ? volm17 :
(x1 == 18) ? volm18 :
(x1 == 19) ? volm19 :
(x1 == 20) ? volm20 :
(x1 == 21) ? volm21 :
(x1 == 22) ? volm22 :
(x1 == 23) ? volm23 :
(x1 == 24) ? volm24 :
(x1 == 25) ? volm25 :
(x1 == 26) ? volm26 :
(x1 == 27) ? volm27 :
(x1 == 28) ? volm28 :
(x1 == 29) ? volm29 :
(x1 == 30) ? volm30 :
(x1 == 31) ? volm31 :
(x1 == 32) ? volm32 :
(x1 == 33) ? volm33 :
(x1 == 34) ? volm34 :
(x1 == 35) ? volm35 :
(x1 == 36) ? volm36 :
(x1 == 37) ? volm37 :
(x1 == 38) ? volm38 :
(x1 == 39) ? volm39 :
(x1 == 40) ? volm40 :
(x1 == 41) ? volm41 :
(x1 == 42) ? volm42 :
(x1 == 43) ? volm43 :
(x1 == 44) ? volm44 :
(x1 == 45) ? volm45 :
(x1 == 46) ? volm46 :
(x1 == 47) ? volm47 :
(x1 == 48) ? volm48 :
(x1 == 49) ? volm49 :
(x1 == 50) ? volm50 :
(x1 == 51) ? volm51 :
(x1 == 52) ? volm52 :
(x1 == 53) ? volm53 :
(x1 == 54) ? volm54 :
(x1 == 55) ? volm55 :
(x1 == 56) ? volm56 :
(x1 == 57) ? volm57 :
(x1 == 58) ? volm58 :
(x1 == 59) ? volm59 :
(x1 == 60) ? volm60 :
(x1 == 61) ? volm61 :
(x1 == 62) ? volm62 :
(x1 == 63) ? volm63 :
(x1 == 64) ? volm64 :
(x1 == 65) ? volm65 :
(x1 == 66) ? volm66 :
(x1 == 67) ? volm67 :
(x1 == 68) ? volm68 :
(x1 == 69) ? volm69 :
(x1 == 70) ? volm70 :
(x1 == 71) ? volm71 :
(x1 == 72) ? volm72 :
(x1 == 73) ? volm73 :
(x1 == 74) ? volm74 :
(x1 == 75) ? volm75 :
(x1 == 76) ? volm76 :
(x1 == 77) ? volm77 :
(x1 == 78) ? volm78 :
(x1 == 79) ? volm79 :
(x1 == 80) ? volm80 :
(x1 == 81) ? volm81 :
(x1 == 82) ? volm82 :
(x1 == 83) ? volm83 :
(x1 == 84) ? volm84 :
(x1 == 85) ? volm85 :
(x1 == 86) ? volm86 :
(x1 == 87) ? volm87 :
(x1 == 88) ? volm88 :
(x1 == 89) ? volm89 :
(x1 == 90) ? volm90 :
(x1 == 91) ? volm91 :
(x1 == 92) ? volm92 :
(x1 == 93) ? volm93 :
(x1 == 94) ? volm94 :
(x1 == 95) ? volm95 :
(x1 == 96) ? volm96 :
(x1 == 97) ? volm97 :
(x1 == 98) ? volm98 :
(x1 == 99) ? volm99 :
(x1 == 100) ? volm100 : na
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//PLOT
//โขโขโขโขโขโขโขโขโขโขโขโขโขโข
//VOLUME ON BACK RANGE
//----------------------------------------------------------------
//SWAP FROM TIME TO BAR INDEX
barindex = (time - endPeriodTime ) / (1000 * timeframe.in_seconds(timeframe.period))
//DEFINE LAST BAR
end = bar_index - barindex
//VARIABLES
var sessionHighPrice = 0.0
var sessionLowPrice = 0.0
var sessionOpenPrice = 0.0
var ylbale = 0.0
var box sessionBox = na
var label sessionLabel = na
// SESSION DEFINITION
start = end-(bar_index - bar_index[x1])
session = end > bar_index and bar_index > start
sessioncount = end[1] < bar_index
count = sessioncount and not sessioncount[1]
// SESSION HIGHEST/LOWEST
if session
sessionHighPrice := high
sessionLowPrice := low
sessionHighPrice := math.max(sessionHighPrice, high)
sessionLowPrice := math.min(sessionLowPrice, low)
//LABEL POSTION
ylbale := ta.highest(high, x1)
// BOXES AND LABELS
if session
sessionBox := box.new(left=start+1, top=na, right=na, bottom=na, xloc = xloc.bar_index, border_width=0, bgcolor = color.new(color.lime,98))
box.set_top(sessionBox, sessionHighPrice)
box.set_bottom(sessionBox, sessionLowPrice)
box.set_right(sessionBox,end+1)
if count
sessionLabel := label.new(end, ylbale + 5, text = "BULLISH VOLUME | " + str.tostring((voldefbull),'#.##') + " | " + str.tostring(((voldefbull)*100/(voldefbull+voldefbear)),'#.##') + "%" + "\n BEARISH VOLUME | " + str.tostring((voldefbear),'#.##') + " | " + str.tostring(((voldefbear)*100/(voldefbull+voldefbear)),'#.##') + "%" + "\n BAR COUNT | " + str.tostring((x1),'#.##'), color = na, style = label.style_label_right, textcolor = color.white )
//----------------------------------------------------------------
//END
|
Inside Candle Viewer | https://www.tradingview.com/script/vAMaNbWD-Inside-Candle-Viewer/ | Fab_Coin_ | https://www.tradingview.com/u/Fab_Coin_/ | 28 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Fab_Coin_
//@version=5
indicator("Inside Candle", overlay = true, timeframe = '')
// HMI inputs
// Vars
var incount = 1
var inside = false
var topinside = 0.0
var lowinside = 0.0
// Draw any insidebar
InsideBAR = (high < high[1] and low > low[1]) ? color.new(#d7d7d7, 0) : na
barcolor(InsideBAR)
// Locate and track inside bars
if high < high[1] and low > low[1] and not inside
inside := true
topinside := high[1]
lowinside := low[1]
if inside and (close > high[incount] or close < low[incount])
incount := 1
inside := false
topinside := 0
lowinside := 0
else if inside
incount := incount + 1
// Plot stuff
plot(topinside == 0 ? na : topinside, 'top value', ta.change(topinside) ? na : color.new(color.blue, 30), linewidth = 2)
plot(lowinside == 0 ? na : lowinside, 'low value', ta.change(lowinside) ? na : color.new(color.blue, 30), linewidth = 2)
// ...TheEnd... |
RSI Momentum Trend Screener | https://www.tradingview.com/script/6jMbFxa8-RSI-Momentum-Trend-Screener/ | TZack88 | https://www.tradingview.com/u/TZack88/ | 256 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ TZack88
//@version=5
indicator(title="RSI Momentum Trend Screener", format=format.price, precision=2,overlay = true)
// ** ---> Inputs ------------- {
array<string> names = array.new_string(0)
array<bool> USEbool = array.new_bool(0)
array<bool> rsi_pos = array.new_bool(0)
array<bool> rsi_neg = array.new_bool(0)
string RSI_group = "RSI Settings"
string mom_group = "Momentum Vales"
string table_name = 'RSI Momentum Trend Screener'
string table_Group = "Table"
int Len2 = input(14,"RSI 1๏ธโฃ",inline = "rsi",group = RSI_group)
int pmom = input(65," Positive above",inline = "rsi1",group =RSI_group )
int nmom = input(32,"Negative below",inline = "rsi1",group =RSI_group )
float rsi = ta.rsi(close, Len2)
// Table data
bool show_table = input.bool(true,title= "Show Table โ",inline = "002",group = table_Group)
string position = input.string("Top Right",
options = ["Middle Right","Top Center","Top Right","Middle Left","Middle Center","Bottom Left","Bottom Center","Bottom Right"],
title = 'Position',
inline = "002",
group = table_Group
)
color textcolos = input.color(color.rgb(255, 186, 75),title = "Text Color",inline = "002",group = table_Group)
table_position() =>
switch position
"Middle Right" => position.middle_right
"Top Center" => position.top_center
"Top Right" => position.top_right
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
var summary_table = table.new(table_position(), 15, 50, frame_color=color.rgb(241, 124, 8), frame_width=2,border_width = 2)
change_color(con)=>
con ? color.rgb(6, 104, 57) : color.rgb(153, 7, 7)
table_cell(table,_row,in1,in2,coloz)=>
text_color = show_table ? color.rgb(210, 210, 210) : color.black
table.cell(table, 0, _row, in1, text_color=text_color,bgcolor = color.rgb(120, 123, 134, 38))
table.cell(table, 1, _row, str.tostring(in2), text_color=text_color,bgcolor = change_color(coloz))
table_cell2(table,_row,in1,in2,coloz)=>
text_color = show_table ? color.rgb(210, 210, 210) : color.black
table.cell(table, 3, _row, in1, text_color=text_color,bgcolor = color.rgb(120, 123, 134, 38))
table.cell(table, 4, _row, str.tostring(in2), text_color=text_color,bgcolor = change_color(coloz))
//------------------- }
// Lets calculate our RSI MOM Trend and return it
GetData(simple string pair) =>
var bool positive = false
var bool negative = false
Pinfo = rsi[1] < pmom and rsi > pmom and rsi > nmom and ta.change(ta.ema(close,5)) > 0
Ninfo = rsi < nmom and ta.change(ta.ema(close,5)) < 0
[ p_mom ,n_mom ] = request.security(pair,"",[Pinfo,Ninfo])
if p_mom
positive:= true
negative:= false
if n_mom
positive:= false
negative:= true
[ positive , negative ]
// ** ---> Momentums ------------- {
bool T01 = input.bool(true, title = "", group = 'Symbols', inline = 's01')
bool T02 = input.bool(true, title = "", group = 'Symbols', inline = 's02')
bool T03 = input.bool(true, title = "", group = 'Symbols', inline = 's03')
bool T04 = input.bool(true, title = "", group = 'Symbols', inline = 's04')
bool T05 = input.bool(true, title = "", group = 'Symbols', inline = 's05')
bool T06 = input.bool(true, title = "", group = 'Symbols', inline = 's06')
bool T07 = input.bool(true, title = "", group = 'Symbols', inline = 's07')
bool T08 = input.bool(true, title = "", group = 'Symbols', inline = 's08')
bool T09 = input.bool(true, title = "", group = 'Symbols', inline = 's09')
bool T10 = input.bool(true, title = "", group = 'Symbols', inline = 's10')
bool T11 = input.bool(true, title = "", group = 'Symbols', inline = 's11')
bool T12 = input.bool(true, title = "", group = 'Symbols', inline = 's12')
bool T13 = input.bool(true, title = "", group = 'Symbols', inline = 's13')
bool T14 = input.bool(true, title = "", group = 'Symbols', inline = 's14')
bool T15 = input.bool(true, title = "", group = 'Symbols', inline = 's15')
bool T16 = input.bool(true, title = "", group = 'Symbols', inline = 's16')
bool T17 = input.bool(true, title = "", group = 'Symbols', inline = 's17')
bool T18 = input.bool(true, title = "", group = 'Symbols', inline = 's18')
bool T19 = input.bool(true, title = "", group = 'Symbols', inline = 's19')
bool T20 = input.bool(true, title = "", group = 'Symbols', inline = 's20')
bool T21 = input.bool(true, title = "", group = 'Symbols', inline = 's21')
bool T22 = input.bool(true, title = "", group = 'Symbols', inline = 's22')
bool T23 = input.bool(true, title = "", group = 'Symbols', inline = 's23')
bool T24 = input.bool(true, title = "", group = 'Symbols', inline = 's24')
bool T25 = input.bool(true, title = "", group = 'Symbols', inline = 's25')
bool T26 = input.bool(true, title = "", group = 'Symbols', inline = 's26')
bool T27 = input.bool(true, title = "", group = 'Symbols', inline = 's27')
bool T28 = input.bool(true, title = "", group = 'Symbols', inline = 's28')
bool T29 = input.bool(true, title = "", group = 'Symbols', inline = 's29')
bool T30 = input.bool(true, title = "", group = 'Symbols', inline = 's30')
bool T31 = input.bool(true, title = "", group = 'Symbols', inline = 's31')
bool T32 = input.bool(true, title = "", group = 'Symbols', inline = 's32')
bool T33 = input.bool(true, title = "", group = 'Symbols', inline = 's33')
bool T34 = input.bool(true, title = "", group = 'Symbols', inline = 's34')
bool T35 = input.bool(true, title = "", group = 'Symbols', inline = 's35')
bool T36 = input.bool(true, title = "", group = 'Symbols', inline = 's36')
bool T37 = input.bool(true, title = "", group = 'Symbols', inline = 's37')
bool T38 = input.bool(true, title = "", group = 'Symbols', inline = 's38')
bool T39 = input.bool(true, title = "", group = 'Symbols', inline = 's39')
bool T40 = input.bool(true, title = "", group = 'Symbols', inline = 's40')
string s01 = input.symbol('XRPUSDT', group = 'Symbols', inline = 's01',title = "Symbol 1")
string s02 = input.symbol('BTCUSDT', group = 'Symbols', inline = 's02',title = "Symbol 2")
string s03 = input.symbol('DOGEUSDT', group = 'Symbols', inline = 's03',title = "Symbol 3")
string s04 = input.symbol('BNBUSDT', group = 'Symbols', inline = 's04',title = "Symbol 4")
string s05 = input.symbol('ETHUSDT', group = 'Symbols', inline = 's05',title = "Symbol 5")
string s06 = input.symbol('ADAUSDT', group = 'Symbols', inline = 's06',title = "Symbol 6")
string s07 = input.symbol('XRPBTC', group = 'Symbols', inline = 's07',title = "Symbol 7")
string s08 = input.symbol('DOGEBTC', group = 'Symbols', inline = 's08',title = "Symbol 8")
string s09 = input.symbol('TRXUSDT', group = 'Symbols', inline = 's09',title = "Symbol 9")
string s10 = input.symbol('BTCBUSD', group = 'Symbols', inline = 's10',title = "Symbol 10")
string s11 = input.symbol('ETHBUSD', group = 'Symbols', inline = 's11',title = "Symbol 11")
string s12 = input.symbol('BNBBUSD', group = 'Symbols', inline = 's12',title = "Symbol 12")
string s13 = input.symbol('VETUSDT', group = 'Symbols', inline = 's13',title = "Symbol 13")
string s14 = input.symbol('ETHBTC', group = 'Symbols', inline = 's14',title = "Symbol 14")
string s15 = input.symbol('BNBBTC', group = 'Symbols', inline = 's15',title = "Symbol 15")
string s16 = input.symbol('EOSUSDT', group = 'Symbols', inline = 's16',title = "Symbol 16")
string s17 = input.symbol('XLMUSDT', group = 'Symbols', inline = 's17',title = "Symbol 17")
string s18 = input.symbol('LTCUSDT', group = 'Symbols', inline = 's18',title = "Symbol 18")
string s19 = input.symbol('XRPBUSD', group = 'Symbols', inline = 's19',title = "Symbol 19")
string s20 = input.symbol('WINUSDT', group = 'Symbols', inline = 's20',title = "Symbol 20")
string s21 = input.symbol('DOTUSDT', group = 'Symbols', inline = 's21',title = "Symbol 21")
string s22 = input.symbol('BTTUSDT', group = 'Symbols', inline = 's22',title = "Symbol 22")
string s23 = input.symbol('BCHUSDT', group = 'Symbols', inline = 's23',title = "Symbol 23")
string s24 = input.symbol('ADABTC', group = 'Symbols', inline = 's24',title = "Symbol 24")
string s25 = input.symbol('IOSTUSDT', group = 'Symbols', inline = 's25',title = "Symbol 25")
string s26 = input.symbol('CHZUSDT', group = 'Symbols', inline = 's26',title = "Symbol 26")
string s27 = input.symbol('LINKUSDT', group = 'Symbols', inline = 's27',title = "Symbol 27")
string s28 = input.symbol('TRXBTC', group = 'Symbols', inline = 's28',title = "Symbol 28")
string s29 = input.symbol('DOGEBUSD', group = 'Symbols', inline = 's29',title = "Symbol 29")
string s30 = input.symbol('BTCEUR', group = 'Symbols', inline = 's30',title = "Symbol 30")
string s31 = input.symbol('FILUSDT', group = 'Symbols', inline = 's31',title = "Symbol 31")
string s32 = input.symbol('HOTUSDT', group = 'Symbols', inline = 's32',title = "Symbol 32")
string s33 = input.symbol('SXPUSDT', group = 'Symbols', inline = 's33',title = "Symbol 33")
string s34 = input.symbol('ADABUSD', group = 'Symbols', inline = 's34',title = "Symbol 34")
string s35 = input.symbol('RVNUSDT', group = 'Symbols', inline = 's35',title = "Symbol 35")
string s36 = input.symbol('ATOMUSDT', group = 'Symbols', inline = 's36',title = "Symbol 36")
string s37 = input.symbol('XRPBNB', group = 'Symbols', inline = 's37',title = "Symbol 37")
string s38 = input.symbol('LTCBTC', group = 'Symbols', inline = 's38',title = "Symbol 38")
string s39 = input.symbol('IOSTBTC', group = 'Symbols', inline = 's39',title = "Symbol 39")
string s40 = input.symbol('GRTUSDT', group = 'Symbols', inline = 's40',title = "Symbol 40")
[positive01 , negative01] = GetData(s01) , [positive02 , negative02] = GetData(s02)
[positive03 , negative03] = GetData(s03) , [positive04 , negative04] = GetData(s04)
[positive05 , negative05] = GetData(s05) , [positive06 , negative06] = GetData(s06)
[positive07 , negative07] = GetData(s07) , [positive08 , negative08] = GetData(s08)
[positive09 , negative09] = GetData(s09) , [positive10 , negative10] = GetData(s10)
[positive11 , negative11] = GetData(s11) , [positive12 , negative12] = GetData(s12)
[positive13 , negative13] = GetData(s13) , [positive14 , negative14] = GetData(s14)
[positive15 , negative15] = GetData(s15) , [positive16 , negative16] = GetData(s16)
[positive17 , negative17] = GetData(s17) , [positive18 , negative18] = GetData(s18)
[positive19 , negative19] = GetData(s19) , [positive20 , negative20] = GetData(s20)
[positive21 , negative21] = GetData(s21) , [positive22 , negative22] = GetData(s22)
[positive23 , negative23] = GetData(s23) , [positive24 , negative24] = GetData(s24)
[positive25 , negative25] = GetData(s25) , [positive26 , negative26] = GetData(s26)
[positive27 , negative27] = GetData(s27) , [positive28 , negative28] = GetData(s28)
[positive29 , negative29] = GetData(s29) , [positive30 , negative30] = GetData(s30)
[positive31 , negative31] = GetData(s31) , [positive32 , negative32] = GetData(s32)
[positive33 , negative33] = GetData(s33) , [positive34 , negative34] = GetData(s34)
[positive35 , negative35] = GetData(s35) , [positive36 , negative36] = GetData(s36)
[positive37 , negative37] = GetData(s37) , [positive38 , negative38] = GetData(s38)
[positive39 , negative39] = GetData(s39) , [positive40 , negative40] = GetData(s40)
// Lets add the symbols into array using array.form to write less close
array<string> raw_names =
array.from(
s01,s02,s03,s04,s05,s06,s07,s08,s09,s10,
s11,s12,s13,s14,s15,s16,s17,s18,s19,s20,
s21,s22,s23,s24,s25,s26,s27,s28,s29,s30,
s31,s32,s33,s34,s35,s36,s37,s38,s39,s40
)
for name in raw_names
array.push(names, syminfo.ticker(name))
// Lets add the activation bool into array using array.form to write less close
array<bool> raw_bools =
array.from(
T01,T02,T03,T04,T05,T06,T07,T08,T09,T10,
T11,T12,T13,T14,T15,T16,T17,T18,T19,T20,
T21,T22,T23,T24,T25,T26,T27,T28,T29,T30,
T31,T32,T33,T34,T35,T36,T37,T38,T39,T40
)
for _bool in raw_bools
array.push(USEbool, _bool)
// Lets add the Positive signals into array using array.form to write less close
array<bool> raw_positive =
array.from(
positive01,positive02,positive03,positive04,positive05,
positive06,positive07,positive08,positive09,positive10,
positive11,positive12,positive13,positive14,positive15,
positive16,positive17,positive18,positive19,positive20,
positive21,positive22,positive23,positive24,positive25,
positive26,positive27,positive28,positive29,positive30,
positive31,positive32,positive33,positive34,positive35,
positive36,positive37,positive38,positive39,positive40
)
for _pos in raw_positive
array.push(rsi_pos, _pos)
// if the positive signal is false means we are in a Negative Trend .. So !
// We technically wouldn't require this negative signal. however, I included it for future purposes and potential utilization.
//
array<bool> raw_negative =
array.from(
negative01,negative02,negative03,negative04,negative05,
negative06,negative07,negative08,negative09,negative10,
negative11,negative12,negative13,negative14,negative15,
negative16,negative17,negative18,negative19,negative20,
negative21,negative22,negative23,negative24,negative25,
negative26,negative27,negative28,negative29,negative30,
negative31,negative32,negative33,negative34,negative35,
negative36,negative37,negative38,negative39,negative40
)
for _neg in raw_negative
array.push(rsi_neg, _neg)
// lets have out table to show the signal .
if barstate.islast
if show_table
text_color = show_table ? color.rgb(210, 210, 210) : color.black
table.cell(summary_table, 0, 0, table_name, bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)))
table.cell(summary_table, 1, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.cell(summary_table, 2, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.cell(summary_table, 3, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.cell(summary_table, 4, 0, "", bgcolor=color.from_gradient(close,low,high ,color.rgb(16, 194, 167), color.rgb(240, 141, 71)),text_halign = text.align_left)
table.merge_cells(summary_table, 0, 0, 4, 0)
table.cell(summary_table, 0, 1, 'Symbol', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
table.cell(summary_table, 1, 1, 'Status', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
table.cell(summary_table, 3, 1, 'Symbol', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
table.cell(summary_table, 4, 1, 'Status', bgcolor=color.rgb(120, 123, 134, 38),text_color = textcolos)
// first table
for i = 0 to 19
if array.get(USEbool, i)
table_cell(summary_table,(i+1)+ 1 , array.get(names, i),array.get(rsi_pos,i) ? "Positive" : "Negative",array.get(rsi_pos, i))
// 2nd table
for i = 20 to 39
if array.get(USEbool, i)
table_cell2(summary_table,(i-19) + 1 , array.get(names, i),array.get(rsi_pos,i) ? "Positive" : "Negative",array.get(rsi_pos, i))
// signal function
signal()=>
for i = 0 to 39
if array.get(rsi_pos, i)
conditioin = true
conditioin
sig = signal()
sig2 = not signal()
// plotting --
plotshape(sig and not sig[1], style=shape.labelup, location=location.belowbar, color=color.rgb(14, 232, 240), size=size.small,text = "P")
plotshape(sig2 and not sig2[1], style=shape.labeldown, location=location.abovebar, color=color.rgb(250, 165, 7), size=size.small,text = "N") |
HILOCLOP Analysis | https://www.tradingview.com/script/IkhW8Ko8-HILOCLOP-Analysis/ | dt440032 | https://www.tradingview.com/u/dt440032/ | 11 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ dt440032
//@version=5
indicator("HILOCLOP Analysis", overlay = false)
//Inputs-User Controllable
len = input(100, "Sample Length")
raw = input(true, 'Raw Up', tooltip="Shows the # of Higher 'High, Low, Open, Close' of the Sample")
raw1 = input(true, 'Raw Dn', tooltip="Shows the # of Lower 'High, Low, Open, Close' of the Sample")
hiclop = input(true, 'HICLOP', tooltip="HICLOP Analysis Color Scheme, Uncheck for Trend Analysis")
analysis = input(false, 'Analysis Up V Dn', tooltip="Shows the # of Occurences of where a Higher or Lower 'High, Low, Open, Close' all occured at once in the Sample")
analysis1 = input(false, 'Analysis High V Low', tooltip="Shows the # of Occurences of where there were more Higher Highs then Higher Lows in the Sample and Vice Versa")
analysis2 = input(false, 'Analysis Open V Close', tooltip="Shows the # of Occurences of where there were more Higher Closes then Higher Opens in the Sample and Vice Versa")
//Root Calculations
high1 = high[1]
low1 = low[1]
open1 = open[1]
close1 = close[1]
uptrend = high1 < high
uptrend1 = low1 < low
uptrend2 = open1 < open
uptrend3 = close1 < close
dntrend = high1 > high
dntrend1 = low1 > low
dntrend2 = open1 > open
dntrend3 = close1 > close
//Raw Forms
cnt = math.sum(uptrend ? 1 : 0, len)
cnt1 = math.sum(uptrend1 ? 1 : 0, len)
cnt2 = math.sum(uptrend2 ? 1 : 0, len)
cnt3 = math.sum(uptrend3 ? 1 : 0, len)
cnt4 = math.sum(dntrend ? 1 : 0, len)
cnt5 = math.sum(dntrend1 ? 1 : 0, len)
cnt6 = math.sum(dntrend2 ? 1 : 0, len)
cnt7 = math.sum(dntrend3 ? 1 : 0, len)
color1 = cnt > cnt[1] ? color.white:color.black
color2 = cnt1 > cnt1[1] ? color.blue:color.black
color3 = cnt2 > cnt2[1] ? color.red:color.black
color4 = cnt3 > cnt3[1] ? color.orange:color.black
color9= cnt4 > cnt4[1] ? color.rgb(0, 169, 31):color.black
color10 = cnt5 > cnt5[1] ? color.rgb(0, 169, 31):color.black
color11 = cnt6 > cnt6[1] ? color.rgb(0, 169, 31):color.black
color12 = cnt7 > cnt7[1] ? color.rgb(0, 169, 31):color.black
col1 = hiclop ? color1:color9
col2 = hiclop ? color2:color10
col3 = hiclop ? color3:color11
col4 = hiclop ? color4:color12
plot(raw? cnt:na, color = col1, title = "HighU")
plot(raw? cnt1:na, color = col2, title = "LowU")
plot(raw? cnt2:na, color = col3, title = "OpenU")
plot(raw? cnt3:na, color = col4, title = "CloseU")
color5= cnt4 > cnt4[1] ? color.white:color.black
color6 = cnt5 > cnt5[1] ? color.blue:color.black
color7 = cnt6 > cnt6[1] ? color.red:color.black
color8 = cnt7 > cnt7[1] ? color.orange:color.black
color13= cnt4 > cnt4[1] ? color.rgb(255, 0, 0):color.black
color14 = cnt5 > cnt5[1] ? color.rgb(255, 0, 0):color.black
color15 = cnt6 > cnt6[1] ? color.rgb(255, 0, 0):color.black
color16 = cnt7 > cnt7[1] ? color.rgb(255, 0, 0):color.black
col5 = hiclop ? color5:color13
col6 = hiclop ? color6:color14
col7 = hiclop ? color7:color15
col8 = hiclop ? color8:color16
plot(raw1? cnt4:na, color = col5, title = "HighD")
plot(raw1? cnt5:na, color = col6, title = "LowD")
plot(raw1? cnt6:na, color = col7, title = "OpenD")
plot(raw1? cnt7:na, color = col8, title = "CloseD")
//Analysis
up = cnt > cnt[1] and cnt1 > cnt1[1] and cnt2 > cnt2[1] and cnt3 > cnt3[1]
cnt8 = math.sum(up ? 1 : 0, len)
dn = cnt4 > cnt4[1] and cnt5 > cnt5[1] and cnt6 > cnt6[1] and cnt7 > cnt7[1]
cnt9 = math.sum(dn ? 1 : 0, len)
up1 = cnt > cnt1
cnt10 = math.sum(up1 ? 1 : 0, len)
dn1 = cnt < cnt1
cnt11 = math.sum(dn1 ? 1 : 0, len)
up2 = cnt3 > cnt2
cnt12 = math.sum(up2 ? 1 : 0, len)
dn2 = cnt3 < cnt2
cnt13 = math.sum(dn2 ? 1 : 0, len)
plot(analysis? cnt8:na, color = cnt8 > cnt8[1] ? color.rgb(0, 255, 229):color.rgb(0, 0, 0, 100), title = "All Up", style= plot.style_circles, linewidth = 3)
plot(analysis? cnt9:na, color = cnt9 > cnt9[1] ? color.rgb(255, 0, 72):color.rgb(0, 0, 0, 100), title = "All Dn", style= plot.style_circles, linewidth = 3)
plot(analysis1? cnt10:na, color = cnt > cnt1 ? color.rgb(0, 255, 229):color.rgb(0, 0, 0, 100), title = "High Over Low", style= plot.style_circles, linewidth = 3)
plot(analysis1? cnt11:na, color = cnt1 > cnt ? color.rgb(255, 0, 72):color.rgb(0, 0, 0, 100), title = "Low Over High", style= plot.style_circles, linewidth = 3)
plot(analysis2? cnt12:na, color = cnt3 > cnt2 ? color.rgb(0, 255, 229):color.rgb(0, 0, 0, 100), title = "Close Over Open", style= plot.style_circles, linewidth = 3)
plot(analysis2? cnt13:na, color = cnt2 > cnt3 ? color.rgb(255, 0, 72):color.rgb(0, 0, 0, 100), title = "Open Over Close", style= plot.style_circles, linewidth = 3)
|
ARSIX | https://www.tradingview.com/script/Rau0VnXg-ARSIX/ | morady0hamid | https://www.tradingview.com/u/morady0hamid/ | 56 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ morady0hamid
//@version=5
indicator('ARSIX' , precision = 0,
timeframe = '', timeframe_gaps = false, explicit_plot_zorder = true)
// inputs
len = input(14, title='Length')
mom = input.int(4, title='Momentum', minval=0)
mom20 = input.int(20, title='Momentum20', minval=0)
ob = input(70, title='Overbought')
os = input(30, title='Oversold')
c = close
docol = input(true, title='Change Color?')
showemasignal = input(false, title='Show EMA Signal Line?')
showcomposignal = input(false, title='Show Copmposite Signal Line?')
smaLength = input(9, title='SMA Length')
sigone = input(9, title='Signal One Length')
sigtwo = input(33, title='Signal Two Length')
dohist = input(true , title='Show Hist?')
showrmi = input(false, title='Show RMI?')
showrmi20 = input(true, title='Show RMI20?')
showcomposite = input(false, title='Show Composite?')
showrsi = input(true, title='Show RSI?')
showrsiemas = input(false, title='Show RSI ENAs?')
//calc
upp = ta.ema(math.max(c - c[mom], 0), len)
dnn = ta.ema(math.max(c[mom] - c, 0), len)
rmi = dnn == 0 ? 0 : 100 - 100 / (1 + upp / dnn)
up20 = ta.ema(math.max(c - c[mom20], 0), len)
dn20 = ta.ema(math.max(c[mom20] - c, 0), len)
rmi20 = dnn == 0 ? 0 : 100 - 100 / (1 + up20 / dn20)
rmiema = ta.ema(rmi, smaLength)
signalone = ta.ema(rmi, sigone)
signaltwo = ta.ema(rmi, sigtwo)
histogram = dohist ? rmi - rmiema : na
histup = true ? histogram >= 0 : na
histdown = true ? histogram < 0 : na
plot(histup ? histogram : na, title='RMIs Histogram UP', color=color.rgb(0, 68, 0, 86), histbase=0, style=plot.style_histogram, linewidth=4)
plot(histdown ? histogram : na, title='RMIs Histogram DOWN', color=color.rgb(107, 1, 168, 86), histbase=0, style=plot.style_histogram, linewidth=4)
//plots
//hline(ob)
//hline(os)
//plot( dohist?(rmi-rmisma)+50:na , color=color.rgb(0, 68, 89 , 58) ,histbase=50,style=plot.style_histogram ,linewidth=3 , title = "RMI's Histogram")
//plot( histogram ? color.rgb(0,68,0,50) : color.rgb(255,0,0,50) ,histbase=50,style=plot.style_histogram ,linewidth=3 , title = "RMI's Histogram")
plot(showemasignal ? signalone : na, color=color.new(color.orange, 0), title='RMI\'s EMA ONE line')
plot(showemasignal ? signaltwo : na, color=color.new(color.green, 0), title='RMI\'s EMA TWO line')
col = docol ? rmi > rmi[1] ? color.rgb(73, 225, 252, 11) : color.rgb(255, 176, 73, 21) : #0094FF
plot(showrmi ? rmi : na, color=col, linewidth=2, title='RMI line')
plot(showrmi20 ? (rmi20/2)-25 : na, color=col, linewidth=2, title='RMI line')
/////composite
rsi_length = input(14, title='RSI Length')
rsi_mom_length = input(9, title='RSI Momentum Length')
rsi_ma_length = input(3, title='RSI MA Length')
ma_length = input(3, title='SMA Length')
fastLength = input(13)
slowLength = input(33)
r = ta.rsi(close, rsi_length)
rsidelta = ta.mom(r, rsi_mom_length)
rsisma = ta.sma(ta.rsi(close, rsi_ma_length), ma_length)
composit = rsidelta + rsisma
compositline = composit / 2 + 25
greenline = ta.sma(composit, fastLength) / 2 + 25
redline = ta.sma(composit, slowLength) / 2 + 25
rsiemasignalone = ta.ema(r, 19)
rsiemasignaltwo = ta.ema(r, 66)
plot(showcomposignal ? greenline : na, color=color.new(color.green, 0), title='Green Line')
plot(showcomposignal ? redline : na, color=color.new(color.red, 0), title='Red Line')
plot(showcomposite ? (compositline)-175 : na, color=color.rgb(254, 0, 1), linewidth=2, title='Composite Line')
plot(showrsi ? (r)-50 : na, color=color.new(#423ffc, 0), linewidth=2, title='RSI line')
plot(showrsiemas ? rsiemasignalone : na, color=color.new(color.orange, 0), linewidth=1, title='RSI EMA ONE')
plot(showrsiemas ? rsiemasignaltwo : na, color=color.new(color.green, 0), linewidth=1, title='RSI EMA TWO')
//LINES
// rmizeroline = hline(0, color=color.rgb(68,0,0,68) , title = "RMI 0 Level" )
rsi70 = hline(20, color=color.rgb(255, 174, 69, 67) , title = "RSI 60 Level" )
rsi60 = hline(10, color=color.rgb(250, 66, 66, 59) , title = "RSI 70 Level" )
rsi30 = hline(30, color=color.rgb(72, 210, 245, 66) , title = "RSI 30 Level" )
rsi50 = hline(50, color=color.rgb(70, 203, 255, 63) , title = "RSI 33.3 Level" )
rsimines35= hline(-35,color=color.rgb(255, 176, 73, 59) , title = "RSI 30 Level")
rsimines20= hline(-20, color=color.rgb(253, 69, 69, 60) , title = "RSI 20 Level")
rsimines50 = hline(-50, color=color.rgb(70, 203, 255, 54) , title = "RSI -50 Level" )
//rsi67 = hline(66.67, color=color.rgb(69, 252, 252, 60) , title = "RSI 66.67 Level" )
everex70 = hline(75, color=color.rgb(76, 219, 255) , title = "Everex 70 Level" )
//rsi80 = hline(35, color=color.rgb(71, 247, 106, 60), title = "RSI 80 Level" )
rsi85 = hline(40, color=color.rgb(74, 243, 130, 60) , title = "RSI 85 Level" )
// rmihanderedline = hline(100, color=color.rgb(68,0,0,68) , title = "RMI 100 Level" )
// fill(rsi85 , rsi80 , color=color.rgb(222, 219, 227 , 80) , title = "RSI MIDDLE Level")
// fill(rsi70 , rsi67 , color=color.rgb(103, 151, 34 , 95) , title = "RSI MIDDLE Level")
// fill(rsiMiddleDownLevel , rsiMiddleUpLevel, color=color.aqua , transp = 90, title = "RSI MIDDLE Level")
// fill(rsi33 , rsi30, color=color.rgb(255, 87, 80 , 95) , title = "RSI MIDDLE Level")
// fill(rsi20 , rsi15 , color=color.rgb(222, 219, 227 , 80) , title = "RSI MIDDLE Level")
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ RedKTrader - March 2023
//@version=5
// ******************************
// EVEREX v2.0 adds markers for key patterns based on nPrice:nVol ratios
// starting with EoM and Compression - maybe add "Balanced" and "Mega" ??
// to-do list
// inspecting the effort vs result concept by plotting volume vs. price change
// this is like looking at distance versus fuel consumption - but comparing a normalized average of each
// to help reveal areas of volume & price action anomalies, contraction & expansion
//indicator('RedK Effort Versus Results Explorer v2.0', 'RedK EVEREX v2.0')
// ***********************************************************************************************************
// This function calcualtes a selectable average type
GetAverage(_data, _len, MAOption) =>
value = switch MAOption
'SMA' => ta.sma(_data, _len)
'EMA' => ta.ema(_data, _len)
'HMA' => ta.hma(_data, _len)
'RMA' => ta.rma(_data, _len)
=>
ta.wma(_data, _len)
// ***********************************************************************************************************
// ========================================================================================
// Normalization function - Normalizes values that are not restricted within a zero to 100 range
// This technique provides a scale that is closer to a "human" estimation of value in "bands"
// as in: low, below average, average, above average, high, super high
// this also avoids the issue of extreme values when using the stoch() -based technique
// these values are subjective, and can be changed - but slight changes here won't lead to major changes in outcome
// since all is relative to the same data series.
//
Normalize(_Value, _Avg) =>
_X = _Value / _Avg
_Nor =
_X > 1.50 ? 1.00 :
_X > 1.20 ? 0.90 :
_X > 1.00 ? 0.80 :
_X > 0.80 ? 0.70 :
_X > 0.60 ? 0.60 :
_X > 0.40 ? 0.50 :
_X > 0.20 ? 0.25 :
0.1
// ===================================================================================
// ===========================================================================================================
// Inputs
// ===========================================================================================================
grp_1 = 'Rate of FLow (RoF)'
grp_2 = 'Lookback Parameters'
grp_3 = 'Bias / Sentiment'
grp_4 = 'EVEREX Bands'
length = input.int(10, minval = 1, inline = 'ROF', group = grp_1)
MA_Type = input.string(defval = 'WMA', title = 'MA type',
options = ['WMA', 'EMA', 'SMA', 'HMA', 'RMA'], inline = 'ROF', group = grp_1)
smooth = input.int(defval = 3, title = 'Smooth', minval = 1, inline = 'ROF', group = grp_1)
//src = input.source(close, title = "Source (for 2-Bar Shift)", group = grp_1)
sig_length = input.int(5, 'Signal Length', minval = 1, inline = 'Signal', group = grp_1)
S_Type = input.string(defval = 'WMA', title = 'Signal Type',
options = ['WMA', 'EMA', 'SMA', 'HMA', 'RMA'], inline = 'Signal', group = grp_1)
lookback = input.int(defval = 20, title = 'Length', minval = 1, inline = 'Lookback', group = grp_2)
lkbk_Calc = input.string(defval = 'Simple', title = 'Averaging',
options = ['Simple', 'Same as RRoF'], inline='Lookback', group = grp_2 )
showBias = input.bool(defval = false, title = 'Bias Plot ? -- ', inline = 'Bias', group = grp_3)
B_Length = input.int(defval = 30, title = 'Length', minval = 1, inline = 'Bias', group = grp_3)
B_Type = input.string(defval = 'WMA', title = 'MA type',
options = ['WMA', 'EMA', 'SMA', 'HMA', 'RMA'], inline = 'Bias', group = grp_3)
showEVEREX = input.bool(true, 'Show EVEREX Bands ? -- ', inline = 'EVEREX', group = grp_4)
// a simple mechanism to control/change the strength band scale for improving visualization
// applies only to the "bands" and the level hlines
bandscale = str.tonumber(input.string("100", title = "Band Scale",
options = ['100', '200', '400'], inline = 'EVEREX', group = grp_4))
DispBias = showBias ? display.pane : display.none
DispBands = showEVEREX ? display.pane : display.none
showhlines = showEVEREX ? display.all : display.none
Disp_vals = display.status_line + display.data_window
// ===========================================================================================================
// Calculations
// ===========================================================================================================
// Volume "effort" Calculation -- will revert to no volume acceleration for instruments with no volume data
v = na(volume) ? 1 : volume // this part ensures we're not hit with calc issues due to NaN's
NoVol_Flag = na(volume) ? true : false // this is a flag to use later
lkbk_MA_Type = lkbk_Calc == 'Simple' ? 'SMA' : MA_Type
Vola = GetAverage(v, lookback, lkbk_MA_Type)
Vola_n_pre = Normalize(v, Vola) * 100
//Now trap the case of no volume data - ensure final calculation not impacted
Vola_n = NoVol_Flag ? 100 : Vola_n_pre
//plot(Vola_n , "Volume Normalized", color = color.white, display = display.none)
// ===============================================================================================================
// Price "result" calculation
// we'll consider "result" (strength or weakness) to be the outcome (average) of 6 elements:
// Same (in-)Bar strength elements:
// 1 - Bar Closing: the closing within the bar --> this will be a direct +100 / -100 value
// 2 - Spread to range: the spread to range ratio (that's BoP formula) --> direct +100 / -100 value
// 3 - Relative Spread: spread relative to average spread during lookback period --> normalized
// 2-bar strength elements:
// 4 - 2-bar closing: the closing within 2-bar range (that accomodates open gap effect)
// 5 - 2-bar Closing Shift to Range: Change in close relative to the 2-bar range
// 6 - 2-bar Relative Shift: the 2-bar Close (or source price) shift - relative to the average 2-bar shift during lookback period --> normalized
BarSpread = close - open
BarRange = high - low
R2 = ta.highest(2) - ta.lowest(2)
SrcShift = ta.change(close)
//TR = ta.tr(true)
sign_shift = math.sign(SrcShift)
sign_spread = math.sign(BarSpread)
// =========================================================================================================
// in-bar assessments
// =========================================================================================================
// 1. Calculate closing within bar - should be max value at either ends of the bar range
barclosing = 2 * (close - low) / BarRange * 100 - 100
//plot(barclosing, "Bar Closing %" , color=color.fuchsia, display = display.none)
// 2. caluclate spread to range ratio
s2r = BarSpread / BarRange * 100
//plot(s2r, "Spread:Range", color = color.lime, display = display.none)
// 3. Calculate relative spread compared to average spread during lookback
BarSpread_abs = math.abs(BarSpread)
BarSpread_avg = GetAverage(BarSpread_abs, lookback, lkbk_MA_Type)
BarSpread_ratio_n = Normalize(BarSpread_abs, BarSpread_avg) * 100 * sign_spread
//plot(BarSpread_ratio_n, "Bar Spread Ratio", color=color.orange, display=display.none)
// =========================================================================================================
// 2-bar assessments
// =========================================================================================================
// 4. Calculate closing within 2 bar range - should be max value at either ends of the 2-bar range
barclosing_2 = 2 * (close - ta.lowest(2)) / R2 * 100 - 100
//plot(barclosing_2, "2-Bar Closing %" , color=color.navy, display = display.none)
// 5. calculate 2-bar shift to range ratio
Shift2Bar_toR2 = SrcShift / R2 * 100
//plot(Shift2Bar_toR2, "2-bar Shift vs 2R", color=color.yellow, display = display.none)
// 6. Calculate 2-bar Relative Shift
SrcShift_abs = math.abs(SrcShift)
srcshift_avg = GetAverage(SrcShift_abs, lookback, lkbk_MA_Type)
srcshift_ratio_n = Normalize(SrcShift_abs, srcshift_avg) * 100 * sign_shift
//plot(srcshift_ratio_n, "2-bar Shift vs Avg", color=color.white, display = display.none)
// ===============================================================================
// =========================================================================================
// Relative Price Strength combining all strength elements
Pricea_n = (barclosing + s2r + BarSpread_ratio_n + barclosing_2 + Shift2Bar_toR2 + srcshift_ratio_n) / 6
//plot(Pricea_n, "Price Normalized", color=color.orange, display = display.none)
//Let's take Bar Flow as the combined price strength * the volume:avg ratio
// this works in a similar way to a volume-weighted RSI
bar_flow = Pricea_n * Vola_n / 100
//plot(bar_flow, 'bar_flow', color=color.green, display = display.none)
// calc avergae relative rate of flow, then smooth the resulting average
// classic formula would be this
//RROF = f_ma(bar_flow, length, MA_Type)
//
// or we can create a relative index by separating bulls from bears, like in an RSI - my preferred method
// here we have an added benefit of plotting the (average) bulls vs bears separately - as an option
bulls = math.max(bar_flow, 0)
bears = -1 * math.min(bar_flow, 0)
bulls_avg = GetAverage(bulls, length, MA_Type)
bears_avg = GetAverage(bears, length, MA_Type)
dx = bulls_avg / bears_avg
RROF = 2 * (100 - 100 / (1 + dx)) - 100
RROF_s = ta.wma(RROF, smooth)
Signal = GetAverage(RROF_s, sig_length, S_Type)
// Calculate Bias / sentiment on longer length
dx_b = GetAverage(bulls, B_Length, B_Type) / GetAverage(bears, B_Length, B_Type)
RROF_b = 2 * (100 - 100 / (1 + dx_b)) - 100
RROF_bs = ta.wma(RROF_b, smooth)
// ===========================================================================================================
// Colors & plots
// ===========================================================================================================
c_zero = color.new(#1161f6, 62)
c_band = color.new(#41e981, 50)
c_up = color.aqua
c_dn = color.orange
c_sup = color.new(#00aa00, 70)
c_sdn = color.new(#ff180b, 70)
up = RROF_s >= 0
s_up = RROF_bs >=0
// ==================================== Plots ==========================================================
// // Display the ATR & VOl Ratio values only on the indicator status line & in the Data Window
// plotchar(shift, title = "Shift", char = "", color = color.white, editable=false, display=display.status_line + display.data_window)
// plotchar(lbk_tr, title = "Avg Shift", char = "", color = color.aqua, editable=false, display=display.status_line + display.data_window)
// plotchar(vola/lbk_vola, title = "Vol Ratio", char = "", color = color.yellow, editable=false, display=display.status_line + display.data_window)
hline(0, 'Zero Line', c_zero, linestyle = hline.style_solid)
// plot the band scale guide lines -- these lines will show/hide along with the EVEREX "Equalizer Bands Plot"
hline(0.25 * bandscale, title = '1/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
hline(0.50 * bandscale, title = '2/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
hline(0.75 * bandscale, title = '3/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
hline(bandscale, title = '4/4 Level', color=c_band, linestyle = hline.style_dotted, display = showhlines)
// Plot Bulls & Bears - these are optional plots and hidden by default - adjust this section later
plot(ta.wma(bulls_avg, smooth), "Bulls", color = #11ff20, linewidth = 2, display = display.none)
plot(ta.wma(bears_avg, smooth), "Bears", color = #d5180b, linewidth = 2, display = display.none)
// =============================================================================
// Plot Bias / Sentiment
plot (RROF_bs, "Bias / Sentiment", style=plot.style_area,
color = s_up ? c_sup : c_sdn, linewidth = 4, display = DispBias )
// =============================================================================
// Plot Price Strength & Relative Volume as stacked "equalizer bands"
// adding visualization option to make the bands joint or separate at the mid-scale mark
Eq_band_option = input.string("Joint", title = 'Band Option', options = ["Joint", "Separate"], group = grp_4)
nPrice = math.max(math.min(Pricea_n, 100), -100)
nVol = math.max(math.min(Vola_n, 100), -100)
bar = bar_flow
c_vol_grn = color.new(#26a69a, 75)
c_vol_red = color.new(#ef5350, 75)
cb_vol_grn = color.new(#26a69a, 20)
cb_vol_red = color.new(#ef5350, 20)
c_vol = bar > 0 ? c_vol_grn : c_vol_red
cb_vol = bar > 0 ? cb_vol_grn : cb_vol_red
vc_lo = 0
vc_hi = nVol * bandscale / 100 / 2
//plotcandle(vc_lo, vc_hi, vc_lo, vc_hi , "Volume Band", c_vol, c_vol, bordercolor = cb_vol, display = DispBands)
c_pri_grn = color.new(#3ed73e, 75)
c_pri_red = color.new(#ff870a, 75)
cb_pri_grn = color.new(#3ed73e, 20)
cb_pri_red = color.new(#ff870a, 20)
c_pri = bar > 0 ? c_pri_grn : c_pri_red
cb_pri = bar > 0 ? cb_pri_grn : cb_pri_red
pc_lo_base = Eq_band_option == "Joint" ? vc_hi : 0.50 * bandscale
pc_lo = pc_lo_base
pc_hi = pc_lo_base + math.abs(nPrice) * bandscale / 100 / 2
//plotcandle(pc_lo, pc_hi, pc_lo ,pc_hi , "Price Band", c_pri, c_pri, bordercolor = cb_pri, display = DispBands)
// print the normalized volume and price values - only on statys line and in the data window
// these values are independant of the band scale or visualization options
plotchar(nVol/2 + 75, "Normalized Vol", char = "", color = c_vol, editable = false, display = Disp_vals)
plotchar(nPrice/2 + 75, "Normalized Price", char = "", color = c_pri, editable = false, display = Disp_vals)
// =============================================================================
// =============================================================================
// Plot main plot, smoothed plot and signal line
plot(RROF/2 + 75, 'RROF Raw', color.new(#2470f0, 9), display=display.none)
plot(RROF_s/2 + 75 , 'RROF Smooth', color = color.new(#fc427a, 100), linewidth = 2)
plot(Signal/2 + 75 , "Signal Line", up ? c_up : c_dn, 3)
// ===========================================================================================================
// basic alerts
// ===========================================================================================================
Alert_up = ta.crossover(RROF_s,0)
Alert_dn = ta.crossunder(RROF_s,0)
Alert_swing = ta.cross(RROF_s,0)
// "." in alert title for the alerts to show in the right order up/down/swing
alertcondition(Alert_up, ". RROF Crossing 0 Up", "RROF Up - Buying Action Detected!")
alertcondition(Alert_dn, ".. RROF Crossing 0 Down", "RROF Down - Selling Action Detected!")
alertcondition(Alert_swing, "... RROF Crossing 0", "RROF Swing - Possible Reversal")
// ===========================================================================================================
// v2.0 Adding Markers for Key Patterns
// ===========================================================================================================
// we can re-utilize the Normailize() function here too - but it's cleaner to have a separate ratio calc
nPrice_abs = math.abs(nPrice)
//EV_Ratio = 100 * Normalize(nPrice_abs, nVol)
EV_Ratio = 100 * nPrice_abs / nVol
// initial mapping of return ratios (to be revised)
// -------------------------------------------------------
// Case (1): Price > Vol => ratio > 120 = Ease of Move (EoM)
// Case (2): Price close to Vol => ratio between 80 - 120 = Reasonable Balance
// Case (3): Price less than Vol but reasonable => ratio between 80 - 50 = Drift / "nothing much to see here" bar
// Case (4): Price a lot less than Vol => 50 or less = Compression / Squat
// we're most interested in cases 1 & 4
//plot (EV_Ratio) // for validation only
is_positive = nPrice > 0
is_Compression = EV_Ratio <= 50
is_EoM = EV_Ratio >= 120
//Provide option to show/hide those EVEREX Markers - and an option for Compression bar
// - some folks would prefer a cross, others may prefer a circle - can adjust based on feedback
// no option for Ease of Move, guessing the triangle has the right significance
var showMarkers = input.bool(true, 'Show EVEREX Markers ?')
var Mshape = input.string("Circles", "Compression Marker", options = ['Circles','Crosses'])
SetShape(_x) =>
switch _x
'Circles' => shape.circle
'Crosses' => shape.cross
//** Plot markers
//plotshape(showMarkers and is_EoM and is_positive ? 0 : na, "EoM +ve", shape.triangleup, color=color.green,
//location=location.absolute, size=size.auto, editable = false, display = display.pane)
//plotshape(showMarkers and is_EoM and not(is_positive) ? 0 : na, "EoM -ve", shape.triangledown, color=color.red,
//location=location.absolute, size=size.auto, editable = false, display = display.pane)
//plotshape(showMarkers and is_Compression and is_positive ? 0 : na, "Compression +ve", style = SetShape(Mshape),
//color=color.green, location=location.absolute, size = size.auto, editable = false, display = display.pane)
//plotshape(showMarkers and is_Compression and not(is_positive) ? 0 : na, "Compression -ve", style = SetShape(Mshape),
// color=color.red, location=location.absolute, size=size.auto, editable = false, display = display.pane)
|
Colors | https://www.tradingview.com/script/zOp6CsPr-Colors/ | miivanov | https://www.tradingview.com/u/miivanov/ | 3 | library | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ miivanov
//@version=5
// @description Helpers for color manipulations
library("Colors")
// @function Applies opacity to color
// @param oldColor color
// @param opacity opacity
// @returns color with opacity
export opacify(color oldColor, float opacity) =>
color.rgb(color.r(oldColor), color.g(oldColor), color.b(oldColor), opacity)
// @function Gets two colors as parameters and number of colors you need. Returns range of colors between them
// @param topColor color color
// @param bottomColor color
// @param numColors number of colors in range
export getColorsRange(color topColor, color bottomColor, int numColors) =>
var result = array.new<color>()
for i = 1 to 6
array.push(result, color.from_gradient(i, 1, numColors, topColor, bottomColor))
result |
Webby's Tight Indicator | https://www.tradingview.com/script/YaNSPhOj-Webby-s-Tight-Indicator/ | Amphibiantrading | https://www.tradingview.com/u/Amphibiantrading/ | 199 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Amphibiantrading
//@version=5
indicator("Webby's Tight Indicator", shorttitle = 'Webby\'s Tight')
//inputs
upColor = input.color(color.blue, 'Positive Ratio Color')
downColor = input.color(color.red, 'Negative Ratio Color')
showEma = input.bool(true, 'Show EMA')
showHiLo = input.bool(false, 'Show Highest / Lowest Ratio')
//short atrs
short1 = ta.atr(3)
short2 = ta.atr(5)
short3 = ta.atr(8)
shortAvg = (short1 + short2 + short3) / 3
//long atrs
long1 = ta.atr(55)
long2 = ta.atr(89)
long3 = ta.atr(144)
longAvg = (long1 + long2 + long3) / 3
// calculations
ratio = (longAvg - shortAvg) / math.max(longAvg, shortAvg)
ema = ta.ema(ratio, 5)
//colors
histCol = ratio > 0 ? upColor : downColor
emaCol = ema > ema[1] ? color.green : color.red
//plots
plot(ratio, 'Ratio', color= histCol, style = plot.style_histogram)
plot(showEma ? ema : na, 'Ema of Ratio', color = emaCol)
//highest lowest
var label hLab = na
var label lLab = na
highest = ta.highest(ratio,251)
lowest = ta.lowest(ratio,251)
if ratio == highest and showHiLo
(hLab[1]).delete()
hLab := label.new(bar_index, ratio, style = label.style_xcross ,size = size.tiny, color=color.green)
if ratio == lowest and showHiLo
(lLab[1]).delete()
lLab := label.new(bar_index, ratio, style = label.style_xcross ,size = size.tiny, color=color.green)
|
CE - Market Performance Table | https://www.tradingview.com/script/b3k0PAWb-CE-Market-Performance-Table/ | Celestial-Eye | https://www.tradingview.com/u/Celestial-Eye/ | 107 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Celestial-Eye
//@version=5
indicator("๐ CE - ๐๐ช๐ป๐ด๐ฎ๐ฝ ๐๐ฎ๐ป๐ฏ๐ธ๐ป๐ถ๐ช๐ท๐ฌ๐ฎ ๐ฃ๐ช๐ซ๐ต๐ฎ ๐")
// Individual ticker symbols
SPHD = request.security("SPHD","D", close, barmerge.gaps_off)
SPLV = request.security("SPLV","D", close, barmerge.gaps_off)
QUAL = request.security("QUAL","D", close, barmerge.gaps_off)
DEF = request.security("DEF", "D", close, barmerge.gaps_off)
IWF = request.security("IWF", "D", close, barmerge.gaps_off)
SPHB = request.security("SPHB","D", close, barmerge.gaps_off)
IYT = request.security("IYT", "D", close, barmerge.gaps_off)
IWN = request.security("IWN", "D", close, barmerge.gaps_off)
IWD = request.security("IWD", "D", close, barmerge.gaps_off)
IWM = request.security("IWM", "D", close, barmerge.gaps_off)
IWR = request.security("IWR", "D", close, barmerge.gaps_off)
MGK = request.security("MGK", "D", close, barmerge.gaps_off)
OEF = request.security("OEF", "D", close, barmerge.gaps_off)
MTUM = request.security("MTUM","D", close, barmerge.gaps_off)
IWB = request.security("IWB", "D", close, barmerge.gaps_off)
// // Plotting the close prices - for convenience
// plot(SPHD, color=color.blue, title="SPHD")
// plot(SPLV, color=color.red, title="SPLV")
// plot(QUAL, color=color.green, title="QUAL")
// plot(DEF, color=color.orange, title="DEF")
// plot(IWF, color=color.purple, title="IWF")
// plot(SPHB, color=color.yellow, title="SPHB")
// plot(IYT, color=color.teal, title="IYT")
// plot(IWN, color=color.maroon, title="IWN")
// plot(IWD, color=color.fuchsia, title="IWD")
// plot(IWM, color=color.gray, title="IWM")
// plot(IWR, color=color.olive, title="IWR")
// plot(MGK, color=color.aqua, title="MGK")
// plot(OEF, color=color.navy, title="OEF")
// plot(MTUM, color=color.lime, title="MTUM")
// plot(IWB, color=color.silver, title="IWB")
showCorrTab = input.bool(true, "Show Correlation Table", tooltip = "Plots the Correlation table", group = "๐ Table Settings Correlation ๐")
l = input.int (14, "Correlation Length", tooltip = "Defines the time horizon for the Correlation Table", group = "๐ Table Settings Correlation ๐")
showPerfTab = input.bool(true, "Show Performance Table", tooltip = "Plots the Performance table", group = "๐ Table Settings Performance ๐")
rocPeriod = input.int (14, "ROC Period", minval=1, tooltip = "Defines the time horizon for the Performance Table", group = "๐ Table Settings Performance ๐")
showCorr = input.bool(false, "Show Correlations?", group = "Visuals")
showTrend = input.bool(false, "Show Trends?", tooltip = "Only shows Trend Values in Status Line... In case you want to export it to Sheets or something", group = "Visuals")
showImplied = input.bool(false, "Show Implied Correlation?", tooltip = "Shows Implied Correlation on Chart, disable all other Visuals for best Experience", group = "Visuals")
// Calculate correlation
correlation_SPHD = ta.correlation(close, SPHD,l)
correlation_SPLV = ta.correlation(close, SPLV,l)
correlation_QUAL = ta.correlation(close, QUAL,l)
correlation_DEF = ta.correlation(close, DEF,l)
correlation_IWF = ta.correlation(close, IWF,l)
correlation_SPHB = ta.correlation(close, SPHB,l)
correlation_IYT = ta.correlation(close, IYT,l)
correlation_IWN = ta.correlation(close, IWN,l)
correlation_IWD = ta.correlation(close, IWD,l)
correlation_IWM = ta.correlation(close, IWM,l)
correlation_IWR = ta.correlation(close, IWR,l)
correlation_MGK = ta.correlation(close, MGK,l)
correlation_OEF = ta.correlation(close, OEF,l)
correlation_MTUM = ta.correlation(close, MTUM,l)
correlation_IWB = ta.correlation(close, IWB,l)
plot(showCorr and barstate.isconfirmed ? correlation_SPHD :na, color=color.teal, title="CORR SPHD")
plot(showCorr and barstate.isconfirmed ? correlation_SPLV :na, color=color.aqua, title="CORR SPLV")
plot(showCorr and barstate.isconfirmed ? correlation_QUAL :na, color=color.gray, title="CORR QUAL")
plot(showCorr and barstate.isconfirmed ? correlation_DEF :na, color=color.maroon, title="CORR DEF")
plot(showCorr and barstate.isconfirmed ? correlation_IWF :na, color=color.orange, title="CORR IWF")
plot(showCorr and barstate.isconfirmed ? correlation_SPHB :na, color=color.rgb(239, 136, 227), title="CORR SPHB")
plot(showCorr and barstate.isconfirmed ? correlation_IYT :na, color=color.yellow, title="CORR IYT")
plot(showCorr and barstate.isconfirmed ? correlation_IWN :na, color=color.yellow, title="CORR IWN")
plot(showCorr and barstate.isconfirmed ? correlation_IWD :na, color=color.fuchsia, title="CORR IWD")
plot(showCorr and barstate.isconfirmed ? correlation_IWM :na, color=color.purple, title="CORR IWM")
plot(showCorr and barstate.isconfirmed ? correlation_IWR :na, color=color.blue, title="CORR IWR")
plot(showCorr and barstate.isconfirmed ? correlation_MGK :na, color=color.red, title="CORR MGK")
plot(showCorr and barstate.isconfirmed ? correlation_OEF :na, color=color.olive, title="CORR OEF")
plot(showCorr and barstate.isconfirmed ? correlation_MTUM :na, color=color.lime, title="CORR MTUM")
plot(showCorr and barstate.isconfirmed ? correlation_IWB :na, color=color.silver, title="CORR IWB")
//Calculate Trend Value for each Asset with Normalized KAMA Oscillator by IKKE OMAR
// -> https://www.tradingview.com/script/OwtiIzT3-Normalized-KAMA-Oscillator-Ikke-Omar/
kama(asset) =>
// Define input parameters
fast_period = input.int(title='Fast Period', defval=7, minval=1, group = "Norm KAMA", tooltip = "Normalized KAMA Oscillator by IkkeOmar")
slow_period = input.int(title='Slow Period', defval=19, minval=1, group = "Norm KAMA")
er_period = input.int(title='Efficiency Ratio Period', defval=8, minval=1, group = "Norm KAMA")
norm_period = input.int(title='Normalization lookback', defval=10, minval=1, group = "Norm KAMA", tooltip = "Defines the time horizon for the Trend calculation of the ETF's - For longer term Trends over weeks or months a length of 50 is usually pretty accurate")
// Calculate the efficiency ratio
change = math.abs(asset - asset[er_period])
volatility = math.sum(math.abs(asset - asset[1]), er_period)
er = change / volatility
// Calculate the smoothing constant
sc = er * (2 / (fast_period + 1) - 2 / (slow_period + 1)) + 2 / (slow_period + 1)
// Calculate the KAMA
kama = ta.ema(asset, fast_period) + sc * (asset - ta.ema(asset, fast_period))
// Normalize the Oscillator
lowest = ta.lowest (kama, norm_period)
highest = ta.highest(kama, norm_period)
normalized = (kama - lowest) / (highest - lowest) - 0.5
normalized
kamaSPHD = kama(SPHD) > 0? 1 : -1
kamaSPLV = kama(SPLV) > 0? 1 : -1
kamaQUAL = kama(QUAL) > 0? 1 : -1
kamaDEF = kama(DEF) > 0? 1 : -1
kamaIWF = kama(IWF) > 0? 1 : -1
kamaSPHB = kama(SPHB) > 0? 1 : -1
kamaIYT = kama(IYT) > 0? 1 : -1
kamaIWN = kama(IWN) > 0? 1 : -1
kamaIWD = kama(IWD) > 0? 1 : -1
kamaIWM = kama(IWM) > 0? 1 : -1
kamaIWR = kama(IWR) > 0? 1 : -1
kamaMGK = kama(MGK) > 0? 1 : -1
kamaOEF = kama(OEF) > 0? 1 : -1
kamaMTUM = kama(MTUM) > 0? 1 : -1
kamaIWB = kama(IWB) > 0? 1 : -1
plot(showTrend?kamaSPHD :na, color=color.teal, title="Trend SPHD", display = display.status_line)
plot(showTrend?kamaSPLV :na, color=color.aqua, title="Trend SPLV", display = display.status_line)
plot(showTrend?kamaQUAL :na, color=color.gray, title="Trend QUAL", display = display.status_line)
plot(showTrend?kamaDEF :na, color=color.maroon, title="Trend DEF", display = display.status_line)
plot(showTrend?kamaIWF :na, color=color.orange, title="Trend IWF", display = display.status_line)
plot(showTrend?kamaSPHB :na, color=color.rgb(239, 136, 227), title="Trend SPHB", display = display.status_line)
plot(showTrend?kamaIYT :na, color=color.yellow, title="Trend IYT", display = display.status_line)
plot(showTrend?kamaIWN :na, color=color.yellow, title="Trend IWN", display = display.status_line)
plot(showTrend?kamaIWD :na, color=color.fuchsia, title="Trend IWD", display = display.status_line)
plot(showTrend?kamaIWM :na, color=color.purple, title="Trend IWM", display = display.status_line)
plot(showTrend?kamaIWR :na, color=color.blue, title="Trend IWR", display = display.status_line)
plot(showTrend?kamaMGK :na, color=color.red, title="Trend MGK", display = display.status_line)
plot(showTrend?kamaOEF :na, color=color.olive, title="Trend OEF", display = display.status_line)
plot(showTrend?kamaMTUM :na, color=color.lime, title="Trend MTUM", display = display.status_line)
plot(showTrend?kamaIWB :na, color=color.silver, title="Trend IWB", display = display.status_line)
//Calculate Implied Correlation
ImplCorrAvg = math.avg(
math.round(correlation_SPHD* kamaSPHD, 2),
math.round(correlation_SPLV* kamaSPLV, 2),
math.round(correlation_QUAL* kamaQUAL, 2),
math.round(correlation_DEF* kamaDEF, 2),
math.round(correlation_IWF* kamaIWF, 2),
math.round(correlation_SPHB* kamaSPHB, 2),
math.round(correlation_IYT* kamaIYT, 2),
math.round(correlation_IWN* kamaIWN, 2),
math.round(correlation_IWD* kamaIWD, 2),
math.round(correlation_IWM* kamaIWM, 2),
math.round(correlation_IWR* kamaIWR, 2),
math.round(correlation_MGK* kamaMGK, 2),
math.round(correlation_OEF* kamaOEF, 2),
math.round(correlation_MTUM* kamaMTUM, 2),
math.round(correlation_IWB* kamaIWB, 2))
// Display correlation values
var string G3 = "๐ Table Settings Correlation ๐"
string table0_y_pos = input.string(defval = "top", title = "Table Position", options = ["top", "middle", "bottom"], group = G3, inline = "1")
string table0_x_pos = input.string(defval = "center", title = "", options = ["left", "center", "right"], group = G3, inline = "1")
string i_text_size = input.string(defval=size.tiny, title='Text Size:', options=[size.tiny, size.small, size.normal, size.large, size.huge, size.auto], group = G3 )
var table table0 = table.new(table0_y_pos + "_" + table0_x_pos, columns = 16, rows = 6, frame_color = color.white,
frame_width = 1, border_color = color.white, border_width = 1)
if showCorrTab
table.merge_cells(table0, 0, 0, 15, 0)
table.merge_cells(table0, 0, 4, 15, 4)
if showCorrTab and barstate.islast
table.cell(table0, 0, 0, "๐ CE - MARKET CORRELATION "+str.tostring(l)+"D ๐", text_size = i_text_size, text_color = color.purple)
table.cell(table0, 0, 1, "Symbol:", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 2, "Correlation:", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 3, "Trend:", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 4, "Implied Trend to Chart "+str.tostring(l)+"D :", text_size = i_text_size, text_color = color.white, bgcolor = color.black)
table.cell(table0, 0, 5, "Avg: " + str.tostring(math.round(ImplCorrAvg, 2)), text_size = i_text_size, text_color = math.round(ImplCorrAvg, 2) > 0 ?color.green:color.red)
table.cell(table0, 1, 1, "SPHD", text_size = i_text_size, text_color = color.teal)
table.cell(table0, 1, 2, str.tostring(math.round(correlation_SPHD, 2)), text_size = i_text_size, text_color = correlation_SPHD > 0 ? color.green : color.red)
table.cell(table0, 1, 3, str.tostring(kamaSPHD), text_size = i_text_size, text_color = kamaSPHD > 0 ? color.green : color.red)
table.cell(table0, 1, 5, str.tostring(math.round(correlation_SPHD*kamaSPHD, 2)), text_size = i_text_size, text_color = math.round(correlation_SPHD*kamaSPHD, 2) > 0 ? color.green : color.red)
table.cell(table0, 2, 1, "SPLV", text_size = i_text_size, text_color = color.aqua)
table.cell(table0, 2, 2, str.tostring(math.round(correlation_SPLV, 2)), text_size = i_text_size, text_color = correlation_SPLV > 0 ? color.green : color.red)
table.cell(table0, 2, 3, str.tostring(kamaSPLV), text_size = i_text_size, text_color = kamaSPLV > 0 ? color.green : color.red)
table.cell(table0, 2, 5, str.tostring(math.round(correlation_SPLV*kamaSPLV, 2)), text_size = i_text_size, text_color = math.round(correlation_SPLV*kamaSPLV, 2) > 0 ? color.green : color.red)
table.cell(table0, 3, 1, "QUAL", text_size = i_text_size, text_color = color.gray)
table.cell(table0, 3, 2, str.tostring(math.round(correlation_QUAL, 2)), text_size = i_text_size, text_color = correlation_QUAL > 0 ? color.green : color.red)
table.cell(table0, 3, 3, str.tostring(kamaQUAL), text_size = i_text_size, text_color = kamaQUAL > 0 ? color.green : color.red)
table.cell(table0, 3, 5, str.tostring(math.round(correlation_QUAL*kamaQUAL, 2)), text_size = i_text_size, text_color = math.round(correlation_SPLV*kamaSPLV, 2) > 0 ? color.green : color.red)
table.cell(table0, 4, 1, "DEF", text_size = i_text_size, text_color = color.maroon)
table.cell(table0, 4, 2, str.tostring(math.round(correlation_DEF, 2)), text_size = i_text_size, text_color = correlation_DEF > 0 ? color.green : color.red)
table.cell(table0, 4, 3, str.tostring(kamaDEF), text_size = i_text_size, text_color = kamaDEF > 0 ? color.green : color.red)
table.cell(table0, 4, 5, str.tostring(math.round(correlation_DEF*kamaDEF, 2)), text_size = i_text_size, text_color = math.round(correlation_DEF*kamaDEF, 2) > 0 ? color.green : color.red)
table.cell(table0, 5, 1, "IWF", text_size = i_text_size, text_color = color.orange)
table.cell(table0, 5, 2, str.tostring(math.round(correlation_IWF, 2)), text_size = i_text_size, text_color = correlation_IWF > 0 ? color.green : color.red)
table.cell(table0, 5, 3, str.tostring(kamaIWF), text_size = i_text_size, text_color = kamaIWF > 0 ? color.green : color.red)
table.cell(table0, 5, 5, str.tostring(math.round(correlation_IWF*kamaIWF, 2)), text_size = i_text_size, text_color = math.round(correlation_IWF*kamaIWF, 2) > 0 ? color.green : color.red)
table.cell(table0, 6, 1, "SPHB", text_size = i_text_size, text_color = color.rgb(239, 136, 227))
table.cell(table0, 6, 2, str.tostring(math.round(correlation_SPHB, 2)), text_size = i_text_size, text_color = correlation_SPHB > 0 ? color.green : color.red)
table.cell(table0, 6, 3, str.tostring(kamaSPHB), text_size = i_text_size, text_color = kamaSPHB> 0 ? color.green : color.red)
table.cell(table0, 6, 5, str.tostring(math.round(correlation_SPHB*kamaSPHB, 2)), text_size = i_text_size, text_color = math.round(correlation_SPHB*kamaSPHB, 2) > 0 ? color.green : color.red)
table.cell(table0, 7, 1, "IYT", text_size = i_text_size, text_color = color.yellow)
table.cell(table0, 7, 2, str.tostring(math.round(correlation_IYT, 2)), text_size = i_text_size, text_color = correlation_IYT > 0 ? color.green : color.red)
table.cell(table0, 7, 3, str.tostring(kamaIYT), text_size = i_text_size, text_color = kamaIYT > 0 ? color.green : color.red)
table.cell(table0, 7, 5, str.tostring(math.round(correlation_IYT*kamaIYT, 2)), text_size = i_text_size, text_color = math.round(correlation_IYT*kamaIYT, 2) > 0 ? color.green : color.red)
table.cell(table0, 8, 1, "IWN", text_size = i_text_size, text_color = color.yellow)
table.cell(table0, 8, 2, str.tostring(math.round(correlation_IWN, 2)), text_size = i_text_size, text_color = correlation_IWN > 0 ? color.green : color.red)
table.cell(table0, 8, 3, str.tostring(kamaIWN), text_size = i_text_size, text_color = kamaIWN > 0 ? color.green : color.red)
table.cell(table0, 8, 5, str.tostring(math.round(correlation_IWN*kamaIWN, 2)), text_size = i_text_size, text_color = math.round(correlation_IWN*kamaIWN, 2) > 0 ? color.green : color.red)
table.cell(table0, 9, 1, "IWD", text_size = i_text_size, text_color = color.fuchsia)
table.cell(table0, 9, 2, str.tostring(math.round(correlation_IWD, 2)), text_size = i_text_size, text_color = correlation_IWD > 0 ? color.green : color.red)
table.cell(table0, 9, 3, str.tostring(kamaIWD), text_size = i_text_size, text_color = kamaIWD > 0 ? color.green : color.red)
table.cell(table0, 9, 5, str.tostring(math.round(correlation_IWD*kamaIWD, 2)), text_size = i_text_size, text_color = math.round(correlation_IWD*kamaIWD, 2) > 0 ? color.green : color.red)
table.cell(table0, 10, 1, "IWM", text_size = i_text_size, text_color = color.purple)
table.cell(table0, 10, 2, str.tostring(math.round(correlation_IWM, 2)), text_size = i_text_size, text_color = correlation_IWM > 0 ? color.green : color.red)
table.cell(table0, 10, 3, str.tostring(kamaIWM), text_size = i_text_size, text_color = kamaIWM > 0 ? color.green : color.red)
table.cell(table0, 10, 5, str.tostring(math.round(correlation_IWM*kamaIWM, 2)), text_size = i_text_size, text_color = math.round(correlation_IWM*kamaIWM, 2) > 0 ? color.green : color.red)
table.cell(table0, 11, 1, "IWR", text_size = i_text_size, text_color = color.blue)
table.cell(table0, 11, 2, str.tostring(math.round(correlation_IWR, 2)), text_size = i_text_size, text_color = correlation_IWR > 0 ? color.green : color.red)
table.cell(table0, 11, 3, str.tostring(kamaIWR), text_size = i_text_size, text_color = kamaIWR > 0 ? color.green : color.red)
table.cell(table0, 11, 5, str.tostring(math.round(correlation_IWR*kamaIWR, 2)), text_size = i_text_size, text_color = math.round(correlation_IWR*kamaIWR, 2) > 0 ? color.green : color.red)
table.cell(table0, 12, 1, "MGK", text_size = i_text_size, text_color = color.red)
table.cell(table0, 12, 2, str.tostring(math.round(correlation_MGK, 2)), text_size = i_text_size, text_color = correlation_MGK > 0 ? color.green : color.red)
table.cell(table0, 12, 3, str.tostring(kamaMGK), text_size = i_text_size, text_color = kamaMGK > 0 ? color.green : color.red)
table.cell(table0, 12, 5, str.tostring(math.round(correlation_MGK*kamaMGK, 2)), text_size = i_text_size, text_color = math.round(correlation_MGK*kamaMGK, 2) > 0 ? color.green : color.red)
table.cell(table0, 13, 1, "OEF", text_size = i_text_size, text_color = color.olive)
table.cell(table0, 13, 2, str.tostring(math.round(correlation_OEF, 2)), text_size = i_text_size, text_color = correlation_OEF > 0 ? color.green : color.red)
table.cell(table0, 13, 3, str.tostring(kamaOEF), text_size = i_text_size, text_color = kamaOEF > 0 ? color.green : color.red)
table.cell(table0, 13, 5, str.tostring(math.round(correlation_OEF*kamaOEF, 2)), text_size = i_text_size, text_color = math.round(correlation_OEF*kamaOEF, 2) > 0 ? color.green : color.red)
table.cell(table0, 14, 1, "MTUM", text_size = i_text_size, text_color = color.lime)
table.cell(table0, 14, 2, str.tostring(math.round(correlation_MTUM, 2)), text_size = i_text_size, text_color = correlation_MTUM > 0 ? color.green : color.red)
table.cell(table0, 14, 3, str.tostring(kamaMTUM), text_size = i_text_size, text_color = kamaMTUM > 0 ? color.green : color.red)
table.cell(table0, 14, 5, str.tostring(math.round(correlation_MTUM*kamaMTUM, 2)), text_size = i_text_size, text_color = math.round(correlation_MTUM*kamaMTUM, 2) > 0 ? color.green : color.red)
table.cell(table0, 15, 1, "IWB", text_size = i_text_size, text_color = color.silver)
table.cell(table0, 15, 2, str.tostring(math.round(correlation_IWB, 2)), text_size = i_text_size, text_color = correlation_IWB > 0 ? color.green : color.red)
table.cell(table0, 15, 3, str.tostring(kamaIWB), text_size = i_text_size, text_color = kamaIWB > 0 ? color.green : color.red)
table.cell(table0, 15, 5, str.tostring(math.round(correlation_IWB*kamaIWB, 2)), text_size = i_text_size, text_color = math.round(correlation_IWB*kamaIWB, 2) > 0 ? color.green : color.red)
plot(showImplied?ImplCorrAvg:na,"Implied Correlation Avg", ImplCorrAvg > 0.1 ?color.green : ImplCorrAvg < -0.1 ? color.red : color.gray, style = plot.style_columns)
hline(showImplied? 0.1 : na, color = color.green, linewidth = 2)
hline(showImplied? 0 : na)
hline(showImplied? -0.1 : na, color = color.red , linewidth = 2)
barcolor(ImplCorrAvg > 0.1 ?color.green : ImplCorrAvg < -0.1 ? color.red : color.gray)
// Rate of Change (ROC) calculation
showRoC = input.bool(false, "Show RoC?", group = "Visuals")
// Calculate average ROC
avgROC = (ta.roc(SPHD, rocPeriod) +
ta.roc(SPLV, rocPeriod) +
ta.roc(QUAL, rocPeriod) +
ta.roc(DEF, rocPeriod) +
ta.roc(IWF, rocPeriod) +
ta.roc(SPHB, rocPeriod) +
ta.roc(IYT, rocPeriod) +
ta.roc(IWN, rocPeriod) +
ta.roc(IWD, rocPeriod) +
ta.roc(IWM, rocPeriod) +
ta.roc(IWR, rocPeriod) +
ta.roc(MGK, rocPeriod) +
ta.roc(OEF, rocPeriod) +
ta.roc(MTUM, rocPeriod) +
ta.roc(IWB, rocPeriod)) / 15
// Calculate ROC relative to average ROC
rocSPHD = ta.roc(SPHD, rocPeriod) - avgROC
rocSPLV = ta.roc(SPLV, rocPeriod) - avgROC
rocQUAL = ta.roc(QUAL, rocPeriod) - avgROC
rocDEF = ta.roc(DEF, rocPeriod) - avgROC
rocIWF = ta.roc(IWF, rocPeriod) - avgROC
rocSPHB = ta.roc(SPHB, rocPeriod) - avgROC
rocIYT = ta.roc(IYT, rocPeriod) - avgROC
rocIWN = ta.roc(IWN, rocPeriod) - avgROC
rocIWD = ta.roc(IWD, rocPeriod) - avgROC
rocIWM = ta.roc(IWM, rocPeriod) - avgROC
rocIWR = ta.roc(IWR, rocPeriod) - avgROC
rocMGK = ta.roc(MGK, rocPeriod) - avgROC
rocOEF = ta.roc(OEF, rocPeriod) - avgROC
rocMTUM = ta.roc(MTUM, rocPeriod) - avgROC
rocIWB = ta.roc(IWB, rocPeriod) - avgROC
// Plotting the ROC values
plot(showRoC?rocSPHD :na, color=color.teal, title="ROC SPHD")
plot(showRoC?rocSPLV :na, color=color.aqua, title="ROC SPLV")
plot(showRoC?rocQUAL :na, color=color.gray, title="ROC QUAL")
plot(showRoC?rocDEF :na, color=color.maroon, title="ROC DEF")
plot(showRoC?rocIWF :na, color=color.orange, title="ROC IWF")
plot(showRoC?rocSPHB :na, color=color.rgb(239, 136, 227), title="ROC SPHB")
plot(showRoC?rocIYT :na, color=color.yellow, title="ROC IYT")
plot(showRoC?rocIWN :na, color=color.yellow, title="ROC IWN")
plot(showRoC?rocIWD :na, color=color.fuchsia, title="ROC IWD")
plot(showRoC?rocIWM :na, color=color.purple, title="ROC IWM")
plot(showRoC?rocIWR :na, color=color.blue, title="ROC IWR")
plot(showRoC?rocMGK :na, color=color.red, title="ROC MGK")
plot(showRoC?rocOEF :na, color=color.olive, title="ROC OEF")
plot(showRoC?rocMTUM :na, color=color.lime, title="ROC MTUM")
plot(showRoC?rocIWB :na, color=color.silver, title="ROC IWB")
Goldilocks = (rocSPHB>0?+1:0) + (rocIWM>0?+1:0) + (rocMGK>0?+1:0) + (rocIYT>0?+1:0) +(rocIWN>0?+1:0) + (rocIWR>0?+1:0) + (rocSPLV<0?+1:0) + (rocDEF<0?+1:0) + (rocSPHD<0?+1:0) + (rocQUAL<0?+1:0) + (rocOEF<0?+1:0)
Reflation = (rocSPHB>0?+1:0) + (rocIWM>0?+1:0) + (rocMGK>0?+1:0) + (rocIYT>0?+1:0) +(rocIWN>0?+1:0) + (rocMTUM>0?+1:0) + (rocSPLV<0?+1:0) + (rocDEF<0?+1:0) + (rocSPHD<0?+1:0) + (rocQUAL<0?+1:0) + (rocIWB<0?+1:0)
Inflation = (rocSPLV>0?+1:0) + (rocDEF>0?+1:0) + (rocMGK>0?+1:0) + (rocSPHD>0?+1:0) +(rocQUAL>0?+1:0) + (rocSPHB<0?+1:0) + (rocIWM<0?+1:0) + (rocIYT<0?+1:0) + (rocIWN<0?+1:0) + (rocIWR<0?+1:0) + (rocIWD<0?+1:0)
Deflation = (rocSPLV>0?+1:0) + (rocDEF>0?+1:0) + (rocMGK>0?+1:0) + (rocSPHD>0?+1:0) +(rocIWF>0?+1:0) + (rocSPHB<0?+1:0) + (rocIWM<0?+1:0) + (rocIYT<0?+1:0) + (rocIWN<0?+1:0) + (rocIWR<0?+1:0) + (rocIWD<0?+1:0)
Denumerator = Goldilocks + Reflation + Inflation + Deflation
Risk = (Goldilocks > Inflation or Goldilocks > Deflation or Reflation > Inflation or Reflation > Deflation) ? "RISK ON" : "RISK OFF"
RiskCol = (Risk == "RISK ON"? color.green : color.red)
RiskBg = (Risk == "RISK ON"? color.new(color.green, 40) : color.new(color.red, 40))
var string G2 = "๐ Table Settings Performance ๐"
string table_y_pos = input.string(defval = "bottom", title = "Table Position", options = ["top", "middle", "bottom"], group = G2, inline = "1")
string table_x_pos = input.string(defval = "center", title = "", options = ["left", "center", "right"], group = G2, inline = "1")
color positive_color_input = color(color.new(color.green, 0))
color negative_color_input = color(color.new(color.red, 0))
var table table = table.new(table_y_pos + "_" + table_x_pos, columns = 10, rows = 17, frame_color = color.white,
frame_width = 1, border_color = color.white, border_width = 1)
if showPerfTab
table.merge_cells(table, 0, 0, 7, 0)
table.merge_cells(table, 0, 1, 1, 1)
table.merge_cells(table, 2, 1, 3, 1)
table.merge_cells(table, 4, 1, 5, 1)
table.merge_cells(table, 6, 1, 7, 1)
table.merge_cells(table, 0, 2, 7, 2)
table.merge_cells(table, 0, 8, 7, 8)
table.merge_cells(table, 0, 14, 7, 14)
table.merge_cells(table, 0, 16, 7, 16)
// Definitions
if showPerfTab and barstate.islast
table.cell(table, 0, 0, text = "๐ CE - MARKET PERFORMANCE "+str.tostring(rocPeriod)+"D ๐", text_size = i_text_size, text_color = color.purple)
table.cell(table, 0, 2, text = "Top 5 Equity Style Factors ", text_size = i_text_size, text_color = color.green)
table.cell(table, 0, 8, text = "Bottom 5 Equity Style Factors ", text_size = i_text_size, text_color = color.red)
table.cell(table, 0, 14, text = "Risk Period: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 0, 16, text = Risk, text_size = i_text_size, text_color = color.white , bgcolor = RiskBg, text_font_family = font.family_monospace)
table.cell(table, 0, 1,"GOLDILOCKS", text_size = i_text_size, text_color = color.green) // *10 is just for better visual purpose
table.cell(table, 0, 3,"High Beta (SPHB) ", text_size = i_text_size, text_color = color.rgb(239, 136, 227))
table.cell(table, 1, 3,str.tostring(math.round(rocSPHB,2)), text_size = i_text_size, text_color = rocSPHB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 4,"Small Caps (IWM)", text_size = i_text_size, text_color = color.purple)
table.cell(table, 1, 4,str.tostring(math.round(rocIWM,2)), text_size = i_text_size, text_color = rocIWM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 5,"Mega Cap Growth (MGK) ", text_size = i_text_size, text_color = color.red)
table.cell(table, 1, 5,str.tostring(math.round(rocMGK,2)), text_size = i_text_size, text_color = rocMGK > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 6,"Cyclicals (IYT, IWN) ", text_size = i_text_size, text_color = color.yellow)
table.cell(table, 1, 6,str.tostring(math.round(rocIYT,2)) + ", " + str.tostring(math.round(rocIWN,2)), text_size = i_text_size, text_color = rocIYT > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 7,"Mid Caps (IWR)", text_size = i_text_size, text_color = color.blue)
table.cell(table, 1, 7,str.tostring(math.round(rocIWR,2)), text_size = i_text_size, text_color = rocIWR > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 9, text = "Low Beta (SPLV) ", text_size = i_text_size, text_color = color.aqua)
table.cell(table, 1, 9,str.tostring(math.round(rocSPLV,2)), text_size = i_text_size, text_color = rocSPLV > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 10, text = "Defensives (DEF) ", text_size = i_text_size, text_color = color.maroon)
table.cell(table, 1, 10,str.tostring(math.round(rocDEF,2)), text_size = i_text_size, text_color = rocDEF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 11, text = "Dividends (SPHD)", text_size = i_text_size, text_color = color.teal)
table.cell(table, 1, 11,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 12, text = "Quality (QUAL) ", text_size = i_text_size, text_color = color.gray)
table.cell(table, 1, 12,str.tostring(math.round(rocQUAL,2)), text_size = i_text_size, text_color = rocQUAL > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 13, text = "Size (OEF) ", text_size = i_text_size, text_color = color.olive)
table.cell(table, 1, 13,str.tostring(math.round(rocOEF,2)), text_size = i_text_size, text_color = rocOEF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 0, 15, text = "Goldilocks Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 1, 15,str.tostring(math.round(Goldilocks/Denumerator*100, 2))+"% | "+str.tostring(Goldilocks)+ " / 11", text_size = i_text_size, text_color = RiskCol)
table.cell(table, 2, 1,"REFLATION", text_size = i_text_size, text_color = color.lime)
table.cell(table, 2, 3,"High Beta (SPHB)", text_size = i_text_size, text_color = color.rgb(239, 136, 227))
table.cell(table, 3, 3,str.tostring(math.round(rocSPHB,2)), text_size = i_text_size, text_color = rocSPHB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 4,"Small Caps (IWM)", text_size = i_text_size, text_color = color.purple)
table.cell(table, 3, 4,str.tostring(math.round(rocIWM,2)), text_size = i_text_size, text_color = rocIWM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 5,"Mega Cap Growth (MGK)", text_size = i_text_size, text_color = color.red)
table.cell(table, 3, 5,str.tostring(math.round(rocMGK,2)), text_size = i_text_size, text_color = rocMGK > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 6,"Cyclicals (IYT, IWN)", text_size = i_text_size, text_color = color.yellow)
table.cell(table, 3, 6,str.tostring(math.round(rocIYT,2)) + ", " + str.tostring(math.round(rocIWN,2)), text_size = i_text_size, text_color = rocIYT > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 7,"Momentum (MTUM)", text_size = i_text_size, text_color = color.lime)
table.cell(table, 3, 7,str.tostring(math.round(rocMTUM,2)), text_size = i_text_size, text_color = rocMTUM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 9, text = "Low Beta (SPLV)", text_size = i_text_size, text_color = color.aqua)
table.cell(table, 3, 9,str.tostring(math.round(rocSPLV,2)), text_size = i_text_size, text_color = rocSPLV > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 10, text = "Defensives (DEF)", text_size = i_text_size, text_color = color.maroon)
table.cell(table, 3, 10,str.tostring(math.round(rocDEF,2)), text_size = i_text_size, text_color = rocDEF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 11, text = "Dividends (SPHD)", text_size = i_text_size, text_color = color.teal)
table.cell(table, 3, 11,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 12, text = "Quality (QUAL)", text_size = i_text_size, text_color = color.gray)
table.cell(table, 3, 12,str.tostring(math.round(rocQUAL,2)), text_size = i_text_size, text_color = rocQUAL > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 13, text = "Large Caps (IWB)", text_size = i_text_size, text_color = color.silver)
table.cell(table, 3, 13,str.tostring(math.round(rocIWB,2)), text_size = i_text_size, text_color = rocIWB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 2, 15, text = "Reflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 3, 15,str.tostring(math.round(Reflation/Denumerator*100, 2))+"% | "+str.tostring(Reflation)+ " / 11", text_size = i_text_size, text_color = RiskCol)
table.cell(table, 4, 1,"INFLATION", text_size = i_text_size, text_color = color.red)
table.cell(table, 4, 3,"Low Beta (SPLV)", text_size = i_text_size, text_color = color.aqua)
table.cell(table, 5, 3,str.tostring(math.round(rocSPLV,2)), text_size = i_text_size, text_color = rocSPLV > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 4,"Defensives (DEF)", text_size = i_text_size, text_color = color.maroon)
table.cell(table, 5, 4,str.tostring(math.round(rocDEF,2)), text_size = i_text_size, text_color = rocDEF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 5,"Mega Cap Growth (MGK)", text_size = i_text_size, text_color = color.red)
table.cell(table, 5, 5,str.tostring(math.round(rocMGK,2)), text_size = i_text_size, text_color = rocMGK > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 6,"Dividends (SPHD) ", text_size = i_text_size, text_color = color.teal)
table.cell(table, 5, 6,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 7,"Quality (QUAL) ", text_size = i_text_size, text_color = color.gray)
table.cell(table, 5, 7,str.tostring(math.round(rocQUAL,2)), text_size = i_text_size, text_color = rocQUAL > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 9, text = "High Beta (SPHB)", text_size = i_text_size, text_color = color.rgb(239, 136, 227))
table.cell(table, 5, 9,str.tostring(math.round(rocSPHB,2)), text_size = i_text_size, text_color = rocSPHB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 10, text = "Small Caps (IWM)", text_size = i_text_size, text_color = color.purple)
table.cell(table, 5, 10,str.tostring(math.round(rocIWM,2)), text_size = i_text_size, text_color = rocIWM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 11, text = "Cyclicals (IYT, IWN)", text_size = i_text_size, text_color = color.yellow)
table.cell(table, 5, 11,str.tostring(math.round(rocIYT,2)) + ", " + str.tostring(math.round(rocIWN,2)), text_size = i_text_size, text_color = rocIYT > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 12, text = "Mid Caps (IWR)", text_size = i_text_size, text_color = color.blue)
table.cell(table, 5, 12,str.tostring(math.round(rocIWR,2)), text_size = i_text_size, text_color = rocIWR > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 13, text = "Value (IWD)", text_size = i_text_size, text_color = color.fuchsia)
table.cell(table, 5, 13,str.tostring(math.round(rocIWD,2)), text_size = i_text_size, text_color = rocIWD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 4, 15, text = "Inflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 5, 15,str.tostring(math.round(Inflation/Denumerator*100, 2))+"% | "+str.tostring(Inflation)+ " / 11", text_size = i_text_size, text_color = RiskCol)
table.cell(table, 6, 1,"DEFLATION", text_size = i_text_size, text_color = color.blue)
table.cell(table, 6, 3,"Low Beta (SPLV)", text_size = i_text_size, text_color = color.aqua)
table.cell(table, 7, 3,str.tostring(math.round(rocSPLV,2)), text_size = i_text_size, text_color = rocSPLV > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 4,"Defensives (DEF)", text_size = i_text_size, text_color = color.maroon)
table.cell(table, 7, 4,str.tostring(math.round(rocDEF,2)), text_size = i_text_size, text_color = rocDEF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 5,"Mega Cap Growth (MGK)", text_size = i_text_size, text_color = color.red)
table.cell(table, 7, 5,str.tostring(math.round(rocMGK,2)), text_size = i_text_size, text_color = rocMGK > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 6,"Dividends (SPHD) ", text_size = i_text_size, text_color = color.teal)
table.cell(table, 7, 6,str.tostring(math.round(rocSPHD,2)), text_size = i_text_size, text_color = rocSPHD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 7,"Growth (IWF)", text_size = i_text_size, text_color = color.orange)
table.cell(table, 7, 7,str.tostring(math.round(rocIWF,2)), text_size = i_text_size, text_color = rocIWF > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 9, text = "High Beta (SPHB)", text_size = i_text_size, text_color = color.rgb(239, 136, 227))
table.cell(table, 7, 9,str.tostring(math.round(rocSPHB,2)), text_size = i_text_size, text_color = rocSPHB > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 10, text = "Small Caps (IWM)", text_size = i_text_size, text_color = color.purple)
table.cell(table, 7, 10,str.tostring(math.round(rocIWM,2)), text_size = i_text_size, text_color = rocIWM > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 11, text = "Cyclicals (IYT, IWN)", text_size = i_text_size, text_color = color.yellow)
table.cell(table, 7, 11,str.tostring(math.round(rocIYT,2)) + ", " + str.tostring(math.round(rocIWN,2)), text_size = i_text_size, text_color = rocIYT > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 12, text = "Mid Caps (IWR)", text_size = i_text_size, text_color = color.blue)
table.cell(table, 7, 12,str.tostring(math.round(rocIWR,2)), text_size = i_text_size, text_color = rocIWR > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 13, text = "Value (IWD)", text_size = i_text_size, text_color = color.fuchsia)
table.cell(table, 7, 13,str.tostring(math.round(rocIWD,2)), text_size = i_text_size, text_color = rocIWD > 0 ? positive_color_input : negative_color_input)
table.cell(table, 6, 15, text = "Deflation Probability: ", text_size = i_text_size, text_color = color.white)
table.cell(table, 7, 15,str.tostring(math.round(Deflation/Denumerator*100, 2))+"% | "+str.tostring(Deflation)+ " / 11", text_size = i_text_size, text_color = RiskCol)
|
Inside Candle by Harshini | https://www.tradingview.com/script/2ERlEkkp-Inside-Candle-by-Harshini/ | Harshini_A_L | https://www.tradingview.com/u/Harshini_A_L/ | 74 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// ยฉ Harshini_A_L
//@version=5
indicator('Inside Candle by Harshini', overlay=true)
fastAverage = ta.sma(close, 20)
if (high < high[1] and low > low[1] )
var insidedescription = " Inside candle formation, you can buy/sell based on the next candle close"
label.new(bar_index, high + 10 , "INS", style=label.style_label_down, color=color.yellow, size = size.small, tooltip = insidedescription)
inside_bar = high[1] < high[2] and low[1] > low[2]
// Entry conditions
long_condition = false
if inside_bar and close > high[1] and (high > fastAverage)
long_condition := true
short_condition = false
if inside_bar and close < low[1] and (low < fastAverage)
short_condition := true
// Plotting
//plotshape(insidebar, title="Inside Bar", text="Inside Bar", style=shape.diamond, location=location.abovebar, color=color.blue, size=size.tiny)
plotshape(long_condition, title="Buy Signal", text="Buy", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(short_condition, title="Sell Signal", text="Sell", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)
|
Price & Volume Profile (Expo) | https://www.tradingview.com/script/PMCQfmCE-Price-Volume-Profile-Expo/ | Zeiierman | https://www.tradingview.com/u/Zeiierman/ | 2,212 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ Zeiierman
//@version=5
indicator('Price & Volume Profile (Expo)', overlay=true, max_boxes_count=500)
//~~}
// ~~ Inputs {
src = input.source(close,"Source")
rows = input.int(20,"Row Size",minval=5, maxval=500)
disp = input.string("Counter","Display",["Counter","Volume"])
offset = input.int(100,"Offset",step=25)
poc = input.bool(true,"Point of Control")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Variables & Array's {
b = bar_index
var start = int(na)
var top = float(na)
var bot = float(na)
levels = array.new_float(rows+1)
var boxes = array.new<box>(rows+3)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Coloring Function {
Gradient(a,i)=>
sort = a.copy()
sort.sort()
val = a.get(i)
idx = sort.indexof(val)
out = color.from_gradient(idx,0,a.size()-1,color.red,color.lime)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Code {
//Check visible chart
if time == chart.left_visible_bar_time
start := b
top := high
bot := low
else if time>chart.left_visible_bar_time
top := math.max(high,top)
bot := math.min(low,bot)
//Set the levels
step = (top-bot)/rows
for i=0 to rows by 1
levels.set(i, bot + step * i)
//Check levels
if barstate.islast
sum = array.new<int>(rows,0)
vol = array.new<float>(rows,0.0)
for i=0 to (b-start)-1
price = src[i]
for x=0 to levels.size()-2 by 1
dn = levels.get(x)
up = levels.get(x+1)
if price>dn and price<up
sum.set(x,sum.get(x)+1)
vol.set(x,vol.get(x)+volume[x])
break
//Plots the profile
for [i,element] in sum
boxes.get(i).delete()
col = Gradient(sum,i)
boxes.set(i,box.new(b+offset-element,levels.get(i+1),b+offset,levels.get(i),
col,border_style=line.style_dotted,bgcolor=color.new(col,50),
text=disp=="Volume"?str.tostring(vol.get(i),format.volume):str.tostring(element),text_color=chart.fg_color))
if poc
maxIdx = disp=="Volume"?vol.indexof(vol.max()):sum.indexof(sum.max())
boxes.get(boxes.size()-2).delete()
boxes.set(boxes.size()-2,box.new(start,levels.get(maxIdx),b+offset-sum.get(maxIdx),levels.get(maxIdx+1),
#E0F2E9,border_style=line.style_dashed,bgcolor=color.new(#5B7B7A,75),
text="POC",text_color=chart.fg_color))
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} |
Enhanced WaveTrend Oscillator | https://www.tradingview.com/script/9GmOkVyH-Enhanced-WaveTrend-Oscillator/ | QuantiLuxe | https://www.tradingview.com/u/QuantiLuxe/ | 502 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉ QuantiLuxe
//@version=5
indicator("Enhanced WaveTrend Oscillator", "๐๐ป๐ต๐ฎ๐ป๐ฐ๐ฒ๐ฑ ๐ช๐ง", false)
f_ewave(src, chlen, avglen) =>
basis = ta.ema(src, chlen)
dev = ta.stdev(src, chlen)
wave = (src - basis) / dev * 100
ta.ema(wave, avglen)
src = input.source(hlc3, "Source")
chlen = input.int(10, "Channel Length")
avglen = input.int(21, "Average Length")
smooth = input.int(4, "Signal Length")
revshow = input.bool(true, "", inline = "0", group = "UI Options")
revt = input.int(100, "Reversion Threshold", options = [100, 125], inline = "0", group = "UI Options")
colbar = input.string("None", "Bar Coloring", ["None", "Midline Cross", "Extremities", "Reversions", "Slope"], group = "UI Options")
wt = f_ewave(src, chlen, avglen)
sig = ta.sma(wt, smooth)
hist = wt - sig
col_up = #5996ff
col_dn = #e864ff
h_col = hist > 0 ? (hist > hist[1] ? #d9a8ff9a : #b68bd49a) : (hist > hist[1] ? #ffc9739a : #d8aa609a)
hline(0, "Mid Line", #ffffff80, hline.style_solid)
max = hline(150, display = display.none)
hh = hline(125, display = display.none)
lh = hline(100, display = display.none)
fill(lh, hh, color = #ffc97325)
fill(hh, max, color = #ffc97336)
min = hline(-150, display = display.none)
ll = hline(-125, display = display.none)
hl = hline(-100, display = display.none)
fill(ll, hl, color = #d9a8ff21)
fill(ll, min, color = #d9a8ff34)
plot(hist, "๐", h_col, 1, plot.style_area)
w = plot(wt, "๐ช๐ง", wt > sig ? col_up : col_dn)
s = plot(sig, display = display.none)
fill(w, s, wt > sig ? #3179f579 : #aa47bc79)
plotchar(revshow ? wt > revt and wt < sig and not (wt[1] < sig[1]) ? wt + 40 : na : na, "OB", "โฌ", location.absolute, col_dn, size = size.tiny)
plotchar(revshow ? wt < -revt and wt > sig and not (wt[1] > sig[1]) ? wt - 40 : na : na, "OS", "โฌ", location.absolute, col_up, size = size.tiny)
color col = switch colbar
"None" => na
"Midline Cross" => wt > 0 ? col_up : col_dn
"Extremities" => wt > revt ? col_up : wt < -revt ? col_dn : #b3b3b3c2
"Reversions" => wt > revt and wt < wt[1] and not (wt[1] < wt[2]) ? col_dn : wt < -revt and wt > wt[1] and not (wt[1] > wt[2]) ? col_up : #b3b3b3c2
"Slope" => wt > sig ? col_up : col_dn
barcolor(col) |
ICT Silver Bullet [LuxAlgo] | https://www.tradingview.com/script/fq4wSUev-ICT-Silver-Bullet-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 5,131 | study | 5 | CC-BY-NC-SA-4.0 | // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// ยฉLuxAlgo
//@version=5
indicator("ICT Silver Bullet [LuxAlgo]", shorttitle='LuxAlgo - ICT Silver Bullet', max_lines_count=500, max_boxes_count=500, max_labels_count=500, overlay=true)
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
left = input.int ( 5 , '' , minval=1, maxval=20, group='Swings settings (left)')
showSB = input.bool ( true , 'Show SB session', inline='SB' , group='Silver Bullet session' )
col_SB = input.color(#b2b5be50, 'ย ย ย ย ย ' , inline='SB' , group='Silver Bullet session' )
choice = input.string('Super-Strict', '' , inline='fvg' , group='FVG'
, options =['All FVG', 'Only FVG in the same direction of trend', 'Strict', 'Super-Strict'] )
superstrict = choice == 'Super-Strict'
iTrend = choice != 'All FVG'
strict = choice == 'Strict'
stricty = superstrict or strict
cBullFVG = input.color (#4dd0e160, '' , inline='fvg' , group='FVG' )
cBearFVG = input.color (#ffc1b160, '' , inline='fvg' , group='FVG' )
extend = input.bool ( true , 'extend' , inline='fvg' , group='FVG' )
opt = input.string('previous session (similar)','', inline='TG' , group='Targets ย ย ย ย ย ย ย ย ย -ย ย ย ย ย ย ย ย Support/Resistance'
, options =['previous session (any)', 'previous session (similar)'] )
prev = opt == 'previous session (any)'
cSupLine = input.color (#b22833 , '' , inline='TG' , group='Targets ย ย ย ย ย ย ย ย ย -ย ย ย ย ย ย ย ย Support/Resistance')
cResLine = input.color (#3e89fa , '' , inline='TG' , group='Targets ย ย ย ย ย ย ย ย ย -ย ย ย ย ย ย ย ย Support/Resistance')
keep = input.bool (true , 'Keep lines (only in [super-]strict mode)', group='Targets ย ย ย ย ย ย ย ย ย -ย ย ย ย ย ย ย ย Support/Resistance')
showT = input.bool (false, title = 'MSS ~ session' , group='Show' )
showZZ = input.bool (false, title = 'Trend' , group='Show' )
//show_minFr= input.bool (false, title = 'Minimum Trade Framework' , group='Show' )
n = bar_index
maxSize = 250
minT = syminfo.mintick
//------------------------------------------------------------------------------
//UDT's
//-----------------------------------------------------------------------------{
type piv
int b
float p
bool br
type ZZ
int [] d
int [] x
float [] y
line [] l
type FVG
box box
bool active
bool current
type actLine
line ln
bool active
type aPiv
piv []GN_swingH
piv []GN_swingL
float GN_mnPiv
float GN_mxPiv
line[]GN_targHi
line[]GN_targLo
piv []LN_swingH
piv []LN_swingL
float LN_mnPiv
float LN_mxPiv
line[]LN_targHi
line[]LN_targLo
piv []AM_swingH
piv []AM_swingL
float AM_mnPiv
float AM_mxPiv
line[]AM_targHi
line[]AM_targLo
piv []PM_swingH
piv []PM_swingL
float PM_mnPiv
float PM_mxPiv
line[]PM_targHi
line[]PM_targLo
//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var aPiv a = aPiv.new(
GN_swingH = array.new<piv>(1, piv.new(na, na))
, GN_swingL = array.new<piv>(1, piv.new(na, na))
, GN_mnPiv = 10e6
, GN_mxPiv = 0
, GN_targHi = array.new<line>()
, GN_targLo = array.new<line>()
, LN_swingH = array.new<piv>(1, piv.new(na, na))
, LN_swingL = array.new<piv>(1, piv.new(na, na))
, LN_mnPiv = 10e6
, LN_mxPiv = 0
, LN_targHi = array.new<line>()
, LN_targLo = array.new<line>()
, AM_swingH = array.new<piv>(1, piv.new(na, na))
, AM_swingL = array.new<piv>(1, piv.new(na, na))
, AM_mnPiv = 10e6
, AM_mxPiv = 0
, AM_targHi = array.new<line>()
, AM_targLo = array.new<line>()
, PM_swingH = array.new<piv>(1, piv.new(na, na))
, PM_swingL = array.new<piv>(1, piv.new(na, na))
, PM_mnPiv = 10e6
, PM_mxPiv = 0
, PM_targHi = array.new<line>()
, PM_targLo = array.new<line>()
)
var ZZ aZZ =
ZZ.new(
array.new < int >(maxSize, 0),
array.new < int >(maxSize, 0),
array.new < float >(maxSize, na),
array.new < line >(maxSize, na)
)
var FVG[] bFVG_bull = array.new<FVG>(
1, FVG.new(
box = box.new(na, na, na, na)
, active = na
)
)
var FVG[] bFVG_bear = array.new<FVG>(
1, FVG.new(
box = box.new(na, na, na, na)
, active = na
)
)
var min = 10e6
var max = 0.
//var minTrFr = line.new(na, na, na, na, style=line.style_arrow_right, color=color.yellow )
//var maxTrFr = line.new(na, na, na, na, style=line.style_arrow_left , color=color.fuchsia)
var hilo = array.from(0, 10e6)
var aTrend= array.from(0)
var l_SB = array.new< line>()
var highs = array.new<actLine>()
var lows = array.new<actLine>()
var tab = table.new(position = position.top_right, columns = 1, rows = 1, bgcolor = color(na), border_width = 1)
//-----------------------------------------------------------------------------}
//General calculations
//-----------------------------------------------------------------------------{
ph = ta.pivothigh(left, 1)
pl = ta.pivotlow (left, 1)
//-----------------------------------------------------------------------------}
//Methods/Functions
//-----------------------------------------------------------------------------{
method type(string str) =>
( syminfo.type == 'stock' and str == 'stock' ) or
(syminfo.type == 'futures' and str == 'futures') or
(syminfo.type == 'index' and str == 'index' ) or
(syminfo.type == 'forex' and str == 'forex' ) or
(syminfo.type == 'crypto' and str == 'crypto' ) or
(syminfo.type == 'fund' and str == 'fund' )
method timeSess(string timezone, string session) => time(timeframe.period, session, timezone)
//Silver Bullet Periods
SB_LN_per = "America/New_York".timeSess("0300-0400") // period/session ~ The London Open Silver Bullet ( 3 AM โ 4 AM New York local time) 03:00 - 04:00
SB_AM_per = "America/New_York".timeSess("1000-1100") // period/session ~ The AM Session Silver Bullet (10 AM โ 11 AM New York local time) 10:00 - 11:00
SB_PM_per = "America/New_York".timeSess("1400-1500") // period/session ~ The PM Session Silver Bullet ( 2 PM โ 3 PM New York local time) 14:00 - 15:00
is_in_SB = SB_LN_per or SB_AM_per or SB_PM_per
strSB = is_in_SB and not is_in_SB [1]
strLN = SB_LN_per and not SB_LN_per[1]
strAM = SB_AM_per and not SB_AM_per[1]
strPM = SB_PM_per and not SB_PM_per[1]
endSB = not is_in_SB and is_in_SB [1]
endLN = not SB_LN_per and SB_LN_per[1]
endAM = not SB_AM_per and SB_AM_per[1]
endPM = not SB_PM_per and SB_PM_per[1]
minimum_trade_framework =
'forex'.type () ? syminfo.mintick * 15 * 10 :
'index'.type () or
'futures'.type() ? syminfo.mintick * 40 : 0
method in_out(ZZ aZZ, int d, int x1, float y1, int x2, float y2) =>
aZZ.d.unshift(d), aZZ.x.unshift(x2), aZZ.y.unshift(y2), aZZ.d.pop(), aZZ.x.pop(), aZZ.y.pop()
if showZZ
aZZ.l.unshift(line.new(x1, y1, x2, y2, color= color.new(color.blue, 50))), aZZ.l.pop().delete()
f_setTrend() =>
//
MSS_dir = aTrend.get(0)
iH = aZZ.d.get(2) == 1 ? 2 : 1
iL = aZZ.d.get(2) == -1 ? 2 : 1
//
switch
// MSS Bullish
close > aZZ.y.get(iH) and aZZ.d.get(iH) == 1 and MSS_dir < 1 =>
aTrend.set(0, 1)
// MSS Bearish
close < aZZ.y.get(iL) and aZZ.d.get(iL) == -1 and MSS_dir > -1 =>
aTrend.set(0, -1)
f_swings(start, end, str, col, min, max) =>
//
max_bars_back(time, 1000)
var int MSS_dir = aTrend.get(0)
//
x2 = n -1
piv[] swingH = na
piv[] swingL = na
float mnPiv = na
float mxPiv = na
line[]targHi = na
line[]targLo = na
bool active = na
switch str
'GN' =>
swingH := a.GN_swingH
swingL := a.GN_swingL
mnPiv := a.GN_mnPiv
mxPiv := a.GN_mxPiv
targHi := a.GN_targHi
targLo := a.GN_targLo
active := is_in_SB
'LN' =>
swingH := a.LN_swingH
swingL := a.LN_swingL
mnPiv := a.LN_mnPiv
mxPiv := a.LN_mxPiv
targHi := a.LN_targHi
targLo := a.LN_targLo
active := SB_LN_per
'AM' =>
swingH := a.AM_swingH
swingL := a.AM_swingL
mnPiv := a.AM_mnPiv
mxPiv := a.AM_mxPiv
targHi := a.AM_targHi
targLo := a.AM_targLo
active := SB_AM_per
'PM' =>
swingH := a.PM_swingH
swingL := a.PM_swingL
mnPiv := a.PM_mnPiv
mxPiv := a.PM_mxPiv
targHi := a.PM_targHi
targLo := a.PM_targLo
active := SB_PM_per
if start
hilo.set(0, 0 )
hilo.set(1, 10e6)
if stricty ? not keep : true
while highs.size() > 0
get=highs.pop()
get.ln.delete()
while lows.size() > 0
get= lows.pop()
get.ln.delete()
while targHi.size() > 0
targHi.pop().delete()
while targLo.size() > 0
targLo.pop().delete()
while a.GN_targHi.size() > 0
a.GN_targHi.pop().delete()
while a.LN_targHi.size() > 0
a.LN_targHi.pop().delete()
while a.AM_targHi.size() > 0
a.AM_targHi.pop().delete()
while a.PM_targHi.size() > 0
a.PM_targHi.pop().delete()
while a.GN_targLo.size() > 0
a.GN_targLo.pop().delete()
while a.LN_targLo.size() > 0
a.LN_targLo.pop().delete()
while a.AM_targLo.size() > 0
a.AM_targLo.pop().delete()
while a.PM_targLo.size() > 0
a.PM_targLo.pop().delete()
if active
hilo.set(0, math.max(hilo.get(0), high))
hilo.set(1, math.min(hilo.get(1), low ))
if ph
if ph > mxPiv
mxPiv := ph
if swingH.size() > 0
for i = swingH.size() -1 to 0
get = swingH.get(i)
if ph >= get.p
swingH.remove(i)
swingH.unshift(piv.new(n -1, ph))
if str == 'GN' or str == 'LN'
dir = aZZ.d.get (0)
x1 = aZZ.x.get (0)
y1 = aZZ.y.get (0)
y2 = nz(high[1])
//
if dir < 1 // if previous point was a pl, add, and change direction ( 1)
aZZ.in_out( 1, x1, y1, x2, y2)
else
if dir == 1 and ph > y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if showZZ
aZZ.l.get(0).set_xy2 (x2 , y2)
if pl
if pl < mnPiv
mnPiv := pl
if swingL.size() > 0
for i = swingL.size() -1 to 0
get = swingL.get(i)
if pl <= get.p
swingL.remove(i)
swingL.unshift(piv.new(n -1, pl))
//
if str == 'GN' or str == 'LN'
dir = aZZ.d.get (0)
x1 = aZZ.x.get (0)
y1 = aZZ.y.get (0)
y2 = nz(low [1])
//
if dir > -1 // if previous point was a ph, add, and change direction (-1)
aZZ.in_out(-1, x1, y1, x2, y2)
else
if dir == -1 and pl < y1
aZZ.x.set(0, x2), aZZ.y.set(0, y2)
if showZZ
aZZ.l.get(0).set_xy2 (x2 , y2)
//
iH = aZZ.d.get(2) == 1 ? 2 : 1
iL = aZZ.d.get(2) == -1 ? 2 : 1
//
switch
// MSS Bullish
close > aZZ.y.get(iH) and aZZ.d.get(iH) == 1 and MSS_dir < 1 =>
MSS_dir := 1
if active and showT
line.new(aZZ.x.get(iH), aZZ.y.get(iH), n, aZZ.y.get(iH), color=cResLine, width=2)
// MSS Bearish
close < aZZ.y.get(iL) and aZZ.d.get(iL) == -1 and MSS_dir > -1 =>
MSS_dir := -1
if active and showT
line.new(aZZ.x.get(iL), aZZ.y.get(iL), n, aZZ.y.get(iL), color=cSupLine, width=2)
if end
sz = swingH.size()
if sz > 0
for i = 0 to sz -1
y = swingH.get(i).p
if y > (stricty ? min : hilo.get(0))
targHi.unshift(line.new(swingH.get(i).b, y, n, y, color=cResLine))
highs.unshift(actLine.new(line.new( n, y, n, y, color=cResLine), true))
sz := swingL.size()
if sz > 0
for i = 0 to sz -1
y = swingL.get(i).p
if y < (stricty ? max : hilo.get(1))
targLo.unshift(line.new(swingL.get(i).b, y, n, y, color=cSupLine))
lows.unshift(actLine.new(line.new( n, y, n, y, color=cSupLine), true))
swingH.clear()
swingL.clear()
mnPiv := 10e6
mxPiv := 0
if showZZ
if ph or pl
aZZ.l.get(0).set_color(MSS_dir == 1 ? cResLine : cSupLine)
aTrend.set(0, MSS_dir)
//-------------------------------------------}
//Execution
//-------------------------------------------}
f_setTrend()
trend = aTrend.get(0)
//Targets
targetHi = false
targetLo = false
hSz = highs.size()
if hSz > 200
highs.pop().ln.delete()
hSz := highs.size()
if hSz > 0
for i = 0 to hSz -1
get = highs.get(i)
if get.active
get.ln.set_x2(n)
if high > get.ln.get_y2()
get.active := false
targetHi := true
lSz = lows.size()
if lSz > 200
lows.pop().ln.delete()
lSz := lows.size()
if lSz > 0
for i = 0 to lSz -1
get = lows.get(i)
if get.active
get.ln.set_x2(n)
if low < get.ln.get_y2()
get.active := false
targetLo := true
if l_SB.size() > 100
l_SB.pop().delete()
// SB session vLines & 'lock' previous FVG boxes
if strSB
min := 10e6
max := 0.
if showSB
l_SB.unshift(line.new(n, close, n, close + minT
, color= col_SB, extend=extend.both))
for i = 0 to bFVG_bull.size ( ) -1
get = bFVG_bull.get (i)
if n > get.box.get_right( ) -1
if get.current == true
get.current := false
for i = 0 to bFVG_bear.size ( ) -1
get = bFVG_bear.get (i)
if n > get.box.get_right( ) -1
if get.current == true
get.current := false
//FVG's
if is_in_SB
trend := aTrend.get(0)
if iTrend
switch trend
//bullish
1 =>
if low > high[2]
bFVG_bull.unshift(
FVG.new(
box = box.new(
n-2, low, n, high[2]
,border_color=color(na)
,bgcolor = cBullFVG)
, active = false
, current = true
)
)
//bearish
=>
if high < low [2]
bFVG_bear.unshift(
FVG.new(
box = box.new(
n-2, low[2], n, high
,border_color=color(na)
,bgcolor = cBearFVG)
, active = false
, current = true
)
)
else
if low > high[2]
bFVG_bull.unshift(
FVG.new(
box = box.new(
n , low, n, high[2]
,border_color=color(na)
,bgcolor = cBullFVG)
, active = false
, current = true
)
)
if high < low [2]
bFVG_bear.unshift(
FVG.new(
box = box.new(
n , low[2], n, high
,border_color=color(na)
,bgcolor = cBearFVG)
, active = false
, current = true
)
)
if endSB
if showSB
l_SB.unshift(line.new(n, close, n, close + minT
, color= col_SB, extend=extend.both))
if bFVG_bull.size() > 0
for i = 0 to bFVG_bull.size ( ) -1
get = bFVG_bull.get (i)
bLeft = get. box.get_left ( )
bTop = get. box.get_top ( )
bBot = get. box.get_bottom( )
if n - bLeft < 1000
if get.current
if is_in_SB
if close < bBot
if superstrict
get.current := false
get.box.set_bgcolor(color.new(color.blue, 100))
get.box.set_right(bLeft)
if superstrict or strict
get.active := false
else
if extend
if get.active
//update right when extend
get.box.set_right(n)
//trigger retrace -> activated
if not get.active
if low < bTop and close > bBot
get.active := true
if extend
get.box.set_right(n)
//if last bar of session and no retrace or close < bottom -> FVG invisible
if endSB
if get.active
if strict
if close < bBot // needs to be above box bottom
get.active := false
if superstrict
if close < bTop // needs to be above box top
get.active := false
//All FVG's who are not retraced (activated) are made invisible
if not get.active
get.box.set_bgcolor(color.new(color.blue, 100))
get.box.set_right(bLeft)
if get.active
min := math.min(min, bBot + minimum_trade_framework)
if extend
get.box.set_right(n)
if endSB[1]
get.active := false
//if show_minFr
// minTrFr.set_xy1(n -1, min - minimum_trade_framework)
// minTrFr.set_xy2(n -1, min )
if bFVG_bear.size() > 0
for i = 0 to bFVG_bear.size ( ) -1
get = bFVG_bear.get (i)
bLeft = get.box. get_left ( )
bTop = get.box. get_top ( )
bBot = get.box. get_bottom( )
if n - bLeft < 1000
if get.current
if is_in_SB
if close > bTop
if superstrict
get.current := false
get.box.set_bgcolor(color.new(color.blue, 100))
get.box.set_right(bLeft)
if superstrict or strict
get.active := false
else // if close < bTop
if extend
if get.active
//update right when extend
get.box.set_right(n)
//trigger retrace -> activated
if not get.active
if high > bBot and close < bTop
get.active := true
if extend
get.box.set_right(n)
//if last bar of session and no retrace -> FVG invisible
if endSB
if get.active
if strict
if close > bTop // needs to be below box top
get.active := false
if superstrict
if close > bBot // needs to be below box bottom
get.active := false
//All FVG's who are not retraced (activated) are made invisible
if not get.active
get.box.set_bgcolor(color.new(color.blue, 100))
get.box.set_right(bLeft)
if get.active
max := math.max(max, bTop - minimum_trade_framework)
if extend
get.box.set_right(n)
if endSB[1]
get.active := false
//if show_minFr
// maxTrFr.set_xy1(n -1, max )
// maxTrFr.set_xy2(n -1, max + minimum_trade_framework)
if prev
f_swings(strSB, endSB, 'GN', col_SB, min, max)
else
f_swings(strLN, endLN, 'LN', col_SB, min, max)
f_swings(strAM, endAM, 'AM', col_SB, min, max)
f_swings(strPM, endPM, 'PM', col_SB, min, max)
//-------------------------------------------}
//Plotchar/table
//-------------------------------------------}
tfs = (60 / (timeframe.in_seconds(timeframe.period) / 60)) / 2
plotchar(not na(SB_LN_per) and na(SB_LN_per[1]) and showSB
, title= '3-4 AM' , location=location.top, text= '3-4 AM\nNY', color=color(na)
, textcolor=col_SB, offset= +tfs)
plotchar(not na(SB_AM_per) and na(SB_AM_per[1]) and showSB
, title='10-11 AM', location=location.top, text='10-11 AM\nNY', color=color(na)
, textcolor=col_SB, offset= +tfs)
plotchar(not na(SB_PM_per) and na(SB_PM_per[1]) and showSB
, title= '2-3 PM' , location=location.top, text= '2-3 PM\nNY', color=color(na)
, textcolor=col_SB, offset= +tfs)
plotchar(targetHi ? high : na, 'target high', 'โข', location.abovebar, color=cResLine, size=size.small)
plotchar(targetLo ? low : na, 'target low' , 'โข', location.belowbar, color=cSupLine, size=size.small)
if barstate.islast
if timeframe.in_seconds(timeframe.period) > 15 * 60
table.cell(tab, 0, 0, text = 'Please use a timeframe <= 15 minutes', text_color=#FF0000)
//-------------------------------------------} |
Subsets and Splits