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
|
---|---|---|---|---|---|---|---|---|
wnG - Spikes Identifier | https://www.tradingview.com/script/iljuhcRZ-wnG-Spikes-Identifier/ | wingoutoulouse | https://www.tradingview.com/u/wingoutoulouse/ | 458 | 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/
// Β© wingoutoulouse
//@version=5
indicator(title="wnG - Spikes Identifier", shorttitle="wnG - Spikes Identifier [p]", overlay=true)
// NO INPUTS - TRADING SYSTEM
src_SPIKE = input(ohlc4,"Spike Source",group="Spike")
lps = input (false, title = "",group="Spike",inline="line 1")
len1_SMA = input.int(7,"Low Spike",group="Spike",inline="line 1")
mps = input (false, title = "",group="Spike",inline="line 2")
len2_SMA = input.int(14,"Mid Spike",group="Spike",inline="line 2")
hps = input (true, title = "",group="Spike",inline="line 3")
len3_SMA = input.int(21,"High Spike",group="Spike",inline="line 3")
vhps = input (true, title = "",group="Spike",inline="line 4")
len4_SMA = input.int(28,"Very High Spike",group="Spike",inline="line 4")
i_background = input.bool(true,title="Show BackGround ?",group="Charts")
i_strat = input.bool(true,title="Show Shapes ?",group="Charts")
i_line = input.bool(false,title="Show Levels ?",group="Charts")
spk1 = 1.6
spk2 = 2.4
spk3 = 3.2
spk4 = 4.
// Moving Average (Mid Point Fair Value)
ma1_Spike = ta.sma(src_SPIKE, len1_SMA)
ma2_Spike = ta.sma(src_SPIKE, len2_SMA)
ma3_Spike = ta.sma(src_SPIKE, len3_SMA)
ma4_Spike = ta.sma(src_SPIKE, len4_SMA)
// ATR (Dynamic Volatility Units)
rng1 = ta.sma(ta.tr,len1_SMA)
rng2 = ta.sma(ta.tr,len2_SMA)
rng3 = ta.sma(ta.tr,len3_SMA)
rng4 = ta.sma(ta.tr,len4_SMA)
// ATR deviation
up1 = ma1_Spike + rng1 * spk1
up2 = ma2_Spike + rng2 * spk2
up3 = ma3_Spike + rng3 * spk3
up4 = ma4_Spike + rng4 * spk4
dn1 = ma1_Spike - rng1 * spk1
dn2 = ma2_Spike - rng2 * spk2
dn3 = ma3_Spike - rng3 * spk3
dn4 = ma4_Spike - rng4 * spk4
// Low Probability Trade Setup
ERhigh1 = high > up1 ? 1 : 0
ERlow1 = low < dn1 ? 1 : 0
// Medium Probability Trade Setup
ERhigh2 = high > up1 and high > up2 ? 1 : 0
ERlow2 = low < dn1 and low < dn2 ? 1 : 0
// High Probability Trade Setup
ERhigh3 = high > up1 and high > up2 and high > up3 ? 1 : 0
ERlow3 = low < dn1 and low < dn2 and low < dn3 ? 1 : 0
// Very High Probability Trade Setup
ERhigh4 = high > up1 and high > up2 and high > up3 and high > up4 ? 1 : 0
ERlow4 = low < dn1 and low < dn2 and low < dn3 and low < dn4 ? 1 : 0
// Plots Based on Selection
vHiPERh = vhps and ERhigh4 and i_background ? color.new(color.red,80) : na
vHiPERl = vhps and ERlow4 and i_background ? color.new(color.lime,80) : na
HiPERh = hps and ERhigh3 and i_background ? color.new(color.red,80) : na
HiPERl = hps and ERlow3 and i_background ? color.new(color.green,80) : na
MiPERh = mps and ERhigh2 and i_background ? color.new(color.orange,80) : na
MiPERl = mps and ERlow2 and i_background ? color.new(color.teal,80) : na
LoPERh = lps and ERhigh1 and i_background ? color.new(color.yellow,80) : na
LoPERl = lps and ERlow1 and i_background ? color.new(color.navy,80) : na
// Highlights
bgcolor(vHiPERh)
bgcolor(vHiPERl)
bgcolor(HiPERh)
bgcolor(HiPERl)
bgcolor(MiPERh)
bgcolor(MiPERl)
bgcolor(LoPERh)
bgcolor(LoPERl)
plot(i_line and lps ? up1 : na, color=color.new(color.maroon,50))
plot(i_line and lps ? dn1 : na, color=color.new(color.maroon,50))
plot(i_line and mps ? up2 : na, color=color.new(color.orange,50))
plot(i_line and mps ? dn2 : na, color=color.new(color.orange,50))
plot(i_line and hps ? up3 : na, color=color.new(color.yellow,50))
plot(i_line and hps ? dn3 : na, color=color.new(color.yellow,50))
plot(i_line and vhps ? up4 : na, color=color.new(color.white,50))
plot(i_line and vhps ? dn4 : na, color=color.new(color.white,50))
plotshape(i_strat and lps and ERhigh1 ? 1 : na,style=shape.triangledown, color=color.red, location=location.abovebar, size=size.small)
plotshape(i_strat and lps and ERlow1 ? 1 : na,style=shape.triangleup, color=color.lime, location=location.belowbar, size=size.small)
plotshape(i_strat and mps and ERhigh2 ? 1 : na,style=shape.triangledown, color=color.red, location=location.abovebar, size=size.small)
plotshape(i_strat and mps and ERlow2 ? 1 : na,style=shape.triangleup, color=color.lime, location=location.belowbar, size=size.small)
plotshape(i_strat and hps and ERhigh3 ? 1 : na,style=shape.triangledown, color=color.red, location=location.abovebar, size=size.small)
plotshape(i_strat and hps and ERlow3 ? 1 : na,style=shape.triangleup, color=color.lime, location=location.belowbar, size=size.small)
plotshape(i_strat and vhps and ERhigh4 ? 1 : na,style=shape.triangledown, color=color.red, location=location.abovebar, size=size.small)
plotshape(i_strat and vhps and ERlow4 ? 1 : na,style=shape.triangleup, color=color.lime, location=location.belowbar, size=size.small)
alertcondition(ERhigh1, title="High Spike [low]", message = "High Spike - Low probability")
alertcondition(ERlow1, title="Low Spike [low]", message = "Low Spike - Low probability")
alertcondition(ERhigh2, title="High Spike [medium]", message = "High Spike - Medium probability")
alertcondition(ERlow2, title="Low Spike [medium]", message = "Low Spike - Medium probability")
alertcondition(ERhigh3, title="High Spike [high]", message = "High Spike - High probability")
alertcondition(ERlow1, title="Low Spike [high]", message = "Low Spike - High probability")
alertcondition(ERhigh4, title="High Spike [very high]", message = "High Spike - Very High probability")
alertcondition(ERlow4, title="Low Spike [very high]", message = "Low Spike - Very High probability")
|
multiple_ma_envelope | https://www.tradingview.com/script/9xHzezOr-multiple-ma-envelope/ | palitoj_endthen | https://www.tradingview.com/u/palitoj_endthen/ | 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/
// Β© palitoj_endthen
//@version=5
indicator(title = 'Multiple Moving Average Envelope', shorttitle = 'ma_envelope', overlay = true)
// input
src = input.source(defval = ohlc4, title = 'Source', group = 'Options', tooltip = 'Determines the source of input data')
ma_type = input.string(defval = 'WMA', title = 'MA Type', group = 'Options', options = ['EMA', 'SMA', 'WMA', 'HMA'], tooltip = 'Choose between moving average types')
mult = input.float(defval = 0.1, title = 'Initial Multiplier', group = 'Options', step = 0.1, maxval = 1, tooltip = 'Determines value of multiplier for upper and lower band')
value_at_risk = input.float(defval = 5.0, title = 'Confidence', group = 'Options', tooltip = 'Input confidence level (ps: no need convert to decimal)')
show_ma = input.bool(defval = true, title = 'MA', group = 'Moving Average', tooltip = 'Determines whether to display moving average line', inline = 'f')
length = input.int(defval = 10, title = 'Length', group = 'Moving Average', tooltip = 'Determines lookback period of moving average', inline = 'f')
// switch between moving average type
float ma = switch ma_type
"EMA" => ta.ema(src, length)
"SMA" => ta.sma(src, length)
"WMA" => ta.wma(src, length)
"HMA" => ta.hma(src, length)
// multiple moving envelope
env(mult_)=>
upper_band = ma*(1+mult_)
lower_band = ma*(1-mult_)
[upper_band, lower_band]
// visualize
// moving average envelope
[u1, l1] = env(mult) // -> base
[u2, l2] = env(mult+.2) // -> mult = .3
[u3, l3] = env(mult+.4) // -> mult = .5
[u4, l4] = env(mult+.6) // -> mult = .7
fill(plot(u1, color = na), plot(l1, color = na), color.new(#1E90FF, 97))
fill(plot(u2, color = na), plot(l2, color = na), color.new(#1E90FF, 97))
fill(plot(u3, color = na), plot(l3, color = na), color.new(#1E90FF, 97))
fill(plot(u4, color = na), plot(l4, color = na), color.new(#1E90FF, 97))
// moving average
plot(show_ma ? ma : na, color = color.maroon, linewidth = 2)
// information table
y = input.string(defval = 'top', title = 'Position', inline = '8', options = ['top', 'middle', 'bottom'], group = 'Information Value')
x = input.string(defval = 'right', title = '', inline = '8', options = ['left', 'center', 'right'], group = 'Information Value')
var table information_table = table.new(y + "_" + x, 2, 5)
table.cell(information_table, 0, 1, 'Information' , text_halign = text.align_left, text_size = size.normal, text_color = color.new(color.maroon, 50))
table.cell(information_table, 1, 1, 'Value' , text_size = size.normal, text_color = color.new(color.maroon, 50))
// deviation
returns = (close/close[1])-1
stdev = math.round(ta.stdev(returns, length), 3)*100
table.cell(information_table, 0, 2, 'Std. Deviation' , text_halign = text.align_left, text_size = size.normal, text_color = color.new(color.white, 50))
table.cell(information_table, 1, 2, str.tostring(stdev)+'%' , text_size = size.normal, text_color = color.new(color.white, 50))
// compounding growth
compounded_growth = math.round(((math.pow((close/close[length]), (1/length))-1)*100),3)
table.cell(information_table, 0, 3, 'Growth Rate' , text_halign = text.align_left, text_size = size.normal, text_color = color.new(color.white, 50))
table.cell(information_table, 1, 3, str.tostring(compounded_growth) + '%', text_halign = text.align_left, text_size = size.normal, text_color = color.new(color.white, 50))
// value-at-risk
VaR = math.round(ta.percentile_nearest_rank(returns, length, value_at_risk),3)*100
table.cell(information_table, 0, 4, 'Value-at-Risk' , text_halign = text.align_left, text_size = size.normal, text_color = color.new(color.white, 50))
table.cell(information_table, 1, 4, str.tostring(VaR)+'%' ,text_size = size.normal, text_color = color.new(color.white, 50)) |
FinancialWisdom Breakout Indicator | https://www.tradingview.com/script/K4XRmTNU-FinancialWisdom-Breakout-Indicator/ | FittestTrader | https://www.tradingview.com/u/FittestTrader/ | 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/
// Β© FittestTrader
//@version=5
indicator("FW Breakout Indicator", overlay=true)
//INPUTS
Bars = input (6)
minimum = input.int(1, "Min Breakout %")
maximum = input.int(20, "Max Breakout %")
min = input.int(5, "Min Breakout Size %")
max = input.int(20, "Max Breakout Size %")
Volume = input.int(30, "Min Volume Breakout %")
Consolidation = input.int(15, "Consolidation Range")
Stoploss = input.int(20, "Stoploss Percentage")
MovingAverage = input (20)
atrlength = input(title="NATR Length", defval=14)
atrval = input(title="Max NATR Value", defval=8)
//MACD
fastLength = input(12)
slowlength = input(26)
MACDLength = input(9)
MACD = ta.ema(close, fastLength) - ta.ema(close, slowlength)
aMACD = ta.ema(MACD, MACDLength)
delta = MACD - aMACD
//MACD
//INPUTS
//Calculation
highest=ta.highest(high, Bars)[1]
change=ta.change(close,Bars)[1]
lowest=ta.lowest(low,Bars) [1]
diff= ((highest/lowest) - 1)*100
minbo = highest * ((minimum/100)+1)
maxbo = highest * ((maximum/100)+1)
Vol = ((volume / volume[1]) - 1) * 100
SL = ((close/lowest) - 1) * 100
MA = ta.sma(close,MovingAverage)
minbos = close[1] * ((min/100)+1)
maxbos = close[1] * ((max/100)+1)
natr = 100 * ta.atr(atrlength) / close
//Calculation
Breakout = diff < Consolidation and close > minbo and close < maxbo and MACD>aMACD and Vol > Volume and SL < Stoploss and close > MA and natr < atrval and close >= minbos and close < maxbos
plotshape(Breakout,"Breakout",shape.labelup ,location.belowbar ,#26a69a,text="B",textcolor=color.white,size=size.normal)
alertcondition(Breakout,'Upper Breakout','Price broke upper trendline')
|
Asset compared to asset/market | https://www.tradingview.com/script/g9ojBOS3-Asset-compared-to-asset-market/ | lyubo94 | https://www.tradingview.com/u/lyubo94/ | 109 | 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/
// Β© lyubo
//@version=5
indicator("Asset compared to asset/market", overlay=false, precision=7)
// Utility functions - start
// for testing
// plotshape(some_bool_condition, 'Green label', shape.diamond, location.bottom, color.green, -1, size=size.tiny)
// label.new(bar_index, whatToPlot[1], str.tostring(multiplier) + ' - ' + str.tostring(), size = size.normal)
func_print_1_key_and_value_pair(key1, val1) =>
if barstate.islast
label.new(bar_index, 1.008*high, str.tostring(key1) + ' - ' + str.tostring(val1), size = size.normal)
func_print_2_key_and_value_pairs(key1, val1, key2, val2) =>
if barstate.islast
label.new(bar_index, 1.008*high, str.tostring(key1) + ' - ' + str.tostring(val1) + '\n' + str.tostring(key2) + ' - ' + str.tostring(val2), size = size.normal)
func_print_3_key_and_value_pairs(key1, val1, key2, val2, key3, val3) =>
if barstate.islast
label.new(bar_index, 1.008*high, str.tostring(key1) + ' - ' + str.tostring(val1) + '\n' + str.tostring(key2) + ' - ' + str.tostring(val2) + '\n' + str.tostring(key3) + ' - ' + str.tostring(val3), size = size.normal)
// Utility functions - end
// *********************** Global variables declarations - start ***********************
var lastMajorBullCross = false
var lastMajorBearCross = false
var number_to_multiply_by_to_determine_decimal_points = 10000
timeframe = input.timeframe("", title = "Timeframe:")
comparedToSymbol = input.symbol("TOTAL", "Compare to symbol:")
securityOfComparedToSymbol = request.security(comparedToSymbol, timeframe, close)
ema1length = input.int(20, "EMA 1 length:")
ema2length = input.int(45, "EMA 2 length:")
ema3length = input.int(200, "EMA 3/Mean reversion 2 length:")
ema4lengthMeanReversion1 = input.int(100, "EMA 4/Mean reversion 1 length:")
securitySymbolToCompare = request.security(syminfo.tickerid, timeframe, close)
compareAnotherSymbolThanCurrent = input.bool(false, "Compare another symbol other than the current one:")
otherSymbolToCompare = input.symbol("BTCUSD", "Symbol to compare:")
securityOfOtherSymbolToCompare=request.security(otherSymbolToCompare, timeframe, close)
whatToPlot = ((securitySymbolToCompare)/(securityOfComparedToSymbol)) * 100
x = if compareAnotherSymbolThanCurrent
whatToPlot:=(securityOfOtherSymbolToCompare/securityOfComparedToSymbol)*100
// logic to prevent calculation mistakes with too discrepant numbers
number_of_multiplied_times = 0
while whatToPlot < 1 and (whatToPlot * number_to_multiply_by_to_determine_decimal_points < 1)
whatToPlot := whatToPlot * 10
number_of_multiplied_times += 1
// fix for cases which go from ...9 to ...1 and vice versa
prev_value_first_num = ''
curr_value_first_num = ''
num_prev = whatToPlot[1]
while num_prev < 1
num_prev := num_prev * 10
num_curr = whatToPlot
while num_curr < 1
num_curr := num_curr * 10
prev_value_first_num := str.substring(str.tostring(num_prev), 0, 1)
curr_value_first_num := str.substring(str.tostring(num_curr), 0, 1)
var multiplier = 1.0
if number_of_multiplied_times > number_of_multiplied_times[1]
multiplier := multiplier / 10
else if number_of_multiplied_times < number_of_multiplied_times[1]
multiplier := multiplier * 10
whatToPlot := whatToPlot * multiplier
ema1 = ta.ema(whatToPlot, ema1length)
ema2 = ta.ema(whatToPlot, ema2length)
ema3 = ta.ema(whatToPlot, ema3length)
emaPrice20 = ta.ema(close, ema1length)
emaPrice45 = ta.ema(close, ema2length)
emaPrice200 = ta.ema(close, ema3length)
emaPrice100 = ta.ema(close, ema4lengthMeanReversion1)
includeBullBackground = input.bool(true, "Include Bull background")
includeBearBackground = input.bool(true, "Include Bear background")
strongBullAlignment= whatToPlot > ema1 and ema1 > ema2 and ema2 > ema3
strongBearAlignment= whatToPlot < ema1 and ema1 < ema2 and ema2 < ema3
strongBullInPrice = close > emaPrice20 and emaPrice20 > emaPrice45 and emaPrice45 > emaPrice200
strongBearInPrice = close < emaPrice20 and emaPrice20 < emaPrice45 and emaPrice45 < emaPrice200
// *********************** Global variables declarations - end ***********************
bgcolor(includeBullBackground and strongBullAlignment ? color.new(color.green, 70) : na, title="Bull")
bgcolor(includeBearBackground and strongBearAlignment ? color.new(color.red,70) : na, title="Bear")
bgcolor(includeBullBackground and strongBullInPrice ? color.new(color.green, 70) : na, title="Bull")
bgcolor(includeBearBackground and strongBearInPrice ? color.new(color.red,70) : na, title="Bear")
plot(whatToPlot, "Asset compared to asset index", color=color.black, linewidth=2)
plot(ema1, "EMA 1", color=color.new(#2196f3,0))
plot(ema2, "EMA 2", color=color.new(#f803c1,0))
plot(ema3, "EMA 3", color=color.new(#ff1100, 0), linewidth=2)
// Alarms
bearPriceCross = ta.crossunder(close, emaPrice200)
bullPriceCross = ta.crossover(close, emaPrice200)
bearPriceCondition = close < emaPrice200
bullPriceCondition = close > emaPrice200
bearIndexCross = ta.crossunder(whatToPlot,ema3)
bullIndexCross = ta.crossover(whatToPlot,ema3)
bearIndexCondition = whatToPlot<ema3
bullIndexCondition = whatToPlot>ema3
MajorBearAlert= (bearPriceCross and bearIndexCondition) or (bearIndexCross and bearPriceCondition)
MajorBullAlert= (bullPriceCross and bullIndexCondition) or (bullIndexCross and bullPriceCondition)
if MajorBullAlert
lastMajorBullCross = true
lastMajorBearCross = false
if MajorBearAlert
lastMajorBullCross = false
lastMajorBearCross = true
PriceBearAlert = bearPriceCross //and strongBearInPrice
PriceBullAlert = bullPriceCross //and strongBullInPrice
IndexBearAlert = bearIndexCross //and strongBearAlignment
IndexBullAlert = bullIndexCross //and strongBullAlignment
// *********************** Alerts - start ***********************
// Any of major, price or index alerts
if MajorBearAlert or PriceBearAlert or IndexBearAlert // maybe to add the condition saying that before that there was a bear cross of both PA and index with ema200 or something like that
alert("Any bear alert", alert.freq_once_per_bar_close)
if MajorBullAlert or PriceBullAlert or IndexBullAlert
alert("Any bull alert", alert.freq_once_per_bar_close)
// Mean reversion alerts - Price
// 100 EMA mean reversion 1
if lastMajorBullCross and ta.crossunder(close, emaPrice100)
alert('Mean reversion 1 - Bull', alert.freq_once_per_bar_close)
if lastMajorBearCross and ta.crossover(close, emaPrice100)
alert('Mean reversion 1 - Bear', alert.freq_once_per_bar_close)
// 200 EMA mean reversion 2
if lastMajorBullCross and ta.crossunder(close, emaPrice200)
alert('Mean reversion 1 - Bull', alert.freq_once_per_bar_close)
if lastMajorBearCross and ta.crossover(close, emaPrice200)
alert('Mean reversion 1 - Bear', alert.freq_once_per_bar_close)
// *********************** Alerts - end ***********************
alertcondition(MajorBearAlert, title='Major Bear alert', message='Major Bear - 200 EMA crossed on both price and Asset vs asset indicator')
alertcondition(MajorBullAlert, title='Major Bull alert', message='Major Bull - 200 EMA crossed on both price and Asset vs asset indicator')
alertcondition(PriceBearAlert, title='Price Bear alert', message='Price Bear - 200 EMA crossed on price')
alertcondition(PriceBullAlert, title='Price Bull alert', message='Price Bull - 200 EMA crossed on price')
alertcondition(IndexBearAlert, title='Index Bear alert', message='Index Bear - 200 EMA crossed on price')
alertcondition(IndexBullAlert, title='Index Bull alert', message='Index Bull - 200 EMA crossed on price')
|
MACD Divergence Fast by RSU | https://www.tradingview.com/script/GMTSAf1Q/ | rsu9 | https://www.tradingview.com/u/rsu9/ | 210 | 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/
// Β© rsu9111
//@version=5
indicator("MACD Divergence Fast by RSU",max_bars_back=1000)
fastlinelen=input.int(12,title="Fast line Length")
slowlinelen=input.int(26,title="Slow line Length")
smoothlinelen=input.int(9,title="Smooth line Length")
usdBB=input.bool(false,"Enhanced Mode:Bollinger bands instead of dea lines")
//MACD
diff=ta.ema(close,fastlinelen)-ta.ema(close,slowlinelen)
dea=ta.ema(diff,smoothlinelen)
macd=(diff-dea)
//plot macd Histogram
col_grow_above = #26A69A
col_grow_below = #FFCDD2
col_fall_above = #B2DFDB
col_fall_below = #EF5350
plot(usdBB?na:macd, title="Histogram", style=plot.style_columns, color=(macd>=0 ? (macd[1] < macd ? col_grow_above : col_fall_above) : (macd[1] < macd ? col_grow_below : col_fall_below) ))
//Bollinger bands instead of dea lines
stdev = ta.stdev(diff,9)
upper = dea + stdev
lower = dea - stdev
ul=plot(usdBB?upper:na,color=color.new(color.gray,70))
ll=plot(usdBB?lower:na,color=color.new(color.gray,70))
fill(ul,ll,color=color.new(color.gray,90))
dl=plot(diff,color=usdBB?diff>upper?color.new(#008000,0):diff<lower?color.new(#FF0000,0):color.blue:color.orange,title="MACD Diff Line",linewidth=2)
fill(dl,ul,color=diff>upper?color.new(#008000,50):na)
fill(dl,ll,color=diff<lower?color.new(#FF0000,50):na)
plot(dea,color=color.purple)
plot(0,color=color.new(color.gray,70),linewidth=2)
//Divergance function
findMACDTopBl(len)=>
src=diff
top= ta.pivothigh(src,len, len)
topc = 0
topc := top ? len : nz(topc[1]) + 1
newtop=ta.pivothigh(src,len,0)
topBL_z=newtop[1] and not newtop and high[1]>high[topc] and src[1]<src[topc] and diff[topc]>dea[topc] and src[topc]>0
topBL_h=newtop[1] and not newtop and high[1]<high[topc] and src[1]>src[topc] and diff[topc]>dea[topc] and src[topc]>0
BLTopc=0
if topBL_z or topBL_h
BLTopc:=topc
BLTopc
findMACDBotBl(len)=>
src=diff
bot= ta.pivotlow(src,len, len)
botc = 0
botc := bot ? len : nz(botc[1]) + 1
newbot=ta.pivotlow(src,len,0)
BotBL_z=newbot[1] and not newbot and low[1]<low[botc] and src[1]>src[botc] and diff[botc]<dea[botc] and src[botc]<0
BotBL_h=newbot[1] and not newbot and low[1]>low[botc] and src[1]<src[botc] and diff[botc]<dea[botc] and src[botc]<0
BLBotc=0
if BotBL_z or BotBL_h
BLBotc:=botc
BLBotc
//Different Len from short to long
//5,20,40,60
mt5result=findMACDTopBl(5)
mt10result=findMACDTopBl(10)
mt20result=findMACDTopBl(20)
mt40result=findMACDTopBl(40)
mt60result=findMACDTopBl(60)
mb5result=findMACDBotBl(5)
mb10result=findMACDBotBl(10)
mb20result=findMACDBotBl(20)
mb40result=findMACDBotBl(40)
mb60result=findMACDBotBl(60)
string notfinished=""
if timenow<time_close
notfinished:="\nK not end"
var toplines = array.new_line()
var toplabels = array.new_label()
var botlines = array.new_line()
var botlabels = array.new_label()
//keep array length within 5
pushArray(array1,obj)=>
if array.size(array1)>4
array.shift(array1)
array.push(array1,obj)
//label and line
if mt5result
pushArray(toplabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.red,40),size=size.tiny,style=label.style_label_down))
pushArray(toplines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mt5result],y2=diff[mt5result]*1.1,color=color.red,width=1))
if mt10result
pushArray(toplabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.red,40),size=size.tiny,style=label.style_label_down))
pushArray(toplines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mt10result],y2=diff[mt10result]*1.1,color=color.red,width=1))
if mt20result
pushArray(toplabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.red,40),size=size.tiny,style=label.style_label_down))
pushArray(toplines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mt20result],y2=diff[mt20result]*1.1,color=color.red,width=1))
if mt40result
pushArray(toplabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.red,40),size=size.tiny,style=label.style_label_down))
pushArray(toplines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mt40result],y2=diff[mt40result]*1.1,color=color.red,width=1))
if mt60result
pushArray(toplabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.red,40),size=size.tiny,style=label.style_label_down))
pushArray(toplines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mt60result],y2=diff[mt60result]*1.1,color=color.red,width=1))
//recolor previous error divergence lines
if array.size(toplines)>=1
for i=0 to array.size(toplines)-1
templine=array.get(toplines,i)
x1=line.get_x1(templine)
if bar_index-x1-1<4 and diff>diff[bar_index-x1]
line.set_color(templine,color.new(color.gray,80))
//delete previous error divergance labels
if array.size(toplabels)>=1
for i=0 to array.size(toplabels)-1
templabel=array.get(toplabels,i)
x1=label.get_x(templabel)
if bar_index-x1-1<4 and diff>diff[bar_index-x1]
label.delete(templabel)
if mb5result
pushArray(botlines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mb5result],y2=diff[mb5result]*1.1,color=color.green,width=1))
pushArray(botlabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.green,40),size=size.tiny,style=label.style_label_up))
if mb10result
pushArray(botlines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mb10result],y2=diff[mb10result]*1.1,color=color.green,width=1))
pushArray(botlabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.green,40),size=size.tiny,style=label.style_label_up))
if mb20result
pushArray(botlines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mb20result],y2=diff[mb20result]*1.1,color=color.green,width=1))
pushArray(botlabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.green,40),size=size.tiny,style=label.style_label_up))
if mb40result
pushArray(botlines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mb40result],y2=diff[mb40result]*1.1,color=color.green,width=1))
pushArray(botlabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.green,40),size=size.tiny,style=label.style_label_up))
if mb60result
pushArray(botlines,line.new(x1=bar_index[1],y1=diff[1]*1.1,x2=bar_index[mb60result],y2=diff[mb60result]*1.1,color=color.green,width=1))
pushArray(botlabels,label.new(x=bar_index,y=diff[1]*1.1,text="m"+notfinished,textcolor=#ffffff,color=color.new(color.green,40),size=size.tiny,style=label.style_label_up))
if array.size(botlines)>=1
for i=0 to array.size(botlines)-1
templine=array.get(botlines,i)
x1=line.get_x1(templine)
if bar_index-x1-1<4 and diff<diff[bar_index-x1]
line.set_color(templine,color.new(color.gray,80))
//line.delete(templine)
//delete previous error divergance labels
if array.size(botlabels)>=1
for i=0 to array.size(botlabels)-1
templabel=array.get(botlabels,i)
x1=label.get_x(templabel)
if bar_index-x1-1<4 and diff<diff[bar_index-x1]
label.delete(templabel)
|
SMOOTHED RSI SWITCH | https://www.tradingview.com/script/bxUuwVdx-SMOOTHED-RSI-SWITCH/ | TShong99 | https://www.tradingview.com/u/TShong99/ | 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/
// Β© TShong99
// Β© ThembShong99
//@version=5
indicator('SMOOTHED RSI SWITCH')
Sensitivity = input(14)
Smoothness = input(25)
osc = ta.rsi(close, Sensitivity)
smoothOsc = ta.hma(osc, Smoothness)
oscPlot = plot(smoothOsc)
fairLine = hline(50, title='fair', linestyle=hline.style_solid, editable=false, color=color.gray)
cheapPrice = hline(30, title='cheap', linestyle=hline.style_solid, editable=false, color=color.lime)
expensivePrice = hline(70, title='expensive', linestyle=hline.style_solid, editable=false, color=color.red)
fairLinePlot = plot(50, color=na, editable=false)
cheapLinePlot = plot(30, color=na, editable=false)
expensLinePlot = plot(70, color=na, editable=false)
fill(oscPlot, fairLinePlot, color=smoothOsc > 50 and smoothOsc > smoothOsc[1] ? color.new(color.lime, 50): na)
fill(oscPlot, fairLinePlot, color=smoothOsc < 50 and smoothOsc < smoothOsc[1] ? color.new(color.red, 50) : na)
fill(oscPlot, expensLinePlot, color=smoothOsc > 70 and smoothOsc > smoothOsc[1] ? color.new(color.lime, 50) : na)
fill(oscPlot, expensLinePlot, color=smoothOsc > 70 and smoothOsc < smoothOsc[1] ? color.new(color.lime, 70) : na)
fill(oscPlot, cheapLinePlot, color=smoothOsc < 30 and smoothOsc < smoothOsc[1] ? color.new(color.red, 50) : na)
fill(oscPlot, cheapLinePlot, color=smoothOsc < 30 and smoothOsc > smoothOsc[1] ? color.new(color.red, 70) : na)
|
Williams Fractals - LH/HL | https://www.tradingview.com/script/xpslxsWD-Williams-Fractals-LH-HL/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 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/
// Β© platsn
//@version=5
indicator("Williams Fractals - LH/HL", shorttitle="Fractals - LH/HL", format=format.price, precision=0, overlay=true)
// Define "n" as the number of periods and keep a minimum value of 2 for error handling.
n = input.int(title="Periods", defval=2, minval=2)
show_HL = input.bool(true, title="Show LH / HL Fractals")
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
// downFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
plotshape(downFractal, style=shape.triangleup, location=location.belowbar, offset=-n, color=color.green, size = size.small)
plotshape(upFractal, style=shape.triangledown, location=location.abovebar, offset=-n, color=color.red, size = size.small)
LHF = upFractal and high[n] < ta.valuewhen(upFractal, high[n], 1)
HLF = downFractal and low[n] > ta.valuewhen(downFractal, low[n], 1)
plotshape(show_HL and LHF, "LowerHighFractal",style=shape.triangledown, location=location.abovebar, offset=-n, color=color.red, size = size.tiny)
plotshape(show_HL and HLF, "HigherLowFractal", style=shape.triangleup, location=location.belowbar, offset=-n, color=color.green, size = size.tiny)
alertcondition(LHF,"Lower High Fractal")
alertcondition(HLF,"Higher Low Fractal")
|
Stochastic OB/OS Zones Heatmap | https://www.tradingview.com/script/NcE0pH4P-Stochastic-OB-OS-Zones-Heatmap/ | vranabanana | https://www.tradingview.com/u/vranabanana/ | 30 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© vranabanana
// The code is based on the Stochastic RSI Heatmap, but uses a normal Stochastic instead the Stochastic RSI when calculating "k" for more accuracy.
// Credit for the idea goes to Indicator-Jones
//@version=5
//---------------Stochastic Overbought/Oversold Heatmap-----------------
indicator(title="Stochastic OB/OS zones Heatmap", overlay=true, shorttitle="Stochastic zones", format=format.price, precision=2, timeframe="", timeframe_gaps=false)
// Stochastic settings
var string GRP1 = 'ββββββββββ ββSettingsββ ββββββββββ'
lengthStoch = input.int(14, "Stochastic Length", minval=1, group=GRP1)
smoothK = input.int(3, "K", minval=1, group=GRP1)
smoothD = input.int(3, "D", minval=1, group=GRP1)
lengthRSI = input.int(14, "RSI Length", minval=1, group=GRP1)
src = input(close, title="RSI Source", group=GRP1)
rsi1 = ta.rsi(src, lengthRSI)
k = ta.stoch(src, high, low, lengthStoch)
d = ta.sma(k, smoothD)
// BUY ZONE levels
var string GRP2 = 'ββββββββββ ββBUY ZONEββ ββββββββββ'
BuySto1 = input.int (defval = 20, title="Oversold Zone 1", minval=1, maxval=100, group=GRP2)
BuySto2 = input.int (defval = 15, title="Oversold Zone 2", minval=1, maxval=100, group=GRP2)
BuySto3 = input.int (defval = 10, title="Oversold Zone 3", minval=1, maxval=100, group=GRP2)
BuySto4 = input.int (defval = 5, title="Oversold Zone 4", minval=1, maxval=100, group=GRP2)
// SELL ZONE levels
var string GRP3 = 'ββββββββββ ββSELL ZONEββ ββββββββββ'
SellSto1 = input.int (defval = 80, title="Overbought Zone 1", minval=1, maxval=100, group=GRP3)
SellSto2 = input.int (defval = 85, title="Overbought Zone 2", minval=1, maxval=100, group=GRP3)
SellSto3 = input.int (defval = 90, title="Overbought Zone 3", minval=1, maxval=100, group=GRP3)
SellSto4 = input.int (defval = 95, title="Overbought Zone 4", minval=1, maxval=100, group=GRP3)
// Calculations
BUY1 = k < BuySto1 and d < BuySto1
BUY2 = k < BuySto2 and d < BuySto2
BUY3 = k < BuySto3 and d < BuySto3
BUY4 = k < BuySto4 and d < BuySto4
SELL1 = k > SellSto1 and d > SellSto1
SELL2 = k > SellSto2 and d > SellSto2
SELL3 = k > SellSto3 and d > SellSto3
SELL4 = k > SellSto4 and d > SellSto4
// Colors
bgcolor (BUY1 ? color.new(color.blue,65) : na, title= "Background Oversold Zone 1")
bgcolor (BUY2 ? color.new(color.blue,65) : na, title= "Background Oversold Zone 2")
bgcolor (BUY3 ? color.new(color.blue,55) : na, title= "Background Oversold Zone 3")
bgcolor (BUY4 ? color.new(color.blue,1) : na, title= "Background Oversold Zone 4")
bgcolor (SELL1 ? color.new(color.fuchsia,75) : na, title= "Background Overbought Zone 1")
bgcolor (SELL2 ? color.new(color.fuchsia,65) : na, title= "Background Overbought Zone 2")
bgcolor (SELL3 ? color.new(color.fuchsia,55) : na, title= "Background Overbought Zone 3")
bgcolor (SELL4 ? color.new(color.fuchsia,1) : na, title= "Background Overbought Zone 4")
|
Guppy Waves | https://www.tradingview.com/script/TkhfNk08-Guppy-Waves/ | animecummer | https://www.tradingview.com/u/animecummer/ | 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/
//@version=5
indicator(title='Guppy Waves', shorttitle='Guppy Waves', overlay=true, timeframe="", timeframe_gaps=true)
//COLOR INPUTS
Color_type = input.string('User Colors', '', inline='0',
options=['User Colors',
'RSI Rainbow'])
rainbowon = if Color_type == 'RSI Rainbow'
true
else
false
color bullma = input.color(color.new(color.lime, 100), '', inline='0')
color bearma = input.color(color.new(color.fuchsia, 100), '', inline='0')
filloffset = input.int(0, 'Fill Transparency Offset', inline='0', minval=-100, maxval=100)
//SPECIAL MA SETTINGS
lsmaoffset = input.int(title='LEAST SQUARES (LSMA) ONLY - LS Offset', defval=0, inline='00', group='Special MA Settings')
almaoffset = input.float(title='ALMA Offset', defval=0.85, step=0.01, inline='01', group='Special MA Settings')
almasigma = input.float(title='ALMA Sigma', defval=6, inline='01', group='Special MA Settings')
a1 = input.float(title='Tillson T3 Volume Factor', defval=0.7, step=0.001, inline='02', group='Special MA Settings')
//FUNCTIONS BLOCK
f_ehma(_source, _length) =>
_return = ta.ema(2 * ta.ema(_source, _length / 2) - ta.ema(_source, _length), math.round(math.sqrt(_length)))
_return
f_tema(_source, _length) =>
_out = 3 * (ta.ema(_source, _length) - ta.ema(ta.ema(_source, _length), _length)) + ta.ema(ta.ema(ta.ema(_source, _length), _length), _length)
_out
f_t3(_source, _length, _a1) =>
_output = (-_a1 * _a1 * _a1) * (ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(_source, _length), _length), _length), _length), _length), _length)) + (3 * _a1 * _a1 + 3 * _a1 * _a1 * _a1) * (ta.ema(ta.ema(ta.ema(ta.ema(ta.ema(_source, _length), _length), _length), _length), _length)) + (-6 * _a1 * _a1 - 3 * _a1 - 3 * _a1 * _a1 * _a1) * (ta.ema(ta.ema(ta.ema(ta.ema(_source, _length), _length), _length), _length)) + (1 + 3 * _a1 + _a1 * _a1 * _a1 + 3 * _a1 * _a1) * (ta.ema(ta.ema(ta.ema(_source, _length), _length), _length))
_output
f_donchian(_length) =>
math.avg(ta.lowest(_length), ta.highest(_length))
MA(source, length, type) =>
type == 'SMA' ? ta.sma(source, length) :
type == 'EMA' ? ta.ema(source, length) :
type == 'SMMA (RMA)' ? ta.rma(source, length) :
type == 'WMA' ? ta.wma(source, length) :
type == 'VWMA' ? ta.vwma(source, length) :
type == 'HMA' ? ta.hma(source, length) :
type == 'EHMA' ? f_ehma(source, length) :
type == 'TEMA' ? f_tema(source, length) :
type == 'Donchian' ? f_donchian(length) :
type == 'ALMA' ? ta.alma(source, length, almaoffset, almasigma) :
type == 'Tillson T3' ? f_t3(source, length, a1) :
type == 'LSMA' ? ta.linreg(source, length, lsmaoffset) : na
//MA RIBBON BLOCK
show_MA1 = input.bool(true, 'MA β1', inline='MA #1', group='Moving Average Ribbon')
MA1_type = input.string('Tillson T3', '', inline='MA #1', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA1_length = input.int(5, '', inline='MA #1', minval=1, group='Moving Average Ribbon')
MA1_source = input.source(close, '', inline='MA #1', group='Moving Average Ribbon')
MA1 = MA(MA1_source, MA1_length, MA1_type)
show_MA2 = input.bool(true, 'MA β2', inline='MA #2', group='Moving Average Ribbon')
MA2_type = input.string('SMA', '', inline='MA #2', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA2_length = input.int(9, '', inline='MA #2', minval=1, group='Moving Average Ribbon')
MA2_source = input.source(close, '', inline='MA #2', group='Moving Average Ribbon')
MA2 = MA(MA2_source, MA2_length, MA2_type)
show_MA3 = input.bool(true, 'MA β3', inline='MA #3', group='Moving Average Ribbon')
MA3_type = input.string('EMA', '', inline='MA #3', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA3_length = input.int(12, '', inline='MA #3', minval=1, group='Moving Average Ribbon')
MA3_source = input.source(close, '', inline='MA #3', group='Moving Average Ribbon')
MA3 = MA(MA3_source, MA3_length, MA3_type)
show_MA4 = input.bool(true, 'MA β4', inline='MA #4', group='Moving Average Ribbon')
MA4_type = input.string('WMA', '', inline='MA #4', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA4_length = input.int(26, '', inline='MA #4', minval=1, group='Moving Average Ribbon')
MA4_source = input.source(close, '', inline='MA #4', group='Moving Average Ribbon')
MA4 = MA(MA4_source, MA4_length, MA4_type)
show_MA5 = input.bool(true, 'MA β5', inline='MA #5', group='Moving Average Ribbon')
MA5_type = input.string('ALMA', '', inline='MA #5', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA5_length = input.int(50, '', inline='MA #5', minval=1, group='Moving Average Ribbon')
MA5_source = input.source(close, '', inline='MA #5', group='Moving Average Ribbon')
MA5 = MA(MA5_source, MA5_length, MA5_type)
show_MA6 = input.bool(true, 'MA β6', inline='MA #6', group='Moving Average Ribbon')
MA6_type = input.string('EHMA', '', inline='MA #6', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA6_length = input.int(100, '', inline='MA #6', minval=1, group='Moving Average Ribbon')
MA6_source = input.source(close, '', inline='MA #6', group='Moving Average Ribbon')
MA6 = MA(MA6_source, MA6_length, MA6_type)
show_MA7 = input.bool(true, 'MA β7', inline='MA #7', group='Moving Average Ribbon')
MA7_type = input.string('HMA', '', inline='MA #7', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA', 'HMA', 'EHMA', 'TEMA', 'ALMA', 'Tillson T3', 'LSMA', 'Donchian'], group='Moving Average Ribbon')
MA7_length = input.int(200, '', inline='MA #7', minval=1, group='Moving Average Ribbon')
MA7_source = input.source(close, '', inline='MA #7', group='Moving Average Ribbon')
MA7 = MA(MA7_source, MA7_length, MA7_type)
//OPTIONAL RAINBOW RSI GRADIENT
var grad2 = array.new_color(na)
if barstate.isfirst
array.push(grad2, color.gray)
array.push(grad2, #800080)
array.push(grad2, #890089)
array.push(grad2, #910091)
array.push(grad2, #9a009a)
array.push(grad2, #a300a3)
array.push(grad2, #ab00ab)
array.push(grad2, #b400b4)
array.push(grad2, #bd00bd)
array.push(grad2, #c700c7)
array.push(grad2, #d000d0)
array.push(grad2, #d900d9)
array.push(grad2, #e200e2)
array.push(grad2, #ec00ec)
array.push(grad2, #f500f5)
array.push(grad2, #ff00ff)
array.push(grad2, #ff00f0)
array.push(grad2, #ff00e1)
array.push(grad2, #ff00d2)
array.push(grad2, #ff00c4)
array.push(grad2, #ff00b7)
array.push(grad2, #ff00aa)
array.push(grad2, #ff009d)
array.push(grad2, #ff0091)
array.push(grad2, #ff0086)
array.push(grad2, #ff187c)
array.push(grad2, #ff2972)
array.push(grad2, #ff3669)
array.push(grad2, #ff4160)
array.push(grad2, #ff4a59)
array.push(grad2, #ff5252)
array.push(grad2, #ff5a4e)
array.push(grad2, #ff624a)
array.push(grad2, #ff6a45)
array.push(grad2, #ff7240)
array.push(grad2, #ff7b3b)
array.push(grad2, #ff8336)
array.push(grad2, #ff8c30)
array.push(grad2, #ff942a)
array.push(grad2, #ff9d23)
array.push(grad2, #ffa61c)
array.push(grad2, #ffaf12)
array.push(grad2, #ffb805)
array.push(grad2, #ffc100)
array.push(grad2, #ffca00)
array.push(grad2, #ffd300)
array.push(grad2, #ffdc00)
array.push(grad2, #ffe500)
array.push(grad2, #ffed00)
array.push(grad2, #fff600)
array.push(grad2, #ffff00)
array.push(grad2, #eefd1d)
array.push(grad2, #ddfb2d)
array.push(grad2, #ccf83a)
array.push(grad2, #bcf546)
array.push(grad2, #adf150)
array.push(grad2, #9eee59)
array.push(grad2, #8fea62)
array.push(grad2, #81e66a)
array.push(grad2, #74e172)
array.push(grad2, #66dc79)
array.push(grad2, #5ad87f)
array.push(grad2, #4dd385)
array.push(grad2, #41cd8a)
array.push(grad2, #36c88f)
array.push(grad2, #2cc393)
array.push(grad2, #24bd96)
array.push(grad2, #1fb798)
array.push(grad2, #1eb299)
array.push(grad2, #21ac9a)
array.push(grad2, #26a69a)
array.push(grad2, #26aca0)
array.push(grad2, #26b1a6)
array.push(grad2, #25b7ad)
array.push(grad2, #24bdb3)
array.push(grad2, #24c3ba)
array.push(grad2, #23c9c0)
array.push(grad2, #21cfc7)
array.push(grad2, #20d5ce)
array.push(grad2, #1edbd4)
array.push(grad2, #1be1db)
array.push(grad2, #18e7e2)
array.push(grad2, #15ede9)
array.push(grad2, #10f3f0)
array.push(grad2, #09f9f8)
array.push(grad2, #00ffff)
array.push(grad2, #00f5ff)
array.push(grad2, #00ebff)
array.push(grad2, #00e1ff)
array.push(grad2, #00d6ff)
array.push(grad2, #00cbff)
array.push(grad2, #00bfff)
array.push(grad2, #00b3ff)
array.push(grad2, #00a6ff)
array.push(grad2, #0099ff)
array.push(grad2, #008aff)
array.push(grad2, #007bff)
array.push(grad2, #0069ff)
array.push(grad2, #0055ff)
array.push(grad2, #003bff)
array.push(grad2, #0000ff)
dncolor1 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA1, MA1_length)))))
upcolor1 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA1, MA1_length)))))
dncolor2 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA2, MA2_length)))))
upcolor2 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA2, MA2_length)))))
dncolor3 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA3, MA3_length)))))
upcolor3 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA3, MA3_length)))))
dncolor4 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA4, MA4_length)))))
upcolor4 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA4, MA4_length)))))
dncolor5 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA5, MA5_length)))))
upcolor5 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA5, MA5_length)))))
dncolor6 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA6, MA6_length)))))
upcolor6 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA6, MA6_length)))))
dncolor7 = array.get(grad2, math.round(math.avg(0, math.round(ta.rsi(MA7, MA7_length)))))
upcolor7 = array.get(grad2, math.round(math.avg(50, math.round(ta.rsi(MA7, MA7_length)))))
//PLOTS BLOCK
p1 = plot(show_MA1 ? MA1 : na, title='Fast MA 1', linewidth=1, color=MA1 > MA1[1] ? bullma : bearma)
p2 = plot(show_MA2 ? MA2 : na, title='Fast MA 2', linewidth=1, color=MA2 > MA2[1] ? bullma : bearma)
p3 = plot(show_MA3 ? MA3 : na, title='Fast MA 3', linewidth=1, color=MA3 > MA3[1] ? bullma : bearma)
p4 = plot(show_MA4 ? MA4 : na, title='Fast MA 4', linewidth=1, color=MA4 > MA4[1] ? bullma : bearma)
p5 = plot(show_MA5 ? MA5 : na, title='Fast MA 5', linewidth=1, color=MA5 > MA5[1] ? bullma : bearma)
p6 = plot(show_MA6 ? MA6 : na, title='Fast MA 6', linewidth=1, color=MA6 > MA6[1] ? bullma : bearma)
p7 = plot(show_MA7 ? MA7 : na, title='Fast MA 7', linewidth=1, color=MA7 > MA7[1] ? bullma : bearma)
//GUPPY WAVES
fill(p1, p2, color= MA1 > MA2 ? rainbowon == true ? color.new(upcolor1,82+filloffset) : color.new(bullma, 82+filloffset) : rainbowon == true ? color.new(dncolor1,82+filloffset) : color.new(bearma, 82+filloffset))
fill(p2, p3, color= MA2 > MA3 ? rainbowon == true ? color.new(upcolor2,85+filloffset) : color.new(bullma, 85+filloffset) : rainbowon == true ? color.new(dncolor2,85+filloffset) : color.new(bearma, 85+filloffset))
fill(p3, p4, color= MA3 > MA4 ? rainbowon == true ? color.new(upcolor3,88+filloffset) : color.new(bullma, 88+filloffset) : rainbowon == true ? color.new(dncolor3,88+filloffset) : color.new(bearma, 88+filloffset))
fill(p4, p5, color= MA4 > MA5 ? rainbowon == true ? color.new(upcolor4,91+filloffset) : color.new(bullma, 91+filloffset) : rainbowon == true ? color.new(dncolor4,91+filloffset) : color.new(bearma, 91+filloffset))
fill(p5, p6, color= MA5 > MA6 ? rainbowon == true ? color.new(upcolor5,94+filloffset) : color.new(bullma, 94+filloffset) : rainbowon == true ? color.new(dncolor5,94+filloffset) : color.new(bearma, 94+filloffset))
fill(p6, p7, color= MA6 > MA7 ? rainbowon == true ? color.new(upcolor6,97+filloffset) : color.new(bullma, 97+filloffset) : rainbowon == true ? color.new(dncolor6,97+filloffset) : color.new(bearma, 97+filloffset)) |
Market Close Countdown | https://www.tradingview.com/script/F32Hl3Sr-Market-Close-Countdown/ | zero54 | https://www.tradingview.com/u/zero54/ | 46 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator("Market Close Countdown", overlay=true)
head_tcolor = input(color.new(#ffffff,20),'Header Text Color',group='Table Style')
head_area = input(color.new(#232423,20),'Header Background Color',group='Table Style')
TextsizeOption = input.string(title="Label Size", options=["Auto", "Huge", "Large", "Normal", "Small", "Tiny"], defval="Auto",group='Table Style')
TextSize = (TextsizeOption == "Huge") ? size.huge :
(TextsizeOption == "Large") ? size.large :
(TextsizeOption == "Small") ? size.small :
(TextsizeOption == "Tiny") ? size.tiny :
(TextsizeOption == "Auto") ? size.auto :
size.normal
Table_loc = input.string(title="Table Position",options=["Top Right","Bottom Right","Top Left","Bottom Left", "Middle Right","Bottom Center"],defval="Bottom Right",group='Table Style')
var Table_position = Table_loc == 'Top Left' ? position.top_left : Table_loc == 'Bottom Left' ? position.bottom_left : Table_loc == 'Middle Right' ? position.middle_right :
Table_loc == 'Bottom Center' ? position.bottom_center : Table_loc == 'Top Right' ? position.top_right : position.bottom_right
_r = barstate.isrealtime
_x = time_close
_y = timenow
[barval,timecloseval,timenowval] = request.security(syminfo.ticker,"D",[_r, _x, _y])
secLeft = (timecloseval - timenowval) / 1000
hoursleft = math.floor(secLeft / 3600)
minsleft = math.floor (((secLeft / 3600) - math.floor(secLeft / 3600))*60)
var tb = table.new(Table_position,1,1,border_color=#000000,border_width = 1)
if barstate.islast
table.cell(tb,0,0,str.tostring(hoursleft,'###')+":"+str.tostring(minsleft,'###'),text_color=head_tcolor,bgcolor=head_area,text_size=TextSize)
|
Ichimoku Kinko Hyo [+Conditions] | https://www.tradingview.com/script/oihkDV6F-Ichimoku-Kinko-Hyo-Conditions/ | thermal_winds | https://www.tradingview.com/u/thermal_winds/ | 83 | 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/
// Β©thermal_winds
// @version=5
indicator(title="Ichimoku Cloud Twist", shorttitle="ICT", overlay=true)
// strategy(title="Ichimoku Cloud Twist", shorttitle="ICT", overlay=true, max_bars_back=4900, calc_on_every_tick=false, calc_on_order_fills=false, initial_capital=100.0, default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_type=strategy.commission.percent, commission_value=0.1)
// --- (Start) Ichimoku kinko Hyo ------------------------------------------- // Credits : LonesomeTheBlue
middleDonchian(Length) =>
lower = ta.lowest(Length), upper = ta.highest(Length)
math.avg(upper, lower)
conversionPeriods = input.int(defval=9, minval=1)
basePeriods = input.int(defval=26, minval=1)
laggingSpan2Periods = input.int(defval=52, minval=1)
displacement = input.int(defval=26, minval=1)
Tenkan = middleDonchian(conversionPeriods)
Kijun = middleDonchian(basePeriods)
xChikou = close
SenkouA = middleDonchian(laggingSpan2Periods)
SenkouB = (Tenkan[basePeriods-displacement] + Kijun[basePeriods-displacement]) / 2
plot(Tenkan, color=color.red, title="Tenkan", linewidth=2, display=display.all)
plot(Kijun, color=color.blue, title="Kijun", linewidth=2, display=display.all)
plot(xChikou, color= color.lime , title="Chikou", offset = -displacement, display=display.all)
A = plot(SenkouA, color=color.new(color.red,70), title="SenkouA", offset=displacement, display=display.none)
B = plot(SenkouB, color=color.new(color.green,70), title="SenkouB", offset=displacement, display=display.none)
fill(A, B, color= (SenkouA > SenkouB) ? color.new(color.red,90) : color.new(color.green,90), title='Kumo Cloud')
// --- (End) Ichimoku kinko Hyo --------------------------------------------- //
// --- (Start) Ichimoku conditions ------------------------------------------ //
red_kumo_cloud = SenkouA[displacement] > SenkouB[displacement] // Verified
green_kumo_cloud = SenkouA[displacement] < SenkouB[displacement] // Verified
red_kumo_cloud_future = SenkouA > SenkouB // Verified
green_kumo_cloud_future = SenkouA < SenkouB // Verified
close_crosses_kijun = close > Kijun and close[1] < Kijun[1] // Verified
tenkan_over_kijun = Tenkan > Kijun // Verified
tenkan_below_kijun_tenkan_up_kijun_flat = (Tenkan < Kijun) and (ta.change(Tenkan, 1) > 0) and (Kijun[0] == Kijun[1]) // Verified
[close_middle_bb, close_upper_bb, close_lower_bb] = ta.bb(series=close, length=20, mult=1)
chikou_open_space = (xChikou < close_lower_bb[displacement] and xChikou < SenkouA[2*displacement] and xChikou < SenkouB[2*displacement] and xChikou < 2*low[displacement]) or (xChikou > close_upper_bb[displacement] and xChikou > SenkouA[2*displacement] and xChikou > SenkouB[2*displacement] and xChikou > 2*high[displacement]) // Verified
future_senkouB_up_flat = green_kumo_cloud_future and (ta.change(SenkouB, 1) > 0 or SenkouB[0] == SenkouB[1]) // Verified
tenkan_in_cloud = (Tenkan < SenkouA[displacement] and Tenkan > SenkouB[displacement]) or (Tenkan > SenkouA[displacement] and Tenkan < SenkouB[displacement]) // Verified
kijun_in_cloud = (Kijun < SenkouA[displacement] and Kijun > SenkouB[displacement]) or (Kijun > SenkouA[displacement] and Kijun < SenkouB[displacement]) // Verified
price_in_green_cloud = green_kumo_cloud and ((open < SenkouB[displacement] and open > SenkouA[displacement]) or (high < SenkouB[displacement] and high > SenkouA[displacement]) or (low < SenkouB[displacement] and low > SenkouA[displacement]) or (close < SenkouB[displacement] and close > SenkouA[displacement])) // Verified
price_in_red_cloud = red_kumo_cloud and ((open < SenkouA[displacement] and open > SenkouB[displacement]) or (high < SenkouA[displacement] and high > SenkouB[displacement]) or (low < SenkouA[displacement] and low > SenkouB[displacement]) or (close < SenkouA[displacement] and close > SenkouB[displacement])) // Verified
price_in_cloud = price_in_green_cloud or price_in_red_cloud // Verified
chikou_in_cloud = (green_kumo_cloud[displacement] and (xChikou < SenkouB[2*displacement] and xChikou > SenkouA[2*displacement])) or (red_kumo_cloud[displacement] and (xChikou < SenkouA[2*displacement] and xChikou > SenkouB[2*displacement])) // Verified
price_tenkan_kijun_chikou_not_in_cloud = (not tenkan_in_cloud) and (not kijun_in_cloud) and (not price_in_cloud) and (not chikou_in_cloud) // Verified
cloud_thickness = math.abs(SenkouA[displacement] - SenkouB[displacement])
percent_thick_cloud = green_kumo_cloud ? (cloud_thickness * 100) / SenkouA[displacement] : (cloud_thickness * 100) / SenkouB[displacement]
thickness_threshold = 14, thickest_cloud = ta.highest(percent_thick_cloud, 10000)
thick_cloud = percent_thick_cloud >= (thickest_cloud * (thickness_threshold/100)) // Verified
price_tenkan_kijun_chikou_in_thick_cloud = (not price_tenkan_kijun_chikou_not_in_cloud) and thick_cloud // Verified
proximity_mult = 0.001 // 0.1 %
tenkan_middle_bb = Tenkan + (Tenkan*0), tenkan_upper_bb = Tenkan + (Tenkan*proximity_mult), tenkan_lower_bb = Tenkan + (Tenkan*-proximity_mult)
kijun_middle_bb = Kijun + (Kijun*0), kijun_upper_bb = Kijun + (Kijun*proximity_mult), kijun_lower_bb = Kijun + (Kijun*-proximity_mult)
price_near_tenkan = (open < tenkan_upper_bb and open > tenkan_lower_bb) or (high < tenkan_upper_bb and high > tenkan_lower_bb) or (low < tenkan_upper_bb and low > tenkan_lower_bb) or (close < tenkan_upper_bb and close > tenkan_lower_bb)
price_near_kijun = (open < kijun_upper_bb and open > kijun_lower_bb) or (high < kijun_upper_bb and high > kijun_lower_bb) or (low < kijun_upper_bb and low > kijun_lower_bb) or (close < kijun_upper_bb and close > kijun_lower_bb)
price_near_tenkan_kijun = price_near_tenkan or price_near_kijun
cloud_thickness_future = math.abs(SenkouA[0] - SenkouB[0])
percent_thick_cloud_future = green_kumo_cloud_future ? (cloud_thickness_future * 100) / SenkouA[0] : (red_kumo_cloud_future ? (cloud_thickness_future * 100) / SenkouB[0] : na)
thickness_threshold_future = 0.20
thin_cloud = percent_thick_cloud_future <= thickness_threshold_future
red_2_green_cloud = (SenkouA[displacement+1] > SenkouB[displacement+1]) and (SenkouA[displacement+0] < SenkouB[displacement+0])
green_2_red_cloud = (SenkouA[displacement+1] < SenkouB[displacement+1]) and (SenkouA[displacement+0] > SenkouB[displacement+0])
close_above_cloud = close > SenkouA[displacement] and close > SenkouB[displacement]
close_below_kijun = close < Kijun
tenkan_crossover_kijun = ta.crossover(Tenkan, Kijun)
tenkan_over_cloud = Tenkan > SenkouA[displacement] and Tenkan > SenkouB[displacement]
tenkan_over_red_cloud = red_kumo_cloud and tenkan_over_cloud
kijun_crosses_red_cloud = red_kumo_cloud and ta.crossover(Kijun, SenkouA[displacement])
// --- (End) Ichimoku conditions -------------------------------------------- //
// --- Trade Conditions ----------------------------------------------------- //
var is_long_open=false, var is_short_open=false
long_e = red_2_green_cloud // and close_above_cloud
long_x = green_2_red_cloud
long_e_color = input.color(defval=color.new(color.green,0), title='Long Entry', group='Signals Style - Setting', inline='il1')
long_x_color = input.color(defval=color.new(color.red,0), title='Long Exit', group='Signals Style - Setting', inline='il1')
is_trade_bar = (long_e and not is_long_open) or (long_x and is_long_open)
barcolor(color=is_trade_bar ? na : (close>open ? color.new(color.green,90) : color.new(color.red,90)))
barcolor(color=long_e and not is_long_open ? long_e_color : na, title="Long - Entry Bar", editable=false)
barcolor(color=long_x and is_long_open ? long_x_color : na, title="Long - Exit Bar", editable=false)
plotshape(long_e and not is_long_open, text="B", textcolor=color.white, style=shape.labelup, color=long_e_color, size=size.tiny, location=location.belowbar, title="Long - Entry Labels", editable=false)
plotshape(long_x and is_long_open, text="S", textcolor=color.white, style=shape.labeldown, color=long_x_color, size=size.tiny, location=location.abovebar, title="Long - Exit Labels", editable=false)
if long_e and not is_long_open
is_long_open:=true
if long_x and is_long_open
is_long_open:=false
// --- Trade Executions ----------------------------------------------------- //
start_date = input.time(title='Testing Start Date', defval=timestamp("1975-01-01T00:00:00"), group='Trading Settings')
finish_date = input.time(title='Testing End Date', defval=timestamp("2025-01-01T00:00:00"), group='Trading Settings')
_testperiod = time >= start_date and time <= finish_date // and timeframe.period == 'D'
// strategy.entry("Long", strategy.long, comment=" ", when=long_e and _testperiod)
// strategy.close("Long", comment=" ", when=long_x and _testperiod)
|
4C NYSE Market Breadth Ratio | https://www.tradingview.com/script/j9SeDLRu-4C-NYSE-Market-Breadth-Ratio/ | FourC | https://www.tradingview.com/u/FourC/ | 412 | 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/
// Β© FourC
//Credit goes to author=@auron9000 as the bulk of this code was from their Breadth Ratio Bubbles indicator.
//I introduced bug fixes, fixed the way the breadth is calculated to be accurate, made the plot a histogram in its own pane.
//@version=5
indicator("4C NYSE Market Breadth Ratio", shorttitle="4C Breadth", overlay=false)
textsizing = input.string(title = 'Table Text Size', defval = 'Auto', options=['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'])
var sizing = textsizing == 'Auto' ? size.auto : textsizing == 'Tiny' ? size.tiny : textsizing == 'Small' ? size.small : textsizing == 'Normal' ? size.normal : textsizing == 'Large' ? size.large : textsizing == 'Huge' ? size.huge : na
//Up and down VOL for NYSE and NASDAQ
UVOL = request.security("USI:UVOL","",close)
DVOL = request.security("USI:DVOL","",close)
UVOLQ = request.security("USI:UVOLQ","",close)
DVOLQ = request.security("USI:DVOLQ","",close)
//ADD data
ADVDCL = request.security("USI:ADD","",close)
//NYSE Breadth
NYSEratio = UVOL >= DVOL ? UVOL/DVOL : -(DVOL/UVOL)
//plot(NYSEratio)
//NASDAQ Breadth
NASDAQratio = UVOLQ >= DVOLQ ? UVOLQ/DVOLQ : -(DVOLQ/UVOLQ)
//plot(NASDAQratio)
//Table Creation
var table breadthTable = table.new(position.top_right, 1, 3, border_color = color.black, border_width = 2)
string breadthformat = '##.##'
string addformat = ''
//Plot Table
if barstate.islast
table.cell(breadthTable, 0, 0, str.tostring(NYSEratio, breadthformat) + " NYSE", text_size = sizing, text_color = #000000, bgcolor = NYSEratio > 0 ? color.green : color.red)
table.cell(breadthTable, 0, 1, str.tostring(NASDAQratio, breadthformat) + " NASD", text_size = sizing, text_color = #000000, bgcolor = NASDAQratio > 0 ? color.green : color.red)
table.cell(breadthTable, 0, 2, str.tostring(ADVDCL, addformat) + " ADD", text_size = sizing, text_color = #000000, bgcolor = ADVDCL > 0 ? color.green : color.red)
//Plot NYSE Ratio
plot(NYSEratio, title='NYSE Breadth',color = NYSEratio > 0 ? color.green : color.red, style=plot.style_columns)
hline(0, '0 Line', color.white, linestyle=hline.style_solid, linewidth=1) |
1 year ROI BUY ZONE | https://www.tradingview.com/script/tfXQYbN9-1-year-ROI-BUY-ZONE/ | Vreckovka | https://www.tradingview.com/u/Vreckovka/ | 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/
// Β© Vreckovka
//@version=5
indicator("1 year ROI BUY ZONE",overlay=true,max_labels_count=500)
source = input(close, "Source")
minDays = input(45, "Min. days of session")
maxIndecisionDays = input(10, "Max. indecision days")
showActual = input(false, "Show actual label")
showShoppingCart = input(false, "Show Shopping Cart")
showBullBaner = input(false, "Show Bull Baner")
showBearBaner = input(false, "Show Bear Baner")
bullColor = input(color.rgb(101, 194, 85), "Bull color")
bearColor = input(color.rgb(225, 232, 88), "Bear color")
signalColor = input(color.rgb(255, 66, 66), "Signal color")
indecisionColor = input(color.rgb(66, 138, 255), "Indecision color")
outOfRangeColor = input(color.black, "Out of range")
buyRoiSignal = input(-55,"ROI signal")
lookBackyears = input(1, "Years lookback")
YearCTD = year(time) - lookBackyears
monthCTD = month(time)
dateCTD = dayofmonth(time)
isMonthOlder(p_month, p_year,actualMonth,actualYear) =>
if(p_month < actualMonth and p_year <= actualYear)
true
else if(p_month >= actualMonth and p_year < actualYear)
true
else
false
getLastYearClose() =>
indexOfLastYearCandle = 0
for offset = 0 to lookBackyears * 380
newTime = time[offset]
if(na(newTime))
-1
break
newYear = year(newTime)
newMonth = month(newTime)
newDay = dayofmonth(newTime)
higherTimeFrame = false
moreThanYear = false
if(timeframe.isweekly or timeframe.ismonthly or (timeframe.isdaily and timeframe.multiplier > 1))
higherTimeFrame := (newDay > dateCTD and isMonthOlder(newMonth,newYear,month(time), year(time)))
dayDiff = time - newTime
if(dayDiff >= 31536000000 * lookBackyears)
moreThanYear := true
if(newYear <= YearCTD and (isMonthOlder(newMonth,newYear,monthCTD,YearCTD) or monthCTD == newMonth) and moreThanYear)
indexOfLastYearCandle := offset
break
indexOfLastYearCandle
lastYearCloseIndex = getLastYearClose()
dayDiff = lastYearCloseIndex > 0
lastYearClose = source[lastYearCloseIndex]
roi = ((source / lastYearClose) - 1) * 100
var bear = false
var candlesOfBear = 0
var candlesOfBull = 0
var indecisionIndex = 0
sessionIndex = candlesOfBear > candlesOfBull ? candlesOfBear : candlesOfBull
sessionDiff = (timestamp(year(time),month(time), dayofmonth(time)) - timestamp(year(time[sessionIndex]),month(time[sessionIndex]), dayofmonth(time[sessionIndex]))) / (24 * 60 * 60 * 1000)
//if(bear)
//label.new(bar_index, na, str.tostring(sessionIndex), yloc = yloc.abovebar, style = label.style_label_down,color= color.rgb(255,50,100,75),textcolor = color.white, size = size.normal)
strDays = sessionDiff > 0 ? str.tostring(sessionDiff) + " days" : ""
change = false
if(dayDiff)
if(roi <= 0)
if(not bear and (sessionDiff >= minDays or sessionIndex == 0 or indecisionIndex >= maxIndecisionDays))
bear := true
change := true
candlesOfBull := 0
candlesOfBear := 0
indecisionIndex := 0
candlesOfBear := candlesOfBear + 1
else
if(bear and (sessionDiff >= minDays or sessionIndex == 0 or indecisionIndex >= maxIndecisionDays))
bear := false
change := true
candlesOfBull := 0
candlesOfBear := 0
indecisionIndex := 0
candlesOfBull := candlesOfBull + 1
isInIndecision = ((bear and roi > 0) or (not bear and roi < 0))
if(isInIndecision)
if(bear)
candlesOfBear := candlesOfBear + 1
else
candlesOfBull := candlesOfBull + 1
indecisionIndex := indecisionIndex + 1
else if(indecisionIndex > 0)
indecisionIndex := 0
barColor = dayDiff ? isInIndecision ? indecisionColor : (bear ? roi <= buyRoiSignal ? signalColor : bearColor : bullColor) : outOfRangeColor
labelColor = ((bear and roi > 0) or (not bear and roi < 0)) ? (color.rgb(50,50,255,75)) : (bear ? color.rgb(255,50,100,75) : color.rgb(50,255,100,75))
barcolor(barColor)
singnalPrice = lastYearClose * (1 - (-0.01 * buyRoiSignal))
if(barstate.islast and showActual)
label.new(bar_index - lastYearCloseIndex, na, "COMPARING", yloc = yloc.abovebar,style = label.style_label_down,color= color.rgb(255,255,20,75),textcolor = color.white, size = size.small)
if(bear)
label.new(bar_index, na, "ACTUAL BEAR\n" + str.tostring(lastYearClose) + " ( " + str.tostring(roi,"##.##") + " % )\n" + str.tostring(singnalPrice) + " ( " + str.tostring(((singnalPrice / close) - 1) * 100, "##.##") + " % )" + "\n" + str.tostring(sessionDiff) + " days" + "\n " + str.tostring(sessionIndex) + " bars", yloc = yloc.belowbar,style = label.style_label_up,color= labelColor,textcolor = color.white, size = size.small)
else
label.new(bar_index, na, "ACTUAL BULL\n" + str.tostring(lastYearClose) + " ( " + str.tostring(roi,"##.##") + " % )\n" + str.tostring(sessionDiff) + " days" + "\n " + str.tostring(sessionIndex) + " bars", yloc = yloc.belowbar,style = label.style_label_up,color= labelColor,textcolor = color.white, size = size.small)
if(bear and roi < buyRoiSignal and showShoppingCart)
label.new(bar_index, na, "π", yloc = yloc.abovebar, style = label.style_none, textcolor = color.rgb(255,255,100), size = size.normal)
if(change)
if(bear)
if(showBullBaner)
label.new(bar_index, na, "BULL END\n" + strDays + "\n " + str.tostring(sessionIndex) + " bars", yloc = yloc.abovebar, style = label.style_label_down,color= color.rgb(50,255,100,75),textcolor = color.white, size = size.normal)
else if(showBearBaner)
label.new(bar_index, na, "BEAR END\n" + strDays + "\n " + str.tostring(sessionIndex) + " bars", yloc = yloc.abovebar, style = label.style_label_down,color= color.rgb(255,50,100,75),textcolor = color.white, size = size.normal) |
Selamat Hari Raya | https://www.tradingview.com/script/WXmaGadA-Selamat-Hari-Raya/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 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/
// Β© RozaniGhani-RG
//@version=5
indicator('Selamat Hari Raya')
// 0. Inputs
// 1. Arrays
// 2. Variable
// 3. Custom function
// 4. Construct
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 0. Inputs {
i_color = input.color( color.green, 'Color')
i_s_Y = input.string( 'middle', 'Positionβ', inline = 'Position', options = ['top', 'middle', 'bottom'])
i_s_X = input.string( 'center', '', inline = 'Position', options = ['left', 'center', 'right'])
i_s_font = input.string( 'normal', 'Font Size', inline = 'Font', options = ['tiny', 'small', 'normal', 'large', 'huge'])
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 1. Arrays {
row_0 = array.from('0','0','0',' ','0','0','0',' ','0',' ',' ',' ',' ','0',' ',' ','0',' ',' ',' ','0',' ',' ','0',' ',' ','0','0','0',' ',' ','0',' ','0',' ',' ','0',' ',' ','0','0',' ',' ','0',' ',' ','0','0',' ',' ',' ','0',' ',' ','0',' ','0',' ',' ','0',' ')
row_1 = array.from('0',' ',' ',' ','0',' ',' ',' ','0',' ',' ',' ','0',' ','0',' ','0','0',' ','0','0',' ','0',' ','0',' ',' ','0',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ','0',' ','0',' ','0',' ','0','0','0',' ','0',' ','0')
row_2 = array.from('0','0','0',' ','0','0','0',' ','0',' ',' ',' ','0','0','0',' ','0',' ','0',' ','0',' ','0','0','0',' ',' ','0',' ',' ',' ','0','0','0',' ','0','0','0',' ','0','0',' ',' ','0',' ',' ','0','0',' ',' ','0','0','0',' ',' ','0',' ',' ','0','0','0')
row_3 = array.from(' ',' ','0',' ','0',' ',' ',' ','0',' ',' ',' ','0',' ','0',' ','0',' ',' ',' ','0',' ','0',' ','0',' ',' ','0',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ',' ','0',' ','0')
row_4 = array.from('0','0','0',' ','0','0','0',' ','0','0','0',' ','0',' ','0',' ','0',' ',' ',' ','0',' ','0',' ','0',' ',' ','0',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ',' ','0',' ','0')
row_5 = array.from(' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ')
row_6 = array.from('0',' ',' ',' ','0',' ',' ','0',' ',' ',' ','0',' ',' ','0','0','0',' ',' ',' ',' ',' ','0','0','0',' ',' ','0',' ',' ','0',' ','0',' ','0',' ','0','0',' ',' ',' ',' ',' ','0','0',' ',' ',' ','0',' ',' ','0','0','0',' ','0',' ','0',' ',' ','0')
row_7 = array.from('0','0',' ','0','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ',' ',' ',' ',' ',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ',' ',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ',' ','0',' ','0','0',' ','0')
row_8 = array.from('0',' ','0',' ','0',' ','0','0','0',' ','0','0','0',' ','0','0','0',' ',' ',' ',' ',' ',' ','0',' ',' ','0','0','0',' ','0','0','0',' ','0',' ','0','0',' ',' ',' ',' ',' ','0','0',' ',' ','0','0','0',' ',' ','0',' ',' ','0',' ','0',' ','0','0')
row_9 = array.from('0',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ',' ',' ',' ',' ',' ','0',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ',' ',' ','0',' ','0',' ','0',' ','0',' ',' ','0',' ',' ','0',' ','0',' ',' ','0')
row_10 = array.from('0',' ',' ',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ',' ',' ',' ',' ',' ','0','0','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ','0',' ',' ',' ',' ','0','0',' ',' ','0',' ','0',' ',' ','0',' ',' ','0',' ','0',' ',' ','0')
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 2. Variable {
var raya = table.new(i_s_Y + '_' + i_s_X, columns = 61, rows = 11, border_width = 1)
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 3. Custom function {
f_cell(_id, int x, int y) =>
table.cell(raya, x, y, array.get(_id, x), text_size = i_s_font)
table.cell_set_bgcolor( raya, x, y, array.get(_id, x) == '0' ? color.new(i_color, 0) : color.new(i_color, 100))
table.cell_set_text_color(raya, x, y, array.get(_id, x) == ' ' ? color.new(i_color, 100) : color.new(i_color, 0))
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 4. Construct {
if barstate.islast
for x = 0 to 60
f_cell(row_0, x, 0)
f_cell(row_1, x, 1)
f_cell(row_2, x, 2)
f_cell(row_3, x, 3)
f_cell(row_4, x, 4)
f_cell(row_5, x, 5)
f_cell(row_6, x, 6)
f_cell(row_7, x, 7)
f_cell(row_8, x, 8)
f_cell(row_9, x, 9)
f_cell(row_10, x, 10)
// } |
Intraday Super Sectors v2.0 | https://www.tradingview.com/script/lkofeKah-Intraday-Super-Sectors-v2-0/ | TIG_That-Indicator-Guy | https://www.tradingview.com/u/TIG_That-Indicator-Guy/ | 207 | 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/
// Β© TIG_That-Indicator-Guy
//@version=5
indicator(" ", overlay = false)
/////////////////////////////////////////////////
// LET'S GET THIS PARTY STARTED
/////////////////////////////////////////////////
var oGroup0 = "Welcome to the New Super Sector Indicator !"
oStudyTitle = input.string("New Super Sectors", "What title would you like displayed?", inline = "00", group = oGroup0)
var oGroup1 = "Super Sector Lines"
oColorCyclical = input.color(color.rgb(255, 153, 51,0), "Sector Colors:βββCyclical", inline = "11", group = oGroup1)
oColorDefensive = input.color(color.rgb(51, 153, 255, 0), "Defensive", inline = "11", group = oGroup1)
var oGroup2 = "ββββββββββEMA LengthββββββββββLinewidthββββββShow ?"
oTickEma = input.int(1, "Tickβ", minval = 1, inline = "21", group = oGroup2)
oLineWidthTick = input.int(1, "", minval = 1, maxval = 5, inline = "21", group = oGroup2)
oShowTick = input.bool(true, "", inline = "21", group = oGroup2)
oFastEma = input.int(6, "Fastβ", minval = 1, inline = "22", group = oGroup2)
oLineWidthFast = input.int(2, "", minval = 1, maxval = 5, inline = "22", group = oGroup2)
oShowFast = input.bool(true, "", inline = "22", group = oGroup2)
oSlowEma = input.int(30, "Slowβ", minval = 1, inline = "23", group = oGroup2)
oLineWidthSlow = input.int(3, "", minval = 1, maxval = 5, inline = "23", group = oGroup2)
oShowSlow = input.bool(true, "", inline = "23", group = oGroup2)
oShowCloud = input.bool(true, "Show Clouds between Fast and Slow lines?", inline = "24", group = oGroup2)
oSoftGreen = input.color(color.rgb(0, 255, 0, 85), "βββUptrending", inline = "25", group = oGroup2)
oSoftRed = input.color(color.rgb(255, 0, 0, 80), "ββDowndtrending", inline = "25", group = oGroup2)
var oGroup3 = "SPXβββββββEMA LengthββββββββββLinewidthββββββShow ?β"
oSpxEma = input.int(3, "SPXββ", minval = 1, inline = "41", group = oGroup3)
oLineWidthSpx = input.int(1, "", minval = 1, maxval = 5, inline = "31", group = oGroup3)
oShowSpx = input.bool(false, "", inline = "31", group = oGroup3)
oColorSpx = input.color(color.rgb(255, 255, 255, 50), "", inline = "31", group = oGroup3)
var oGroup4 = "Text Colors"
oTextColor = input.color(color.rgb(128, 128, 128, 0), "Titles", inline = "41", group = oGroup4)
oTextGreen = input.color(color.rgb(64, 192, 64, 0), "βββUp Text", inline = "41", group = oGroup4)
oTextRed = input.color(color.rgb(255, 0, 0, 0), "βββDown Text", inline = "41", group = oGroup4)
oShowSectors = input.bool(true, "Show All The Sector Data? (untick for phone use)", inline = "42", group = oGroup4)
// Sector data retrieved from https://finance.yahoo.com/quote/SPY/holdings/ on May 1, 2022
var oGroup6 = "SectorββββββββββββββββββββββββββWeight / Cyclical-Defensive?"
oWeightXLB = input.float(2.31, "XLB (Materials) ββββββββββββββ", minval = 0, inline = "61", group = oGroup6)
oSectorXLB = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "61", group = oGroup6)
oWeightXLC = input.float(9.34, "XLC (Communications Services)", minval = 0, inline = "62", group = oGroup6)
oSectorXLC = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "62", group = oGroup6)
oWeightXLE = input.float(3.86, "XLE (Energy) ββββββββββββββββ", minval = 0, inline = "63", group = oGroup6)
oSectorXLE = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "63", group = oGroup6)
oWeightXLF = input.float(13.19, "XLF (Financials) βββββββββββββ", minval = 0, inline = "64", group = oGroup6)
oSectorXLF = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "64", group = oGroup6)
oWeightXLI = input.float(8.13, "XLI (Industrials) βββββββββββββ", minval = 0, inline = "65", group = oGroup6)
oSectorXLI = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "65", group = oGroup6)
oWeightXLK = input.float(25.51, "XLK (Information Technology)β", minval = 0, inline = "66", group = oGroup6)
oSectorXLK = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "66", group = oGroup6)
oWeightXLP = input.float(6.49, "XLP (Consumer Staples) ββββββ", minval = 0, inline = "67", group = oGroup6)
oSectorXLP = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "67", group = oGroup6)
oWeightXLRE = input.float(2.71, "XLRE (Real Estate) βββββββββββ", minval = 0, inline = "68", group = oGroup6)
oSectorXLRE = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "68", group = oGroup6)
oWeightXLU = input.float(2.45, "XLU (Utilities) βββββββββββββββ", minval = 0, inline = "69", group = oGroup6)
oSectorXLU = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "69", group = oGroup6)
oWeightXLV = input.float(13.66, "XLV (Health Care) ββββββββββββ", minval = 0, inline = "6A", group = oGroup6)
oSectorXLV = input.string("Defensive", "", options = ["Cyclical", "Defensive"], inline = "6A", group = oGroup6)
oWeightXLY = input.float(11.81, "XLY (Consumer Discretionary)ββ", minval = 0, inline = "6B", group = oGroup6)
oSectorXLY = input.string("Cyclical", "", options = ["Cyclical", "Defensive"], inline = "6B", group = oGroup6)
// Initialize Global Variables
oColorNone = color.rgb(0, 0, 0, 255)
oColorGray = color.rgb(128, 128, 128, 50)
var oOpenSpx = 0.0
var oOpenCyclical = 0.0
var oOpenDefensive = 0.0
var oBarCount = 0
var oOpenXLB = 0.0
var oOpenXLC = 0.0
var oOpenXLE = 0.0
var oOpenXLF = 0.0
var oOpenXLI = 0.0
var oOpenXLK = 0.0
var oOpenXLP = 0.0
var oOpenXLRE = 0.0
var oOpenXLU = 0.0
var oOpenXLV = 0.0
var oOpenXLY = 0.0
var oFactor = 0.0
var oTickCyclical = 0.0
var oFastCyclical = 0.0
var oSlowCyclical = 0.0
var oTickDefensive = 0.0
var oFastDefensive = 0.0
var oSlowDefensive = 0.0
var oFastSpx = 0.0
/////////////////////////////////////////////////
// DO SOME CALCULATIONS
/////////////////////////////////////////////////
// Intialize for a new session
oCashSession = time(timeframe.period, "0930-1600", "America/New_York")
oNewSession = (oCashSession and not(oCashSession[1])) or (oCashSession and (dayofweek != dayofweek[1]))
oShow = (oCashSession and not(oNewSession))
// !!! can delete this after testing!!
var oOpenTotal = 0.0
oOpenSpx := oNewSession ? request.security("SPX", timeframe.period, open) : oOpenSpx
oOpenXLB := oNewSession ? request.security("XLB", timeframe.period, open) : oOpenXLB
oOpenXLC := oNewSession ? request.security("XLC", timeframe.period, open) : oOpenXLC
oOpenXLE := oNewSession ? request.security("XLE", timeframe.period, open) : oOpenXLE
oOpenXLF := oNewSession ? request.security("XLF", timeframe.period, open) : oOpenXLF
oOpenXLI := oNewSession ? request.security("XLI", timeframe.period, open) : oOpenXLI
oOpenXLK := oNewSession ? request.security("XLK", timeframe.period, open) : oOpenXLK
oOpenXLP := oNewSession ? request.security("XLP", timeframe.period, open) : oOpenXLP
oOpenXLRE := oNewSession ? request.security("XLRE", timeframe.period, open) : oOpenXLRE
oOpenXLU := oNewSession ? request.security("XLU", timeframe.period, open) : oOpenXLU
oOpenXLV := oNewSession ? request.security("XLV", timeframe.period, open) : oOpenXLV
oOpenXLY := oNewSession ? request.security("XLY", timeframe.period, open) : oOpenXLY
if oNewSession
oOpenCyclical := (oSectorXLB == "Cyclical" ? oOpenXLB * oWeightXLB : 0) +
(oSectorXLC == "Cyclical" ? oOpenXLC * oWeightXLC : 0) +
(oSectorXLE == "Cyclical" ? oOpenXLE * oWeightXLE : 0) +
(oSectorXLF == "Cyclical" ? oOpenXLF * oWeightXLF : 0) +
(oSectorXLI == "Cyclical" ? oOpenXLI * oWeightXLI : 0) +
(oSectorXLK == "Cyclical" ? oOpenXLK * oWeightXLK : 0) +
(oSectorXLP == "Cyclical" ? oOpenXLP * oWeightXLP : 0) +
(oSectorXLRE == "Cyclical" ? oOpenXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Cyclical" ? oOpenXLU * oWeightXLU : 0) +
(oSectorXLV == "Cyclical" ? oOpenXLV * oWeightXLV : 0) +
(oSectorXLY == "Cyclical" ? oOpenXLY * oWeightXLY : 0)
oOpenDefensive := (oSectorXLB == "Defensive" ? oOpenXLB * oWeightXLB : 0) +
(oSectorXLC == "Defensive" ? oOpenXLC * oWeightXLC : 0) +
(oSectorXLE == "Defensive" ? oOpenXLE * oWeightXLE : 0) +
(oSectorXLF == "Defensive" ? oOpenXLF * oWeightXLF : 0) +
(oSectorXLI == "Defensive" ? oOpenXLI * oWeightXLI : 0) +
(oSectorXLK == "Defensive" ? oOpenXLK * oWeightXLK : 0) +
(oSectorXLP == "Defensive" ? oOpenXLP * oWeightXLP : 0) +
(oSectorXLRE == "Defensive" ? oOpenXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Defensive" ? oOpenXLU * oWeightXLU : 0) +
(oSectorXLV == "Defensive" ? oOpenXLV * oWeightXLV : 0) +
(oSectorXLY == "Defensive" ? oOpenXLY * oWeightXLY : 0)
// I don't know why, but the open values for the sectors appear to usually be slightly 'wrong'. So need correction!
oOpenTotal := oOpenXLB * oWeightXLB +
oOpenXLC * oWeightXLC +
oOpenXLE * oWeightXLE +
oOpenXLF * oWeightXLF +
oOpenXLI * oWeightXLI +
oOpenXLK * oWeightXLK +
oOpenXLP * oWeightXLP +
oOpenXLRE * oWeightXLRE +
oOpenXLU * oWeightXLU +
oOpenXLV * oWeightXLV +
oOpenXLY * oWeightXLY
oFactor := oOpenSpx / oOpenTotal
oOpenXLB *= oFactor
oOpenXLC *= oFactor
oOpenXLE *= oFactor
oOpenXLF *= oFactor
oOpenXLI *= oFactor
oOpenXLK *= oFactor
oOpenXLP *= oFactor
oOpenXLRE *= oFactor
oOpenXLU *= oFactor
oOpenXLV *= oFactor
oOpenXLY *= oFactor
oOpenCyclical *= oFactor
oOpenDefensive *= oFactor
oOpenTotal := oOpenTotal * oFactor
oBarCount := 0
// So where are we now?
oCurrentSpx = request.security("SPX", timeframe.period, close)
oCurrentXLB = request.security("XLB", timeframe.period, close)
oCurrentXLC = request.security("XLC", timeframe.period, close)
oCurrentXLE = request.security("XLE", timeframe.period, close)
oCurrentXLF = request.security("XLF", timeframe.period, close)
oCurrentXLI = request.security("XLI", timeframe.period, close)
oCurrentXLK = request.security("XLK", timeframe.period, close)
oCurrentXLP = request.security("XLP", timeframe.period, close)
oCurrentXLRE = request.security("XLRE", timeframe.period, close)
oCurrentXLU = request.security("XLU", timeframe.period, close)
oCurrentXLV = request.security("XLV", timeframe.period, close)
oCurrentXLY = request.security("XLY", timeframe.period, close)
oCurrentCyclical = (oSectorXLB == "Cyclical" ? oCurrentXLB * oWeightXLB : 0) +
(oSectorXLC == "Cyclical" ? oCurrentXLC * oWeightXLC : 0) +
(oSectorXLE == "Cyclical" ? oCurrentXLE * oWeightXLE : 0) +
(oSectorXLF == "Cyclical" ? oCurrentXLF * oWeightXLF : 0) +
(oSectorXLI == "Cyclical" ? oCurrentXLI * oWeightXLI : 0) +
(oSectorXLK == "Cyclical" ? oCurrentXLK * oWeightXLK : 0) +
(oSectorXLP == "Cyclical" ? oCurrentXLP * oWeightXLP : 0) +
(oSectorXLRE == "Cyclical" ? oCurrentXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Cyclical" ? oCurrentXLU * oWeightXLU : 0) +
(oSectorXLV == "Cyclical" ? oCurrentXLV * oWeightXLV : 0) +
(oSectorXLY == "Cyclical" ? oCurrentXLY * oWeightXLY : 0)
oCurrentDefensive = (oSectorXLB == "Defensive" ? oCurrentXLB * oWeightXLB : 0) +
(oSectorXLC == "Defensive" ? oCurrentXLC * oWeightXLC : 0) +
(oSectorXLE == "Defensive" ? oCurrentXLE * oWeightXLE : 0) +
(oSectorXLF == "Defensive" ? oCurrentXLF * oWeightXLF : 0) +
(oSectorXLI == "Defensive" ? oCurrentXLI * oWeightXLI : 0) +
(oSectorXLK == "Defensive" ? oCurrentXLK * oWeightXLK : 0) +
(oSectorXLP == "Defensive" ? oCurrentXLP * oWeightXLP : 0) +
(oSectorXLRE == "Defensive" ? oCurrentXLRE * oWeightXLRE : 0) +
(oSectorXLU == "Defensive" ? oCurrentXLU * oWeightXLU : 0) +
(oSectorXLV == "Defensive" ? oCurrentXLV * oWeightXLV : 0) +
(oSectorXLY == "Defensive" ? oCurrentXLY * oWeightXLY : 0)
oCurrentTotal = oCurrentXLB * oWeightXLB +
oCurrentXLC * oWeightXLC +
oCurrentXLE * oWeightXLE +
oCurrentXLF * oWeightXLF +
oCurrentXLI * oWeightXLI +
oCurrentXLK * oWeightXLK +
oCurrentXLP * oWeightXLP +
oCurrentXLRE * oWeightXLRE +
oCurrentXLU * oWeightXLU +
oCurrentXLV * oWeightXLV +
oCurrentXLY * oWeightXLY
oFactor := oCurrentSpx / oCurrentTotal
oCurrentCyclical *= oFactor
oCurrentDefensive *= oFactor
oBarCount += 1
oXLB = 100 * (oCurrentXLB * oFactor / oOpenXLB - 1)
oXLC = 100 * (oCurrentXLC * oFactor / oOpenXLC - 1)
oXLE = 100 * (oCurrentXLE * oFactor / oOpenXLE - 1)
oXLF = 100 * (oCurrentXLF * oFactor / oOpenXLF - 1)
oXLI = 100 * (oCurrentXLI * oFactor / oOpenXLI - 1)
oXLK = 100 * (oCurrentXLK * oFactor / oOpenXLK - 1)
oXLP = 100 * (oCurrentXLP * oFactor / oOpenXLP - 1)
oXLRE = 100 * (oCurrentXLRE * oFactor / oOpenXLRE - 1)
oXLU = 100 * (oCurrentXLU * oFactor / oOpenXLU - 1)
oXLV = 100 * (oCurrentXLV * oFactor / oOpenXLV - 1)
oXLY = 100 * (oCurrentXLY * oFactor / oOpenXLY - 1)
// Calculate the changes
oSpx = 100 * (oCurrentSpx / oOpenSpx - 1)
oCyclical = 100 * (oCurrentCyclical / oOpenCyclical - 1)
oDefensive = 100 * (oCurrentDefensive / oOpenDefensive - 1)
// Calculate the plot values
// Grrrrr ... have to calculate EMA values manually 'cos TA doesn't allow dynamic (variable) lengths
oTickMultiplier = (2 / (math.min(oBarCount, oTickEma) + 1))
oFastMultiplier = (2 / (math.min(oBarCount, oFastEma) + 1))
oSlowMultiplier = (2 / (math.min(oBarCount, oSlowEma) + 1))
oTickCyclical := oBarCount == 1 ? oCyclical : oCyclical * oTickMultiplier + oTickCyclical[1] * (1 - oTickMultiplier)
oFastCyclical := oBarCount == 1 ? oCyclical : oCyclical * oFastMultiplier + oFastCyclical[1] * (1 - oFastMultiplier)
oSlowCyclical := oBarCount == 1 ? oCyclical : oCyclical * oSlowMultiplier + oSlowCyclical[1] * (1 - oSlowMultiplier)
oTickDefensive := oBarCount == 1 ? oDefensive : oDefensive * oTickMultiplier + oTickDefensive[1] * (1 - oTickMultiplier)
oFastDefensive := oBarCount == 1 ? oDefensive : oDefensive * oFastMultiplier + oFastDefensive[1] * (1 - oFastMultiplier)
oSlowDefensive := oBarCount == 1 ? oDefensive : oDefensive * oSlowMultiplier + oSlowDefensive[1] * (1 - oSlowMultiplier)
oSpxMultiplier = (2 / (math.min(oBarCount, oSpxEma) + 1))
oFastSpx := oBarCount == 1 ? oSpx : oSpx * oSpxMultiplier + oFastSpx[1] * (1 - oSpxMultiplier)
/////////////////////////////////////////////////
// DISPLAY STUFF
/////////////////////////////////////////////////
// Plot the lines and infill
plot(0, color = oColorGray)
oPlotCyclicalTick = plot(oCyclical, linewidth = oLineWidthTick, color = oShow and oShowTick ? oColorCyclical : oColorNone)
oPlotCyclicalFast = plot(oFastCyclical, linewidth = oLineWidthFast, color = oShow and oShowFast ? oColorCyclical : oColorNone)
oPlotCyclicalSlow = plot(oSlowCyclical, linewidth = oLineWidthSlow, color = oShow and oShowSlow ? oColorCyclical : oColorNone)
fill(oPlotCyclicalFast, oPlotCyclicalSlow, color = oShow and oShowCloud ? oFastCyclical > oSlowCyclical ? oSoftGreen : oSoftRed : oColorNone)
oPlotDefensiveTick = plot(oDefensive, linewidth = oLineWidthTick, color = oShow and oShowTick ? oColorDefensive : oColorNone)
oPlotDefensiveFast = plot(oFastDefensive, linewidth = oLineWidthFast, color = oShow and oShowFast ? oColorDefensive : oColorNone)
oPlotDefensiveSlow = plot(oSlowDefensive, linewidth = oLineWidthSlow, color = oShow and oShowSlow ? oColorDefensive : oColorNone)
fill(oPlotDefensiveFast, oPlotDefensiveSlow, color = oShow and oShowCloud ? oFastDefensive > oSlowDefensive ? oSoftGreen : oSoftRed : oColorNone)
plot(oFastSpx, linewidth = oLineWidthSpx, color = oShow and oShowSpx ? oColorSpx : oColorNone)
// Plot the title
var table oTableTitle = table.new(position.top_left, 1, 1)
table.cell(oTableTitle, 0, 0, " " + oStudyTitle, text_color = oTextColor, text_halign = text.align_left)
// Plot the data table
var table oTable1 = table.new(position.bottom_left, 13, 6)
var oCount = 0
if barstate.isfirst
table.cell(oTable1, 1, 0, "SPX", text_color = oTextColor, text_halign = text.align_left)
table.cell(oTable1, 0, 2, "β", bgcolor = oColorDefensive)
table.cell(oTable1, 0, 3, "β", bgcolor = oColorDefensive)
table.cell(oTable1, 1, 2, "Defensive", text_color = oTextColor, text_halign = text.align_left)
table.cell(oTable1, 0, 4, "β", bgcolor = oColorCyclical)
table.cell(oTable1, 0, 5, "β", bgcolor = oColorCyclical)
table.cell(oTable1, 1, 4, "Cyclical", text_color = oTextColor, text_halign = text.align_left)
oCount := 2
if oSectorXLB == "Defensive"
table.cell(oTable1, oCount, 2, "XLB", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLC == "Defensive"
table.cell(oTable1, oCount, 2, "XLC", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLE == "Defensive"
table.cell(oTable1, oCount, 2, "XLE", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLF == "Defensive"
table.cell(oTable1, oCount, 2, "XLF", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLI == "Defensive"
table.cell(oTable1, oCount, 2, "XLI", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLK == "Defensive"
table.cell(oTable1, oCount, 2, "XLK", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLP == "Defensive"
table.cell(oTable1, oCount, 2, "XLP", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLRE == "Defensive"
table.cell(oTable1, oCount, 2, "XLRE", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLU == "Defensive"
table.cell(oTable1, oCount, 2, "XLU", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLV == "Defensive"
table.cell(oTable1, oCount, 2, "XLV", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLY == "Defensive"
table.cell(oTable1, oCount, 2, "XLY", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
oCount := 2
if oSectorXLB == "Cyclical"
table.cell(oTable1, oCount, 4, "XLB", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLC == "Cyclical"
table.cell(oTable1, oCount, 4, "XLC", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLE == "Cyclical"
table.cell(oTable1, oCount, 4, "XLE", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLF == "Cyclical"
table.cell(oTable1, oCount, 4, "XLF", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLI == "Cyclical"
table.cell(oTable1, oCount, 4, "XLI", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLK == "Cyclical"
table.cell(oTable1, oCount, 4, "XLK", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLP == "Cyclical"
table.cell(oTable1, oCount, 4, "XLP", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLRE == "Cyclical"
table.cell(oTable1, oCount, 4, "XLRE", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLU == "Cyclical"
table.cell(oTable1, oCount, 4, "XLU", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLV == "Cyclical"
table.cell(oTable1, oCount, 4, "XLV", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLY == "Cyclical"
table.cell(oTable1, oCount, 4, "XLY", text_color = oShowSectors ? oTextColor : oColorNone, text_halign = text.align_center)
oCount += 1
table.cell(oTable1, 1, 1, str.format("{0, number, #.##}", math.abs(oSpx)), text_color = oShow ? oSpx > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_left)
table.cell(oTable1, 1, 3, str.format("{0, number, #.##}", math.abs(oDefensive)), text_color = oShow ? oDefensive > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_left)
table.cell(oTable1, 1, 5, str.format("{0, number, #.##}", math.abs(oCyclical)), text_color = oShow ? oCyclical > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_left)
oCount := 2
if oSectorXLB == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLB)), text_color = oShow and oShowSectors ? oXLB > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLC == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLC)), text_color = oShow and oShowSectors ? oXLC > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLE == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLE)), text_color = oShow and oShowSectors ? oXLE > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLF == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLF)), text_color = oShow and oShowSectors ? oXLF > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLI == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLI)), text_color = oShow and oShowSectors ? oXLI > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLK == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLK)), text_color = oShow and oShowSectors ? oXLK > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLP == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLP)), text_color = oShow and oShowSectors ? oXLP > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLRE == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLRE)), text_color = oShow and oShowSectors ? oXLRE > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLU == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLU)), text_color = oShow and oShowSectors ? oXLU > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLV == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLV)), text_color = oShow and oShowSectors ? oXLV > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLY == "Defensive"
table.cell(oTable1, oCount, 3, str.format("{0, number, #.##}", math.abs(oXLY)), text_color = oShow and oShowSectors ? oXLY > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
oCount := 2
if oSectorXLB == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLB)), text_color = oShow and oShowSectors ? oXLB > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLC == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLC)), text_color = oShow and oShowSectors ? oXLC > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLE == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLE)), text_color = oShow and oShowSectors ? oXLE > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLF == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLF)), text_color = oShow and oShowSectors ? oXLF > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLI == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLI)), text_color = oShow and oShowSectors ? oXLI > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLK == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLK)), text_color = oShow and oShowSectors ? oXLK > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLP == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLP)), text_color = oShow and oShowSectors ? oXLP > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLRE == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLRE)), text_color = oShow and oShowSectors ? oXLRE > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLU == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLU)), text_color = oShow and oShowSectors ? oXLU > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLV == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLV)), text_color = oShow and oShowSectors ? oXLV > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
if oSectorXLY == "Cyclical"
table.cell(oTable1, oCount, 5, str.format("{0, number, #.##}", math.abs(oXLY)), text_color = oShow and oShowSectors ? oXLY > 0 ? oTextGreen : oTextRed : oColorNone, text_halign = text.align_center)
oCount += 1
// That's all folks
|
Highs/Lows difference [OrganicPunch] | https://www.tradingview.com/script/1ItghQo8-Highs-Lows-difference-OrganicPunch/ | OrganicPunch | https://www.tradingview.com/u/OrganicPunch/ | 63 | 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/
// Β© OrganicPunch
//@version=5
indicator("Highs/Lows difference [OrganicPunch]", "Highs/Lows [OP]")
// To visually evaluate the difference between highs and lows
difference_ema_lenght = input.int(7, title="Highs/Lows Difference EMA", minval=1)
highs = high > high[1] ? high - high[1] : high[1] - high
lows = low > low[1] ? low - low[1] : low[1] - low
difference = highs-lows
change_ema = ta.ema(difference, difference_ema_lenght)
plot(highs, "Highs", color.green, 1, plot.style_histogram)
plot(-lows, "Lows", color.red, 1, plot.style_histogram)
plot(difference, "Difference", difference>=0?color.green:color.red, 2, plot.style_circles)
plot(change_ema, "Difference EMA", color.yellow)
hline(0, "Middle line", color.gray, hline.style_solid)
|
Volume Spikes & Growing Volume Signals With Alerts & Scanner | https://www.tradingview.com/script/MukNTOH1-Volume-Spikes-Growing-Volume-Signals-With-Alerts-Scanner/ | FriendOfTheTrend | https://www.tradingview.com/u/FriendOfTheTrend/ | 1,130 | 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/
// Β© FriendOfTheTrend
//@version=5
indicator("Volume Spikes & Growing Volume Signals With Alerts & Scanner", shorttitle="Volume Spike Scanner", overlay=true)
//Inputs
info = input.bool(false, title="This indicator takes a while to load because it has to pull data and calculations from 8 other tickers, so please be patient when you load it on a chart. This indicator calculates volume spikes and growing volume. The top inputs are controlling the numbers used to calculate volume spikes which is using only 1 bar of volume data to catch these spikes. The second input section has the numbers used for calculations for when volume is growing over a certain amount of bars compared to the overall average. Read the tooltips for more clarification. You will need to adjust these settings on different charts as some tickers will have larger or smaller volume spikes and medians.", confirm=true)
spikeMultiple = input.int(3, title="Volume Spike Amount", tooltip="If volume spikes by this amount, an arrow will be shown. Ex: if set to 3, the volume will need to spike to a level that is 3 times the amount of the median of the last 100 bars or whatever amount of bars you set in the next input.", group="Volume Spike")
barsBack = input.int(1000, title="How Many Bars Back To Calculate The Median From", tooltip="This number is the amount of bars back you want the median to be calculated from. So if it is set to 100, the indicator will calculate the median or average of the last 100 bars. The number calculated is the median and will determine what level needs to be hit to achieve a Volume Spike, multiplied by the amount set in the first input.", group="Volume Spike")
medianLengthCurrent = input.int(5, title="Number Of Bars To Caluclate Current Volume Median", tooltip="This number is used to calculate the current median of volume for the last few bars. If you put 5 in here, then this will use the 5 most recent bars of data to calculate the current median volume which will be used to look for growing volume trends using the next two inputs.", group="Volume Growing")
spikeMultipleCurrent = input.int(3, title="Volume Spike Amount For Current Median", tooltip="This is a multplier for the median of the current volume trend. If 5 bars were used from the previous input, then the volume median over the last 5 bars will need to be greater than the median multiplied by this number. So if the median is 300 and this input is set to 3, volume median will need to reach 900 for it to give a signal.", group="Volume Growing")
barsBackCurrent = input.int(1000, title="Number Of Bars Back To Calculate Overall Median", tooltip="This value corresponds to the number of bars back to be used to calculate the current volume median. If you enter 1000 here, it will calculate the avergae volume over the last 1000 bars and use this as a benchmark to calculate growing volume or volume spikes.", group="Volume Growing")
maLength = input.int(20, title="Volume Moving Average Length", tooltip="If the volume moving average is increasing for 3 bars consecutively, then the indicator will give a signal. The moving average length chosen here will detemine how long of a volume moving average you are using for this calculation.", group="Volume Growing")
//Scanner Table Inputs
tableOn = input.bool(true, title="Turn Table On/Off", group="Table Settings")
bright = position.bottom_right
bleft = position.bottom_left
bcenter = position.bottom_center
tright = position.top_right
tleft = position.top_left
tcenter = position.top_center
mright = position.middle_right
mleft = position.middle_left
mcenter = position.middle_center
tablePosition = input.string(bcenter, title="Table Position", options=[bright, bleft, bcenter, tright, tleft, tcenter, mright, mleft, mcenter], group="Table Settings")
//DMI Input Controls
dilength = input.int(1, title="DMI Length", group="Buy & Sell Pressure")
smoothing = input.int(1, title="DMI Smoothing", group="Buy & Sell Pressure")
//Ticker 1
ticker1 = input.symbol("COINBASE:BTCUSD", title="Ticker #1", group="Tickers To Scan")
ticker2 = input.symbol("COINBASE:ETHUSD", title="Ticker #2", group="Tickers To Scan")
ticker3 = input.symbol("COINBASE:AVAXUSD", title="Ticker #3", group="Tickers To Scan")
ticker4 = input.symbol("COINBASE:ADAUSD", title="Ticker #4", group="Tickers To Scan")
ticker5 = input.symbol("COINBASE:SOLUSD", title="Ticker #5", group="Tickers To Scan")
ticker6 = input.symbol("COINBASE:DOTUSD", title="Ticker #6", group="Tickers To Scan")
ticker7 = input.symbol("COINBASE:LTCUSD", title="Ticker #7", group="Tickers To Scan")
ticker8 = input.symbol("COINBASE:LINKUSD", title="Ticker #8", group="Tickers To Scan")
//Color
volBuildColor = #00e67610
green = #00e67610
red = #ff525210
//DMI
[plus, minus, adx] = ta.dmi(dilength, smoothing)
if plus > minus
volBuildColor := green
else
volBuildColor := red
//Volume Spikes
vol = ta.median(volume, barsBack)
volCurrent = ta.median(volume, barsBackCurrent)
upSpike = false
downSpike = false
if volume > vol*spikeMultiple and plus > minus
upSpike := true
else if volume > vol*spikeMultiple and minus > plus
downSpike := true
plotchar(upSpike, title="Volume Up Spike Marker", char="π ", location=location.belowbar, color=color.lime, size=size.small)
plotchar(downSpike, title="Volume Down Spike Marker", char="π ", location=location.abovebar, color=color.red, size=size.small)
//Volume Increasing
volBuild = false
currentMedian = ta.median(volume, medianLengthCurrent)
volLine = ta.sma(volume, maLength)
maUp = false
if currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3]
volBuild := true
bgcolor(volBuild ? volBuildColor : na)
//Ticker #1
ticker1upspike = request.security(ticker1, "", volume > vol*spikeMultiple and plus > minus)
ticker1downspike = request.security(ticker1, "", volume > vol*spikeMultiple and minus > plus)
ticker1volbuild = request.security(ticker1, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker1text = str.tostring(ticker1)
ticker1bg = color.aqua
if ticker1upspike or ticker1downspike or ticker1volbuild
ticker1bg := color.orange
//Ticker #2
ticker2upspike = request.security(ticker2, "", volume > vol*spikeMultiple and plus > minus)
ticker2downspike = request.security(ticker2, "", volume > vol*spikeMultiple and minus > plus)
ticker2volbuild = request.security(ticker2, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker2text = str.tostring(ticker2)
ticker2bg = color.aqua
if ticker2upspike or ticker2downspike or ticker2volbuild
ticker2bg := color.orange
//Ticker #3
ticker3upspike = request.security(ticker3, "", volume > vol*spikeMultiple and plus > minus)
ticker3downspike = request.security(ticker3, "", volume > vol*spikeMultiple and minus > plus)
ticker3volbuild = request.security(ticker3, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker3text = str.tostring(ticker3)
ticker3bg = color.aqua
if ticker3upspike or ticker3downspike or ticker3volbuild
ticker3bg := color.orange
//Ticker #4
ticker4upspike = request.security(ticker4, "", volume > vol*spikeMultiple and plus > minus)
ticker4downspike = request.security(ticker4, "", volume > vol*spikeMultiple and minus > plus)
ticker4volbuild = request.security(ticker4, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker4text = str.tostring(ticker4)
ticker4bg = color.aqua
if ticker4upspike or ticker4downspike or ticker4volbuild
ticker4bg := color.orange
//Ticker #5
ticker5upspike = request.security(ticker5, "", volume > vol*spikeMultiple and plus > minus)
ticker5downspike = request.security(ticker5, "", volume > vol*spikeMultiple and minus > plus)
ticker5volbuild = request.security(ticker5, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker5text = str.tostring(ticker5)
ticker5bg = color.aqua
if ticker5upspike or ticker5downspike or ticker5volbuild
ticker5bg := color.orange
//Ticker #6
ticker6upspike = request.security(ticker6, "", volume > vol*spikeMultiple and plus > minus)
ticker6downspike = request.security(ticker6, "", volume > vol*spikeMultiple and minus > plus)
ticker6volbuild = request.security(ticker6, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker6text = str.tostring(ticker6)
ticker6bg = color.aqua
if ticker6upspike or ticker6downspike or ticker6volbuild
ticker6bg := color.orange
//Ticker #7
ticker7upspike = request.security(ticker7, "", volume > vol*spikeMultiple and plus > minus)
ticker7downspike = request.security(ticker7, "", volume > vol*spikeMultiple and minus > plus)
ticker7volbuild = request.security(ticker7, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker7text = str.tostring(ticker7)
ticker7bg = color.aqua
if ticker7upspike or ticker7downspike or ticker7volbuild
ticker7bg := color.orange
//Ticker #8
ticker8upspike = request.security(ticker8, "", volume > vol*spikeMultiple and plus > minus)
ticker8downspike = request.security(ticker8, "", volume > vol*spikeMultiple and minus > plus)
ticker8volbuild = request.security(ticker8, "", currentMedian > volCurrent*spikeMultipleCurrent or volLine > volLine[1] and volLine[1] > volLine[2] and volLine[2] > volLine[3])
ticker8text = str.tostring(ticker8)
ticker8bg = color.aqua
if ticker8upspike or ticker8downspike or ticker8volbuild
ticker8bg := color.orange
//Plot Scanner Table
dataTable = table.new(tablePosition, columns=8, rows=1, border_color=color.white, border_width=1)
if tableOn and barstate.islast
table.cell(table_id=dataTable, column=0, row=0, text=ticker1text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker1bg)
table.cell(table_id=dataTable, column=1, row=0, text=ticker2text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker2bg)
table.cell(table_id=dataTable, column=2, row=0, text=ticker3text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker3bg)
table.cell(table_id=dataTable, column=3, row=0, text=ticker4text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker4bg)
table.cell(table_id=dataTable, column=4, row=0, text=ticker5text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker5bg)
table.cell(table_id=dataTable, column=5, row=0, text=ticker6text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker6bg)
table.cell(table_id=dataTable, column=6, row=0, text=ticker7text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker7bg)
table.cell(table_id=dataTable, column=7, row=0, text=ticker8text, height=0, text_color=color.white, text_halign=text.align_center, text_valign= text.align_center, bgcolor=ticker8bg)
//Alerts
alertcondition(upSpike, title="Bullish Volume Spike Alert", message="Bullish Volume Spike")
alertcondition(downSpike, title="Bearish Volume Spike Alert", message="Bearish Volume Spike")
alertcondition(volBuild, title="Volume Growing Alert", message="Volume Is Growing") |
Rma Stdev Bands | https://www.tradingview.com/script/YqeZsyPC/ | Arranger77 | https://www.tradingview.com/u/Arranger77/ | 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/
// Β© Arranger77
// Stdev @gorx1
// Renko @umur.ozkul
//@version=5
indicator("Rma Stdev Bands", overlay=true)
wstdev(x, y, b) =>
sum = 0.0
w_sum = 0.0
for i = 0 to y - 1
w = y - i
sum := sum + math.pow(x[i] - b, 2) * w
w_sum := w_sum + w
math.sqrt(sum/w_sum)
W='RMA STDEV BANDS'
_MA = input.string(defval="RMA",title="",options=["RMA","SMA"],group=W,inline='1')
source = input(ohlc4 , '' , inline='1',group=W)
len = input(365 , '' , inline='1',group=W)
Upper = input(false , 'Upper' , inline='2',group=W)
Lower = input(false , 'Lower' , inline='2',group=W)
log = input(false, 'math.exp' , inline='2',group=W)
m_u = input.float(1,step=0.1,title='Upper',inline='3',group=W)
m_u2 = input.float(2,step=0.1,title='',inline='3',group=W)
m_l = input.float(-1,step=0.1,title='Lower',inline='4',group=W)
m_l2 = input.float(-2,step=0.1,title='',inline='4',group=W)
src = log ? math.log(source) : source
Ma = _MA=="RMA"?ta.rma(src,len):ta.sma(src,len)
dev = wstdev(src, len, Ma)
dev_u = Ma + dev * m_u
dev_u2 = Ma + dev * m_u2
dev_l = Ma + dev * m_l
dev_l2 = Ma + dev * m_l2
color_Ma = Ma > Ma[1] ? color.green : color.orange
MA=log?math.exp(Ma):Ma, Dev_u=log?math.exp(dev_u):dev_u, Dev_u2=log?math.exp(dev_u2):dev_u2,
Dev_l=log?math.exp(dev_l):dev_l, Dev_l2=log?math.exp(dev_l2):dev_l2
plot(MA, 'Moving Average', color_Ma ,linewidth=2)
plot(Upper?Dev_u:na, 'Upper band' , color.orange)
plot(Upper?Dev_u2:na, 'Upper band2' , color.purple)
f2=plot(Lower?Dev_l:na, 'Lower band' , color.green)
f1=plot(Lower?Dev_l2:na, 'Lower band2' , Dev_l2<0?color.black:color.purple)
percentL2=input(true,"Upper2 %",inline='5',group=W)
_prcnt=input.float(93,"",step=0.1,inline='5',group=W), _Z=Dev_u2*(1-_prcnt/100)
F1=plot(percentL2?_Z:na,color=_Z>_Z[1]?color.new(color.green,0):color.new(color.red,0),linewidth=1,title="Upper2 Percent")
__prcnt=input.float(83,"",step=0.1,inline='5',group=W), __Z=Dev_u2*(1-__prcnt/100)
F2=plot(percentL2?__Z:na,color=__Z>__Z[1]?color.new(color.green,0):color.new(color.red,0),linewidth=1,title="Upper2 Percent")
///////////////////////////////////////////////////////////////////////////////////////////////////////////
Renko=input(true,title="",group="Renko",inline="Renko")
IgnorePercent=input(50.,"%",group="Renko",inline="Renko")
H=input.string(defval="Upper2",options=["Upper2","Upper","Lower","Lower2"],group="Renko",inline="Renko",title="Src")
R_info=input(true,title="Renko Δ°nfo",group="Renko",inline="Renko_")
Table=input(true,title="Chart History",group="Renko",inline="Renko_")
oth=input(true,title="L2",group="Renko",inline="Renko_",tooltip="L2:Previous LOWER Value, Last Not Trend Box and Average(Last not trendbox@first not trendbox)")
SRC=H=="Lower2"?Dev_l2 : H=="Lower"?Dev_l: H=="Upper"?Dev_u : Dev_u2
float CENTER = -1
float prevCENTER = 0
float UPPER = 0
float LOWER = 0
goup = SRC>nz(UPPER[1])
godown = SRC<nz(LOWER[1])
CENTERRequired = na(CENTER[1]) or goup or godown
prevCENTER:= CENTERRequired ? CENTER[1] : prevCENTER[1]
CENTER:= CENTERRequired ? SRC : CENTER[1]
UPPER:= CENTERRequired ? CENTER * (1+IgnorePercent/100) : UPPER[1]
LOWER:= CENTERRequired ? CENTER / (1+IgnorePercent/100) : LOWER[1]
trending= nz(CENTER) > nz(prevCENTER)
//--- Renko Count
Barscountt=ta.barssince(trending),Barscounttt=ta.barssince(not trending), trendnottrend=not trending?Barscountt:Barscounttt
plotchar(trendnottrend,"RENKO COUNT","",color=not trending?color.red:color.green)
barscountt=ta.barssince(nz(CENTER) != nz(CENTER)[1]),plotchar(barscountt+1,"RENKO COUNT2","",color=trending?color.green:color.red)
TP=plot(Renko?UPPER:na, "Upper - Line1", color=color.black, style=plot.style_stepline,linewidth=1)
Avg1=math.avg(UPPER,CENTER),plot(Renko?Avg1:na,"Avg(Upper,Center) - Line2",style=plot.style_stepline)
mp=plot(Renko?CENTER:na, "Center - Line3", color=color.gray, style=plot.style_stepline,linewidth=2)
Avg2=math.avg(LOWER,CENTER),plot(Renko?Avg2:na,"Avg(Lower,Center) - Line4",style=plot.style_stepline)
bp=plot(Renko?LOWER:na, "Lower - Line5", color=color.black, style=plot.style_stepline,linewidth=1)
//--- Previous LOWER Value
prevl=nz(CENTER) > nz(CENTER)[1]
Prevlower=ta.valuewhen(prevl,LOWER[1],0)
//--- Last Not Trend Box Lower
lastnot=nz(CENTER) != nz(CENTER)[1] and not trending
lastnottrendbox=ta.valuewhen(lastnot,LOWER,0)
//--- AVERAGE(LAST NOT TREND BOX @ FIRST NOT TREND BOX)
average=ta.valuewhen(lastnottrendbox[1]!=lastnottrendbox,math.avg(lastnottrendbox[1],LOWER),0)
//---
AV_=math.avg(lastnottrendbox,Prevlower)
//--- Plot
color1=Prevlower >= LOWER?color.new(color.purple,100):color.new(color.purple,50)
color2=average >= LOWER?color.new(color.orange,100):color.new(color.orange,0)
color3=lastnottrendbox >= LOWER?color.new(color.blue,100):color.new(color.blue,0)
plot(oth?Prevlower:na, color=color1,style=plot.style_stepline,linewidth=2,title="Previous LOWER Value")
plot(ta.valuewhen(oth and trending and AV_<Prevlower,math.avg(lastnottrendbox,Prevlower),0),style=plot.style_stepline,linewidth=2,color=#8ee5ee,title="Average Previous LOWER Value, Last Not Trend Box Lower")
plot(oth?lastnottrendbox:na, color=color3, style=plot.style_stepline,linewidth=2,title="Last Not Trend Box Lower")
plot(oth?average:na,color=color2,style=plot.style_stepline,linewidth=2,title="Average(Last not trendbox @ first not trendbox)")
fill(TP,bp, color= CENTERRequired?na:(trending ? color.new(color.lime,90) : color.new(color.orange,90)),title="Renko fill")
fill(mp,bp, color= not trending?na:(trending ? color.new(color.lime,80) : color.new(color.orange,80)),title="Renko fill")
fill(mp,TP, color= trending?na:(trending ? color.new(color.lime,80) : color.new(color.orange,80)),title="Renko fill")
filcolor=ta.crossunder(Dev_u,LOWER)?(trending?color.new(color.gray,transp=0):color.new(color.green,transp=0)):color.new(color.green,transp=93)
fill(f1,f2,color=filcolor,title="STDEV Lower band2 - lower band fill")
filcolor_=ta.crossunder(Dev_u,LOWER)?(trending?color.new(color.gray,transp=0):color.new(color.green,transp=0)):color.new(color.green,transp=93)
fill(F1,F2,color=filcolor,title="UPPER2 PERCENT93-PERCENT83 FILL")
//RENKO Information
distance1=((LOWER/UPPER)-1)*100 //UPPER-LOWER Percent
distance2=((LOWER/math.avg(UPPER,CENTER))-1)*100 //avg(UPPER,CENTER)-LOWER Percent
distance3=((LOWER/CENTER)-1)*100 //CENTER-LOWER Percent
distance4=((LOWER/math.avg(LOWER,CENTER))-1)*100 //avg(LOWER,CENTER)-LOWER Percent
distance5=((math.avg(LOWER,CENTER)/LOWER)-1)*100 //LOWER+avg(LOWER,CENTER)Percent
distance6=((CENTER/LOWER)-1)*100 //LOWER+CENTER Percent
distance7=((math.avg(UPPER,CENTER)/LOWER)-1)*100 //LOWER+avg(UPPER,CENTER)Percent
distance8=((UPPER/LOWER)-1)*100 //LOWER+UPPER Percent
if Renko and R_info
label Label=label.new(time, CENTER,
text="\n ββββββββπ€Ή Renko Information π€Ή"
+ "\nβββββββββββββββββ"
+ "\nπβββBarssince single box |" + str.tostring(barscountt+1,"#.##")
+ "\nπβββBarssince trend |" +str.tostring(trendnottrend,"#.##")
+ "\nβββββββββββββββββ"
+ "\nπβββLine1 - Line5 Percent |" + str.tostring(distance1,"#.##")
+ "\nπβββLine2 - Line5 Percent |" + str.tostring(distance2,"#.##")
+ "\nπβββLine3 - Line5 Percent |" + str.tostring(distance3,"#.##")
+ "\nπβββLine4 - Line5 Percent |" + str.tostring(distance4,"#.##")
+ "\nβββββββββββββββββ"
+ "\nπβββLine5 + Line1 Percentββ|" + str.tostring(distance8,"#.##")
+ "\nπβββLine5 + Line2 Percentββ|" + str.tostring(distance7,"#.##")
+ "\nπβββLine5 + Line3 Percentββ|" + str.tostring(distance6,"#.##")
+ "\nπβββLine5 + Line4 Percentββ|" + str.tostring(distance5,"#.##"),
color=color.new(color.black,25), xloc= xloc.bar_time, style=label.style_label_left, textcolor=color.new(#ffffff,0), textalign=text.align_left)
label.set_x(Label, label.get_x(Label) + math.round(ta.change(time)*20))
label.delete(Label[1])
//Chart History
var int first_hour=hour, var int first_day=dayofmonth, var int first_year=year, var int first_minute=minute, var int first_month=month
Month=first_month==1?'January':first_month==2?'February':first_month==3?'March':first_month==4?'April':first_month==5?'May':first_month==6?'June':
first_month==7?'July':first_month==8?'August':first_month==9?'September':first_month==10?'October':first_month==11?'November':'December'
datestring= str.tostring(first_day) + '.' + Month + '.' + str.tostring(first_year)
Bar_index= str.tostring((first_day)+bar_index)
var table perfTable = table.new(position.top_right, 1, 3, border_width = 0)
_cellText = datestring, C1=color.new(color.green, 88), C2=color.new(color.black, 0)
table.cell(perfTable, 0, 0, _cellText, bgcolor = Table==true?C1:na, text_color = Table==true?C2:na, width = 10, text_size=size.normal)
_cellText_2 = "Bar Index = " + Bar_index
table.cell(perfTable, 0, 1, _cellText_2, bgcolor = Table==true?C1:na, text_color = Table==true?C2:na, width = 10, text_size=size.normal)
///////////////////////////////////////////////////////////////////////////////////////////////////////////
|
EFT | https://www.tradingview.com/script/83akZN9e/ | koin101 | https://www.tradingview.com/u/koin101/ | 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/
// Β© koin101
//@version=5
indicator("EFT", "", true,format=format.price)
aInput = input.float(0.00, title="Aylik Pozitif Enflasyon")
yInput = input.float(0.00, title="Yillik Pozitif Enflasyon")
anInput = input.float(0.00, title="Aylik Negatif Enflasyon")
ynInput = input.float(0.00, title="Yillik Negatif Enflasyon")
aeft = aInput*close/100+close
yeft = yInput*close/100+close
aneft = anInput*close/100+close
yneft = ynInput*close/100+close
ortaaeft = aeft+aneft
yortaaeft = ortaaeft/2
plot(aeft, "Aylik Pozitif Enflasyon", color.green, linewidth = 1)
plot(yeft, "Yillik Pozitif Enflasyon", color.gray, linewidth = 1)
plot(aneft, "Aylik Negatif Enflasyon", color.red, linewidth = 1)
plot(yneft, "Yillik Negatif Enflasyon", color.gray, linewidth = 1)
plot(yortaaeft, "Enflasyon OrtalamasΔ±", color.blue, linewidth = 1)
|
Williams %R - Smoothed | https://www.tradingview.com/script/5X6fkyPl-Williams-R-Smoothed/ | PtGambler | https://www.tradingview.com/u/PtGambler/ | 403 | 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/
// Β© platsn
//@version=5
indicator(title='Williams %R - Smoothed', shorttitle='The Smooth Willy')
// Williams %R
length = input.int(defval=34, minval=1)
upper = ta.highest(length)
lower = ta.lowest(length)
output = 100 * (close - upper) / (upper - lower)
fast_period = input(defval=5, title='Smoothed %R Length')
slow_period = input(defval=13, title='Slow EMA Length')
fast_ema = ta.wma(output,fast_period)
slow_ema = ta.ema(output,slow_period)
// Plot
h1 = hline(-20, title='Upper Band')
h2 = hline(-80, title='Lower Band')
fill(h1, h2, title='Background', transp=90)
plot(output, title='%R', color=color.new(color.white, 80), linewidth=1)
plot(fast_ema, title='Smoothed %R', color=color.new(color.yellow, 0), linewidth=2)
plot(slow_ema, title='Slow EMA', color=color.new(color.aqua, 0), linewidth=2)
bullX = ta.crossover(fast_ema, slow_ema)
bearX = ta.crossunder(fast_ema, slow_ema)
bullreverse = fast_ema[2] > fast_ema[1] and fast_ema > fast_ema[1] and fast_ema < -30
bearreverse = fast_ema[2] < fast_ema[1] and fast_ema < fast_ema[1] and fast_ema > -70
plotX = input.bool(true, "Show EMA Crossovers")
plotRev = input.bool(true, "Show trend reversals")
plotshape(plotX and bearX ,"Cross down", color=color.red, style=shape.triangledown, location = location.top, size =size.tiny, offset=0)
plotshape(plotX and bullX ,"Cross up", color=color.green, style=shape.triangleup, location = location.bottom, size =size.tiny, offset=0)
plotshape(plotRev and bearreverse ,"Bear reversal", color=color.orange, style=shape.triangledown, location = location.top, size =size.tiny, offset=-1)
plotshape(plotRev and bullreverse ,"Bull reversal", color=color.blue, style=shape.triangleup, location = location.bottom, size =size.tiny, offset=-1)
alertcondition(bearX,"Bearish Crossover", "Bearish cross on William %R")
alertcondition(bullX,"Bullish Crossover", "Bullish cross on William %R")
alertcondition(bearreverse,"Bearish Reversal", "Bearish Reversal on William %R")
alertcondition(bullreverse,"Billish Reversal", "Bullish Reversal on William %R") |
Heikin Ashi Mini Bar | https://www.tradingview.com/script/TZa8ME7M/ | rsu9 | https://www.tradingview.com/u/rsu9/ | 37 | 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/
// Β© rsu9111
//@version=5
indicator("Heikin Ashi Mini Bar",overlay=true,scale=scale.none)
[hc,ho,hl,hh]= request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period,[ close,open,low,high])
color bullColorInput = input.color(#00FF00ff, "Bull")
color bearColorInput = input.color(#FF0080ff, "Bear")
barhigh=input.session("1", "Bar High", options=["1", "2", "3", "4", "5"])
plot(200,show_last=1,editable=false,color=color.new(color.white,100))
plot(str.tonumber(barhigh),style=plot.style_columns,color=hc>ho?bullColorInput:bearColorInput,histbase=0)
|
Moving Average Macro Trend Filter | https://www.tradingview.com/script/Z3E6Hyre-Moving-Average-Macro-Trend-Filter/ | jordanfray | https://www.tradingview.com/u/jordanfray/ | 57 | 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/
// Β© jordanfray
//@version=5
indicator(title="Moving Average Macro Trend Filter", overlay=true)
// Indenting Classs
indent_1 = "β"
indent_2 = "ββ"
indent_3 = "βββ"
indent_4 = "ββββ"
indent_5 = "βββββ"
indent_6 = "ββββββ"
indent_7 = "βββββββ"
indent_8 = "ββββββββ"
indent_9 = "βββββββββ"
indent_10 = "ββββββββββ"
// Group Titles
group_one_title = "Fast EMA Settings"
group_two_title = "Slow EMA Settings"
group_three_title = "Background Colors"
// Input Tips
tooltipDoNotRepaint = "To prevent the moving averages from repainting, you can have the last bar's value be used intead of the current bar's value."
tooltipBullBackground = "The background on the chart when the fast moving average is above the slow moving average."
tooltipBearBackground = "The background on the chart when the slow moving average is above the fast moving average."
tooltipSidewaysBackground = "The background on the chart when the fast moving average and slow moving average don't agree on trend direction."
tooltipBackgroundSmoothing = "How many bars to lookback when comparing the slope of the moving average. The higher the number, the less often short term changes in line slope will cause changes to the background."
oceanBlue = color.new(#0C6090,0)
skyBlue = color.new(#00A5FF,0)
green = color.new(#2DBD85,0)
red = color.new(#E02A4A,0)
lightGreen = color.new(#2DBD85,85)
lightRed = color.new(#E02A4A,85)
lightYellow = color.new(#FFF900,85)
// Fast EMA
fastEMAtimeframe = input.timeframe(defval="", title="Timeframe", group=group_one_title)
fastEMAlength = input.int(defval=50, minval=1, title="Length", group=group_one_title)
fastEMAtype = input.string(defval="EMA", options = ["EMA", "SMA", "RMA", "WMA"], title="Type", group=group_one_title)
fastEMAsource = input.source(defval=close, title="Source", group=group_one_title)
fastEMA = switch fastEMAtype
"EMA" => ta.ema(fastEMAsource, fastEMAlength)
"SMA" => ta.sma(fastEMAsource, fastEMAlength)
"RMA" => ta.rma(fastEMAsource, fastEMAlength)
"WMA" => ta.wma(fastEMAsource, fastEMAlength)
=> na
// Slow EMA
slowEMAtimeframe = input.timeframe(defval="", title="Timeframe", group=group_two_title)
slowEMAlength = input.int(defval=200, minval=1, title="Length", group=group_two_title)
slowEMAtype = input.string(defval="EMA", options = ["EMA", "SMA", "RMA", "WMA"], title="Type", group=group_two_title)
slowEMAsource = input.source(defval=close, title="Source", group=group_two_title)
slowEMA = switch slowEMAtype
"EMA" => ta.ema(slowEMAsource, slowEMAlength)
"SMA" => ta.sma(slowEMAsource, slowEMAlength)
"RMA" => ta.rma(slowEMAsource, slowEMAlength)
"WMA" => ta.wma(slowEMAsource, slowEMAlength)
=> na
// Plot Background
bullColor = input.color(title="Bull Market", defval=lightGreen, tooltip=tooltipBullBackground, group=group_three_title)
bearColor = input(title="Bear Market", defval=lightRed, tooltip=tooltipBearBackground, group=group_three_title)
sidewaysColor = input(title="Sideways", defval=lightYellow, tooltip=tooltipSidewaysBackground, group=group_three_title)
lookbackPeriod = input.int(title="Lookback Smoothing", defval=3, minval=1, tooltip=tooltipBackgroundSmoothing, group=group_three_title)
noRepaint = input.bool(defval=false, title="Don't repaint on higher timeframes", tooltip=tooltipDoNotRepaint, group=group_three_title)
fastEMA_ = fastEMAtimeframe == timeframe.period ? fastEMA : noRepaint ? request.security(syminfo.ticker, fastEMAtimeframe, fastEMA[1], lookahead = barmerge.lookahead_on) : request.security(syminfo.ticker, fastEMAtimeframe, fastEMA)
slowEMA_ = slowEMAtimeframe == timeframe.period ? slowEMA : noRepaint ? request.security(syminfo.ticker, slowEMAtimeframe, slowEMA[1], lookahead = barmerge.lookahead_on) : request.security(syminfo.ticker, slowEMAtimeframe, slowEMA)
color = fastEMA_ > slowEMA_ and fastEMA_ > fastEMA_[lookbackPeriod] ? bullColor : slowEMA_ > fastEMA_ and fastEMA_[lookbackPeriod] > fastEMA_ ? bearColor : sidewaysColor
plot(fastEMA_, title="Fast EMA", linewidth=2, color=skyBlue, editable=true)
plot(slowEMA_, title="Slow EMA", linewidth=2, color=oceanBlue, editable=true)
bgcolor(color=color) |
Price Spread Indicator v2 | https://www.tradingview.com/script/baMmoGzV-Price-Spread-Indicator-v2/ | jroche1973 | https://www.tradingview.com/u/jroche1973/ | 47 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© jroche1973
//@version=5
indicator("Price Spread Indicator v3", overlay=false)
i_sym = input.symbol("SPY", "Symbol")
sym_close = request.security(i_sym, 'D', close)
i_lookback1 = input.int(60, "MA/Days lookback value 1:")
i_lookback2 = input.int(90, "MA/Days lookback value 2:")
i_lookback3 = input.int(200, "MA/Days lookback value 3:")
i_lookback4 = input.int(18, "Short MA/Alt. Days look back")
chk_ratio1= input.float(-0.25, "Spread ratio LB 1")
chk_ratio2= input.float(-1.1, "Spread ratio LB 2")
chk_ratio3 = input.float(-1.4, "Spread ratio LB 3") // -1.3 is been derived from backtests to maximise P&L
chk_ratio4 = input.float(-8.6, "Spread ratio LB 4")
//close lookbacks
cl1 = sym_close[i_lookback1]
cl2 = sym_close[i_lookback2]
cl3 = sym_close[i_lookback3]
cl4= sym_close[i_lookback4]
//Calculate spread
spread1 = ((sym_close-cl1)/sym_close)*100 //60 day default
spread2 = ((sym_close-cl2)/sym_close)*100 //90 day default
spread3 = ((sym_close-cl3)/sym_close)*100 //200 day default
spread4 = ((sym_close-cl4)/sym_close)*100 //alternative catch all 18 day default
//Test Conditions
cond_1 = spread1 < chk_ratio1?true:false //is 60 day spread higher than our check spread
//and
cond_2 = spread2 < chk_ratio2?true:false
//and
cond_3 = spread3 < chk_ratio3?true:false
//or
cond_4 = spread4 < chk_ratio4?true:false
multi_cond = cond_1 and cond_2 and cond_3?true:false
cls_plt = plot(sym_close, color=color.blue, linewidth = 2)
bgcolor(multi_cond or cond_4? #FF9999:na)
|
Volume Highlighter in main by RSU | https://www.tradingview.com/script/eyT09PYR/ | rsu9 | https://www.tradingview.com/u/rsu9/ | 41 | 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/
// Β© rsu9111
//@version=5
indicator("Volume Highlighter in main by RSU",overlay=true,scale=scale.none)
avgleg=input.int(60, "Vol Avg Len", minval=5, maxval=200, step=1)
tshow = input.bool(true, "On/Off show turnover")
v=volume
avg = ta.sma(v,avgleg)
std = ta.stdev(v,avgleg)
largeV = (v-avg) > 4*std
plot(avg,color=color.new(color.gray,avgleg))
plot(v,style=plot.style_columns,color=largeV?color.new(color.yellow,0):close>close[1]?v>=avg?color.new(color.green,30):color.new(color.green,85):v>=avg?color.new(color.red,30):color.new(color.red,85),histbase=0)
plot(avg*20,show_last=1,editable=false,color=color.new(color.white,100))
r=v/1000000*hl2
rinfo=str.tostring(r,"#.##M")+syminfo.currency
if r>10000
rinfo:=str.tostring(r/10000,"#.##B")+syminfo.currency
if tshow
s=label.new(time,0,text=rinfo,color=color.new(#8D8D8D,50),style=label.style_label_lower_left,xloc=xloc.bar_time,textalign=text.align_left)
label.set_x(s, label.get_x(s) + (time-time[1])*5)
label.delete(s[1])
|
ATR Day Grid by RSU | https://www.tradingview.com/script/5pGaQERq/ | rsu9 | https://www.tradingview.com/u/rsu9/ | 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/
// Β© rsu9111
//@version=5
indicator("ATR Day Grid by RSU",overlay=true)
atrgrid=input.bool(true, "On/Off ATR_D Grid Show")
Atrp=input.int(14, "ATR Len", minval=5, maxval=200, step=1)
dt = time - time[1]
label chasehigh1=na
//Day Warning
if timeframe.isdaily and atrgrid
atr14=ta.atr(Atrp)
safe_top = line.new(time+dt, low+atr14*0.5, time+dt*7, low+atr14*0.5, xloc=xloc.bar_time,color=color.green)
risk_top = line.new(time+dt, low+atr14, time+dt*7, low+atr14, xloc=xloc.bar_time,color=color.red)
if close>(low+atr14)
line.set_width(risk_top,5)
chasehigh1:=label.new(bar_index,low+atr14*1.5,text="Donβt chasing!",color=color.new(color.red,100),style=label.style_label_left,textcolor=color.new(color.red,20))
label.delete(chasehigh1[1])
line.delete(safe_top[1])
line.delete(risk_top[1])
if close<open
line.delete(safe_top)
line.delete(risk_top)
//intraday Warning
[time_D,atr_D,open_D,close_D]=request.security(syminfo.tickerid,"D",[time,ta.atr(Atrp),open,close],barmerge.gaps_off, barmerge.lookahead_on)
if timeframe.isminutes and atrgrid
startK=ta.barssince(ta.change(time_D))
safe_top_1h=line.new(time[startK],low[startK]+atr_D*0.5,time+dt*7,low[startK]+atr_D*0.5,xloc=xloc.bar_time,color=color.new(color.green,50))
risk_top_1h = line.new(time[startK],low[startK]+atr_D,time+dt*7,low[startK]+atr_D,xloc=xloc.bar_time,color=color.red)
if close>(low[startK]+atr_D)
line.set_width(risk_top_1h,20)
chasehigh1:=label.new(bar_index,low[startK]+atr_D*1.1,text="Donβt chasing!",color=color.new(color.red,100),style=label.style_label_left,textcolor=color.new(color.red,20))
label.delete(chasehigh1[1])
line.delete(safe_top_1h[1])
line.delete(risk_top_1h[1])
if close_D<open_D
line.delete(safe_top_1h)
line.delete(risk_top_1h)
|
Chips Average Line (volume price) by RSU | https://www.tradingview.com/script/iuyV9fcw/ | rsu9 | https://www.tradingview.com/u/rsu9/ | 146 | 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/
// Β© rsu9111
//@version=5
indicator("Chips Average Line by RSU",overlay=true)
short_term_len=input.int(30, "short term len", minval=5, maxval=500, step=1)
m_show = input.bool(true, "On/Off medium term line")
medium_term_len=input.int(60, "medium term len", minval=5, maxval=500, step=1)
l_show = input.bool(true, "On/Off long term line")
long_term_len=input.int(200, "medium term len", minval=5, maxval=500, step=1)
smooth_len=input.int(3,"smooth_len",options=[1,2,3,4,5])
//
//Function
//
chipsline(len)=>
newvolume=(hl2-close)*(hl2-close)*volume
totalVol=math.sum(newvolume,len)
math.sum(newvolume*close,len)/totalVol
chipsline_s=ta.ema(chipsline(short_term_len),smooth_len)
chipsline_m=ta.ema(chipsline(medium_term_len),smooth_len)
chipsline_l=ta.ema(chipsline(long_term_len),smooth_len)
col12 = hl2 >= chipsline_s
color_UP=color.new(color.blue,25)
color_Down=color.new(color.gray,50)
color2 = col12 ? color_UP : color_Down
//
//Plot
//
plot(chipsline_s,linewidth=2,linewidth=2,color=color2,title="short_term")
plot(m_show?chipsline_m:na,linewidth=2,color=color.new(color.purple,70),title="medium_term")
plot(l_show?chipsline_l:na,linewidth=2,color=color.new(color.blue,70),title="long_term")
|
Patterns | https://www.tradingview.com/script/WKi82pYD-Patterns/ | Mehdifbt | https://www.tradingview.com/u/Mehdifbt/ | 68 | 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/
// Β©mehtism
//@version=5
indicator('Swing Highs/Lows & Candle Patterns', overlay=true)
len = input.int(9, minval=1, title="Length")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.sma(src, len)
plot(out, color=color.blue, title="MA", offset=offset)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="Smoothing")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="Smoothing")
smoothingLine = ma(out, smoothingLength, typeMA)
plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset)
nkj = input(5, title='Length')
Barcolor = input(false, title='Barcolor')
ys1 = (high + low + close * 2) / 4
rk3 = ta.ema(ys1, nkj)
rk4 = ta.stdev(ys1, nkj)
rk5 = (ys1 - rk3) * 100 / rk4
rk6 = ta.ema(rk5, nkj)
up = ta.ema(rk6, nkj)
down = ta.ema(up, nkj)
Oo = up < down ? up : down
Hh = Oo
Ll = up < down ? down : up
Cc = Ll
iff_1 = up > down ? #008000 : #FF0000
b_color = Oo[1] < Oo and Cc < Cc[1] ? #FFFF00 : iff_1
barcolor(Barcolor ? b_color : na)
Buy = ta.crossover(up, down)
Sell = ta.crossunder(up, down)
plotshape(Buy, title='Buy', color=color.new(#008000, 0), style=shape.triangleup, location=location.bottom, text='Buy', size=size.tiny)
plotshape(Sell, title='Sell', color=color.new(#FF0000, 0), style=shape.triangledown, location=location.top, text='Sell', size=size.tiny)
alertcondition(Buy or Sell, title='Buy/Sell Signal', message='Buy/Sell')
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© LonesomeTheBlue
prd = input.int(defval=5, title='Pivot Period', minval=1, maxval=50)
source = input.string(defval='Close', title='Source for Pivot Points', options=['Close', 'High/Low'])
searchdiv = input.string(defval='Regular', title='Divergence Type', options=['Regular', 'Hidden', 'Regular/Hidden'])
showindis = input.string(defval='Full', title='Show Indicator Names', options=['Full', 'First Letter', 'Don\'t Show'])
showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11)
maxpp = input.int(defval=10, title='Maximum Pivot Points to Check', minval=1, maxval=20)
maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=30, maxval=200)
shownum = input(defval=true, title='Show Divergence Number')
showlast = input(defval=false, title='Show Only Last Divergence')
dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation')
showlines = input(defval=true, title='Show Divergence Lines')
showpivot = input(defval=false, title='Show Pivot Points')
calcmacd = input(defval=true, title='MACD')
calcmacda = input(defval=true, title='MACD Histogram')
calcrsi = input(defval=true, title='RSI')
calcstoc = input(defval=true, title='Stochastic')
calccci = input(defval=true, title='CCI')
calcmom = input(defval=true, title='Momentum')
calcobv = input(defval=true, title='OBV')
calcvwmacd = input(true, title='VWmacd')
calccmf = input(true, title='Chaikin Money Flow')
calcmfi = input(true, title='Money Flow Index')
calcext = input(false, title='Check External Indicator')
externalindi = input(defval=close, title='External Indicator')
pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')
neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')
pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')
neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')
pos_div_text_col = input(defval=color.black, title='Positive Divergence Text Color')
neg_div_text_col = input(defval=color.white, title='Negative Divergence Text Color')
reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])
hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])
reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width', minval=1, maxval=5)
hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width', minval=1, maxval=5)
showmas = input.bool(defval=false, title='Show MAs 50 & 200', inline='ma12')
cma1col = input.color(defval=color.lime, title='', inline='ma12')
cma2col = input.color(defval=color.red, title='', inline='ma12')
plot(showmas ? ta.sma(close, 50) : na, color=showmas ? cma1col : na)
plot(showmas ? ta.sma(close, 200) : na, color=showmas ? cma2col : na)
// set line styles
var reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid : reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
var hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid : hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
// get indicators
rsi = ta.rsi(close, 14) // RSI
[macd, signal, deltamacd] = ta.macd(close, 12, 26, 9) // MACD
moment = ta.mom(close, 10) // Momentum
cci = ta.cci(close, 10) // CCI
Obv = ta.obv // OBV
stk = ta.sma(ta.stoch(close, high, low, 14), 3) // Stoch
maFast = ta.vwma(close, 12) // volume weighted macd
maSlow = ta.vwma(close, 26)
vwmacd = maFast - maSlow
Cmfm = (close - low - (high - close)) / (high - low) // Chaikin money flow
Cmfv = Cmfm * volume
cmf = ta.sma(Cmfv, 21) / ta.sma(volume, 21)
Mfi = ta.mfi(close, 14) // Moneyt Flow Index
// keep indicators names and colors in arrays
var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
// names
array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' : 'M')
array.set(indicators_name, 1, showindis == 'Full' ? 'Hist' : 'H')
array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' : 'E')
array.set(indicators_name, 3, showindis == 'Full' ? 'Stoch' : 'S')
array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' : 'C')
array.set(indicators_name, 5, showindis == 'Full' ? 'MOM' : 'M')
array.set(indicators_name, 6, showindis == 'Full' ? 'OBV' : 'O')
array.set(indicators_name, 7, showindis == 'Full' ? 'VWMACD' : 'V')
array.set(indicators_name, 8, showindis == 'Full' ? 'CMF' : 'C')
array.set(indicators_name, 9, showindis == 'Full' ? 'MFI' : 'M')
array.set(indicators_name, 10, showindis == 'Full' ? 'Extrn' : 'X')
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)
// Check if we get new Pivot High Or Pivot Low
float ph = ta.pivothigh(source == 'Close' ? close : high, prd, prd)
float pl = ta.pivotlow(source == 'Close' ? close : low, prd, prd)
plotshape(ph and showpivot, text='H', style=shape.labeldown, color=color.new(color.white, 100), textcolor=color.new(color.red, 0), location=location.abovebar, offset=-prd)
plotshape(pl and showpivot, text='L', style=shape.labelup, color=color.new(color.white, 100), textcolor=color.new(color.lime, 0), location=location.belowbar, offset=-prd)
// keep values and positions of Pivot Highs/Lows in the arrays
var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)
// add PHs to the array
if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)
// add PLs to the array
if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)
// functions to check Regular Divergences and Hidden Divergences
// function to check positive regular or negative hidden divergence
// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : low
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src > src[1] or close > close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - close[len]) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2
if arrived
divlen := len
break
divlen
// function to check negative regular or positive hidden divergence
// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : high
// if indicators higher than last value and close price is higher than las close
if dontconfirm or src < src[1] or close < close[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2
if arrived
divlen := len
break
divlen
// calculate 4 types of divergence if enabled in the options and return divergences in an array
calculate_divs(cond, indicator_1) =>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) : 0)
array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) : 0)
array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) : 0)
array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) : 0)
divs
// array to keep all divergences
var all_divergences = array.new_int(44) // 11 indicators * 4 divergence = 44 elements
// set related array elements
array_set_divs(div_pointer, index) =>
for x = 0 to 3 by 1
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))
// set divergences array
array_set_divs(calculate_divs(calcmacd, macd), 0)
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
array_set_divs(calculate_divs(calcrsi, rsi), 2)
array_set_divs(calculate_divs(calcstoc, stk), 3)
array_set_divs(calculate_divs(calccci, cci), 4)
array_set_divs(calculate_divs(calcmom, moment), 5)
array_set_divs(calculate_divs(calcobv, Obv), 6)
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
array_set_divs(calculate_divs(calccmf, cmf), 8)
array_set_divs(calculate_divs(calcmfi, Mfi), 9)
array_set_divs(calculate_divs(calcext, externalindi), 10)
// check minimum number of divergence, if less than showlimit then delete all divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1 by 1
total_div += math.round(math.sign(array.get(all_divergences, x)))
total_div
if total_div < showlimit
array.fill(all_divergences, 0)
// keep line in an array
var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// remove old lines and labels if showlast option is enabled
delete_old_pos_div_lines() =>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1 by 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)
delete_old_neg_div_lines() =>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1 by 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)
delete_old_pos_div_labels() =>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1 by 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)
delete_old_neg_div_labels() =>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1 by 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)
// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n) =>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n by 1
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n) =>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n by 1
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false
// to remove lines/labels until we met new // PH/PL
var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
last_pos_div_lines
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
last_neg_div_lines
// draw divergences lines and labels
divergence_text_top = ''
divergence_text_bottom = ''
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
for x = 0 to 10 by 1
div_type = -1
for y = 0 to 3 by 1
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if y % 2 == 1
dnumdiv_top += 1
top_label_col := array.get(div_colors, y)
top_label_col
if y % 2 == 0
dnumdiv_bottom += 1
bottom_label_col := array.get(div_colors, y)
bottom_label_col
if not array.includes(distances, array.get(all_divergences, x * 4 + y)) // line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = showlines ? line.new(x1=bar_index - array.get(all_divergences, x * 4 + y), y1=source == 'Close' ? close[array.get(all_divergences, x * 4 + y)] : y % 2 == 0 ? low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4 + y)], x2=bar_index - startpoint, y2=source == 'Close' ? close[startpoint] : y % 2 == 0 ? low[startpoint] : high[startpoint], color=array.get(div_colors, y), style=y < 2 ? reg_div_l_style : hid_div_l_style, width=y < 2 ? reg_div_l_width : hid_div_l_width) : na
if y % 2 == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
last_pos_div_lines
if showlast
delete_old_pos_div_lines()
array.push(pos_div_lines, new_line)
last_pos_div_lines += 1
remove_last_pos_divs := true
remove_last_pos_divs
if y % 2 == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
last_neg_div_lines
if showlast
delete_old_neg_div_lines()
array.push(neg_div_lines, new_line)
last_neg_div_lines += 1
remove_last_neg_divs := true
remove_last_neg_divs
// set variables for alerts
if y == 0
pos_reg_div_detected := true
pos_reg_div_detected
if y == 1
neg_reg_div_detected := true
neg_reg_div_detected
if y == 2
pos_hid_div_detected := true
pos_hid_div_detected
if y == 3
neg_hid_div_detected := true
neg_hid_div_detected
// get text for labels
if div_type >= 0
divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom
// draw labels
if showindis != 'Don\'t Show' or shownum
if shownum and dnumdiv_top > 0
divergence_text_top += str.tostring(dnumdiv_top)
divergence_text_top
if shownum and dnumdiv_bottom > 0
divergence_text_bottom += str.tostring(dnumdiv_bottom)
divergence_text_bottom
if divergence_text_top != ''
if showlast
delete_old_neg_div_labels()
array.push(neg_div_labels, label.new(x=bar_index, y=math.max(high, high[1]), text=divergence_text_top, color=top_label_col, textcolor=neg_div_text_col, style=label.style_label_down))
if divergence_text_bottom != ''
if showlast
delete_old_pos_div_labels()
array.push(pos_div_labels, label.new(x=bar_index, y=math.min(low, low[1]), text=divergence_text_bottom, color=bottom_label_col, textcolor=pos_div_text_col, style=label.style_label_up))
alertcondition(pos_reg_div_detected or neg_reg_div_detected or pos_hid_div_detected or neg_hid_div_detected, title='all Detected', message='Divergence Detected')
//************************************************************************************************************
// Parameter
//************************************************************************************************************
indiSet = input(false, 'βββββββββ MRC Parameter ββββββββ')
source1 = input(hlc3, title='Price Source')
type = input.string('SuperSmoother', title='Filter Type', options=['SuperSmoother', 'Ehlers EMA', 'Gaussian', 'Butterworth', 'BandStop', 'SMA', 'EMA', 'RMA'])
length = input.int(200, title='Lookback Period', minval=1)
innermult = input.float(1.0, title='Inner Channel Size Multiplier', minval=0.1)
outermult = input.float(2.415, title='Outer Channel Size Multiplier', minval=0.1)
ChartSet = input(false, 'βββββββββ Chart Setting ββββββββ')
drawchannel = input(true, title='Draw Channel')
displayzone = input(true, title='Draw Zone (With Channel)')
zonetransp = input.int(60, title='Zone Transparency', minval=0, maxval=100)
displayline = input(true, title='Display Line Extension')
MTFSet = input(false, 'βββββββββ MTF Setting ββββββββ')
enable_mtf = input(true, title='Enable Multiple TimeFrame Analysis')
mtf_disp_typ = input.string('On Hover', title='MTF Display Type', options=['Always Display', 'On Hover'])
mtf_typ = input.string('Auto', title='Multiple TimeFrame Type', options=['Auto', 'Custom'])
mtf_lvl1 = input.timeframe('D', title='Custom MTF Level 1')
mtf_lvl2 = input.timeframe('W', title='Custom MTF Level 2')
//************************************************************************************************************
// Functions Start {
//************************************************************************************************************
var pi = 2 * math.asin(1)
var mult = pi * innermult
var mult2 = pi * outermult
var gradsize = 0.5
var gradtransp = zonetransp
//-----------------------
// Ehler SwissArmyKnife Function
//-----------------------
SAK_smoothing(_type, _src, _length) =>
c0 = 1.0
c1 = 0.0
b0 = 1.0
b1 = 0.0
b2 = 0.0
a1 = 0.0
a2 = 0.0
alpha = 0.0
beta = 0.0
gamma = 0.0
cycle = 2 * pi / _length
if _type == 'Ehlers EMA'
alpha := (math.cos(cycle) + math.sin(cycle) - 1) / math.cos(cycle)
b0 := alpha
a1 := 1 - alpha
a1
if _type == 'Gaussian'
beta := 2.415 * (1 - math.cos(cycle))
alpha := -beta + math.sqrt(beta * beta + 2 * beta)
c0 := alpha * alpha
a1 := 2 * (1 - alpha)
a2 := -(1 - alpha) * (1 - alpha)
a2
if _type == 'Butterworth'
beta := 2.415 * (1 - math.cos(cycle))
alpha := -beta + math.sqrt(beta * beta + 2 * beta)
c0 := alpha * alpha / 4
b1 := 2
b2 := 1
a1 := 2 * (1 - alpha)
a2 := -(1 - alpha) * (1 - alpha)
a2
if _type == 'BandStop'
beta := math.cos(cycle)
gamma := 1 / math.cos(cycle * 2 * 0.1) // delta default to 0.1. Acceptable delta -- 0.05<d<0.5
alpha := gamma - math.sqrt(gamma * gamma - 1)
c0 := (1 + alpha) / 2
b1 := -2 * beta
b2 := 1
a1 := beta * (1 + alpha)
a2 := -alpha
a2
if _type == 'SMA'
c1 := 1 / _length
b0 := 1 / _length
a1 := 1
a1
if _type == 'EMA'
alpha := 2 / (_length + 1)
b0 := alpha
a1 := 1 - alpha
a1
if _type == 'RMA'
alpha := 1 / _length
b0 := alpha
a1 := 1 - alpha
a1
_Input = _src
_Output = 0.0
_Output := c0 * (b0 * _Input + b1 * nz(_Input[1]) + b2 * nz(_Input[2])) + a1 * nz(_Output[1]) + a2 * nz(_Output[2]) - c1 * nz(_Input[_length])
_Output
//-----------------------
// SuperSmoother Function
//-----------------------
supersmoother(_src, _length) =>
s_a1 = math.exp(-math.sqrt(2) * pi / _length)
s_b1 = 2 * s_a1 * math.cos(math.sqrt(2) * pi / _length)
s_c3 = -math.pow(s_a1, 2)
s_c2 = s_b1
s_c1 = 1 - s_c2 - s_c3
ss = 0.0
ss := s_c1 * _src + s_c2 * nz(ss[1], _src[1]) + s_c3 * nz(ss[2], _src[2])
ss
//-----------------------
// Auto TimeFrame Function
//-----------------------
// βββββ Converts current chart resolution into a float minutes value.
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
_resInMinutes
get_tf(_lvl) =>
y = f_resInMinutes()
z = timeframe.period
if mtf_typ == 'Auto'
if y < 1
z := _lvl == 1 ? '1' : _lvl == 2 ? '5' : z
z
else if y <= 3
z := _lvl == 1 ? '5' : _lvl == 2 ? '15' : z
z
else if y <= 10
z := _lvl == 1 ? '15' : _lvl == 2 ? '60' : z
z
else if y <= 30
z := _lvl == 1 ? '60' : _lvl == 2 ? '240' : z
z
else if y <= 120
z := _lvl == 1 ? '240' : _lvl == 2 ? 'D' : z
z
else if y <= 240
z := _lvl == 1 ? 'D' : _lvl == 2 ? 'W' : z
z
else if y <= 1440
z := _lvl == 1 ? 'W' : _lvl == 2 ? 'M' : z
z
else if y <= 10080
z := _lvl == 1 ? 'M' : z
z
else
z := z
z
else
z := _lvl == 1 ? mtf_lvl1 : _lvl == 2 ? mtf_lvl2 : z
z
z
//-----------------------
// Mean Reversion Channel Function
//-----------------------
get_mrc() =>
v_condition = 0
v_meanline = source1
v_meanrange = supersmoother(ta.tr, length)
//-- Get Line value
if type == 'SuperSmoother'
v_meanline := supersmoother(source1, length)
v_meanline
if type != 'SuperSmoother'
v_meanline := SAK_smoothing(type, source1, length)
v_meanline
v_upband1 = v_meanline + v_meanrange * mult
v_loband1 = v_meanline - v_meanrange * mult
v_upband2 = v_meanline + v_meanrange * mult2
v_loband2 = v_meanline - v_meanrange * mult2
//-- Check Condition
if close > v_meanline
v_upband2_1 = v_upband2 + v_meanrange * gradsize * 4
v_upband2_9 = v_upband2 + v_meanrange * gradsize * -4
if high >= v_upband2_9 and high < v_upband2
v_condition := 1
v_condition
else if high >= v_upband2 and high < v_upband2_1
v_condition := 2
v_condition
else if high >= v_upband2_1
v_condition := 3
v_condition
else if close <= v_meanline + v_meanrange
v_condition := 4
v_condition
else
v_condition := 5
v_condition
if close < v_meanline
v_loband2_1 = v_loband2 - v_meanrange * gradsize * 4
v_loband2_9 = v_loband2 - v_meanrange * gradsize * -4
if low <= v_loband2_9 and low > v_loband2
v_condition := -1
v_condition
else if low <= v_loband2 and low > v_loband2_1
v_condition := -2
v_condition
else if low <= v_loband2_1
v_condition := -3
v_condition
else if close >= v_meanline + v_meanrange
v_condition := -4
v_condition
else
v_condition := -5
v_condition
[v_meanline, v_meanrange, v_upband1, v_loband1, v_upband2, v_loband2, v_condition]
//-----------------------
// MTF Analysis
//-----------------------
get_stat(_cond) =>
ret = 'Price at Mean Line\n'
if _cond == 1
ret := 'Overbought (Weak)\n'
ret
else if _cond == 2
ret := 'Overbought\n'
ret
else if _cond == 3
ret := 'Overbought (Strong)\n'
ret
else if _cond == 4
ret := 'Price Near Mean\n'
ret
else if _cond == 5
ret := 'Price Above Mean\n'
ret
else if _cond == -1
ret := 'Oversold (Weak)\n'
ret
else if _cond == -2
ret := 'Oversold\n'
ret
else if _cond == -3
ret := 'Oversold (Strong)\n'
ret
else if _cond == -4
ret := 'Price Near Mean\n'
ret
else if _cond == -5
ret := 'Price Below Mean\n'
ret
ret
//-----------------------
// Chart Drawing Function
//-----------------------
format_price(x) =>
y = str.tostring(x, '0.00000')
if x > 10
y := str.tostring(x, '0.000')
y
if x > 1000
y := str.tostring(x, '0.00')
y
y
f_PriceLine(_ref, linecol) =>
line.new(x1=bar_index, x2=bar_index - 1, y1=_ref, y2=_ref, extend=extend.left, color=linecol)
f_MTFLabel(_txt, _yloc) =>
label.new(x=time + math.round(ta.change(time) * 20), y=_yloc, xloc=xloc.bar_time, text=mtf_disp_typ == 'Always Display' ? _txt : 'Check MTF', tooltip=mtf_disp_typ == 'Always Display' ? '' : _txt, color=color.black, textcolor=color.white, size=size.normal, style=mtf_disp_typ == 'On Hover' and displayline ? label.style_label_lower_left : label.style_label_left, textalign=text.align_left)
//} Function End
//************************************************************************************************************
// Calculate Channel
//************************************************************************************************************
var tf_0 = timeframe.period
var tf_1 = get_tf(1)
var tf_2 = get_tf(2)
[meanline, meanrange, upband1, loband1, upband2, loband2, condition] = get_mrc()
[mtf1_meanline, mtf1_meanrange, mtf1_upband1, mtf1_loband1, mtf1_upband2, mtf1_loband2, mtf1_condition] = request.security(syminfo.tickerid, tf_1, get_mrc())
[mtf2_meanline, mtf2_meanrange, mtf2_upband1, mtf2_loband1, mtf2_upband2, mtf2_loband2, mtf2_condition] = request.security(syminfo.tickerid, tf_2, get_mrc())
//************************************************************************************************************
// Drawing Start {
//************************************************************************************************************
float p_meanline = drawchannel ? meanline : na
float p_upband1 = drawchannel ? upband1 : na
float p_loband1 = drawchannel ? loband1 : na
float p_upband2 = drawchannel ? upband2 : na
float p_loband2 = drawchannel ? loband2 : na
z = plot(p_meanline, color=color.new(#FFCD00, 0), style=plot.style_line, title=' Mean', linewidth=2)
x1 = plot(p_upband1, color=color.new(color.green, 50), style=plot.style_circles, title=' R1', linewidth=1)
x2 = plot(p_loband1, color=color.new(color.green, 50), style=plot.style_circles, title=' S1', linewidth=1)
y1 = plot(p_upband2, color=color.new(color.red, 50), style=plot.style_line, title=' R2', linewidth=1)
y2 = plot(p_loband2, color=color.new(color.red, 50), style=plot.style_line, title=' S2', linewidth=1)
//-----------------------
// Draw zone
//-----------------------
//---
var color1 = #FF0000
var color2 = #FF4200
var color3 = #FF5D00
var color4 = #FF7400
var color5 = #FF9700
var color6 = #FFAE00
var color7 = #FFC500
var color8 = #FFCD00
//---
float upband2_1 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 4 : na
float loband2_1 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 4 : na
float upband2_2 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 3 : na
float loband2_2 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 3 : na
float upband2_3 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 2 : na
float loband2_3 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 2 : na
float upband2_4 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 1 : na
float loband2_4 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 1 : na
float upband2_5 = drawchannel and displayzone ? upband2 + meanrange * gradsize * 0 : na
float loband2_5 = drawchannel and displayzone ? loband2 - meanrange * gradsize * 0 : na
float upband2_6 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -1 : na
float loband2_6 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -1 : na
float upband2_7 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -2 : na
float loband2_7 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -2 : na
float upband2_8 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -3 : na
float loband2_8 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -3 : na
float upband2_9 = drawchannel and displayzone ? upband2 + meanrange * gradsize * -4 : na
float loband2_9 = drawchannel and displayzone ? loband2 - meanrange * gradsize * -4 : na
//---
plot_upband2_1 = plot(upband2_1, color=na, display=display.none, transp=100)
plot_loband2_1 = plot(loband2_1, color=na, display=display.none, transp=100)
plot_upband2_2 = plot(upband2_2, color=na, display=display.none, transp=100)
plot_loband2_2 = plot(loband2_2, color=na, display=display.none, transp=100)
plot_upband2_3 = plot(upband2_3, color=na, display=display.none, transp=100)
plot_loband2_3 = plot(loband2_3, color=na, display=display.none, transp=100)
plot_upband2_4 = plot(upband2_4, color=na, display=display.none, transp=100)
plot_loband2_4 = plot(loband2_4, color=na, display=display.none, transp=100)
plot_upband2_5 = plot(upband2_5, color=na, display=display.none, transp=100)
plot_loband2_5 = plot(loband2_5, color=na, display=display.none, transp=100)
plot_upband2_6 = plot(upband2_6, color=na, display=display.none, transp=100)
plot_loband2_6 = plot(loband2_6, color=na, display=display.none, transp=100)
plot_upband2_7 = plot(upband2_7, color=na, display=display.none, transp=100)
plot_loband2_7 = plot(loband2_7, color=na, display=display.none, transp=100)
plot_upband2_8 = plot(upband2_8, color=na, display=display.none, transp=100)
plot_loband2_8 = plot(loband2_8, color=na, display=display.none, transp=100)
plot_upband2_9 = plot(upband2_9, color=na, display=display.none, transp=100)
plot_loband2_9 = plot(loband2_9, color=na, display=display.none, transp=100)
//---
fill(plot_upband2_1, plot_upband2_2, color=color1, transp=gradtransp)
fill(plot_loband2_1, plot_loband2_2, color=color1, transp=gradtransp)
fill(plot_upband2_2, plot_upband2_3, color=color2, transp=gradtransp)
fill(plot_loband2_2, plot_loband2_3, color=color2, transp=gradtransp)
fill(plot_upband2_3, plot_upband2_4, color=color3, transp=gradtransp)
fill(plot_loband2_3, plot_loband2_4, color=color3, transp=gradtransp)
fill(plot_upband2_4, plot_upband2_5, color=color4, transp=gradtransp)
fill(plot_loband2_4, plot_loband2_5, color=color4, transp=gradtransp)
fill(plot_upband2_5, plot_upband2_6, color=color5, transp=gradtransp)
fill(plot_loband2_5, plot_loband2_6, color=color5, transp=gradtransp)
fill(plot_upband2_6, plot_upband2_7, color=color6, transp=gradtransp)
fill(plot_loband2_6, plot_loband2_7, color=color6, transp=gradtransp)
fill(plot_upband2_7, plot_upband2_8, color=color7, transp=gradtransp)
fill(plot_loband2_7, plot_loband2_8, color=color7, transp=gradtransp)
fill(plot_upband2_8, plot_upband2_9, color=color8, transp=gradtransp)
fill(plot_loband2_8, plot_loband2_9, color=color8, transp=gradtransp)
//-----------------------
// Plot Extension
//-----------------------
if displayline and enable_mtf and mtf_disp_typ == 'Always Display'
displayline := false
displayline
var line mean = na
line.delete(mean)
mean := displayline ? f_PriceLine(meanline, #FFCD00) : na
var line res1 = na
line.delete(res1)
res1 := displayline ? f_PriceLine(upband1, color.green) : na
var line sup1 = na
line.delete(sup1)
sup1 := displayline ? f_PriceLine(loband1, color.green) : na
var line res2 = na
line.delete(res2)
res2 := displayline ? f_PriceLine(upband2, color.red) : na
var line sup2 = na
line.delete(sup2)
sup2 := displayline ? f_PriceLine(loband2, color.red) : na
//--------------
// Prep MTF Label
//--------------
var brl = '\n--------------------------------------'
dist_0 = 'Distance from Mean: ' + str.tostring((close - meanline) / close * 100, '#.##') + ' %'
dist_1 = 'Distance from Mean: ' + str.tostring((close - mtf1_meanline) / close * 100, '#.##') + ' %'
dist_2 = 'Distance from Mean: ' + str.tostring((close - mtf2_meanline) / close * 100, '#.##') + ' %'
var title = 'Mean Reversion Channel\nMultiple TimeFrame Analysis' + brl
tf0 = '\n\nTimeframe: ' + tf_0 + ' (Current)\n\nStatus: ' + get_stat(condition) + dist_0 + brl
tf1 = not timeframe.ismonthly ? '\n\nTimeframe: ' + tf_1 + '\n\nStatus: ' + get_stat(mtf1_condition) + dist_1 + brl : ''
tf2 = not timeframe.isweekly and not timeframe.ismonthly ? '\n\nTimeframe: ' + tf_2 + '\n\nStatus: ' + get_stat(mtf2_condition) + dist_2 + brl : ''
mtf_lbl = title + tf0 + tf1 + tf2
var label label_mtf = na
label.delete(label_mtf)
label_mtf := enable_mtf ? f_MTFLabel(mtf_lbl, meanline) : na
//} Drawing End
|
normalize_heatmap | https://www.tradingview.com/script/CXnEKuim-normalize-heatmap/ | palitoj_endthen | https://www.tradingview.com/u/palitoj_endthen/ | 160 | 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/
// Β© palitoj_endthen
//@version=5
indicator(title = 'Normalize Heatmap Indicator', shorttitle = 'normalize_heatmap', overlay = true)
// input
src = input.source(defval = ohlc4, title = 'Source', group = 'Options', tooltip = 'Determines the source of input data to be normalized')
color_scheme = input.string(defval = 'Rainbow', title = 'Color Scheme', group = 'Options', options = ['Rainbow', 'RGB'], tooltip = 'Choose the applied heatmap color scheme')
ma_type = input.string('WMA', title = 'MA Type', group = 'Options', options = ['WMA', 'EMA', 'SMA', 'RMA'],tooltip = 'Choose between moving average types')
show_ma = input.bool(defval = true, title = 'MA', group = 'Lookback Period', tooltip = 'Determines whether to display moving average line', inline = 'f')
length = input.int(defval = 50, title = 'Length', group = 'Lookback Period', tooltip = 'Determines lookback period of data to be normalized/moving average', inline = 'f')
buy_alert = input.float(defval = .1, title = 'Buy', group = 'Alert', inline = 'f')
sell_alert = input.float(defval = .9, title = 'Sell', group = 'Alert', tooltip = 'Determines the threshold/level to be used on buy/sell alert', inline = 'f')
// normalize data
// @source: source of input data
// @length: lookback period
norm(src_, length_)=>
high_ = ta.highest(src_, length_)
low_ = ta.lowest(src_, length_)
normalized = (src_-low_)/(high_-low_)
normalize = norm(src, length)
// moving average
float ma = switch ma_type
'WMA' => ta.wma(src, length)
'EMA' => ta.ema(src, length)
'SMA' => ta.sma(src, length)
'RMA' => ta.rma(src, length)
// color condition
// (1) scheme1: rainbow heatmap - condition
scheme1 = (normalize < 0.05 ? #0000CA :
normalize < 0.1 ? #0000DF :
normalize < 0.15 ? #0A4CFF :
normalize < 0.2 ? #0A85FF :
normalize < 0.25 ? #0AFFB6 :
normalize < 0.3 ? #0AFF64 :
normalize < 0.35 ? #01EB57 :
normalize < 0.4 ? #01C74A :
normalize < 0.45 ? #01C701 :
normalize < 0.5 ? #33BA02 :
normalize < 0.55 ? #EFFF06 :
normalize < 0.6 ? #CFDE00 :
normalize < 0.65 ? #FFE600 :
normalize < 0.7 ? #FCB000 :
normalize < 0.75 ? #FF9100 :
normalize < 0.8 ? #E88300 :
normalize < 0.85 ? #E85D00 :
normalize < 0.9 ? #D25400 :
normalize < 0.95 ? #FF2E04 :
#DC0404)
// (2) scheme2: rgb - condition
scheme2(x)=>
if x > .5
color.rgb(255*(2-2*x), 255, 0)
else if x < .5
color.rgb(255, 2*255*x, 0)
color_shift = color_scheme == 'Rainbow' ? scheme1 : scheme2(normalize)
// (3) moving average - condition
ma_color = src > ma and ma > ma[1] ? color.green : color.red
ma_color_ = src > ma and ma > ma[1]
// visualize
plotcandle(open, high, low, close, color = color_shift, wickcolor = color_shift, bordercolor = color_shift)
plot(show_ma ? ma : na, color = ma_color, linewidth = 2)
// create alert
// (1) moving average - alert
alertcondition((not ma_color_[1] and ma_color_), title = 'MA Entry', message = 'Buy/Long entry detected')
alertcondition((ma_color_[1] and not ma_color_), title = 'MA Close', message = 'Sell/Short entry detected ')
// (2) normalize heatmap - alert
buy_ = ta.crossunder(normalize, buy_alert)
sell_ = ta.crossover(normalize, sell_alert)
alertcondition(buy_, title = 'Normalized Entry', message = 'Buy/Long entry detected')
alertcondition(sell_, title = 'Normalized Close', message = 'Sell/Short entry detected') |
Midas Mk. II - Ultimate Crypto Swing | https://www.tradingview.com/script/eSNbZ71Y-Midas-Mk-II-Ultimate-Crypto-Swing/ | Bhangerang | https://www.tradingview.com/u/Bhangerang/ | 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/
// Β© Bhangerang
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Bhangerang
//@version=5
indicator(title="Midas Mk. II - Ultimate Crypto Swing", overlay=true)
[MACD_line, Signal_line, hist] = ta.macd(close, 55, 89, 9)
// Strategy conditions
crossover = ta.crossover(ta.ema(close, 21), ta.sma(close, 55))
crossunder = ta.crossunder(ta.ema(close, 21), ta.sma(close, 55))
long_entry_condition = crossover and (hist >= 0 or (hist[0] > hist[1] and hist[1] > hist[2]))
short_entry_condition = crossunder and (hist <= 0 or (hist[0] < hist[1] and hist[1] < hist[2]))
simple_crossover = crossover and not long_entry_condition
simple_crossunder = crossunder and not short_entry_condition
// Plot on the chart
plotchar(long_entry_condition, "Go Long", "β²", location.belowbar, color.lime, size = size.small, text = "long")
plotchar(short_entry_condition, "Go Short", "βΌ", location.abovebar, color.red, size = size.small, text = "short")
plotchar(simple_crossover, "Crossing Up", "β²", location.belowbar, color.lime, size = size.tiny)
plotchar(simple_crossunder, "Crossing Down", "βΌ", location.abovebar, color.red, size = size.tiny)
|
Pivot Points High Low Multi Time Frame | https://www.tradingview.com/script/w2cENzrs-Pivot-Points-High-Low-Multi-Time-Frame/ | LonesomeTheBlue | https://www.tradingview.com/u/LonesomeTheBlue/ | 6,576 | 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/
// Β© LonesomeTheBlue
//@version=5
indicator("Pivot Points High Low Multi Time Frame", overlay = true, max_lines_count = 500, max_labels_count = 500)
timeframe = input.timeframe(defval = '240')
leftBars = input.int(defval = 2, title = "Left Bars", minval = 1)
rightBars = input.int(defval = 2, title = "Right Bars", minval = 1)
phlinecol = input.color(defval = color.lime, title = "Pivot High/Low Line Colors", inline = "lc")
pllinecol = input.color(defval = color.red, title = "", inline = "lc")
phbgcol = input.color(defval = color.lime, title = "Pivot High BG/Text Colors", inline = "ph")
phtextcol = input.color(defval = color.black, title = "", inline = "ph")
plbgcol = input.color(defval = color.red, title = "Pivot Low BG/Text Colors", inline = "pl")
pltextcol = input.color(defval = color.white, title = "", inline = "pl")
get_phpl()=>
float ph = ta.pivothigh(leftBars, rightBars)
float pl = ta.pivotlow(leftBars, rightBars)
phtimestart = ph ? time[rightBars] : na
phtimeend = ph ? time[rightBars - 1] : na
pltimestart = pl ? time[rightBars] : na
pltimeend = pl ? time[rightBars - 1] : na
[ph, phtimestart, phtimeend, pl, pltimestart, pltimeend]
// get if there if Pivot High/low and their start/end times
[ph, phtimestart, phtimeend, pl, pltimestart, pltimeend] = request.security(syminfo.tickerid, timeframe, get_phpl(), lookahead = barmerge.lookahead_on)
// keep time of each bars, this is used for lines/labels
var mytime = array.new_int(0)
array.unshift(mytime, time)
// calculate end of the line/time for pivot high/low
bhend = array.get(mytime, math.min(array.indexof(mytime, phtimeend) + 1, array.size(mytime) - 1))
blend = array.get(mytime, math.min(array.indexof(mytime, pltimeend) + 1, array.size(mytime) - 1))
// to draw once
float pivothigh = na(ph[1]) and ph ? ph : na
float pivotlow = na(pl[1]) and pl ? pl : na
width = (ta.highest(300) - ta.lowest(300)) / 50
if not na(pivothigh)
line.new(x1 = phtimestart, y1 = pivothigh, x2 = bhend, y2 = pivothigh, color = phlinecol, xloc = xloc.bar_time, width = 2)
line.new(x1 = phtimestart, y1 = pivothigh, x2 = phtimestart, y2 = pivothigh + width, color = phlinecol, xloc = xloc.bar_time, width = 2)
line.new(x1 = bhend, y1 = pivothigh, x2 = bhend, y2 = pivothigh + width, color = phlinecol, xloc = xloc.bar_time, width = 2)
label.new(x = (phtimestart + bhend) / 2, y = pivothigh + width,
text = str.tostring(math.round_to_mintick(pivothigh)),
color = phbgcol,
textcolor = phtextcol,
xloc = xloc.bar_time)
if not na(pivotlow)
line.new(x1 = pltimestart, y1 = pivotlow, x2 = blend, y2 = pivotlow, color = pllinecol, xloc = xloc.bar_time, width = 2)
line.new(x1 = pltimestart, y1 = pivotlow, x2 = pltimestart, y2 = pivotlow - width, color = pllinecol, xloc = xloc.bar_time, width = 2)
line.new(x1 = blend, y1 = pivotlow, x2 = blend, y2 = pivotlow - width, color = pllinecol, xloc = xloc.bar_time, width = 2)
label.new(x = (pltimestart + blend) / 2, y = pivotlow - width,
text = str.tostring(math.round_to_mintick(pivotlow)),
color = plbgcol,
textcolor = pltextcol,
style = label.style_label_up,
xloc = xloc.bar_time)
|
MACD Strategy Alert | https://www.tradingview.com/script/qm95kxYh-MACD-Strategy-Alert/ | Nick_M | https://www.tradingview.com/u/Nick_M/ | 115 | 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/
// Β© Nick_M
//@version=5
indicator("MACD Strategy Alert","MACD Entry Alert",overlay =true)
//EMA indicator
len = input.int(200, minval=1, title="Length",group="EMA SETTING")
src = input(close, title="Source")
offset = input.int(title="Offset", defval=0, minval=-500, maxval=500)
out = ta.ema(src, len)
EmaColor = input(#2962FF,"EMA βββββ",group="Color Settings",inline="Above")
plot(out, title="EMA", color=EmaColor, offset=offset)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
typeMA = input.string(title = "Method", defval = "SMA", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MACD",tooltip = "add MACD Indicator to your chart")
smoothingLength = input.int(title = "Length", defval = 5, minval = 1, maxval = 100, group="MACD")
smoothingLine = ma(out, smoothingLength, typeMA)
//plot(smoothingLine, title="Smoothing Line", color=#f37f20, offset=offset)
xUp = ta.crossover ( open, out)
xDn = ta.crossunder(open, out)
//plotchar(xUp, "Go Long", "β²", location.bottom, color.lime, size = size.tiny)
//plotchar(xDn, "Go Short", "βΌ", location.top, color.red, size = size.tiny)
// MACD Indicator
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
srcM = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Plot colors
col_macd = input(#2962FF, "MACD Lineββ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Lineββ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Aboveβββ
Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "BelowβGrow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
Col_Buy_signal = input(#26A69A, "Buy signalβββ
ββ
", group="Color Settings", inline="Below")
Col_Sell_signal = input(#FF5252, "ββ
Sell signal", group="Color Settings", inline="Above")
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
//plot(macd, title="MACD", color=col_macd)
//plot(signal, title="Signal", color=col_signal)
MACDB = ta.crossover (macd, signal)
MACDS = ta.crossunder (macd, signal)
//Open long position
Buy = if open > out and close > out and signal < 0 and macd < 0 and MACDB
1
plotchar(Buy , "Go Long", "β²", location.belowbar, color= Col_Buy_signal, size = size.tiny, text = "Buy", textcolor =Col_Buy_signal)
//strategy.entry("long", strategy.long, 0.01, when = Buy == 1)
//strategy.exit("exit", "long", profit = 1500, loss = 1000)
//plotchar(x , "Go Long", "β²", location.abovebar, color.purple, size = size.tiny)
//alertcondition(Buy or Sell, title='Alert buy', message='Potencial buy')
//Open Short position
Sell = if open < out and close < out and signal > 0 and macd > 0 and MACDS
1
plotchar(Sell , "Go Short", "βΌ", location.abovebar, color= Col_Sell_signal, size = size.tiny, text = "Sell", textcolor =Col_Sell_signal)
alertcondition(Sell or Buy, title='Alert Entry', message='Potential Entry')
//strategy.entry("Short", strategy.short, 0.001, when = Sell == 1)
//strategy.exit("exit", "Short", profit = 1500, loss = 1000)
//plotchar(y , "Go Short", "βΌ", location.top, color.yellow, size = size.tiny)
//plotchar(MACDD , "Go Long", "β²", location.bottom, color.blue, size = size.tiny)
//plotchar(MACDSD , "Go Short", "βΌ", location.top, color.yellow, size = size.tiny)
|
Portfolio Summary | https://www.tradingview.com/script/kULSSOoZ-Portfolio-Summary/ | morzor61 | https://www.tradingview.com/u/morzor61/ | 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/
// Β© morzor61
// Other Works ------------------------------------------------------------------{
// Portfolio
// Portfolio Matrix, https://www.tradingview.com/script/agCQIVZJ-Portfolio-alpha-beta-stdev-variance-mean-max-drawdown/
// https://www.tradingview.com/script/GxQp712Z-Portfolio-Laboratory-Kioseff-Trading/
// Strategy
// https://www.tradingview.com/script/V7IfK3mr-Trailing-Take-Profit-Trailing-Stop-Loss/
// Monthly Return by QuantNomad, https://www.tradingview.com/script/kzp8e4X3-Monthly-Returns-in-PineScript-Strategies/
// Position Size by , https://www.tradingview.com/script/hoCPm5UY-%D0%A1alculation-a-position-size-based-on-risk/
// Position Size, Kelly Method by , https://www.tradingview.com/script/bFXf4IXh-Built-in-Kelly-ratio-for-dynamic-position-sizing/
// Trailing Stop
// https://www.tradingview.com/script/EfbdipVs-Bjorgum-AutoTrail/
// Trail Stop Percent, https://www.tradingview.com/script/XAscppNW-Nick-Rypock-Trailing-Reverse-NRTR/
// https://www.tradingview.com/script/MvlwAzSg-3Commas-Bot/
// Super Trend, https://www.tradingview.com/script/VLWVV7tH-SuperTrend/
// }
// Functions ------------------------------------------------------------------{
// 1. Portfolio Holding List
// Fundamental anlysis and fair price <Future Plan>
// Alert based on financial performance. <Future Plan>
// 2. Stop Loss/Take Profit & Alert
// 3. Portfolio Analysis <Funture Plan>
// 4. Monthly/Yearly Return. <Future Plan>
// 5. Rebalancing <Future Plan>
// }
//@version=5
indicator("Portfolio", format=format.volume)
// FUNCTION START HERE ///////////////////////////////////////////////////////// {
// Get value based on tickerid
fGetValue(_tickerid, _value)=>
value = request.security(_tickerid, timeframe.period, _value, lookahead=barmerge.lookahead_on)
fGetPostion(isPositionActive, assetTicker,
entryDate, exitDate, shareQty,
costPriceType, costPriceManualInput,
stopLossMethod, stopLossInput,
takeProfitMethod, takeProfitInput,
atrLength)=>
// BOOL
bool isHoldingPeriod = time>=entryDate and time <=exitDate
bool isEntryDate = time>= entryDate
var arrayDividend = array.new_float()
// VARIABLE
float avgEntryPrice = ta.valuewhen(isEntryDate and not isEntryDate[1], fGetValue(assetTicker, close),0)
float costValue = na
float marketPrice = isHoldingPeriod ? fGetValue(assetTicker,close) : na
float marketValue = na, float marketValueWithDividend = na
float gainLossValue = na, float gainLossPercent = na
float dailyGainLossValue = na, float dialyGainLossPercent = na
float stopLossPrice = na, float expectedLossValue = na
float expectedGainValue = na
float takeProfitPrice = na
float atr = ta.valuewhen(isEntryDate and not isEntryDate[1], fGetValue(assetTicker, ta.atr(atrLength)),0)
float dvps = nz(request.dividends(assetTicker, dividends.gross, gaps=barmerge.gaps_on, ignore_invalid_symbol=true))
float dividend = na
// CONDITION
if isPositionActive and isHoldingPeriod
avgEntryPrice := costPriceType == "Auto" ? avgEntryPrice : costPriceManualInput
costValue := avgEntryPrice * shareQty
marketValue := marketPrice * shareQty
gainLossValue := (marketPrice - avgEntryPrice) * shareQty
gainLossPercent := (marketPrice - avgEntryPrice)/ avgEntryPrice *100
dailyGainLossValue := ((marketPrice-marketPrice[1])) * shareQty
dialyGainLossPercent := ((marketPrice/marketPrice[1])-1) * 100
stopLossPrice := stopLossMethod == "Price" ? stopLossInput :stopLossMethod == "Percent" ? avgEntryPrice * (1 - (stopLossInput/100)) : avgEntryPrice - (atr*stopLossInput)
takeProfitPrice := takeProfitMethod == "Price" ? takeProfitInput :takeProfitMethod == "Percent" ? avgEntryPrice * (1 + (takeProfitInput/100)) : avgEntryPrice + (atr*takeProfitInput)
expectedLossValue := (stopLossPrice - avgEntryPrice) * shareQty
expectedGainValue := (takeProfitPrice - avgEntryPrice) * shareQty
if dvps
array.push(arrayDividend, dvps * shareQty)
dividend := nz(array.sum(arrayDividend))
marketValueWithDividend := marketValue + nz(dividend)
else
avgEntryPrice := na, costValue := na
marketPrice := na, marketValue := na
marketValueWithDividend := na, gainLossValue := na
gainLossPercent := na, dailyGainLossValue := na
dialyGainLossPercent := na, stopLossPrice := na
takeProfitPrice := na, expectedLossValue := na
expectedGainValue := na, dividend := na
// RETURN
[avgEntryPrice,costValue, marketPrice, marketValue, marketValueWithDividend, gainLossValue, gainLossPercent, dailyGainLossValue, dialyGainLossPercent, stopLossPrice, expectedLossValue, takeProfitPrice, expectedGainValue, dividend]
// } END OF FUNCTION
// GROUP START HERE //////////////////////////////////////////////////////////// {
group01 = "====================== Position 01 ======================"
group02 = "====================== Position 02 ======================"
group03 = "====================== Position 03 ======================"
group04 = "====================== Position 04 ======================"
group05 = "====================== Position 05 ======================"
group06 = "====================== Position 06 ======================"
group07 = "====================== Position 07 ======================"
group08 = "====================== Position 08 ======================"
group09 = "====================== Position 09 ======================"
group10 = "====================== Position 10 ======================"
// } END OF GROUP
// General Set-up //////////////////////////////////////////////////////////////
initialCapital = input.int(100000, "Initial Capital")
initialIndex = input.int(100, "Initial Index")
plotType = input.string("Index", "Plot Type",
options =["Index", "Value", "Ticker 01", "Ticker 02","Ticker 03","Ticker 04","Ticker 05","Ticker 06","Ticker 07","Ticker 08","Ticker 09","Ticker 10"])
// INPUT START HERE //////////////////////////////////////////////////////////// {
// 1 Toggle on/off ------------------------------------------------------------
isPositionActive01 = input.bool(true, "", inline="1-1", group=group01)
isPositionActive02 = input.bool(false, "", inline="1-1", group=group02)
isPositionActive03 = input.bool(false, "", inline="1-1", group=group03)
isPositionActive04 = input.bool(false, "", inline="1-1", group=group04)
isPositionActive05 = input.bool(false, "", inline="1-1", group=group05)
isPositionActive06 = input.bool(false, "", inline="1-1", group=group06)
isPositionActive07 = input.bool(false, "", inline="1-1", group=group07)
isPositionActive08 = input.bool(false, "", inline="1-1", group=group08)
isPositionActive09 = input.bool(false, "", inline="1-1", group=group09)
isPositionActive10 = input.bool(false, "", inline="1-1", group=group10)
// 2 Asset Ticker ID ----------------------------------------------------------
assetTicker01 = input.symbol("FB", "Position 1", inline="1-1",group=group01)
assetTicker02 = input.symbol("FB", "Position 2", inline="1-1",group=group02)
assetTicker03 = input.symbol("FB", "Position 3", inline="1-1",group=group03)
assetTicker04 = input.symbol("FB", "Position 4", inline="1-1",group=group04)
assetTicker05 = input.symbol("FB", "Position 5", inline="1-1",group=group05)
assetTicker06 = input.symbol("FB", "Position 6", inline="1-1",group=group06)
assetTicker07 = input.symbol("FB", "Position 7", inline="1-1",group=group07)
assetTicker08 = input.symbol("FB", "Position 8", inline="1-1",group=group08)
assetTicker09 = input.symbol("FB", "Position 9", inline="1-1",group=group09)
assetTicker10 = input.symbol("FB", "Position 10", inline="1-1",group=group10)
// 3 Share Quantity ----------------------------------------------------------
shareQty01 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group01)
shareQty02 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group02)
shareQty03 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group03)
shareQty04 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group04)
shareQty05 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group05)
shareQty06 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group06)
shareQty07 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group07)
shareQty08 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group08)
shareQty09 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group09)
shareQty10 = input.float(100, "Quantity", minval=0.0, step=100, inline="1-1", group=group10)
// 4 Price -------------------------------------------------------------------
toolTipForCostPriceManualInput ="Auto : Avg Cost Price based on Entry Date. \n Manual : Fill the entry price"
costPriceType01 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group01)
costPriceType02 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group02)
costPriceType03 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group03)
costPriceType04 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group04)
costPriceType05 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group05)
costPriceType06 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group06)
costPriceType07 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group07)
costPriceType08 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group08)
costPriceType09 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group09)
costPriceType10 = input.string("Auto", "Avg Cost Price", options =["Auto", "Manual"], inline="cost price", group=group10)
costPriceManualInput01 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group01)
costPriceManualInput02 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group02)
costPriceManualInput03 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group03)
costPriceManualInput04 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group04)
costPriceManualInput05 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group05)
costPriceManualInput06 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group06)
costPriceManualInput07 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group07)
costPriceManualInput08 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group08)
costPriceManualInput09 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group09)
costPriceManualInput10 = input.float(0.0, "", minval=0.0, step=0.01, tooltip = toolTipForCostPriceManualInput, inline="cost price", group=group10)
// 5 Entry and Exit Date -----------------------------------------------------
entryDate01 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group01)
entryDate02 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group02)
entryDate03 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group03)
entryDate04 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group04)
entryDate05 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group05)
entryDate06 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group06)
entryDate07 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group07)
entryDate08 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group08)
entryDate09 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group09)
entryDate10 = input.time(timestamp("01 Jan 2020"), "Entry Date", group=group10)
exitDate01 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group01)
exitDate02 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group02)
exitDate03 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group03)
exitDate04 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group04)
exitDate05 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group05)
exitDate06 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group06)
exitDate07 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group07)
exitDate08 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group08)
exitDate09 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group09)
exitDate10 = input.time(timestamp("31 Dec 2099"), "Exit Date", group=group10)
// 6 Stop Loss & Take Profit
LineForStopLoss = "In Stop Loss Line",
LineForTakeProfit = "In Take Profit Line",
tooltipForStopLossTakeProfit ="Price : 0.00. \n Percent : 0-100%. \n ATR : Atr Multiplier 0.00 "
// 6.1 Stop Loss
stopLossMethod01 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group01)
stopLossMethod02 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group02)
stopLossMethod03 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group03)
stopLossMethod04 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group04)
stopLossMethod05 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group05)
stopLossMethod06 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group06)
stopLossMethod07 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group07)
stopLossMethod08 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group08)
stopLossMethod09 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group09)
stopLossMethod10 = input.string( "Percent", "S/L Method", options =["Percent","Price","ATR"], inline=LineForStopLoss, group=group10)
stopLossInput01 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group01)
stopLossInput02 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group02)
stopLossInput03 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group03)
stopLossInput04 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group04)
stopLossInput05 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group05)
stopLossInput06 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group06)
stopLossInput07 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group07)
stopLossInput08 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group08)
stopLossInput09 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group09)
stopLossInput10 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForStopLoss, group=group10)
// 6.2 Take Profit
takeProfitMethod01 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group01)
takeProfitMethod02 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group02)
takeProfitMethod03 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group03)
takeProfitMethod04 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group04)
takeProfitMethod05 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group05)
takeProfitMethod06 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group06)
takeProfitMethod07 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group07)
takeProfitMethod08 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group08)
takeProfitMethod09 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group09)
takeProfitMethod10 = input.string( "Percent", "T/P Method", options =["Percent","Price","ATR"],inline=LineForTakeProfit, group=group10)
takeProfitInput01 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group01)
takeProfitInput02 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group02)
takeProfitInput03 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group03)
takeProfitInput04 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group04)
takeProfitInput05 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group05)
takeProfitInput06 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group06)
takeProfitInput07 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group07)
takeProfitInput08 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group08)
takeProfitInput09 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group09)
takeProfitInput10 = input.float( 0.0, "", minval=0, tooltip = tooltipForStopLossTakeProfit, inline=LineForTakeProfit, group=group10)
atrLength01 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group01)
atrLength02 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group02)
atrLength03 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group03)
atrLength04 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group04)
atrLength05 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group05)
atrLength06 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group06)
atrLength07 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group07)
atrLength08 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group08)
atrLength09 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group09)
atrLength10 = input.int( 22, "ATR Length", minval=0, inline="ATR", group=group10)
// } END of INPUT
// CALCUATION START HERE /////////////////////////////////////////////////////// {
[avgEntryPrice01, costValue01, marketPrice01, marketValue01, marketValueWithDividend01,gainLossValue01, gainLossPercent01, dailyGainLossValue01, dialyGainLossPercent01, stopLossPrice01, expectedLossValue01, takeProfitPrice01, expectedGainValue01, dividend01] = fGetPostion(isPositionActive01, assetTicker01, entryDate01, exitDate01, shareQty01, costPriceType01, costPriceManualInput01, stopLossMethod01, stopLossInput01, takeProfitMethod01, takeProfitInput01, atrLength01)
[avgEntryPrice02, costValue02, marketPrice02, marketValue02, marketValueWithDividend02,gainLossValue02, gainLossPercent02, dailyGainLossValue02, dialyGainLossPercent02, stopLossPrice02, expectedLossValue02, takeProfitPrice02, expectedGainValue02, dividend02] = fGetPostion(isPositionActive02, assetTicker02, entryDate02, exitDate02, shareQty02, costPriceType02, costPriceManualInput02, stopLossMethod02, stopLossInput02, takeProfitMethod02, takeProfitInput02, atrLength02)
[avgEntryPrice03, costValue03, marketPrice03, marketValue03, marketValueWithDividend03,gainLossValue03, gainLossPercent03, dailyGainLossValue03, dialyGainLossPercent03, stopLossPrice03, expectedLossValue03, takeProfitPrice03, expectedGainValue03, dividend03] = fGetPostion(isPositionActive03, assetTicker03, entryDate03, exitDate03, shareQty03, costPriceType03, costPriceManualInput03, stopLossMethod03, stopLossInput03, takeProfitMethod03, takeProfitInput03, atrLength03)
[avgEntryPrice04, costValue04, marketPrice04, marketValue04, marketValueWithDividend04,gainLossValue04, gainLossPercent04, dailyGainLossValue04, dialyGainLossPercent04, stopLossPrice04, expectedLossValue04, takeProfitPrice04, expectedGainValue04, dividend04] = fGetPostion(isPositionActive04, assetTicker04, entryDate04, exitDate04, shareQty04, costPriceType04, costPriceManualInput04, stopLossMethod04, stopLossInput04, takeProfitMethod04, takeProfitInput04, atrLength04)
[avgEntryPrice05, costValue05, marketPrice05, marketValue05, marketValueWithDividend05,gainLossValue05, gainLossPercent05, dailyGainLossValue05, dialyGainLossPercent05, stopLossPrice05, expectedLossValue05, takeProfitPrice05, expectedGainValue05, dividend05] = fGetPostion(isPositionActive05, assetTicker05, entryDate05, exitDate05, shareQty05, costPriceType05, costPriceManualInput05, stopLossMethod05, stopLossInput05, takeProfitMethod05, takeProfitInput05, atrLength05)
[avgEntryPrice06, costValue06, marketPrice06, marketValue06, marketValueWithDividend06,gainLossValue06, gainLossPercent06, dailyGainLossValue06, dialyGainLossPercent06, stopLossPrice06, expectedLossValue06, takeProfitPrice06, expectedGainValue06, dividend06] = fGetPostion(isPositionActive06, assetTicker06, entryDate06, exitDate06, shareQty06, costPriceType06, costPriceManualInput06, stopLossMethod06, stopLossInput06, takeProfitMethod06, takeProfitInput06, atrLength06)
[avgEntryPrice07, costValue07, marketPrice07, marketValue07, marketValueWithDividend07,gainLossValue07, gainLossPercent07, dailyGainLossValue07, dialyGainLossPercent07, stopLossPrice07, expectedLossValue07, takeProfitPrice07, expectedGainValue07, dividend07] = fGetPostion(isPositionActive07, assetTicker07, entryDate07, exitDate07, shareQty07, costPriceType07, costPriceManualInput07, stopLossMethod07, stopLossInput07, takeProfitMethod07, takeProfitInput07, atrLength07)
[avgEntryPrice08, costValue08, marketPrice08, marketValue08, marketValueWithDividend08,gainLossValue08, gainLossPercent08, dailyGainLossValue08, dialyGainLossPercent08, stopLossPrice08, expectedLossValue08, takeProfitPrice08, expectedGainValue08, dividend08] = fGetPostion(isPositionActive08, assetTicker08, entryDate08, exitDate08, shareQty08, costPriceType08, costPriceManualInput08, stopLossMethod08, stopLossInput08, takeProfitMethod08, takeProfitInput08, atrLength08)
[avgEntryPrice09, costValue09, marketPrice09, marketValue09, marketValueWithDividend09,gainLossValue09, gainLossPercent09, dailyGainLossValue09, dialyGainLossPercent09, stopLossPrice09, expectedLossValue09, takeProfitPrice09, expectedGainValue09, dividend09] = fGetPostion(isPositionActive09, assetTicker09, entryDate09, exitDate09, shareQty09, costPriceType09, costPriceManualInput09, stopLossMethod09, stopLossInput09, takeProfitMethod09, takeProfitInput09, atrLength09)
[avgEntryPrice10, costValue10, marketPrice10, marketValue10, marketValueWithDividend10,gainLossValue10, gainLossPercent10, dailyGainLossValue10, dialyGainLossPercent10, stopLossPrice10, expectedLossValue10, takeProfitPrice10, expectedGainValue10, dividend10] = fGetPostion(isPositionActive10, assetTicker10, entryDate10, exitDate10, shareQty10, costPriceType10, costPriceManualInput10, stopLossMethod10, stopLossInput10, takeProfitMethod10, takeProfitInput10, atrLength10)
totalDividend =
nz(dividend01)+ nz(dividend02)+ nz(dividend03)+ nz(dividend04)+ nz(dividend05)+ nz(dividend06)+ nz(dividend07)+ nz(dividend08)+ nz(dividend09)+ nz(dividend10)
totalMarketValue =
nz(marketValue01)+ nz(marketValue02)+ nz(marketValue03)+ nz(marketValue04)+ nz(marketValue05)+ nz(marketValue06)+ nz(marketValue07)+ nz(marketValue08)+ nz(marketValue09)+ nz(marketValue10)
totalCostValue =
nz(costValue01)+ nz(costValue02)+ nz(costValue03)+ nz(costValue04)+ nz(costValue05)+ nz(costValue06)+ nz(costValue07)+ nz(costValue08)+ nz(costValue09)+ nz(costValue10)
totalDailyGainLossValue =
nz(dailyGainLossValue01)+ nz(dailyGainLossValue02)+ nz(dailyGainLossValue03)+ nz(dailyGainLossValue04)+ nz(dailyGainLossValue05)+ nz(dailyGainLossValue06)+ nz(dailyGainLossValue07)+ nz(dailyGainLossValue08)+ nz(dailyGainLossValue09)+ nz(dailyGainLossValue10)
totalGainLossValue =
nz(gainLossValue01)+ nz(gainLossValue02)+ nz(gainLossValue03)+ nz(gainLossValue04)+ nz(gainLossValue05)+ nz(gainLossValue06)+ nz(gainLossValue07)+ nz(gainLossValue08)+ nz(gainLossValue09)+ nz(gainLossValue10)
totalExpectedLoss =
nz(expectedLossValue01)+ nz(expectedLossValue02)+ nz(expectedLossValue03)+ nz(expectedLossValue04)+ nz(expectedLossValue05)+ nz(expectedLossValue06)+ nz(expectedLossValue07)+ nz(expectedLossValue08)+ nz(expectedLossValue09)+ nz(expectedLossValue10)
totalMarketValueWithDividend = totalMarketValue + totalDividend
index = totalMarketValue * initialIndex / totalCostValue
indexWithDividend = (totalMarketValue + totalDividend) * initialIndex / totalCostValue
// } END OF CALCULATION
// PLOT START HERE ///////////////////////////////////////////////////////////// {
float avgEntryPrice = na
float marketPrice = na
float stopLossPrice = na
float takeProfitPrice = na
if plotType == "Ticker 01"
avgEntryPrice := avgEntryPrice01
marketPrice := marketPrice01
stopLossPrice := stopLossPrice01
takeProfitPrice := takeProfitPrice01
else if plotType == "Ticker 02"
avgEntryPrice := avgEntryPrice02
marketPrice := marketPrice02
stopLossPrice := stopLossPrice02
takeProfitPrice := takeProfitPrice02
else if plotType == "Ticker 03"
avgEntryPrice := avgEntryPrice03
marketPrice := marketPrice03
stopLossPrice := stopLossPrice03
takeProfitPrice := takeProfitPrice03
else if plotType == "Ticker 04"
avgEntryPrice := avgEntryPrice04
marketPrice := marketPrice04
stopLossPrice := stopLossPrice04
takeProfitPrice := takeProfitPrice04
else if plotType == "Ticker 05"
avgEntryPrice := avgEntryPrice05
marketPrice := marketPrice05
stopLossPrice := stopLossPrice05
takeProfitPrice := takeProfitPrice05
else if plotType == "Ticker 06"
avgEntryPrice := avgEntryPrice06
marketPrice := marketPrice06
stopLossPrice := stopLossPrice06
takeProfitPrice := takeProfitPrice06
else if plotType == "Ticker 07"
avgEntryPrice := avgEntryPrice07
marketPrice := marketPrice07
stopLossPrice := stopLossPrice07
takeProfitPrice := takeProfitPrice07
else if plotType == "Ticker 08"
avgEntryPrice := avgEntryPrice08
marketPrice := marketPrice08
stopLossPrice := stopLossPrice08
takeProfitPrice := takeProfitPrice08
else if plotType == "Ticker 09"
avgEntryPrice := avgEntryPrice09
marketPrice := marketPrice09
stopLossPrice := stopLossPrice09
takeProfitPrice := takeProfitPrice09
else if plotType == "Ticker 10"
avgEntryPrice := avgEntryPrice10
marketPrice := marketPrice10
stopLossPrice := stopLossPrice10
takeProfitPrice := takeProfitPrice10
else
avgEntryPrice := na
marketPrice := na
stopLossPrice := na
takeProfitPrice := na
plot(plotType =="Value" ? totalDividend : na , "Total Dividend", color=color.lime, style=plot.style_stepline_diamond)
plot(plotType =="Value" ? totalCostValue : na , "Total Cost Value", color=color.gray)
plot(plotType =="Value" ? totalMarketValue : na , "Total Market Value", color=color.purple)
plot(plotType =="Value" ? totalMarketValueWithDividend : na , "Total Market Value with Dividend", color=color.blue)
plot(plotType == "Index" ? initialIndex : na, "Index", color=color.gray)
plot(plotType == "Index" ? index : na, "Index", color=color.lime)
plot(plotType == "Index" ? indexWithDividend : na, "Index w/ Dividend", color=color.blue)
plot(marketPrice , "Market Price" , color = color.blue)
plot(avgEntryPrice , "Avg Entry/Cost Price" , color = color.yellow)
plot(stopLossPrice , "Stop Loss Price" , color = color.red)
plot(takeProfitPrice , "Target Price" , color = color.green)
// } END OF PLOT
// ALERT START HERE //////////////////////////////////////////////////////////// {
fAlert(_tickerid, _costPrice, _mktPrice, _stopLossPrice, _takeProfitPrice)=>
cond1 = ta.crossunder( _mktPrice, _costPrice)
cond2 = ta.crossunder( _mktPrice, _stopLossPrice)
cond3 = ta.crossover( _mktPrice, _takeProfitPrice)
if cond1
alert("π‘ "+_tickerid + " has crossed under Cost Price" +"\n"+
"Current Price : " + str.tostring(_mktPrice ,"#,##0.00") +"\n"+
"Cost Price : " + str.tostring(_costPrice ,"#,##0.00") +"\n"+
"Stop Loss Price : " + str.tostring(_stopLossPrice ,"#,##0.00")
, alert.freq_once_per_bar)
else if cond2
alert("β "+_tickerid + " has crossed under Stop Loss Price" +"\n"+
"Current Price : " + str.tostring(_mktPrice ,"#,##0.00") +"\n"+
"Cost Price : " + str.tostring(_costPrice ,"#,##0.00") +"\n"+
"Stop Loss Price : " + str.tostring(_stopLossPrice ,"#,##0.00")
, alert.freq_once_per_bar)
else if cond3
alert("β
"+_tickerid + " has reached Target Price " +"\n"+
"Current Price : " + str.tostring(_mktPrice ,"#,##0.00") +"\n"+
"Cost Price : " + str.tostring(_costPrice ,"#,##0.00") +"\n"+
"Target Price : " + str.tostring(_takeProfitPrice ,"#,##0.00")
, alert.freq_once_per_bar)
fAlert(assetTicker01, avgEntryPrice01, marketPrice01, stopLossPrice01, takeProfitPrice01)
fAlert(assetTicker02, avgEntryPrice02, marketPrice02, stopLossPrice02, takeProfitPrice02)
fAlert(assetTicker03, avgEntryPrice03, marketPrice03, stopLossPrice03, takeProfitPrice03)
fAlert(assetTicker04, avgEntryPrice04, marketPrice04, stopLossPrice04, takeProfitPrice04)
fAlert(assetTicker05, avgEntryPrice05, marketPrice05, stopLossPrice05, takeProfitPrice05)
fAlert(assetTicker06, avgEntryPrice06, marketPrice06, stopLossPrice06, takeProfitPrice06)
fAlert(assetTicker07, avgEntryPrice07, marketPrice07, stopLossPrice07, takeProfitPrice07)
fAlert(assetTicker08, avgEntryPrice08, marketPrice08, stopLossPrice08, takeProfitPrice08)
fAlert(assetTicker09, avgEntryPrice09, marketPrice09, stopLossPrice09, takeProfitPrice09)
fAlert(assetTicker10, avgEntryPrice10, marketPrice10, stopLossPrice10, takeProfitPrice10)
// } End of Alert
// TABLE START HERE //////////////////////////////////////////////////////////// {
// Function for table ---------------------------------------------------------
fBgColor(_value)=>
green = color.new(color.green, 50)
red = color.new(color.red, 50)
yellow = color.new(color.yellow, 50)
var color bgColor = na
bgColor := _value > 0 ? green : _value < 0 ? red : yellow
// Table Customization --------------------------------------------------------
groupTable = "Table Customization"
isTableOn = input.bool(true, "Show Table?", group=groupTable)
tbTxtSizeOption = input.string("Normal", "Table Text Size", options =["Normal", "Small", "Tiny", "Auto", "Large"], group=groupTable)
tbXLocOption = input.string("Right", "Location", options = ["Left","Center","Right"], inline="Table Location", group=groupTable)
tbYLocOption = input.string("Bottom", "", options = ["Bottom","Middle","Top"], inline="Table Location", group=groupTable)
// Table Color -----------------------------------------------------------------
tbBgColor = input.color(color.white, "Color BG/Frame/Border", inline ="Table Color", group=groupTable)
tbFrameColor = input.color(color.black, "", inline ="Table Color", group=groupTable)
tbBorderColor = input.color(color.black, "", inline ="Table Color", group=groupTable)
// Header Row
tbHdTxtColor = input.color(color.white, "Header Color Text/BG", inline="Table Header", group=groupTable)
tbHdBgColor = input.color(color.purple, "", inline="Table Header",group=groupTable)
// Constant --------------------------------------------------------------------
tbX = switch tbXLocOption
"Right" => "right"
"Center" => "center"
=> "left"
tbY = switch tbYLocOption
"Bottom" => "bottom"
"Middle" => "middle"
=> "top"
tbLoc = tbY + "_" + tbX
tbTxtSize = switch tbTxtSizeOption
"Normal" => size.normal
"Small" => size.small
"Tiny" => size.tiny
"Auto" => size.auto
=> size.large
// Function
fTable(table _tableName, int _rowNumber, string _symbol, float _entryPrice, float _mktPrice, float _priceChangePcnt, float _dailyGainLoss, float _share, float _costVal, float _mktVal, float _cumDividend, float _totalCost, float _expectedLossValue, int _initialCapital)=>
GREEN = color.new(color.green, 50)
RED = color.new(color.red, 50)
YELLOW = color.new(color.yellow, 50)
unRealizedVal = 0.0
unRealizedVal := _mktVal - _costVal
unRealizedPcnt = 0.0
unRealizedPcnt := ((_mktVal - _costVal)/_costVal)*100
boughtWeight = 0.0
boughtWeight := _costVal / _totalCost *100
portWeight = 0.0
portWeight := _costVal / _initialCapital *100
gainLossSymbol = _mktPrice < _entryPrice ? "π»" : "π’"
table.cell(table_id = _tableName, column = 0 , row = _rowNumber, text = str.tostring(_rowNumber ), text_size = tbTxtSize)
table.cell(table_id = _tableName, column = 1 , row = _rowNumber, text = str.tostring(_symbol ), text_size = tbTxtSize)
table.cell(table_id = _tableName, column = 2 , row = _rowNumber, text = str.tostring(_share, "#,##0.00" ), text_size = tbTxtSize, text_halign = text.align_right)
table.cell(table_id = _tableName, column = 3 , row = _rowNumber, text = str.tostring(_entryPrice, "#,##0.00" ), text_size = tbTxtSize, text_halign = text.align_right)
table.cell(table_id = _tableName, column = 4 , row = _rowNumber, text = str.tostring(_mktPrice, "#,##0.00" ), text_size = tbTxtSize, text_halign = text.align_right)
table.cell(table_id = _tableName, column = 5 , row = _rowNumber, text = str.tostring(_priceChangePcnt, "#,##0.00" )+gainLossSymbol, text_size = tbTxtSize, text_halign = text.align_right, bgcolor=fBgColor(_priceChangePcnt))
table.cell(table_id = _tableName, column = 6 , row = _rowNumber, text = str.tostring(_dailyGainLoss, "#,##0" ), text_size = tbTxtSize, text_halign = text.align_right,bgcolor=fBgColor(_dailyGainLoss))
table.cell(table_id = _tableName, column = 7 , row = _rowNumber, text = str.tostring(_costVal, "#,##0" ), text_size = tbTxtSize, text_halign = text.align_right)
table.cell(table_id = _tableName, column = 8 , row = _rowNumber, text = str.tostring(_mktVal, "#,##0" ), text_size = tbTxtSize, text_halign = text.align_right)
table.cell(table_id = _tableName, column = 9 , row = _rowNumber,
text = str.tostring(unRealizedVal, "#,##0" ) + " (" +str.tostring(unRealizedPcnt, "#,##0.0" )+")",
text_size = tbTxtSize, text_halign = text.align_right, bgcolor = fBgColor(unRealizedVal))
table.cell(table_id = _tableName, column = 10, row = _rowNumber,
text = str.tostring(_cumDividend, "#,##0" ) + " (" + str.tostring(_cumDividend/_costVal*100, "#,##0")+"%" +")"
, text_size = tbTxtSize)
table.cell(table_id = _tableName, column = 11, row = _rowNumber, text = str.tostring(boughtWeight, "#,##0.0" ), text_size = tbTxtSize)
table.cell(table_id = _tableName, column = 12, row = _rowNumber,
text = str.tostring(_expectedLossValue, "#,###"), text_size = tbTxtSize)
table.cell(table_id = _tableName, column = 13, row = _rowNumber, text = str.tostring(portWeight, "#,##0.0" ), text_size = tbTxtSize, bgcolor = fBgColor(portWeight) ) // Unrealized %
// CREATE TABLE -------------------------------------------------------------------------
var tb = table(na)
if barstate.islast and isTableOn
tb := table.new(tbLoc, 15, 22 , bgcolor=tbBgColor, frame_color = tbFrameColor, frame_width=1, border_color = tbBorderColor, border_width=1)
table.cell(tb, 0, 0, "No" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 1, 0, "Symbol" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 2, 0, "Shares" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 3, 0, "Entry\n Price" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 4, 0, "Market\n Price" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 5, 0, "Change,\n %" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 6, 0, "Gain/\nLoss" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 7, 0, "Total\n Cost" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 8, 0, "Market\n Value" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 9, 0, "Unrealized\n Value (%)", text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 10, 0, "Cumulative \n Dividend", text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 11, 0, "% Total \nBuy" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 12, 0, "Expected \nLoss" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
table.cell(tb, 13, 0, "%Port" , text_size = tbTxtSize, text_color=tbHdTxtColor, bgcolor=tbHdBgColor)
fTable(tb, 01, assetTicker01, avgEntryPrice01, marketPrice01, dialyGainLossPercent01, dailyGainLossValue01, shareQty01, costValue01, marketValue01, dividend01, totalCostValue, expectedLossValue01, initialCapital)
fTable(tb, 02, assetTicker02, avgEntryPrice02, marketPrice02, dialyGainLossPercent02, dailyGainLossValue02, shareQty02, costValue02, marketValue02, dividend02, totalCostValue, expectedLossValue02, initialCapital)
fTable(tb, 03, assetTicker03, avgEntryPrice03, marketPrice03, dialyGainLossPercent03, dailyGainLossValue03, shareQty03, costValue03, marketValue03, dividend03, totalCostValue, expectedLossValue03, initialCapital)
fTable(tb, 04, assetTicker04, avgEntryPrice04, marketPrice04, dialyGainLossPercent04, dailyGainLossValue04, shareQty04, costValue04, marketValue04, dividend04, totalCostValue, expectedLossValue04, initialCapital)
fTable(tb, 05, assetTicker05, avgEntryPrice05, marketPrice05, dialyGainLossPercent05, dailyGainLossValue05, shareQty05, costValue05, marketValue05, dividend05, totalCostValue, expectedLossValue05, initialCapital)
fTable(tb, 06, assetTicker06, avgEntryPrice06, marketPrice06, dialyGainLossPercent06, dailyGainLossValue06, shareQty06, costValue06, marketValue06, dividend06, totalCostValue, expectedLossValue06, initialCapital)
fTable(tb, 07, assetTicker07, avgEntryPrice07, marketPrice07, dialyGainLossPercent07, dailyGainLossValue07, shareQty07, costValue07, marketValue07, dividend07, totalCostValue, expectedLossValue07, initialCapital)
fTable(tb, 08, assetTicker08, avgEntryPrice08, marketPrice08, dialyGainLossPercent08, dailyGainLossValue08, shareQty08, costValue08, marketValue08, dividend08, totalCostValue, expectedLossValue08, initialCapital)
fTable(tb, 09, assetTicker09, avgEntryPrice09, marketPrice09, dialyGainLossPercent09, dailyGainLossValue09, shareQty09, costValue09, marketValue09, dividend09, totalCostValue, expectedLossValue09, initialCapital)
fTable(tb, 10, assetTicker10, avgEntryPrice10, marketPrice10, dialyGainLossPercent10, dailyGainLossValue10, shareQty10, costValue10, marketValue10, dividend10, totalCostValue, expectedLossValue10, initialCapital)
table.cell(tb, 6, 21, str.tostring(totalDailyGainLossValue ,"#,##0"), text_size=tbTxtSize, bgcolor=fBgColor(totalGainLossValue))
table.cell(tb, 7, 21, str.tostring(totalCostValue ,"#,##0"), text_size=tbTxtSize)
table.cell(tb, 8, 21, str.tostring(totalMarketValue ,"#,##0"), text_size=tbTxtSize)
table.cell(tb, 9, 21, str.tostring(totalMarketValue-totalCostValue ,"#,##0") + " ("+str.tostring(((totalMarketValue/totalCostValue)-1)*100 , "#,##0.0")+"%"+")"
, text_size=tbTxtSize, bgcolor=fBgColor(totalMarketValue-totalCostValue))
table.cell(tb, 10, 21, str.tostring(totalDividend ,"#,##0")+"(" +str.tostring(totalDividend/totalCostValue*100, "#,##0")+")"
, text_size=tbTxtSize)
table.cell(tb, 12, 21, str.tostring(totalExpectedLoss ,"#,##0") + " ("+str.tostring(totalExpectedLoss/totalCostValue*100,"#,##0")+"%)"
, text_size=tbTxtSize)
table.cell(tb, 13, 21, str.tostring(totalCostValue/initialCapital*100 ,"#,##0"), text_size=tbTxtSize)
// } END OF TABLE
// LABEL AND LINE START HERE /////////////////////////////////////////////////// {
groupLabel = "Label Customization"
isLabelOn = input.bool(true, "Show label?", group=groupLabel)
lbColor = input.color(color.green, "Color BG/Text", inline="Label Color",group=groupLabel)
lbTxtColor = input.color(color.white, "", inline="Label Color",group=groupLabel)
lbTxtSizeOption = input.string("Normal", "Text Size", options =["Normal", "Small", "Tiny", "Auto", "Large"], group=groupLabel)
yValueAxis = (plotType == "Index" ? index : plotType == "Value" ? totalMarketValue : marketPrice)
lbTxtSize = switch lbTxtSizeOption
"Normal" => size.normal
"Small" => size.small
"Tiny" => size.tiny
"Large" => size.large
=> size.auto
fCreateLabel(string _id, bool _isOn, string _symbol, float _share, float _cost, int _entryDate, float _y)=>
int locationMultiplier = switch _id
"01" => 10
"02" => 20
"03" => 30
"04" => 40
"05" => 50
"06" => 60
"07" => 70
"08" => 80
"09" => 90
=> 100
yLoc = _y*(1+(locationMultiplier/100))
if _isOn and time >= _entryDate and not (time >= _entryDate)[1]
label.new(time, yLoc,
text = _id + " : " +_symbol + " : "
+"Share :" + str.tostring(_share, "#,##0") + " / "
+"Total Cost :" + str.tostring(_cost, "#,##0") ,
xloc =xloc.bar_time,
color =lbColor,
size =lbTxtSize,
style =label.style_label_right,
textcolor = lbTxtColor,
textalign = text.align_left)
if isLabelOn
fCreateLabel("01",isPositionActive01, assetTicker01, shareQty01, costValue01, entryDate01, yValueAxis)
fCreateLabel("02",isPositionActive02, assetTicker02, shareQty02, costValue02, entryDate02, yValueAxis)
fCreateLabel("03",isPositionActive03, assetTicker03, shareQty03, costValue03, entryDate03, yValueAxis)
fCreateLabel("04",isPositionActive04, assetTicker04, shareQty04, costValue04, entryDate04, yValueAxis)
fCreateLabel("05",isPositionActive05, assetTicker05, shareQty05, costValue05, entryDate05, yValueAxis)
fCreateLabel("06",isPositionActive06, assetTicker06, shareQty06, costValue06, entryDate06, yValueAxis)
fCreateLabel("07",isPositionActive07, assetTicker07, shareQty07, costValue07, entryDate07, yValueAxis)
fCreateLabel("08",isPositionActive08, assetTicker08, shareQty08, costValue08, entryDate08, yValueAxis)
fCreateLabel("09",isPositionActive09, assetTicker09, shareQty09, costValue09, entryDate09, yValueAxis)
fCreateLabel("10",isPositionActive10, assetTicker10, shareQty10, costValue10, entryDate10, yValueAxis)
// } END of LABEL
// FORTFOLIO ANALYSIS START HERE /////////////////////////////////////////////// {------------------------------------------------------------------
// } END of ANALYSIS |
% Price change (by OP) | https://www.tradingview.com/script/Z9LRLnNS-Price-change-by-OP/ | OrganicPunch | https://www.tradingview.com/u/OrganicPunch/ | 81 | 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/
// Β© OrganicPunch
//@version=5
indicator("% Price Change [OrganicPunch]", "% Price Change [OP]")
// To visually evaluate the % change in price between two candles
pc_ema_lenght = input.int(7, title="Price Change EMA", minval=1)
pc_display_toggle = input.bool(false, "Two-side display")
pc_price_increase = (close - close[1]) / close[1] * 100
pc_price_decrease = (close[1] - close) / close * 100
pc_price_up = close > close[1]
pc_price_change = pc_price_up ? pc_price_increase : pc_price_decrease
pc_price_change2 = pc_price_up ? pc_price_increase : -pc_price_decrease
pc_price_toggle = pc_display_toggle ? pc_price_change2 : pc_price_change
pc_color = pc_price_up ? color(color.green) : color(color.red)
pc_ema = ta.ema(pc_price_toggle, pc_ema_lenght)
plot(pc_price_toggle, "Price Change 1", pc_color, linewidth=2, style=plot.style_circles)
plot(pc_price_toggle, "Price Change 2", pc_color, linewidth=1, style=plot.style_histogram)
plot(pc_ema, "Price Change EMA", color.yellow)
hline(0, "Zero line", color(color.gray), linestyle=hline.style_solid)
|
Any Ribbon | https://www.tradingview.com/script/myAc2nNJ-Any-Ribbon/ | EltAlt | https://www.tradingview.com/u/EltAlt/ | 57 | 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/
// Β© EltAlt
//@version=5
// -----------------------------------------------------------------------------
//
// Authors: @EltAlt
// Revision: v1.00
// Date: 28-Apr-2022
//
// Description
// =============================================================================
// This indicator displays a ribbon of two individually configured Fast and Slow and Moving Averages for a fixed time frame. It also
// displays the last close price of the configured time frame, colored green when above the band, red below and blue when interacting.
// A label shows the percentage distance of the current price from the band, (again red below, green above, blue interacting), when
// the price is within the band it will show the percentage distance from median of the band.
//
// The Fast and Slow Moving Averages can be set to:
// Simple Moving Average (SMA)
// Exponential Moving Average (EMA)
// Weighted Moving Average (WMA)
// Volume-Weighted Moving Average (VWMA)
// Hull Moving Average (HMA)
// Exponentially Weighted Moving Average (RMA) (SMMA)
// Linear regression curve Moving Average (LSMA)
// Double EMA (DEMA)
// Double SMA (DSMA)
// Double WMA (DWMA)
// Double RMA (DRMA)
// Triple EMA (TEMA)
// Triple SMA (TSMA)
// Triple WMA (TWMA)
// Triple RMA (TRMA)
// Symmetrically Weighted Moving Average (SWMA) ** length does not apply **
// Arnaud Legoux Moving Average (ALMA)
// Variable Index Dynamic Average (VIDYA)
// Fractal Adaptive Moving Average (FRAMA)
//
// I wrote this script after identifying some interesting moving average bands with my AMACD indicator and wanting to see them on the
// price chart. As an example look at the interactions between ETHBUSD 4hr and the band of VIDYA 32 Open and VIDYA 39 Open. Or start
// from the good old BTC Bull market support band, Weekly EMA 21 and SMA 20 and see if you can get a better fit. I find the Double
// RMA 22 a better fast option than the standard EMA 21.
//
//
// =============================================================================
//
// I would gladly accept any suggestions to improve the script.
// If you encounter any problems please share them with me.
//
// Thanks to Smartcryptotrade for "MACD Alert [All MA in one] [Smart Crypto Trade (SCT)]" which gave me the initial starting point.
//
// Changlog
// =============================================================================
//
// 1.00 Initial release.
//
//
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
indicator(title='Any Ribbon',
shorttitle = 'Any Ribbon',
overlay = true)
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Inputs
timeframe = input.timeframe('W', "Timeframe")
FastType = input.string(title='Fast Moving Average Type', defval='EMA', options=['EMA', 'SMA', 'WMA', 'VWMA', 'HMA', 'RMA', 'LSMA', 'Double EMA', 'Double SMA', 'Double WMA', 'Double RMA', 'Triple EMA', 'Triple SMA', 'Triple WMA', 'Triple RMA', 'SWMA', 'ALMA', 'VIDYA', 'FRAMA'], group='Moving Averages')
FastSource = input(title='Fast Source', defval=close, inline='Fast', group='Moving Averages')
FastLength = input.int(title='Fast Length', minval=1, maxval=50, defval=21, inline='Fast', group='Moving Averages')
SlowType = input.string(title='Slow Moving Average Type', defval='SMA', options=['EMA', 'SMA', 'WMA', 'VWMA', 'HMA', 'RMA', 'LSMA', 'Double EMA', 'Double SMA', 'Double WMA', 'Double RMA', 'Triple EMA', 'Triple SMA', 'Triple WMA', 'Triple RMA', 'SWMA', 'ALMA', 'VIDYA', 'FRAMA'], group='Moving Averages')
SlowSource = input(title='Slow Source', defval=close, inline='Slow', group='Moving Averages')
SlowLength = input.int(title='Slow Length', minval=1, maxval=50, defval=20, inline='Slow', group='Moving Averages')
offset_alma = input(title='ALMA Offset', defval=0.85, inline='1', group='Alma')
sigma_alma = input.float(title='ALMA Sigma', defval=6, inline='1', group='Alma')
FC = input.int(1, minval=1, title='FRAMA lower shift limit (FC)', inline='1', group='Frama')
SC = input.int(198, minval=1, title='FRAMA upper shift limit (SC)', inline='1', group='Frama')
showBand = input.bool (true, "Show MA Band", inline = '1', group='Display Options')
showPrice = input.bool (true, "Show Close Price", inline = '1', group='Display Options')
showLabel = input.bool (true, "Show Label", inline = '1', group='Display Options')
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Functions
getCMO(src, length) =>
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), length)
downSum = math.sum(-math.min(mom, 0), length)
out = (upSum - downSum) / (upSum + downSum)
out
vidya(src, length) =>
alpha = 2 / (length + 1)
cmo = math.abs(getCMO(src, length))
vidya = 0.0
vidya := src * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
vidya
frama(x, y, z, v) =>
// x = source , y = length , z = FC , v = SC
HL = (ta.highest(high, y) - ta.lowest(low, y)) / y
HL1 = (ta.highest(high, y / 2) - ta.lowest(low, y / 2)) / (y / 2)
HL2 = (ta.highest(high, y / 2)[y / 2] - ta.lowest(low, y / 2)[y / 2]) / (y / 2)
D = (math.log(HL1 + HL2) - math.log(HL)) / math.log(2)
dim = HL1 > 0 and HL2 > 0 and HL > 0 ? D : nz(D[1])
w = math.log(2 / (v + 1))
alpha = math.exp(w * (dim - 1))
alpha1 = alpha > 1 ? 1 : alpha < 0.01 ? 0.01 : alpha
oldN = (2 - alpha1) / alpha1
newN = (v - z) * (oldN - 1) / (v - 1) + z
newalpha = 2 / (newN + 1)
newalpha1 = newalpha < 2 / (v + 1) ? 2 / (v + 1) : newalpha > 1 ? 1 : newalpha
frama = 0.0
frama := (1 - newalpha1) * nz(frama[1]) + newalpha1 * x
frama
calcMA(_type, _src, _length) =>
switch _type
'EMA' => ta.ema(_src, _length)
'SMA' => ta.sma(_src, _length)
'WMA' => ta.wma(_src, _length)
'VWMA' => ta.vwma(_src, _length)
'HMA' => ta.hma(_src, _length)
'RMA' => ta.rma(_src, _length)
'LSMA' => ta.linreg(_src, _length, 0)
'Double EMA' => 2 * ta.ema(_src, _length) - ta.ema(ta.ema(_src, _length), _length)
'Double SMA' => 2 * ta.sma(_src, _length) - ta.sma(ta.sma(_src, _length), _length)
'Double WMA' => 2 * ta.wma(_src, _length) - ta.wma(ta.wma(_src, _length), _length)
'Double RMA' => 2 * ta.rma(_src, _length) - ta.rma(ta.rma(_src, _length), _length)
'Triple EMA' => 3 * (ta.ema(_src, _length) - ta.ema(ta.ema(_src, _length), _length)) + ta.ema(ta.ema(ta.ema(_src, _length), _length), _length)
'Triple SMA' => 3 * (ta.sma(_src, _length) - ta.sma(ta.sma(_src, _length), _length)) + ta.sma(ta.sma(ta.sma(_src, _length), _length), _length)
'Triple WMA' => 3 * (ta.wma(_src, _length) - ta.wma(ta.wma(_src, _length), _length)) + ta.wma(ta.wma(ta.wma(_src, _length), _length), _length)
'Triple RMA' => 3 * (ta.rma(_src, _length) - ta.rma(ta.rma(_src, _length), _length)) + ta.rma(ta.rma(ta.rma(_src, _length), _length), _length)
'SWMA' => ta.swma(_src) // No Length for SWMA
'ALMA' => ta.alma(_src, _length, offset_alma, sigma_alma)
'VIDYA' => vidya(_src, _length)
'FRAMA' => frama(_src, _length, FC, SC)
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Calculations
FastCalc = calcMA(FastType, FastSource, FastLength)
SlowCalc = calcMA(SlowType, SlowSource, SlowLength)
MA_fast = request.security(syminfo.tickerid, timeframe, FastCalc)
MA_slow = request.security(syminfo.tickerid, timeframe, SlowCalc)
TFclose = request.security(syminfo.tickerid, timeframe, close)
TFhigh = request.security(syminfo.tickerid, timeframe, high)
TFlow = request.security(syminfo.tickerid, timeframe, low)
float delta = na
float deltaPct = na
stateColor = color.blue
string state = ''
if low > math.max (MA_fast, MA_slow)
delta := close - math.max (MA_fast, MA_slow)
deltaPct := delta / math.max (MA_fast, MA_slow) * 100
state := ' Above the \nMoving Average band'
stateColor := color.lime
else
if high < math.min (MA_fast, MA_slow)
delta := math.min (MA_fast, MA_slow) - close
deltaPct := delta / math.min (MA_fast, MA_slow) * 100
state := ' Below the \nMoving Average band'
stateColor := color.red
else
if close > math.avg (MA_fast, MA_slow)
delta := close - math.avg (MA_fast, MA_slow)
deltaPct := delta / math.avg (MA_fast, MA_slow) * 100
state := ' Above the \nBand Median'
stateColor := color.blue
else
delta := math.avg (MA_fast, MA_slow) - close
deltaPct := delta / math.avg (MA_fast, MA_slow) * 100
state := ' Below the \nBand Median'
stateColor := color.blue
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Plots
plot(showPrice ? TFclose: na, title='Price', linewidth=2, color = stateColor)
fastPlot = plot(showBand ? MA_fast: na, color=color.green, title="Fast Moving Average")
slowPlot = plot(showBand ? MA_slow: na, color=color.red, title="Slow Moving Average")
fill(fastPlot, slowPlot, color=color.new(color.orange, 75), fillgaps=true)
string stateText = "Price is currently \n" + str.tostring (deltaPct, format=format.percent) + state
currentState = showLabel ? label.new ( time +2, close, stateText, xloc.bar_time, yloc.price, stateColor, label.style_label_left, color.white, textalign = text.align_left ) : na
label.delete ( currentState[1])
|
[_ParkF]ResponsiveMA | https://www.tradingview.com/script/UG9NaUaR/ | ParkF | https://www.tradingview.com/u/ParkF/ | 62 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© ParkF
//@version=5
indicator("[_ParkF]ResponsiveMA", overlay=true)
// RESPONSIVE MA
// input
group1 = '_____MOVING AVERAGE'
src = input.source(close, 'Source', group=group1)
ma(source, length, type) =>
switch type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)
matype = input.string("SMA", title="MA Type", options=["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA TYPE")
group2 = '_____RESPONSIVE MOVING AVERAGE'
tf_5 = input(25, '5m MA Length', group=group2)
tf_15 = input(25, '15m MA Length', group=group2)
tf_30 = input(25, '30m MA Length', group=group2)
tf_60 = input(60, '1H MA Length', group=group2)
tf_240 = input(100, '4H MA Length', group=group2)
tf_480 = input(60, '8H MA Length', group=group2)
tf_D = input(100, '1D MA Length', group=group2)
tf_W = input(25, '1W MA Length', group=group2)
default = input(100, 'Default MA', group=group2)
// get tf
tf = timeframe.period
// tf func
tf_len1 = switch tf
"5" => tf_5
"15" => tf_15
"30" => tf_30
"60" => tf_60
"240" => tf_240
"480" => tf_480
"D" => tf_D
"W" => tf_W
=> default
// get ma
resp_ma = ma(src, tf_len1, matype)
// plot
plot(resp_ma, title='Responsive MA', style=plot.style_line, color=color.black, linewidth=2) |
StopLoss | https://www.tradingview.com/script/UJNRK9en/ | MrMagic09 | https://www.tradingview.com/u/MrMagic09/ | 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/
// Β© MrMagic09
//@version=5
indicator(title="StopLoss",shorttitle="SL+", overlay=true)
//hiding and showing lines
str=input.string("Low Risk",title="Multiplier",options=["Risk Lover","High Risk","Low Risk","Don't Risk"])
mult=str == "Don't Risk" ? 2.2 : str == "Low Risk" ? 1.7 : str == "High Risk" ? 1.3 : str == "Risk Lover" ? 0.9 : na
src=close
lenght=input(14,"Lenght")
atr=ta.atr(lenght)//getting atr values
ratio=atr/close*100*mult+40000
//getting maximum percentage of losing
longstoploss_level=open-atr*(mult)//determining the levels
shortstoploss_level=open+atr*(mult)// //manupilating mult by try and fail method
plot(ratio,display=display.none,color=color.lime)//plotting ratio
plot(longstoploss_level,title="Long StopLoss",linewidth=2,color=color.red,linewidth=1,style=plot.style_circles)//plotting long sl
plot(shortstoploss_level,title="Short StopLoss",linewidth=2,color=color.green,linewidth=1,style=plot.style_circles)//plotting short sl
bcolor= if high > shortstoploss_level or low < longstoploss_level
color.yellow
barcolor(bcolor,title="Fail Bars")
|
Level 1 - Learn to code simply - PineScript | https://www.tradingview.com/script/fVyxKpgf-Level-1-Learn-to-code-simply-PineScript/ | Maddrix_club | https://www.tradingview.com/u/Maddrix_club/ | 75 | 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/
// Β© Maddrix_club
//@version=4
// The goal of this script is honestly to help everyone learn about trading with bots and algos.
// First of all, you should know that the algo is constantly running, to make it simple, consider that each time a new bar appears, the algo is ran, from top to bottom.
// Every single line of code will be read by the computer, and it will do what you want it to do - it could be drawing something on the chart, it could be doing a calculation,
// it could be sending a signal, etc.
// if you wish to add comments, notes or reminders to your code, you simply add a double slash like so "//" at the beginning of the line. It will become gray and the computer won't read it.
// This specific script uses the version 4 of PineScript. This means the code is evoluting and improving. The latest version is Version 5, which I have not dove into yet.
// This is why I use version 4. You can see it on line 4. You should not change that. Same for lines 1 and 2. No need to touch anything.
study("Level 1 - Learn to code simply - PineScript", shorttitle="This one will appear on the setting dialog box", overlay=true)
// In version 4 you have 2 types of algo - the study and the strategy. The strategy allows you to use special functions that will simulate trading and backtest a specific strategy.
// I personally don't use strategies ever, because I can't see what is going on under the hood, I mean the calculation in detail.
// The other reason is that any strategy that shows great results, are usually only valid "on paper". Once you run it live on the exchange, there is slippage, fees, and all that
// stuff, which invalidates your strategy.
// on line 15 you can see that it says overlay=true, this means that the algo will be applied over the chart. If you wanted your indicator to be an oscillator for example, or
// simply not applied to the chart, you set it to "false" and it will show as a separate drawing below your chart.
// My recommendation is for you to copy/past this code, and change the settings one by one to see what they do and learn from that. This is how I learned all I know.
// Then once you save it and apply to your chart, the bottom windown of your screen will show all the coding errors in red. Only focus on the very first line that is in red
// and try to fix it. It will usually show you at which line number your code is having a problem. Sometimes it is just an easy typing error, sometimes it is harder
// and you have to google it.
// In this Level 1, we will simply call different functions that are built-in tradingview's database, we will plot them, we will create a condition for a signal and then
// we will create a signal.
// --------------- LET'S DO THIS ---------------------//
// --------- More classes on bot trading at ---------- //
// www.maddrix.club //
// Let's calculate the simple moving average of the price for the last 14 bars
SMA14 = sma(close,14)
// ------------ SMA14 in white is a variable that I just create just by typing it. Try to change the name if you want to call it differently.
// ------------ you can also create more variable if you want other SMA's
// ------------ if you hover your mouse over the "sma" in blue, you will see what the function required to work - sma(source, length). The 2 elements are separated by the comma.
// ------------ Basically it will automatically calculate the average "close" for the last "14" bars
// Let's now plot this sma on the chart so we can visually understand what it is
plot(SMA14, color=color.red, style=plot.style_linebr, transp=0, linewidth = 2)
// ------------ SMA14 is what we want to plot, so this is the first element we put, then we give it a color, and a style.
// ------------ We can also the transparency of the line, as well as its width
// Let's calculate the exponential moving average of the price for the last 14 bars
EMA14 = ema(close,14)
// ------------ Notice here, she blue "sma" became "ema"
// ------------ We are still calculating it based on the closing price "close" in red
// ------------ Notice also how I changed the name of the variable, from SMA14 to EMA14
// ------------ you cannot have 2 variables with the same name, or you cannot define/calculate two times the same variable
// Let's plot it as well, this time in green, and also much thicker
plot(EMA14, color=color.green, style=plot.style_linebr, transp=0, linewidth = 4)
// Alright so now we are going to create a condition which we will use to create ou alert
// Our first buy condition will be when the ema14 crosses over the sma14
first_condition = crossover(EMA14,SMA14)
// ------------ Here I create a new variable. Previously the 2 variables creates were going to be numbers with decimal, which means they are "Float" variables.
// ------------ This one though, is not a "float" variable, it will be a "boolean" variable, this means its value can only be TRUE or FALSE. It is like YES or NO, 0 or 1. Opened or Closed.
// ------------ I am using another built-in function which is "crossover". This functions requires 2 elements. In our case both Moving Averages.
// ------------ Herem the "first_condition" will be equal to "true" when EMA14 crosses over SMA14. Also note the underscore, because you can't have spaces within the name of a variable.
// Now that my condition is calculated, I want to show a little label on the chart, to see when that is true
plotshape( first_condition, title="Cross Over" , text="Long" , location=location.belowbar, style=shape.labelup , size=size.tiny, color=color.green, textcolor=color.white, transp=0)
// ------------ Same as with the regular plot, I need to indicate what I want to plotshape. Here it is "first_condition"
// ------------ You can see also that the plotshape function has several options that you can add/remove in order to adjust. If you remove them, they should appear with default settings.
// ------------ If you would like to see other options, you can hover over you mouth on the red part, for example "size.tiny", then hold "Ctrl" and click on it.
// Now, we are going to compare these signal with other ones. Let's create a second condition.
second_condition = crossover(close,EMA14)
// ------------ This time, we want the condition to be true when the closing price "Close" crosses over the EMA14
//Let's plot it as well
plotshape( second_condition, title="Cross Over #2" , text="Long #2" , location=location.belowbar, style=shape.labelup , size=size.tiny, color=color.lime, textcolor=color.red, transp=0)
// ------------ Notice how I changed the name as well as the text color and the color of the label
//Now that I have created my 2 signals, I would like to create 2 alerts for them
alertcondition(first_condition, title="buy #1", message="buy #1 signal!!!")
alertcondition(second_condition, title="buy #2", message="buy #2 signal!!!")
// ------------ Here I am using another function which is alertcondition. This will trigger an alert each time the condition is true
// ------------ This is the type of alert you can create and hook up to your 3commas bot platform for example
// In level 2, I will add more details, more options, more flexibility, how to add user input and show you other functions
// -------------------- END --------------------------//
// --------- More classes on bot trading at ---------- //
// www.maddrix.club //
|
Volatility Calculator for Daily Top and Bottom Range | https://www.tradingview.com/script/DNXywkVK-Volatility-Calculator-for-Daily-Top-and-Bottom-Range/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 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/
// Β© exlux99
//@version=5
indicator("Volatility Calculator", overlay=true)
atr_length = input.int(14)
atr_logic = ta.atr(atr_length)
atr_percent = atr_logic / close * 100
top_channel = close + (close*atr_percent)/100
bot_channel = close - (close*atr_percent)/100
// plot(top_channel)
// plot(bot_channel)
data_top_cross = ta.crossover(high, top_channel[1])
data_bot_cross = ta.crossunder(low, bot_channel[1])
// plotshape(data_top_cross, style=shape.xcross, location=location.abovebar)
// plotshape(data_bot_cross, style=shape.xcross, location=location.belowbar)
var int count_top_crosses = 0
var int count_bot_crosses = 0
if(data_top_cross)
count_top_crosses:=count_top_crosses+1
if(data_bot_cross)
count_bot_crosses:=count_bot_crosses+1
var int count_candles = 0
if(close!=0)
count_candles := count_candles+1
// plot(count_bot_crosses, color=color.red)
// plot(count_top_crosses, color=color.green)
//plot(count_candles, color=color.white)
ratio = (count_top_crosses + count_bot_crosses) / count_candles
////////////////////////////////////////////////////////////////////////////
posInput = input.string(title='Position', defval='Middle Right', options=['Bottom Left', 'Bottom Right', 'Top Left', 'Top Right', 'Middle Right'])
var pos = posInput == 'Bottom Left' ? position.bottom_left : posInput == 'Bottom Right' ? position.bottom_right : posInput == 'Top Left' ? position.top_left : posInput == 'Top Right' ? position.top_right : posInput == 'Middle Right' ? position.middle_right: na
var table table_atr = table.new(pos, 8, 8, border_width=3)
table_fillCell(_table, _column, _row, _value, _timeframe, _c_color) =>
_transp = 70
_cellText = str.tostring(_value, '#.###')
table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_c_color, _transp), text_color=_c_color, width=5)
table.cell_set_text_size(table_atr, 0, 0, size.normal)
table.cell_set_text_size(table_atr, 0, 1, size.normal)
table.cell_set_text_size(table_atr, 0, 2, size.normal)
table.cell_set_text_size(table_atr, 0, 3, size.normal)
table.cell_set_text_size(table_atr, 1, 0, size.normal)
table.cell_set_text_size(table_atr, 1, 1, size.normal)
table.cell_set_text_size(table_atr, 1, 2, size.normal)
table.cell_set_text_size(table_atr, 1, 3, size.normal)
table.cell_set_text_size(table_atr, 2, 0, size.normal)
table.cell_set_text_size(table_atr, 2, 1, size.normal)
table.cell_set_text_size(table_atr, 2, 2, size.normal)
table.cell_set_text_size(table_atr, 2, 3, size.normal)
//table.cell_set_text_size(table_atr, 0, 2, text)
if barstate.islast
table.cell(table_atr, 0, 0, 'TOP Crosses', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 0, 1, count_top_crosses, 'Text', color.white)
table.cell(table_atr, 1, 0, 'BOT Crosses', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 1, 1, count_bot_crosses, 'Text', color.white)
table.cell(table_atr, 2, 0, 'Total Candles', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 2, 1, count_candles, 'Text', color.white)
table.cell(table_atr, 3, 0, 'Occurance Ratio', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 3, 1, ratio, 'Text', color.white)
|
Supertrend Channels [LuxAlgo] | https://www.tradingview.com/script/ECSfVssE-Supertrend-Channels-LuxAlgo/ | LuxAlgo | https://www.tradingview.com/u/LuxAlgo/ | 3,857 | 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("Supertrend Channels [LuxAlgo]",overlay=true,max_lines_count=500)
length = input(14)
mult = input(2)
//------------------------------------------------------------------------------
upper = 0.,lower = 0.,os = 0,max = 0.,min = 0.
src = close
atr = ta.atr(length)*mult
up = hl2 + atr
dn = hl2 - atr
upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn
os := src > upper ? 1 : src < lower ? 0 : os[1]
spt = os == 1 ? lower : upper
max := ta.cross(src,spt) ? nz(math.max(max[1],src),src) :
os == 1 ? math.max(src,max[1]) :
math.min(spt,max[1])
min := ta.cross(src,spt) ? nz(math.min(min[1],src),src) :
os == 0 ? math.min(src,min[1]) :
math.max(spt,min[1])
avg = math.avg(max,min)
//------------------------------------------------------------------------------
var area_up_col = color.new(#0cb51a,80)
var area_dn_col = color.new(#ff1100,80)
plot0 = plot(max,'Upper Channel'
,max != max[1] and os == 1 ? na : #0cb51a)
plot1 = plot(avg,'Average'
,#ff5d00)
plot2 = plot(min,'Lower Channel'
,min != min[1] and os == 0 ? na : #ff1100)
fill(plot0,plot1,area_up_col,'Upper Area')
fill(plot1,plot2,area_dn_col,'Lower Area') |
COG SSMACD COL combo with ADX Filter [orion35] | https://www.tradingview.com/script/5YAuXlmm-COG-SSMACD-COL-combo-with-ADX-Filter-orion35/ | orion35 | https://www.tradingview.com/u/orion35/ | 245 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// by KIVANC using EHLERS' SUPER SMOOTHER FILTER, by alexgrover using Center Of Linearity & by KIVANC using Center of Gravity Oscillator
// Author : orion35
//@version=5
indicator('COG SSMACD COL combo with ADX Filter', 'COG, COL & SSMACD [orion35]', explicit_plot_zorder=true, max_labels_count=500)
brightBlue = #004EFF // double diamond condition down color
tip1 = 'If the COG, SSMACD signals are provided at the same time and the COL line supports it, a triple condition (β² βΌ) occurs.'
tip2 = 'The number of bars required to calculate the color intensity of the COL cloud.
\n\nNote: Default value is 500 but Fibonacci values such as 34, 55, 89, 144, 233, 377, 610 can be used.'
tip3 = 'COG : Center of Gravity
\nCOL : Center of Linearity
\nSSMACD : Super Smoothed MACD
\nH line : SSMACD Horizontal Line'
tip4 = '"Thold" is short for "threshold".
\n\nThe minimum threshold value for ADX is left at 20. When ADX filtering is enabled, signals are not displayed in ADX cases smaller than this threshold value.'
tip5 = '1st MA=3 and 2nd MA=5 are the orjinal length values by KIVANΓ ΓZBΔ°LGΔ°Γ.'
tip6 = 'Filtering Methods:
\n\nNormal: If the price is below the MavilimW line, "bull" signals are filtered out, and above "bear" signals are filtered out.
\n\nReverse : Applies the opposite of the normal method.'
tip7 = 'Filtering by :
\n\nclose : If the bar close is below the VMA line (line source = close), "bull" signals are filtered out, and above "bear" signals are filtered out.
\n\nCOG : If the COG line is below the VMA line (line source = COG), "bull" signals are filtered out, and above "bear" signals are filtered out.
\n\nSSMACD : If the SSMACD line is below the VMA line (line source = SSMACD), "bull" signals are filtered out, and above "bear" signals are filtered out.
\n\nCOG & SSMACD : If the COG and SSMACD lines are below the VMA lines (line sources = COG and SSMACD), "bull" signals are filtered out, and above "bear" signals are filtered out.'
showCOG = input.bool(true, 'COG', inline='1', group='SHOW / HIDE SETTINGS')
showSSMACD = input.bool(false, 'SSMACD', inline='1', group='SHOW / HIDE SETTINGS')
showCOL = input.bool(false, 'COL Area', inline='1', group='SHOW / HIDE SETTINGS')
showCOLline = input.bool(false, 'COL line', inline='1', group='SHOW / HIDE SETTINGS')
showhline = input.bool(false, 'H line', inline='1', group='SHOW / HIDE SETTINGS', tooltip=tip3)
showVMA = input.bool(true, 'Plot VMA Line', inline='1', group='Variable Moving Average, VMA')
calibrateCOG = input.float(0., 'Tune for COG', step=0.0001, inline='2', group='Variable Moving Average, VMA')
lenVMACOG = input.int(6, 'Len', minval=1, step=1, inline='2', group='Variable Moving Average, VMA')
vmaWidthCOG = input.int(2, 'Width', step=1, inline='2', group='Variable Moving Average, VMA')
calibrateSSMACD = input.float(0., 'Tune for SSMACD', step=0.0001, inline='33', group='Variable Moving Average, VMA')
lenVMASSMACD = input.int(6, 'Len', minval=1, step=1, inline='33', group='Variable Moving Average, VMA')
vmaWidthSSMACD = input.int(2, 'Width', step=1, inline='33', group='Variable Moving Average, VMA')
condVMAcol = input.bool(true, 'Conditional Color', inline='3', group='Variable Moving Average, VMA')
col1 = input.color(color.new(color.lime, 0), '', inline='3', group='Variable Moving Average, VMA')
col12 = input.color(color.new(#FF0000, 0), '', inline='3', group='Variable Moving Average, VMA')
col13 = input.color(color.new(color.gray, 0), '', inline='3', group='Variable Moving Average, VMA')
applyVMA_filter = input.bool(true, 'Apply VMA Filter', inline='4', group='Variable Moving Average, VMA')
source = input.string('COG', 'Filter Method', ['close', 'COG', 'SSMACD', 'COG & SSMACD'], inline='5', group='Variable Moving Average, VMA', tooltip=tip7)
applyADX = input.bool(false, 'Filter by ADX', inline='1', group='ADX SETTINGS')
adxlen = input.int(14, title="Smooth", inline='8', group='ADX SETTINGS')
dilen = input.int(14, title="DI Len", inline='8', group='ADX SETTINGS')
threshold = input.float(14.5, minval=0., maxval=80., step=0.5, title="Thold.", inline='8', group='ADX SETTINGS', tooltip=tip4)
applyMAVW = input.bool(false, 'Filter by Mavilim W', inline='81', group='Mavilim W SETTINGS')
filterType = input.string('Normal', title='Filter Method', options=['Normal', 'Reverse'], inline='812', group='Mavilim W SETTINGS', tooltip=tip6)
fmal=input.int(3,"1st MA len", minval=1, inline='82', group='Mavilim W SETTINGS')
smal=input.int(5,"2nd MA len", minval=1, inline='82', group='Mavilim W SETTINGS', tooltip=tip5)
lwCOG = input.int(1, 'COG Line Width', [1,2,3], inline='4', group='LINE WIDTH SETTINGS')
colCOG1 = input.color(color.new(brightBlue, 0), title='', inline='4', group='LINE WIDTH SETTINGS')
colCOG2 = input.color(color.new(color.white, 0), title='', inline='4', group='LINE WIDTH SETTINGS')
lwSSMACD = input.int(1, 'SSMACD Line Width', [1,2,3], inline='42', group='LINE WIDTH SETTINGS')
colSSMACD1 = input.color(color.new(color.blue, 0), title='', inline='42', group='LINE WIDTH SETTINGS')
colSSMACD2 = input.color(color.new(color.red, 0), title='', inline='42', group='LINE WIDTH SETTINGS')
colLw = input.int(9, 'COL Line Width', [5,6,7,8,9,10], inline='43', group='LINE WIDTH SETTINGS')
offsetCOL = input.float(5.49, minval=5., maxval=6., step=0.005, title="COL level.", inline='43', group='LINE WIDTH SETTINGS')
colCOL1 = input.color(#2196f3, title='', inline='43', group='LINE WIDTH SETTINGS')
colCOL2 = input.color(#f57f17, title='', inline='43', group='LINE WIDTH SETTINGS')
lengthCOG = input.int(10, 'COG Len', minval=1, inline='5', group='Length SETTINGS')
lengthCOL = input.int(14, 'COL Len', minval=1, inline='5', group='Length SETTINGS')
setCOL_color_len = input.int(377, 'COL Color Length', minval=2, inline='6', group='Length SETTINGS', tooltip=tip2)
len = input.int(8, minval=1, title='SSMACD Len 1', inline='7', group='Length SETTINGS')
len2 = input.int(13, minval=1, title='Len 2', inline='7', group='Length SETTINGS')
len3 = input.int(3, minval=1, title='Len 3', inline='7', group='Length SETTINGS')
single = input.bool(true, 'Single Signals, (x β)', inline='3', group='SIGNAL SETTINGS')
singleCol1 = input.color(color.new(color.white, 50), title='Bull', inline='31', group='SIGNAL SETTINGS')
singleCol2 = input.color(color.new(color.white, 50), title='Bear', inline='31', group='SIGNAL SETTINGS')
double = input.bool(true, 'Double Signals, (x β)', inline='32', group='SIGNAL SETTINGS')
doubleCol1 = input.color(color.new(color.yellow, 0), title='Bull', inline='33', group='SIGNAL SETTINGS')
doubleCol2 = input.color(color.new(color.yellow, 0), title='Bear', inline='33', group='SIGNAL SETTINGS')
triple = input.bool(true, 'Triple Signals, (β² βΌ)', inline='34', group='SIGNAL SETTINGS', tooltip=tip1)
tripleCol1 = input.color(color.new(brightBlue, 0), title='Bull', inline='35', group='SIGNAL SETTINGS')
tripleCol2 = input.color(color.new(brightBlue, 0), title='Bear', inline='35', group='SIGNAL SETTINGS')
//-------------------------------- VMA Filter ----------------------------
variant_variablema(src, len) =>
k = 1.0 / len
pdm = math.max((src - src[1]), 0)
mdm = math.max((src[1] - src), 0)
pdmS = 0.
mdmS = 0.
pdiS = 0.
mdiS = 0.
iS = 0.
vma = 0.
pdmS := ((1 - k)*nz(pdmS[1]) + k*pdm)
mdmS := ((1 - k)*nz(mdmS[1]) + k*mdm)
s = pdmS + mdmS
pdi = pdmS / s
mdi = mdmS / s
pdiS := ((1 - k)*nz(pdiS[1]) + k*pdi)
mdiS := ((1 - k)*nz(mdiS[1]) + k*mdi)
d = math.abs(pdiS - mdiS)
s1 = pdiS + mdiS
iS := ((1 - k)*nz(iS[1]) + k*d / s1)
hhv = ta.highest(iS, len)
llv = ta.lowest(iS, len)
d1 = hhv - llv
vI = (iS - llv) / d1
vma := (1 - k*vI)*nz(vma[1]) + k*vI*src
vma
//------------ from COL ----------------------------------------------------------
//----
aCOL = 0.
for i = 1 to lengthCOL by 1
aCOL += i * (close[lengthCOL - i] - close[i - 1])
aCOL
//----
plot(showCOL ? aCOL : na, 'COL', aCOL > 0 ? color.new(#2196f3, 0) : color.new(#f57f17, 0), style=plot.style_area)
//-------- Calculate COL Color Intensity ------------------------------------------------------------------------------
thickness = aCOL > 0 ? aCOL : math.abs(aCOL)
normalized_data = (thickness - ta.lowest(thickness, setCOL_color_len)) / (ta.highest(thickness, setCOL_color_len) - ta.lowest(thickness, setCOL_color_len))
scaled_data = normalized_data * (100 - 0) + 0
plot(showCOLline and not (showSSMACD or showCOL) ? offsetCOL : showCOLline and showSSMACD and not showCOL ? 0. : na, 'COL Line', color=aCOL > 0 ? color.new(colCOL1, 90 - scaled_data) : color.new(colCOL2, 90 - scaled_data), style=plot.style_linebr, linewidth=colLw)
//------------ from SSMACD ----------------------------------------------------------
p = close
f = 1.414 * 3.14159 / len
a = math.exp(-f)
c2 = 2 * a * math.cos(f)
c3 = -a * a
c1 = 1 - c2 - c3
ssmooth = 0.0
ssmooth := c1 * (p + p[1]) * 0.5 + c2 * nz(ssmooth[1]) + c3 * nz(ssmooth[2])
f2 = 1.414 * 3.14159 / len2
a2 = math.exp(-f2)
c22 = 2 * a2 * math.cos(f2)
c32 = -a2 * a2
c12 = 1 - c22 - c32
ssmooth2 = 0.0
ssmooth2 := c12 * (p + p[1]) * 0.5 + c22 * nz(ssmooth2[1]) + c32 * nz(ssmooth2[2])
// macd = (ssmooth - ssmooth2)*10000000
macd = ssmooth - ssmooth2
f3 = 1.414 * 3.14159 / len3
a3 = math.exp(-f3)
c23 = 2 * a3 * math.cos(f3)
c33 = -a3 * a3
c13 = 1 - c23 - c33
ssmooth3 = 0.0
ssmooth3 := c13 * (macd + macd[1]) * 0.5 + c23 * nz(ssmooth3[1]) + c33 * nz(ssmooth3[2])
// hline(50, linestyle=hline.style_dotted, title="Upper Threshold" )
hline(showSSMACD and showhline ? 0 : na, title='Center Line')
// hline(-50, linestyle=hline.style_dotted, title="Lower Threshold")
plot(showSSMACD ? macd : na, color=colSSMACD1, linewidth=lwSSMACD, title='MACD Line')
plot(showSSMACD ? ssmooth3 : na, color=colSSMACD2, linewidth=lwSSMACD, title='Super Smoothed Line')
bullSSMACD_sig = ta.crossover(macd, ssmooth3)
bearSSMACD_sig = ta.crossunder(macd, ssmooth3)
//------------ from COG ----------------------------------------------------------
num = ta.wma(close, lengthCOG) * lengthCOG * (lengthCOG + 1) / 2
den = math.sum(close, lengthCOG)
CG = num / den
plot(showCOG and not showSSMACD ? CG : na, 'COG Trigger', color=colCOG1, linewidth=lwCOG)
plot(showCOG and not showSSMACD ? CG[1] : na, 'COG Line', color=colCOG2, linewidth=lwCOG)
cgBear = ta.crossover(CG[1], CG)
cgBull = ta.crossunder(CG[1], CG)
//----------------------------- Variable Moving Average, VMA ----------------------------------------------------------------------------------------------------------------
vma_for_COG = variant_variablema(CG, lenVMACOG)*(1 + calibrateCOG)
vma_for_SSMACD = variant_variablema(macd, lenVMASSMACD)*(1 + calibrateSSMACD*1000)
vma_for_close = variant_variablema(close, lenVMACOG)*(1 + calibrateCOG)
vma_for_COG_col = vma_for_COG[1] < vma_for_COG ? col1 : vma_for_COG[1] > vma_for_COG and condVMAcol ? col12 : vma_for_COG[1] == vma_for_COG and condVMAcol ? col13 : col1
vma_for_SSMACD_col = vma_for_SSMACD[1] < vma_for_SSMACD ? col1 : vma_for_SSMACD[1] > vma_for_SSMACD and condVMAcol ? col12 : vma_for_SSMACD[1] == vma_for_SSMACD and condVMAcol ? col13 : col1
vma = showCOG and not showSSMACD and not showCOL ? vma_for_COG : showSSMACD ? vma_for_SSMACD : na
vma_col = showCOG and not showSSMACD and not showCOL ? vma_for_COG_col : showSSMACD ? vma_for_SSMACD_col : na
plot(showVMA ? vma : na, 'VMA', color=vma_col, linewidth=showCOG and not showSSMACD ? vmaWidthCOG : vmaWidthSSMACD)
vmaBullFilter = (vma_for_close < close and source == 'close' ? true : false) or (vma_for_COG < CG and source == 'COG' ? true : false) or (vma_for_SSMACD < macd and source == 'SSMACD' ? true : false)
or (vma_for_COG < CG and vma_for_SSMACD < macd and source == 'COG & SSMACD' ? true : false)
vmaBearFilter = (vma_for_close > close and source == 'close' ? true : false) or (vma_for_COG > CG and source == 'COG' ? true : false) or (vma_for_SSMACD > macd and source == 'SSMACD' ? true : false)
or (vma_for_COG > CG and vma_for_SSMACD > macd and source == 'COG & SSMACD' ? true : false)
//-------------- ADX Calculations -------------------------------------------------------------------------------------------------------------------------------------------
dirmov(len) =>
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / truerange)
minus = fixnan(100 * ta.rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
//-------------------------------- Mavilim W by KΔ±vanΓ§ ΓzbilgiΓ§ ----------------------------
tmal=fmal+smal
Fmal=smal+tmal
Ftmal=tmal+Fmal
Smal=Fmal+Ftmal
M1 = ta.wma(close, fmal)
M2 = ta.wma(M1, smal)
M3 = ta.wma(M2, tmal)
M4 = ta.wma(M3, Fmal)
M5 = ta.wma(M4, Ftmal)
MAVW = ta.wma(M5, Smal)
bearFilter = filterType == 'Normal' ? (close <= MAVW ? true : false) : (close <= MAVW ? false : true)
bullFilter = filterType == 'Normal' ? (close <= MAVW ? false : true) : (close <= MAVW ? true : false)
//-------------- Combined Conditions & Plots --------------------------
doubleBull = cgBull and bullSSMACD_sig and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bullFilter : true) and (applyVMA_filter ? vmaBullFilter : true)
doubleBear = cgBear and bearSSMACD_sig and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bearFilter : true) and (applyVMA_filter ? vmaBearFilter : true)
tripleBull = doubleBull and (aCOL <= 0) and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bullFilter : true) and (applyVMA_filter ? vmaBullFilter : true)
tripleBear = doubleBear and (aCOL > 0) and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bearFilter : true) and (applyVMA_filter ? vmaBearFilter : true)
singleCgBull = cgBull and not (tripleBull or doubleBull) and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bullFilter : true) and (applyVMA_filter ? vmaBullFilter : true)
singleCgBear = cgBear and not (tripleBear or doubleBear) and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bearFilter : true) and (applyVMA_filter ? vmaBearFilter : true)
singleSSMACDBull = bullSSMACD_sig and not (tripleBull or doubleBull) and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bullFilter : true) and (applyVMA_filter ? vmaBullFilter : true)
singleSSMACDBear = bearSSMACD_sig and not (tripleBear or doubleBear) and (applyADX ? (sig >= threshold) : true) and (applyMAVW ? bearFilter : true) and (applyVMA_filter ? vmaBearFilter : true)
colorBull = tripleBull ? tripleCol1 : doubleBull ? doubleCol1 : singleCgBull or singleSSMACDBull ? singleCol1 : na
colorBear = tripleBear ? tripleCol2 : doubleBear ? doubleCol2 : singleCgBear or singleSSMACDBear ? singleCol2 : na
plotshape(singleSSMACDBull and single, 'Single Bull SSMACD Signal', shape.xcross, location.bottom, colorBull, size=size.auto)
plotshape(singleSSMACDBear and single, 'Single Bear SSMACD Signal', shape.xcross, location.top, colorBear, size=size.auto)
plotshape(singleCgBull and single, 'Single Bull COG Signal', shape.circle, location.bottom, colorBull, size=size.auto)
plotshape(singleCgBear and single, 'Single Bear COG Signal', shape.circle, location.top, colorBear, size=size.auto)
plotshape(doubleBull and not tripleBull and double, 'Double Bull Signal', shape.circle, location.bottom, colorBull, size=size.auto)
plotshape(doubleBear and not tripleBear and double, 'Double Bear Signal', shape.circle, location.top, colorBear, size=size.auto)
plotshape(tripleBull and triple, 'Double Bull Signal', shape.triangleup, location.bottom, colorBull, size=size.auto)
plotshape(tripleBear and triple, 'Double Bear Signal', shape.triangledown, location.top, colorBear, size=size.auto)
// lenVMA
//------------------- ALERT CONDITIONS ----------------------------------------------------------------------------------------
alertcondition(tripleBull, '01 Triple Bull, β²', 'BULL Triple β² COG, COL & SSMACD, {{ticker}}, Price = {{close}}')
alertcondition(tripleBear, '02 Triple Bear, βΌ', 'BEAR Triple βΌ COG, COL & SSMACD, {{ticker}}, Price = {{close}}')
alertcondition(tripleBear or tripleBull, '03 Triple (any), β² βΌ', 'Any Triple β² βΌ COG, COL & SSMACD, {{ticker}}, Price = {{close}}')
alertcondition(doubleBull and not tripleBull, '04 Double Bull, β (yellow)', 'BULL Double (yellow β), COG & SSMACD, {{ticker}}, Price = {{close}}')
alertcondition(doubleBear and not tripleBear, '05 Double Bear, β (yellow)', 'BEAR Double (yellow β), COG & SSMACD, {{ticker}}, Price = {{close}}')
alertcondition((doubleBear and not tripleBear) or (doubleBull and not tripleBull), '06 Double (any), β (yellow)', 'Any Double (yellow β), COG & SSMACD, {{ticker}}, Price = {{close}}')
alertcondition(singleSSMACDBull, '07 Single SSMACD Bull, (white x)', 'BULL Single SSMACD (white x), {{ticker}}, Price = {{close}}')
alertcondition(singleSSMACDBear, '08 Single SSMACD Bear, (white x)', 'BEAR Single SSMACD (white x), {{ticker}}, Price = {{close}}')
alertcondition(singleCgBull, '09 Single COG Bull, (white β)', 'BULL Single COG (white β), {{ticker}}, Price = {{close}}')
alertcondition(singleCgBear, '10 Single COG Bear, (white β)', 'BEAR Single COG (white β), {{ticker}}, Price = {{close}}')
alertcondition(singleCgBull or singleSSMACDBull or doubleBull or tripleBull, '11 Any Bull Condition', 'BULL Any Condition, {{ticker}}, Price = {{close}}')
alertcondition(singleCgBear or singleSSMACDBear or doubleBear or tripleBear, '12 Any Bear Condition', 'BEAR Any Condition, {{ticker}}, Price = {{close}}')
|
wolfpack by multigrain | https://www.tradingview.com/script/plVm2gO8-wolfpack-by-multigrain/ | multigrain | https://www.tradingview.com/u/multigrain/ | 80 | 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/
// Β© multigrain
// @version=5
// _ __ _
// __ _____ | |/ _|_ __ __ _ ___| | __
// \ \ /\ / / _ \| | |_| '_ \ / _` |/ __| |/ /
// \ V V / (_) | | _| |_) | (_| | (__| <
// \_/\_/ \___/|_|_| | .__/ \__,_|\___|_|\_\
// |_|
indicator('wolfpack by multigrain', 'wolfpack')
// _ _
// (_)_ __ _ __ _ _| |_ ___
// | | '_ \| '_ \| | | | __/ __|
// | | | | | |_) | |_| | |_\__ \
// |_|_| |_| .__/ \__,_|\__|___/
// |_|
wp_group = 'WolfPack (Fast, Slow, Source)'
wp_show = input.bool (true, 'Show WolfPack?', inline='0', group=wp_group)
wp_fast = input.int (3, '', inline='1', group=wp_group)
wp_slow = input.int (8, '', inline='1', group=wp_group)
wp_src = input.source (close, '', inline='1', group=wp_group)
ema_group = 'Exponential Moving Average (Length)'
ema_show = input.bool (true, 'Show EMA?', inline='0', group=ema_group)
ema_len = input.int (13, '', inline='1', group=ema_group)
// __ _ _
// / _|_ _ _ __ ___| |_(_) ___ _ __ ___
// | |_| | | | '_ \ / __| __| |/ _ \| '_ \/ __|
// | _| |_| | | | | (__| |_| | (_) | | | \__ \
// |_| \__,_|_| |_|\___|\__|_|\___/|_| |_|___/
//
f_wolf(float src, int _fast, int _slow) =>
slow = ta.sma(src, _slow)
fast = ta.sma(src, _fast)
macdLine = fast - slow
sd_mac = ta.stdev(macdLine, 500)
basis_mac = ta.ema(macdLine, 500)
up_mac = basis_mac + sd_mac * 2
dn_mac = basis_mac - sd_mac * 2
rescaled_mac = ((macdLine - dn_mac) / (up_mac - dn_mac) * 50) - 25
wp = f_wolf(wp_src, wp_fast, wp_slow)
wp_jma = ta.ema(wp, ema_len)
// _
// ___ ___ | | ___ _ __ ___
// / __/ _ \| |/ _ \| '__/ __|
// | (_| (_) | | (_) | | \__ \
// \___\___/|_|\___/|_| |___/
//
green = color.new(#00CB65, 000)
red = color.new(#F05D5E, 000)
yellow = color.new(#F4D03F, 000)
grey = color.new(#939FA6, 000)
blue = color.new(#3980BC, 000)
bull_color = color.new(blue, 80 )
bear_color = color.new(red, 80 )
wp_color = wp > wp_jma and ta.falling(wp, 1) ? yellow : wp < wp_jma and ta.rising(wp, 1) ? green : grey
wp_ema_color = wp > wp_jma ? blue : red
wp_fill_color = wp > wp_jma ? bull_color : bear_color
// _ _
// _ __ | | ___ | |_ ___
// | '_ \| |/ _ \| __/ __|
// | |_) | | (_) | |_\__ \
// | .__/|_|\___/ \__|___/
// |_|
hline(0)
wp_plot = plot (wp, 'WolfPack', wp_color, 1)
wp_ema_plot = plot (wp_jma, 'WolfPack EMA', wp_ema_color, 1)
fill (wp_plot, wp_ema_plot, wp_fill_color)
// _ _ _ _ _
// | |__ _ _ _ __ ___ _ _| | |_(_) __ _ _ __ __ _(_)_ __
// | '_ \| | | | | '_ ` _ \| | | | | __| |/ _` | '__/ _` | | '_ \
// | |_) | |_| | | | | | | | |_| | | |_| | (_| | | | (_| | | | | |
// |_.__/ \__, | |_| |_| |_|\__,_|_|\__|_|\__, |_| \__,_|_|_| |_|
// |___/ |___/ |
EMA of RSI | https://www.tradingview.com/script/dgMenKJi-EMA-of-RSI/ | sarah20 | https://www.tradingview.com/u/sarah20/ | 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/
// Β© sarah20
//@version=5
indicator("Ema of rsi", overlay=false)
rsi_input = input(title="rsi length", defval=14)
rsiema_input = input(title="ema length", defval=14)
rsi_data = ta.rsi(open, rsi_input)
rsiema_data = ta.ema(rsi_data, rsiema_input)
indicator = rsi_data - rsiema_data
plot(0)
colors = indicator > 0 ? color.green:color.red
plot(indicator, "Ema of Rsi", color=color.new(colors, 0))
|
Hull Volume Waves | https://www.tradingview.com/script/hvwTWg2U-Hull-Volume-Waves/ | FractalTrade15 | https://www.tradingview.com/u/FractalTrade15/ | 307 | 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/
// Β© FractalTrade15
//@version=5
indicator("Hull Volume Waves", format = format.volume)
//Pro Advance/Decline Gradient
f_c_gradientAdvDecPro(_source, _center, _steps, _c_bearWeak, _c_bearStrong, _c_bullWeak, _c_bullStrong) =>
var float _qtyAdvDec = 0.
var float _maxSteps = math.max(1, _steps)
bool _xUp = ta.crossover(_source, _center)
bool _xDn = ta.crossunder(_source, _center)
float _chg = ta.change(_source)
bool _up = _chg > 0
bool _dn = _chg < 0
bool _srcBull = _source > _center
bool _srcBear = _source < _center
_qtyAdvDec := _srcBull ? _xUp ? 1 : _up ? math.min(_maxSteps, _qtyAdvDec + 1) : _dn ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _srcBear ? _xDn ? 1 : _dn ? math.min(_maxSteps, _qtyAdvDec + 1) : _up ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _qtyAdvDec
var color _return = na
_return := _srcBull ? color.from_gradient(_qtyAdvDec, 1, _maxSteps, _c_bullWeak, _c_bullStrong) : _srcBear ? color.from_gradient(_qtyAdvDec, 1, _maxSteps, _c_bearWeak, _c_bearStrong) : _return
_return
hlen = input(10, title = "Hull Length")
hsrc = input(close, title = "Hull Source")
gsteps = input(10, title = "Gradient Steps")
mlb = input(50, title = "Lookback for Highs")
bullc1 = input(color.blue, title = "Strong Bullish Color")
bullc2 = input(color.navy, title = "Weak Bullish Color")
bearc1 = input(color.fuchsia, title = "Strong Bearish Color")
bearc2 = input(color.purple, title = "Weak Bearish Color")
hull = ta.hma(hsrc,hlen)
mhull = hull[0]
shull = hull[2]
//Wave Calulation
var float uvol = 0
if mhull > shull
uvol := volume+uvol[1]
else
uvol := 0
var float dvol = 0
if mhull <= shull
dvol := volume+dvol[1]
else
dvol := 0
//Highest Bullish & Bearish Waves
float downvol = 0
for i = 1 to mlb by 1
if dvol[i] > downvol
downvol := dvol[i]
downvol
float upvol = 0
for i = 1 to mlb by 1
if uvol[i] > upvol
upvol := uvol[i]
upvol
huv = ta.highest(upvol, mlb)
hdv = ta.highest(downvol,mlb)
bcol = uvol > huv[1]? color.new(bullc1,90) : dvol > hdv[1]? color.new(bearc1, 90) : na
hvol = mhull > shull ? uvol : -dvol
gcol = f_c_gradientAdvDecPro(hvol, 0, gsteps, bearc2,bearc1, bullc2, bullc1)
hvolplus = mhull > shull ? uvol : dvol
plot(hvolplus, color = gcol, style=plot.style_columns)
bgcolor(bcol) |
SSL Channel [MoonKoder] | https://www.tradingview.com/script/fd5AxtmP-SSL-Channel-MoonKoder/ | MoonKoder | https://www.tradingview.com/u/MoonKoder/ | 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/
// Β© MoonKoder
//@version=5
indicator(title = "SSL Channel [MoonKoder]", overlay = true)
// ======================================================
// == ==
// == I N P U T P A R A M E T E R S ==
// == ==
// ======================================================
// {
// Get User Inputs
Period_High = input.int(title = "Period High", defval = 13)
Color_High = input.color(title = "Color High", defval = color.teal)
Period_Low = input.int(title = "Period Low", defval=13)
Color_Low = input.color(title = "Color Low", defval = color.red)
Resolution = input.timeframe(title = "TimeFrame", defval = "15")
CandleType = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"])
UseGap = input.bool(title = "Use Gap", defval = true)
// }
// ======================================================
// == ==
// == S U P P O R T C A L C U L A T I O N S ==
// == ==
// ======================================================
// {
// Function to Calculate the SSL Channel
Function_SslChannel(_Period_High, _Period_Low) =>
MovAvg_High = ta.sma(high, _Period_High)
MovAvg_Low = ta.sma(low, _Period_Low)
Direction = 0
Direction := close > MovAvg_High ? 1 : close < MovAvg_Low ? -1 : Direction[1]
SSL_Below = Direction < 0 ? MovAvg_High: MovAvg_Low
SSL_Above = Direction < 0 ? MovAvg_Low : MovAvg_High
[SSL_Below, SSL_Above]
// Function to Determine The Choosen Ticker Types
// {
Function_TickerType(_TickerType) =>
if _TickerType == "01 - Current"
syminfo.tickerid
else if _TickerType == "02 - Heikin Ashi"
ticker.heikinashi(syminfo.tickerid)
else if _TickerType == "03 - Renko"
ticker.renko(syminfo.tickerid, "ATR", 10)
else if _TickerType == "04 - Line Break"
ticker.linebreak(syminfo.tickerid, 3)
else if _TickerType == "05 - Kagi"
ticker.kagi(syminfo.tickerid, 3)
// }
// }
// ======================================================
// == ==
// == R E Q U E S T S & P L O T S ==
// == ==
// ======================================================
// {
[_SSL_Below, _SSL_Above] = Function_SslChannel(Period_High, Period_Low)
SSL_Below_GapOn = request.security(Function_TickerType(CandleType), Resolution, _SSL_Below, barmerge.gaps_on)
SSL_Below_GapOff = request.security(Function_TickerType(CandleType), Resolution, _SSL_Below, barmerge.gaps_off)
SSL_Below = UseGap ? SSL_Below_GapOn : SSL_Below_GapOff
SSL_Above_GapOn = request.security(Function_TickerType(CandleType), Resolution, _SSL_Above, barmerge.gaps_on)
SSL_Above_GapOff = request.security(Function_TickerType(CandleType), Resolution, _SSL_Above, barmerge.gaps_off)
SSL_Above = UseGap ? SSL_Above_GapOn : SSL_Above_GapOff
plot(SSL_Below, linewidth = 2, color = Color_High)
plot(SSL_Above, linewidth = 2, color = Color_Low)
// }
// ======================================================
// == ==
// == P R O G R A M E N D ==
// == ==
// ====================================================== |
Simple Volume/RSI Map | https://www.tradingview.com/script/WBhdp9jD-Simple-Volume-RSI-Map/ | atolelole | https://www.tradingview.com/u/atolelole/ | 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/
// Β© atolelole
//@version=5
indicator("Simple Volume/RSI Map", overlay=false, max_lines_count=500, max_labels_count=500, max_bars_back=1000)
top = input(20, "Plot size: ", group="Plot")
bot = 0
left = bar_index - int(top/2)
right = bar_index + int(top/2)
var basebox = box.new(left , top , right , bot , bgcolor=na , border_color=na)
var bearbox_weak = box.new(left , top / 2, bar_index, bot , bgcolor=color.new(color.red, 90) , border_color=na)
var bearbox_strong = box.new(bar_index, top / 2, right , bot , bgcolor=color.new(color.red, 80) , border_color=na)
var bullbox_weak = box.new(left , top , bar_index, top / 2, bgcolor=color.new(color.green, 90), border_color=na)
var bullbox_strong = box.new(bar_index, top , right , top / 2, bgcolor=color.new(color.green, 80), border_color=na)
var rsibox = box.new(left , top*0.7, right , top*0.3, bgcolor=na, border_color=color.gray, border_style=line.style_dashed)
lerp(l, h, s) =>
l + (h - l) * s
lerp_x_axis(s) =>
int(lerp(left, right, s))
lerp_y_axis(s) =>
lerp(bot, top, s)
var l00 = label.new(lerp_x_axis(0.0), lerp_y_axis(0.0), '(0.0, 0.0)\nvol, rsi\nWeak bearish' , style=label.style_label_up , size=size.small, color=color.new(color.blue, 98), textcolor=color.white)
var l10 = label.new(lerp_x_axis(1.0), lerp_y_axis(0.0), '(1.0, 0.0)\nvol, rsi\nStrong bearish', style=label.style_label_up , size=size.small, color=color.new(color.blue, 98), textcolor=color.white)
var l01 = label.new(lerp_x_axis(0.0), lerp_y_axis(1.0), 'Weak bullish\nvol, rsi\n(0.0, 1.0)' , style=label.style_label_down, size=size.small, color=color.new(color.blue, 98), textcolor=color.white)
var l11 = label.new(lerp_x_axis(1.0), lerp_y_axis(1.0), 'Strong bullish\nvol, rsi\n(1.0, 1.0)', style=label.style_label_down, size=size.small, color=color.new(color.blue, 98), textcolor=color.white)
limit_rsi = input.bool(false, "Limit normalization to RSI(30-70) zone")
rsi_len = input(14, "RSI Length" , group="Data")
volume_len = input(35, "Volume Normalization Length", group="Data")
n_samples = input(35, "N Samples (last n candles)" , group="Data")
vol_highest = ta.highest(volume, volume_len)
rsi = ta.rsi(close, rsi_len)
plot(limit_rsi ? ((rsi-30.0) / 40.0) : (rsi / 100.0), color=na)
plot(volume / vol_highest, color=na)
var plotpoints = array.new_label()
if barstate.islast
if limit_rsi
box.set_top(rsibox, top)
box.set_bottom(rsibox, bot)
box.set_left(rsibox, left)
box.set_right(rsibox, right)
box.set_left(basebox, left)
box.set_right(basebox, right)
box.set_left(bearbox_weak, left)
box.set_right(bearbox_weak, bar_index)
box.set_left(bearbox_strong, bar_index)
box.set_right(bearbox_strong, right)
box.set_left(bullbox_weak, left)
box.set_right(bullbox_weak, bar_index)
box.set_left(bullbox_strong, bar_index)
box.set_right(bullbox_strong, right)
for i = 0 to array.size(plotpoints)
if array.size(plotpoints) > 0
label.delete(array.shift(plotpoints))
rsi_avg = 0.0
vol_avg = 0.0
for i = 1 to n_samples - 1
rsi_coef = limit_rsi ? ((rsi[i] - 30.0) / 40.0) : (rsi[i] / 100.0)
vol_coef = volume[i] / vol_highest
rsi_avg += rsi_coef
vol_avg += vol_coef
clr = color.new(color.gray, (100 / n_samples) * i)
array.push(plotpoints, label.new(lerp_x_axis(vol_coef), lerp_y_axis(rsi_coef), 'βΈ', style=label.style_label_center, size=size.small, textcolor=clr, color=na))
crsi_coef = limit_rsi ? ((rsi - 30.0) / 40.0) : (rsi / 100.0)
cvol_coef = volume / vol_highest
array.push(plotpoints, label.new(lerp_x_axis(cvol_coef), lerp_y_axis(crsi_coef), 'β', style=label.style_label_center, size=size.small, textcolor=color.white, color=na))
rsi_avg += crsi_coef
vol_avg += cvol_coef
rsi_avg /= n_samples
vol_avg /= n_samples
clr_avg = rsi_avg < 0.5 ? color.red : color.lime
array.push(plotpoints, label.new(lerp_x_axis(vol_avg), lerp_y_axis(rsi_avg), 'β', style=label.style_label_center, size=size.small, textcolor=clr_avg ,color=na))
label.set_x(l00, bar_index - int(top/2))
label.set_x(l10, bar_index + int(top/2))
label.set_x(l01, bar_index - int(top/2))
label.set_x(l11, bar_index + int(top/2))
|
ATR Bands | https://www.tradingview.com/script/ziTzsSfo-ATR-Bands/ | TheTrdFloor | https://www.tradingview.com/u/TheTrdFloor/ | 3,819 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© TheTrdFloor
//
// In many strategies, it's quite common to use a scaled ATR to help define a stop-loss, and it's not uncommon to use it for take-profit targets
// as well. While there are quite a few indicators that plot ATR bands already on TV, we could not find one that actually performed the exact
// way that we wanted. They all had at least one of the following gaps:
// * The ATR offset was not configurable (usually hard-coded to be based off the high or low, while we generally prefer to use close)
// * It would only print a single band (either the upper or lower), which would require the same indicator to be added twice
// * The ATR scaling factor was either not configurable or only stepped in whole numbers (often time fractional factors like 1.5 yield better results)
//
// Also, when looking at some of the behaviors of the ATR bands, you can see that when price first levels out, you can draw a "consolidation zone" from
// the first peak of the upper ATR band to the first valley of the lower ATR band and look for price to break and close outside of that zone. When that
// happens, price will usually make a notable move in that direction.
//
// While we have made some updates and enhancements to this indicator, and have every intention of continuing to do so as we find worthy opportunities
// for enhancement, credit is still due to the origianl author: AlexanderTeaH
//
//@version=5
indicator('ATR Bands', overlay=true) // These had to be taken out as they're not compatible with plotting a table... , timeframe="", timeframe_gaps=false
// Inputs
atrPeriod = input.int(title='ATR Period', defval=3, minval=1, group="ATR Bands Standard Settings", tooltip="This setting is used in the raw ATR value calculation. Lower values will be more reactive to recent price movement, while higher values will better indicate loger-term trend.\n\n" +
"Most often this is set at either 14 or 21.\nDefault: 3")
// While it seemed like a nice idea at the time, having separately-configurable upper and lower bands just doesn't really seem that useful as 90% of the time the settings for both are the same.
// Therefore, We're going to simplify the config to make these settings unified for both bands, as it would otherwise just add even more confusion with the addition of take-profit bands as well...
//
// atrMultiplierUpper = input.float(title='ATR Upper Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Upper Band Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
// "This will usually be between 1 and 3.")
// srcUpper = input.source(title='ATR Upper Offset Source', defval=close, group="ATR Upper Band Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "For this band, 'high' and 'close' (default) are generally the most appropriate values.")
//
atrMultiplier = input.float(title='ATR Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Bands Standard Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
"This will usually be between 1 and 3.\n\nDefault: 2.5")
// On second thought, I'm going to nix this setting and force it to be the "close" source. Having the ability to offset based on the wicks was a nice idea, but doesn't really seem to have any notable practical application.
atrSourceRef = "close"
//atrSourceRef = input.string(title='ATR Upper Offset Source', defval="close", options=["close","wicks"], group="ATR Bands Standard Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "The default value 'close' should be your go-to, but 'wicks' might provide a bit more breathing room in securities that tend to have large wicks.")
//
// See above - these are deprecated and no longer used...
//
// atrMultiplierLower = input.float(title='ATR Lower Band Scale Factor', defval=2.5, step=0.1, minval=0.01, group="ATR Lower Band Settings", tooltip="Scaling factor (aka multiplier) for the ATR to use for plotting the ATR bands. " +
// "This will usually be between 1 and 3.")
// srcLower = input.source(title='ATR Lower Offset Source', defval=close, group="ATR Lower Band Settings", tooltip="This setting determines the offset point for ATR bands. " +
// "For this band, 'low' and 'close' (default) are generally the most appropriate values.")
//
//
// Take-Profit band settings
showTPBands = input.bool(title="Show opposite bands for take-profit zones", defval=false, tooltip="If enalbled, the existing ATR bands will be treated as 'stop-loss' bands, and 'take-profit' bands will be plotted " +
"to depict potential take-profit targets that are scaled based on the 'stop-loss' band and an additional reward/risk scaling factor (see below).\n\nDefault: Unchecked", group="Take-Profit Settings")
tpScaleFactor = input.float(title="Take-Profit Scale Factor", defval=1.5, minval=1, step=0.1, tooltip="This is a secondary scaling factor used based on the 'stop-loss' ATR bands to calculate and plot a potential take-profit target.\n\n" +
"The easiest way to think of this is as a desired reward/risk ratio, where the primary ATR Bands represent the risk/stop-loss.\n\nDefault: 1.5")
//
//
// As an added bonus, give the option to plot a table containing exact figures for all of the bands...
// Functional settings
showTable = input.bool(title="Show Table for Stops and Targets", defval=false, group="Table Settings", tooltip="If enabled, a table will be placed on-chart showing exact values for both stop bands, as well as optional take-profit bands/targets.\n\n" +
"Note: Take-profit values are based on the 'Take-Profit Scale Factor' setting above.\n\nDefault: Unchecked")
allowTableRepainting = input.bool(title="Allow Table Repainting", defval=false, group="Table Settings", tooltip="If enabled, table data will show real-time values, which will inherently repaint. This may be desirable for people preparing to enter prior " +
"to candle close, but should be used with extreme caution.\n\nDefault: Unchecked")
showTPinTable = input.bool(title="Include additional rows/columns to display take-profit values.", defval=false, group="Table Settings", tooltip="If enabled, additional table rows/columns will be drawn and populated with take-profit band/target values.\n\n" +
"Note: Take-profit values are based on the 'Take-Profit Scale Factor' setting above.\n\nDefault: Unchecked")
//
// Display settings
alignTableVertically = input.bool(title="Align Table Vertically", defval=true, group="Table Settings", tooltip="If enabled, the table will be re-aligned to display vertically (headers to the left) instead of horizontally (headers on top).\n\nDefault: Checked")
tablePosition = input.string(title="Table Location", defval="Bottom Right", options=["Top Right","Top Left","Top Center","Middle Right","Middle Left","Middle Center","Bottom Right","Bottom Left","Bottom Center"], group="Table Settings",
tooltip='This setting controls the position on the chart where the table will be located.\n\nDefault: Bottom Right')
tableColor = input.color(title="Table Color: ", defval=color.rgb(0, 175, 200, 20), group="Table Settings", inline="A")
tableTextHeaderColor = input.color(title="Table Header Color: ", defval=color.rgb(255, 255, 0, 0), group="Table Settings", tooltip="These settings determine the colors used for the table cell borders/outlines, and the text inside the table cells used as data headers.", inline="A")
tableTextColor = input.color(title="Table Text Color: ", defval=color.rgb(255, 255, 255, 0), group="Table Settings", tooltip="This setting determines the color used for the text inside the table cells.", inline="B")
// tableTooltipColor = input.color(title="Table Tooltip Color: ", defval=color.rgb(255, 75, 255, 0), group="Table Display Settings", tooltip="This setting determines the color used for any cell tooltips.") // Not used
tableLongBGColor = input.color(title="Table Background Color - Long: ", defval=color.rgb(0, 255, 0, 90), group="Table Settings", inline="C")
tableShortBGColor = input.color(title="Short: ", defval=color.rgb(255, 0, 0, 80), group="Table Settings", tooltip="These settings determine the background fill colors used for long/short position info.", inline="C")
// Functions
//
// Function to convert the input "source" to a proper "source"
getBandOffsetSource(srcIn, isUpperBand) =>
// Initialize the return to our fail-safe 'close', which is also the default input, then update thru the switch statement
ret = close
switch srcIn
"close" => ret := close
"wicks" => ret := isUpperBand ? high : low
=> ret := close
ret
//
// Function to convert table position input to a an appropriate argument
getTablePosition(posIn) =>
posOut = position.bottom_right
switch (posIn)
"Top Right" => posOut := position.top_right
"Top Left" => posOut := position.top_left
"Top Center" => posOut := position.top_center
"Middle Right" => posOut := position.middle_right
"Middle Left" => posOut := position.middle_left
"Middle Center" => posOut := position.middle_center
"Bottom Right" => posOut := position.bottom_right
"Bottom Left" => posOut := position.bottom_left
"Bottom Center" => posOut := position.bottom_center
=> posOut := position.bottom_right
posOut
// ATR
atr = ta.atr(atrPeriod)
scaledATR = atr * atrMultiplier
upperATRBand = getBandOffsetSource(atrSourceRef, true) + scaledATR
lowerATRBand = getBandOffsetSource(atrSourceRef, false) - scaledATR
//
// Since we can calcualte ATR bands based on either close or wicks, we need to be sure to normalize the true distance
// from the close to the "stop band" before we can then apply our take-profit scaler and calculate the TP bands...
scaledTPLong = close + ((close - lowerATRBand) * tpScaleFactor)
scaledTPShort = close - ((upperATRBand - close) * tpScaleFactor)
// OG ATR Band Plotting
plot(upperATRBand, title="Upper ATR Band", color=color.rgb(0, 255, 0, 50), linewidth=2)
plot(lowerATRBand, title="Lower ATR Band", color=color.rgb(255, 0, 0, 50), linewidth=2)
// TP band plots
plot(showTPBands ? scaledTPLong : na, title="Upper Take-Profit Band", color=color.rgb(255, 255, 255, 80), linewidth=1)
plot(showTPBands ? scaledTPShort : na, title="Lower Take-Profit Band", color=color.rgb(255, 255, 0, 80), linewidth=1)
// ATR and TP table...
if (showTable)
// It's nice that TV will automagically shrink/reposition table cells to not have gaps if a specific row/column are missing,
// so we can define the table to the max number of rows/columns possible for this indicator in any configuration and let TV handle the "shrinking".
var atrTable = table.new(position=getTablePosition(tablePosition), columns=8, rows=8)
//
// Set the base table styles...
table.set_border_width(atrTable, 1)
table.set_frame_width(atrTable, 1)
table.set_border_color(atrTable, tableColor)
table.set_frame_color(atrTable, tableColor)
//
// Since we're giving the option to display the table with 2 different formats (horizontal vs vertical), we need to build out both variations and
// incorporate a method to switch from one to the other based on the 'alignTableVertically' user input setting. While we probably COULD do
// conditional logic inside the 'table.cell' functions, it will be far more intuitive to "read" if we simply break it into an 'if-else' clause.
//
// While this WILL result in a pretty notable duplication of code, it's acceptable in this case as we have a finite number of options (2).
//
// Vertical orientation
if (alignTableVertically)
// Define the Title/Header cells
table.cell(atrTable, 0, 0, text="Long ATR Stop", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor, tooltip="Test")
table.cell(atrTable, 0, 1, text="Long ATR Stop Dist", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor)
if (showTPinTable)
table.cell(atrTable, 0, 2, text="Long ATR TP", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 0, 3, text="Long ATR TP Dist", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor)
table.cell(atrTable, 0, 4, text="Short ATR Stop", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
table.cell(atrTable, 0, 5, text="Short ATR Stop Dist", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
if (showTPinTable)
table.cell(atrTable, 0, 6, text="Short ATR TP", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 0, 7, text="Short ATR TP Dist", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
//
// Now for table values for each header...
// Start with Long position...
table.cell(atrTable, 1, 0, text=str.tostring(allowTableRepainting ? lowerATRBand : lowerATRBand[1], format.mintick), text_color=tableTextColor, bgcolor=tableLongBGColor, tooltip="Test")
table.cell(atrTable, 1, 1, text=str.tostring(math.round_to_mintick(allowTableRepainting ? close - lowerATRBand : close[1] - lowerATRBand[1])), text_color=tableTextColor, bgcolor=tableLongBGColor)
if (showTPinTable)
table.cell(atrTable, 1, 2, text=str.tostring(allowTableRepainting ? scaledTPLong : scaledTPLong[1], format.mintick), text_color=tableTextColor, bgcolor=tableLongBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 1, 3, text=str.tostring(math.round_to_mintick(allowTableRepainting ? scaledATR * tpScaleFactor : scaledATR[1] * tpScaleFactor)), text_color=tableTextColor, bgcolor=tableLongBGColor)
// Now the Short position...
table.cell(atrTable, 1, 4, text=str.tostring(allowTableRepainting ? upperATRBand : upperATRBand[1], format.mintick), text_color=tableTextColor, bgcolor=tableShortBGColor, tooltip="Test 2")
table.cell(atrTable, 1, 5, text=str.tostring(math.round_to_mintick(allowTableRepainting ? upperATRBand - close : upperATRBand[1] - close[1])), text_color=tableTextColor, bgcolor=tableShortBGColor)
if (showTPinTable)
table.cell(atrTable, 1, 6, text=str.tostring(allowTableRepainting ? scaledTPShort : scaledTPShort[1], format.mintick), text_color=tableTextColor, bgcolor=tableShortBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 1, 7, text=str.tostring(math.round_to_mintick(allowTableRepainting ? scaledATR * tpScaleFactor : scaledATR[1] * tpScaleFactor)), text_color=tableTextColor, bgcolor=tableShortBGColor)
//
// Horizontal orientation
else
// Define the Title/Header cells
table.cell(atrTable, 0, 0, text="Long ATR Stop", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor, tooltip="Test")
table.cell(atrTable, 1, 0, text="Long ATR Stop Dist", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor)
if (showTPinTable)
table.cell(atrTable, 2, 0, text="Long ATR TP", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 3, 0, text="Long ATR TP Dist", text_color=tableTextHeaderColor, bgcolor=tableLongBGColor)
table.cell(atrTable, 4, 0, text="Short ATR Stop", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
table.cell(atrTable, 5, 0, text="Short ATR Stop Dist", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
if (showTPinTable)
table.cell(atrTable, 6, 0, text="Short ATR TP", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 7, 0, text="Short ATR TP Dist", text_color=tableTextHeaderColor, bgcolor=tableShortBGColor)
//
// Now for table values for each header...
// Start with Long position...
table.cell(atrTable, 0, 1, text=str.tostring(allowTableRepainting ? lowerATRBand : lowerATRBand[1], format.mintick), text_color=tableTextColor, bgcolor=tableLongBGColor, tooltip="Test")
table.cell(atrTable, 1, 1, text=str.tostring(math.round_to_mintick(allowTableRepainting ? close - lowerATRBand : close[1] - lowerATRBand[1])), text_color=tableTextColor, bgcolor=tableLongBGColor)
if (showTPinTable)
table.cell(atrTable, 2, 1, text=str.tostring(allowTableRepainting ? scaledTPLong : scaledTPLong[1], format.mintick), text_color=tableTextColor, bgcolor=tableLongBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 3, 1, text=str.tostring(math.round_to_mintick(allowTableRepainting ? scaledATR * tpScaleFactor : scaledATR[1] * tpScaleFactor)), text_color=tableTextColor, bgcolor=tableLongBGColor)
// Now the Short position...
table.cell(atrTable, 4, 1, text=str.tostring(allowTableRepainting ? upperATRBand : upperATRBand[1], format.mintick), text_color=tableTextColor, bgcolor=tableShortBGColor, tooltip="Test 2")
table.cell(atrTable, 5, 1, text=str.tostring(math.round_to_mintick(allowTableRepainting ? upperATRBand - close : upperATRBand[1] - close[1])), text_color=tableTextColor, bgcolor=tableShortBGColor)
if (showTPinTable)
table.cell(atrTable, 6, 1, text=str.tostring(allowTableRepainting ? scaledTPShort : scaledTPShort[1], format.mintick), text_color=tableTextColor, bgcolor=tableShortBGColor)
// If the TP scale factor is exactly 1, we can nix the TP distance columns as it will be exactly the same as the stop distance.
if (tpScaleFactor != 1)
table.cell(atrTable, 7, 1, text=str.tostring(math.round_to_mintick(allowTableRepainting ? scaledATR * tpScaleFactor : scaledATR[1] * tpScaleFactor)), text_color=tableTextColor, bgcolor=tableShortBGColor)
|
Magic levels | https://www.tradingview.com/script/e8UqrnKr-Magic-levels/ | ankitgautam87 | https://www.tradingview.com/u/ankitgautam87/ | 200 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
indicator(title="Magic levels", shorttitle="Magic levels", overlay=true)
var float q1 = 0
var float q5 = 0
var float q3 = 0
var float q7 = 0
basePrice = math.floor(math.sqrt(close))
for i = (basePrice - 5) to (basePrice + 5)
q1 := ((i + 0.125) * (i + 0.125))
q5 := ((i + 0.625) * (i + 0.625))
q3 := ((i + 0.375) * (i + 0.375))
q7 := ((i + 0.875) * (i + 0.875))
solidLineq1 = line.new(x1=bar_index[10], y1=q1, x2=bar_index, y2=q1)
line.set_color(solidLineq1, color.rgb(170, 170, 170))
line.set_extend(solidLineq1, extend.both)
line.set_style(solidLineq1, line.style_solid)
line.set_width(solidLineq1, 1)
solidLineq5 = line.new(x1=bar_index[10], y1=q5, x2=bar_index, y2=q5)
line.set_color(solidLineq5, color.rgb(170, 170, 170))
line.set_extend(solidLineq5, extend.both)
line.set_style(solidLineq5, line.style_solid)
line.set_width(solidLineq5, 1)
dashedLineq3 = line.new(x1=bar_index[10], y1=q3, x2=bar_index, y2=q3)
line.set_color(dashedLineq3, color.rgb(170, 170, 170))
line.set_extend(dashedLineq3, extend.both)
line.set_style(dashedLineq3, line.style_dashed)
line.set_width(dashedLineq3, 1)
dashedLineq7 = line.new(x1=bar_index[10], y1=q7, x2=bar_index, y2=q7)
line.set_color(dashedLineq7, color.rgb(170, 170, 170))
line.set_extend(dashedLineq7, extend.both)
line.set_style(dashedLineq7, line.style_dashed)
line.set_width(dashedLineq7, 1)
|
AMACD - All Moving Average Convergence Divergence | https://www.tradingview.com/script/LA4qiY8r-AMACD-All-Moving-Average-Convergence-Divergence/ | EltAlt | https://www.tradingview.com/u/EltAlt/ | 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/
// Β© EltAlt
//@version=5
// -----------------------------------------------------------------------------
//
// Authors: @EltAlt
// Revision: v3.04
// Date: 18-May-2022
//
// Description
// =============================================================================
// This indicator displays the Moving Average Convergane and Divergence (MACD) of individually configured Fast, Slow and Signal Moving
// Averages. Open Long / Close Long / Open Short / Close Short alerts can be set based on moving average crossovers, consecutive
// convergence/divergence of the moving averages, directional changes in the histogram moving averages, moving average crossing zero, or
// divergences between the price and the MACD. Alerts can also be filtered based on the MACD being above or below zero.
//
// The Fast, Slow and Signal Moving Averages can be set to:
// Simple Moving Average (SMA)
// Exponential Moving Average (EMA)
// Weighted Moving Average (WMA)
// Volume-Weighted Moving Average (VWMA)
// Hull Moving Average (HMA)
// Exponentially Weighted Moving Average (RMA) (SMMA)
// Linear regression curve Moving Average (LSMA)
// Double EMA (DEMA)
// Double SMA (DSMA)
// Double WMA (DWMA)
// Double RMA (DRMA)
// Triple EMA (TEMA)
// Triple SMA (TSMA)
// Triple WMA (TWMA)
// Triple RMA (TRMA)
// Symmetrically Weighted Moving Average (SWMA) ** length does not apply **
// Arnaud Legoux Moving Average (ALMA)
// Variable Index Dynamic Average (VIDYA)
// Fractal Adaptive Moving Average (FRAMA)
//
// If you have a strategy that can buy based on External Indicators you can use the 'Backtest Signal' which plots the values set in
// the 'Long / Short Signals' section.
// 'Backtest Signal' is plotted to display.none, so change the Style Settings for the chart if you need to see it for testing.
//
// =============================================================================
//
// I would gladly accept any suggestions to improve the script.
// If you encounter any problems please share them with me.
//
// Thanks to Smartcryptotrade for "MACD Alert [All MA in one] [Smart Crypto Trade (SCT)]" which gave me the initial starting point.
// Thanks to Jason5480 for your help, discussions and "jason5480/hack_utils/2".
//
// Changlog
// =============================================================================
//
// 2.01 β’ Added separate sources for the fast and slow moving averages.
// β’ Added SWMA, because it's "All" moving averages. Interesting that SWMA doesn't take a length, so length will not apply.
// β’ Consolidated MA functions for doubles and triples in to the calcMA function.
// β’ Neatened up the inputs.
// 2.02 β’ Renamed to "AMACD - All Moving Average Convergence Divergence".
// β’ Added ta.rising and ta.falling, which simplified things a lot, why didn't you tell me about these functions! :)
// β’ Added a price plot with display=display.none for testing, color is green when above moving averages, red below and blue when
// interacting.
// β’ First Public release.
// 2.03 β’ Added a case for no signal smoothing, when signal length = 1.
// β’ Re-wrote calcMA as a switch, much more pleasing on the eye.
// β’ Removed all the security fluff which I'd never even read, "terms of the Mozilla Public License 2.0" is more comprehensive anyway.
// β’ Added check boxes to quickly disable some of the default plots.
// 3.00 β’ Added options to generate open and close for both long and short positions. So if you are in a long position and your criteria
// for a negative signal is met it will close your long, if another negative signal is generated it will open a short. If you're
// just trading the crossover this will keep you permanently trading short or long, as it's only when there are two or more
// consecutive signals are generated that will move you from longs to shorts.
// β’ Plots a Green Triangle for Open Long, a Green Square for Close Long, a Red Triangle for Open Short and a Red Square for
// Close Short.
// β’ To do this I needed to track the sate of open deals. Could have done this with variables but thought plotting it may help,
// so "Deal State" plots a 1 if it's in a long, 0 if no deals are open and -1 if it's in a short, to display.none. Enable it
// in Style Settings if you need it for testing.
// β’ If you'd prefer that it just worked as it did before with simple Buy / Sell signals, which makes sense if you're just trading
// the crossover, disable the 'Generate Close Signals for Long / Short Positions' setting.
// β’ Now that it can generate Open Long, Close Long, Open Short and Close Short signals I added a 'Long / Short Signals' section in
// settings, where you can specify what signals your backtester is expecting for each state.
// β’ Moving averages are now plotted to display.none as well in case you want to see the price and the moving averages for testing.
// You're much better off running my other script 'Any Ribbon' on the top pane to show the moving averages ribbon, but these
// options enable you to show them here if you want to.
// β’ Added the option to buy / sell based on the moving average crossing zero, thanks Bu Bader!
// 3.01 β’ Added filters for MACD above and below zero.
// β’ Added the option to buy / sell based on divergences between the price and the MACD. Thanks to Trading View for the 'Divergence
// Indicator' and @DaviddTech for his idea to use that as the basis for a MACD Divergence script.
// β’ REMEMBER you can't trigger a divergence before a local top or bottom is CONFIRMED by closing some bars after that local top
// or bottom. Replay some bars to see how far after the divergence the signal will actually fire.
// β’ Added a bunch of tool tips, I bet there are spelling mistakes in some, tell me if so.
// 3.02 β’ When 'Generate Close Signals for Long / Short Positions' was disabled close long was plotting as open short (-1). Fixed the
// logic. Thanks for the testing Bu Bader!
// 3.03 β’ More signal weirdness, re-wrote the logic completely.
// 3.04 β’ I've had requests to filter based on a few different indicators, I think that the script is getting too complicated as it is
// and I don't want to add a bunch of filters that only one person may use. So I added the option to filter based on the output
// of an external indicator. You can enable or disable trading based any indicator hitting the level that you set. I've tested a
// few indicators but you need to to confirm that your indicator is filtering as you expect it to. Enable the plot of 'Trades
// Enabled' in Style Settings to see if trades are enabled (1) or disabled (0). I expect that this was requested to only open
// longs in an uptrend etc. so it may not be helpful if you want to open longs and shorts.
// Thanks Jason5480 for hack_utils that made this easier.
// β’ The external filter will stop new trades starting but it won't stop any existing trades closing.
// β’ The MACD > 0 filter may not have stopped existing deals closing, changed that so that they can close.
// β’ Added check to do nothing when buy and sell fire in the same bar.
// β’ Corrected signal for consecutive short orders.
//
//
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
//
//
// ============ "AMACD - All Moving Average Convergence Divergence"
indicator(title='AMACD - All Moving Average Convergence Divergence',
shorttitle='AMACD',
overlay = false,
timeframe='',
timeframe_gaps=true)
import jason5480/hack_utils/2 as hu
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Inputs
MATip = 'Simple Moving Average (SMA)\nExponential Moving Average (EMA)\nWeighted Moving Average (WMA)\nVolume-Weighted Moving Average (VWMA)\nHull Moving Average (HMA)\nExponentially Weighted Moving Average (RMA) (SMMA)\nLinear regression curve Moving Average (LSMA)\nDouble EMA (DEMA)\nDouble SMA (DSMA)\nDouble WMA (DWMA)\nDouble RMA (DRMA)\nTriple EMA (TEMA)\nTriple SMA (TSMA)\nTriple WMA (TWMA)\nTriple RMA (TRMA)\nSymmetrically Weighted Moving Average (SWMA)\n** length does not apply to SWMA **\nArnaud Legoux Moving Average (ALMA)\nVariable Index Dynamic Average (VIDYA)\nFractal Adaptive Moving Average (FRAMA)'
FastType = input.string('EMA', title='Fast Moving Average Type', group='Moving Averages', options=['EMA', 'SMA', 'WMA', 'VWMA', 'HMA', 'RMA', 'LSMA', 'Double EMA', 'Double SMA', 'Double WMA', 'Double RMA', 'Triple EMA', 'Triple SMA', 'Triple WMA', 'Triple RMA', 'SWMA', 'ALMA', 'VIDYA', 'FRAMA'], tooltip = MATip)
FastSource = hu.str_to_src(input.string (defval = 'close', title='Fast Source', inline='Fast', group='Moving Averages', options = ['open', 'high', 'low', 'close', 'hl2', 'hlc3', 'ohlc4', 'hlcc4']))
FastLength = input.int (12, title='Fast Length', inline='Fast', group='Moving Averages', minval=2, maxval=1000)
SlowType = input.string ('SMA', title='Slow Moving Average Type', group='Moving Averages', options=['EMA', 'SMA', 'WMA', 'VWMA', 'HMA', 'RMA', 'LSMA', 'Double EMA', 'Double SMA', 'Double WMA', 'Double RMA', 'Triple EMA', 'Triple SMA', 'Triple WMA', 'Triple RMA', 'SWMA', 'ALMA', 'VIDYA', 'FRAMA'], tooltip = MATip)
SlowSource = hu.str_to_src(input.string (defval = 'close', title='Slow Source', inline='Slow', group='Moving Averages', options = ['open', 'high', 'low', 'close', 'hl2', 'hlc3', 'ohlc4', 'hlcc4']))
SlowLength = input.int (26, title='Slow Length', inline='Slow', group='Moving Averages', minval=2, maxval=1000)
sigMATip = 'Setting the Signal Moving Average Length to 1 will disable smoothing and trade based on the Fast and Slow Moving Averages directly.'
SignalType = input.string('EMA', inline='Signal', group='Moving Averages', title='Signal Moving Average Type', options=['EMA', 'SMA', 'WMA', 'VWMA', 'HMA', 'RMA', 'LSMA', 'Double EMA', 'Double SMA', 'Double WMA', 'Double RMA', 'Triple EMA', 'Triple SMA', 'Triple WMA', 'Triple RMA', 'SWMA', 'ALMA', 'VIDYA', 'FRAMA'], tooltip = sigMATip)
SignalLength = input.int (9, inline='Signal', group='Moving Averages',title='Signal Length', minval=1, maxval=1000)
extTip = 'Take an input from another indicator to enable or disable new trades.\nWhile new longs or shorts will not be opened any existing trade will still be closed.\nThe filter will remain applied until the counter signal is received.'
MACDAboveZero = input.bool (true, inline='1', group='Filters', title='Long Only When MACD is Above 0')
MACDBelowZero = input.bool (true, inline='1', group='Filters', title='Short Only When MACD is Below 0')
externalFilter = input.bool (false, inline='2', group='Filters', title= 'Enable External Filter', tooltip = extTip)
externalSource = input (close, inline='2', group='Filters', title= 'βββExternal Source', tooltip = extTip)
extStartOp = input.string ('==', inline='3', group='Filters', title = 'Enable Trades When External Input', options=['==', '<', '>', '<=', '>=', 'crossover', 'crossunder'])
extStart = input.int (1, inline='3', group='Filters', title='')
extStopOp = input.string ('==', inline='4', group='Filters', title = 'Disable Trades When Extranal Input', options=['==', '<', '>', '<=', '>=', 'crossover', 'crossunder'])
extStop = input.int (2, inline='4', group='Filters', title='')
signalTip = 'Here you can set the signals that will enable backtester to open and close deals.\nIf the backtester you are using can only work with long OR short deals you may need to save diffent chart layouts for longs and shorts.\nIf \'Generate Close Signals for Long / Short Positions\' is not selected only the \'Open Long\' and \'Close Long\' settings will plot.'
generateClose = input.bool (true, inline='0', group='Long / Short Signals', title='Generate Close Signals for Long / Short Positions', tooltip = signalTip)
longOpenSignal = input.int (1, inline='1', group='Long / Short Signals', title='Open Long = ')
longCloseSignal = input.int (2, inline='1', group='Long / Short Signals', title='Close Long = ')
shortOpenSignal = input.int (-1, inline='2', group='Long / Short Signals', title='Open Short = ')
shortCloseSignal = input.int (-2, inline='2', group='Long / Short Signals', title='Close Short = ')
crossoverTip = 'Generate buy signals when the fast moving average crosses up on the slow moving average, or sell signals when the fast moving average crosses down on the slow moving average.\nThis is the same as the histogram crossing zero.'
cross0Tip = 'Generate buy signals when the MACD crossses zero moving upwards, or sell signals when the MACD crossses zero moving downwards'
backtestBuyCrossover = input.bool (true, inline='1', group='Buy / Sell Moving Averages', title='Buy Moving Average Crossover', tooltip = crossoverTip)
backtestSellCrossover = input.bool (true, inline='1', group='Buy / Sell Moving Averages', title='Sell Moving Average Crossover')
backtestMACrossUpZero = input.bool (false, inline='2', group='Buy / Sell Moving Averages', title='Buy MACD Crossing Zero', tooltip = cross0Tip)
backtestMACrossDownZero = input.bool (false, inline='2', group='Buy / Sell Moving Averages', title='Sell MACD Average Crossing Zero')
divTip = 'Generate buy and sell signals based on divergences between the MACD and the close price. \nREMEMBER you can\'t trigger a divergence before a local top or bottom is CONFIRMED by closing some bars after that local top or bottom.'
lbR = input.int (5, inline='1', group='MACD Divergences', title ='Pivot Lookback Right', tooltip = divTip)
lbL = input.int (5, inline='1', group='MACD Divergences', title ='Pivot Lookback Left')
rangeUpper = input.int (60, inline='2', group='MACD Divergences', title ='Lookback Range Max')
rangeLower = input.int (5, inline='2', group='MACD Divergences', title ='Lookback Range Min')
plotBull = input.bool (true, inline='3', group='MACD Divergences', title ='Buy Bullish Divergence')
plotHiddenBull = input.bool (false, inline='3', group='MACD Divergences', title ='Buy Hidden Bullish Divergence')
plotBear = input.bool (true, inline='4', group='MACD Divergences', title ='Sell Bearish Divergence')
plotHiddenBear = input.bool (false, inline='4', group='MACD Divergences', title ='Sell Hidden Bearish Divergence')
histMATip = 'Generate buy signals when the histogram goes above the histogram moving average, this shows that the histogram is in an uptrend. \nGenerate sell signals when the histogram goes below the histogram moving average, this shows that the histogram is in an downtrend.'
backtestBuyHistMA = input.bool (false, inline='1', group='Buy / Sell Histogram Moving Averages', title='Buy Histogram MA Positive', tooltip = histMATip)
backtestSellHistMA = input.bool (false, inline='1', group='Buy / Sell Histogram Moving Averages', title='Sell Histogram MA Negative')
MAHistLength = input.int (5, minval=2, inline='2', group='Buy / Sell Histogram Moving Averages', title='Histogram MA Length')
MAHistType = input.string('EMA', inline='2', group='Buy / Sell Histogram Moving Averages', title='Histogram MA Type', options=['EMA', 'VWMA', 'SMA', 'WMA', 'HMA', 'RMA', 'ALMA', 'Double EMA', 'Double SMA', 'Double WMA', 'Double RMA', 'Triple EMA', 'Triple SMA', 'Triple WMA', 'Triple RMA', 'LSMA', 'VIDYA', 'FRAMA'])
risingHistTip = 'Generate buy and sell signals when the histogram has been rising / falling for a number of consecutive bars.'
backtestBuyRisingHist = input.bool (false, inline='1', group='Buy / Sell Histogram Rising / Falling', title='Buy Histogram Rising', tooltip = risingHistTip)
backtestBuyRisingHistBelow = input.bool (false, inline='1', group='Buy / Sell Histogram Rising / Falling', title='Buy Histogram Rising Only Below Zero')
risingHistLength = input.int (1, minval=1, inline='2', group='Buy / Sell Histogram Rising / Falling', title='Consecutive Rising Bars to Trigger Buy')
backtestSellFallingHist = input.bool (false, inline='3', group='Buy / Sell Histogram Rising / Falling', title='Sell Histogram Falling')
backtestSellFallingHistAbove = input.bool (false, inline='3', group='Buy / Sell Histogram Rising / Falling', title='Sell Histogram Falling Only Above Zero')
fallingHistLength = input.int (1, minval=1, inline='4', group='Buy / Sell Histogram Rising / Falling', title='Consecutive Falling Bars to Trigger Sell')
almaTip = 'Only required if ALMA is used as one of the moving averages.'
offset_alma = input (0.85, title='ALMA Offset', inline='1', group='Alma', tooltip = almaTip)
sigma_alma = input.float (6, title='ALMA Sigma', inline='1', group='Alma')
framaTip = 'Only required if FRAMA is used as one of the moving averages.'
FC = input.int(1, minval=1, title='FRAMA lower shift limit (FC)', inline='1', group='Frama', tooltip = framaTip)
SC = input.int(198, minval=1, title='FRAMA upper shift limit (SC)', inline='1', group='Frama')
plotAlerts = input.bool (true, inline='1', group='Plot Options', title='Plot Alerts')
plotMA = input.bool (true, inline='1', group='Plot Options', title='Plot Moving Average')
plotSig = input.bool (true, inline='1', group='Plot Options', title='Plot Signal')
plotH = input.bool (true, inline='2', group='Plot Options', title='Plot Histogram')
plotHMA = input.bool (true, inline='2', group='Plot Options', title='Plot Histogram Moving Average')
plotDivLabels = input.bool (false, inline='3', group='Plot Options', title="Plot Divergence Labels")
plotDivLines = input.bool (true, inline='3', group='Plot Options', title="Plot Divergence Lines")
col_macd = input.color(#2962FF, 'MACD Lineββ', group='Color Settings', inline='MACD')
col_signal = input.color(#FF6D00, 'βSignal Lineββ', group='Color Settings', inline='MACD')
col_grow_above = input.color(#26A69A, 'Histogram AboveββGrow', group='Color Settings', inline='Above')
col_fall_above = input.color(#B2DFDB, 'Fall', group='Color Settings', inline='Above')
col_grow_below = input.color(#FFCDD2, 'Histogram BelowββGrow', group='Color Settings', inline='Below')
col_fall_below = input.color(#FF5252, 'Fall', group='Color Settings', inline='Below')
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Functions
getCMO(src, length) =>
mom = ta.change(src)
upSum = math.sum(math.max(mom, 0), length)
downSum = math.sum(-math.min(mom, 0), length)
out = (upSum - downSum) / (upSum + downSum)
out
vidya(src, length) =>
alpha = 2 / (length + 1)
cmo = math.abs(getCMO(src, length))
vidya = 0.0
vidya := src * alpha * cmo + nz(vidya[1]) * (1 - alpha * cmo)
vidya
frama(x, y, z, v) =>
// x = source , y = length , z = FC , v = SC
HL = (ta.highest(high, y) - ta.lowest(low, y)) / y
HL1 = (ta.highest(high, y / 2) - ta.lowest(low, y / 2)) / (y / 2)
HL2 = (ta.highest(high, y / 2)[y / 2] - ta.lowest(low, y / 2)[y / 2]) / (y / 2)
D = (math.log(HL1 + HL2) - math.log(HL)) / math.log(2)
dim = HL1 > 0 and HL2 > 0 and HL > 0 ? D : nz(D[1])
w = math.log(2 / (v + 1))
alpha = math.exp(w * (dim - 1))
alpha1 = alpha > 1 ? 1 : alpha < 0.01 ? 0.01 : alpha
oldN = (2 - alpha1) / alpha1
newN = (v - z) * (oldN - 1) / (v - 1) + z
newalpha = 2 / (newN + 1)
newalpha1 = newalpha < 2 / (v + 1) ? 2 / (v + 1) : newalpha > 1 ? 1 : newalpha
frama = 0.0
frama := (1 - newalpha1) * nz(frama[1]) + newalpha1 * x
frama
calcMA(_type, _src, _length) =>
switch _type
'EMA' => ta.ema(_src, _length)
'SMA' => ta.sma(_src, _length)
'WMA' => ta.wma(_src, _length)
'VWMA' => ta.vwma(_src, _length)
'HMA' => ta.hma(_src, _length)
'RMA' => ta.rma(_src, _length)
'LSMA' => ta.linreg(_src, _length, 0)
'Double EMA' => 2 * ta.ema(_src, _length) - ta.ema(ta.ema(_src, _length), _length)
'Double SMA' => 2 * ta.sma(_src, _length) - ta.sma(ta.sma(_src, _length), _length)
'Double WMA' => 2 * ta.wma(_src, _length) - ta.wma(ta.wma(_src, _length), _length)
'Double RMA' => 2 * ta.rma(_src, _length) - ta.rma(ta.rma(_src, _length), _length)
'Triple EMA' => 3 * (ta.ema(_src, _length) - ta.ema(ta.ema(_src, _length), _length)) + ta.ema(ta.ema(ta.ema(_src, _length), _length), _length)
'Triple SMA' => 3 * (ta.sma(_src, _length) - ta.sma(ta.sma(_src, _length), _length)) + ta.sma(ta.sma(ta.sma(_src, _length), _length), _length)
'Triple WMA' => 3 * (ta.wma(_src, _length) - ta.wma(ta.wma(_src, _length), _length)) + ta.wma(ta.wma(ta.wma(_src, _length), _length), _length)
'Triple RMA' => 3 * (ta.rma(_src, _length) - ta.rma(ta.rma(_src, _length), _length)) + ta.rma(ta.rma(ta.rma(_src, _length), _length), _length)
'SWMA' => ta.swma(_src) // No Length for SWMA
'ALMA' => ta.alma(_src, _length, offset_alma, sigma_alma)
'VIDYA' => vidya(_src, _length)
'FRAMA' => frama(_src, _length, FC, SC)
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Calculations
MA_fast = calcMA(FastType, FastSource, FastLength)
MA_slow = calcMA(SlowType, SlowSource, SlowLength)
macd = MA_fast - MA_slow
signal = SignalLength > 1 ? calcMA(SignalType, macd, SignalLength) : 0
hist = macd - signal
histMA = calcMA(MAHistType, hist, MAHistLength)
// ------------ Divergences
osc = macd
plFound = na(ta.pivotlow (osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
// Regular Bullish, Osc: Higher Low, Price: Lower Low
oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
// Hidden Bullish, Osc: Lower Low, Higher Low
oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
// Regular Bearish, Osc: Lower High, Price: Higher High
oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
// Hidden Bearish, Osc: Higher High, Price: Lower High
oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Logic
var bool tradesEnabled = true
tradesEnabled := externalFilter ? hu.eval_cond(externalSource, extStopOp, extStop) ? false : hu.eval_cond(externalSource, extStartOp, extStart) ? true : tradesEnabled[1] : tradesEnabled==true
longSignal = ta.crossover(hist, 0)
shortSignal = ta.crossunder(hist, 0)
MACrossUpZero = ta.crossover(macd, 0)
MACrossDownZero = ta.crossover(macd, 0)
longHistMA = histMA > histMA[1]
shortHistMA = histMA < histMA[1]
risingHist = ta.rising (hist, risingHistLength) and (hist < 0 or not backtestBuyRisingHistBelow)
fallingHist = ta.falling (hist, fallingHistLength) and (hist > 0 or not backtestSellFallingHistAbove)
var int dealstate = 0
bool openLong = false
bool closeLong = false
bool openShort = false
bool closeShort = false
backtestBuy = (backtestBuyCrossover and longSignal)
or (backtestBuyHistMA and longHistMA and not longHistMA[1])
or (backtestBuyRisingHist and risingHist and not risingHist[1])
or (backtestMACrossUpZero and MACrossUpZero)
or (plotBull and bullCond)
or (plotHiddenBull and hiddenBullCond)
backtestSell = (backtestSellCrossover and shortSignal)
or (backtestSellHistMA and shortHistMA and not shortHistMA[1])
or (backtestSellFallingHist and fallingHist and not fallingHist[1])
or (backtestMACrossDownZero and MACrossDownZero)
or (plotBear and bearCond)
or (plotHiddenBear and hiddenBearCond)
if backtestBuy and not backtestSell
if tradesEnabled and (macd > 0 or not MACDAboveZero)
if generateClose and dealstate == -1
closeShort := true
dealstate := 0
else
openLong := true
dealstate := 1
else
if generateClose and dealstate == -1
closeShort := true
dealstate := 0
if backtestSell and not backtestBuy
if tradesEnabled and (macd < 0 or not MACDBelowZero)
if generateClose and dealstate <= 0
openShort := true
dealstate := -1
else
closeLong := true
dealstate := 0
else
if generateClose and dealstate == 1
closeLong := true
dealstate := 0
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Plot
plot(plotH ? hist : na, title='Histogram', style=plot.style_columns, color=hist >= 0 ? hist[1] < hist ? col_grow_above : col_fall_above : hist[1] < hist ? col_grow_below : col_fall_below, linewidth=2)
plot(plotHMA ? histMA : na, title='Histogram Moving Average', color=histMA > histMA[1] ? col_grow_above : col_fall_below, linewidth=2)
plot(plotMA ? macd : na, title='Moving Average', color=col_macd, linewidth=2)
plot(plotSig ? signal : na, title='Signal', color=col_signal, linewidth=2)
plot(closeShort ? shortCloseSignal : openLong ? longOpenSignal : closeLong ? longCloseSignal : openShort ? shortOpenSignal : 0, 'Backtest Signal', color=openLong or closeShort ? color.lime : openShort or closeLong? color.red : color.gray, display=display.none)
plot(close, title='Price', display=display.none, color = (low > MA_fast and low > MA_slow ? true : false) ? color.lime : (high < MA_fast and high < MA_slow ? true : false) ? color.red : color.blue)
plot(MA_fast, title= 'Fast Moving Average', display=display.none, color = color.red)
plot(MA_slow, title= 'Slow Moving Average', display=display.none, color = color.green)
plot(tradesEnabled ? 1 : 0 , title= 'Trades Enabled', display=display.none)
plot(dealstate, title='Deal State', display=display.none, color = (dealstate > 0 ? color.lime : dealstate < 0 ? color.red : color.gray))
// ------------ Divergences
bearColor = color.red
bullColor = color.green
hiddenBullColor = color.new(color.green, 50)
hiddenBearColor = color.new(color.red, 50)
textColor = color.white
noneColor = color.new(color.white, 100)
// Regular Bullish
plot(
plFound and plotDivLines ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor)
)
plotshape(
bullCond and plotDivLabels ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
// Hidden Bullish
plot(
plFound and plotDivLines ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
hiddenBullCond and plotDivLabels ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text=" H Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor
)
// Regular Bearish
plot(
phFound and plotDivLines ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor)
)
plotshape(
bearCond and plotDivLabels ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
// Hidden Bearish
plot(
phFound and plotDivLines ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
hiddenBearCond and plotDivLabels ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text=" H Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor
)
// ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ============ Alerts
alertcondition (openLong, title='AMACD Open Long!', message='Buy signal, put your JSON here to open longs or start bots.')
alertcondition (openShort, title='AMACD Open Short!', message='Sell signal, put your JSON here to open shorts or stop bots.')
alertcondition (closeShort, title='AMACD Close Short!', message='Buy signal, put your JSON here to close shorts or start bots.')
alertcondition (closeLong, title='AMACD Close Long!', message='Sell signal, put your JSON here to close longs or stop bots.')
plotshape (plotAlerts ? openLong and longOpenSignal : na, style=shape.triangleup, color=color.lime, location=location.bottom, size=size.tiny, title='Open Long')
plotshape (plotAlerts ? closeLong and longCloseSignal : na, style=shape.square, color=color.lime, location=location.bottom, size=size.tiny, title='Close Long')
plotshape (plotAlerts ? openShort and shortOpenSignal : na, style=shape.triangledown, color=color.red, location=location.bottom, size=size.tiny, title='Open Short')
plotshape (plotAlerts ? closeShort and shortCloseSignal : na, style=shape.square, color=color.red, location=location.bottom, size=size.tiny, title='Close Short') |
Daily Scalping Moving Averages | https://www.tradingview.com/script/eA2Ys1LA-Daily-Scalping-Moving-Averages/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 194 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© exlux99
//@version=5
indicator("Daily Scalping Moving Averages", overlay=true)
ema10 = input(10, title="EMA Fast", group="EMA Lengths")
ema20 = input(20, title="EMA Medium", group="EMA Lengths")
ema50 = input(50, title="EMA Slow", group="EMA Lengths")
// SMAS input
sma10 = input(10, title="SMA Fast", group="SMA Lengths")
sma20 = input(20, title="SMA Medium", group="SMA Lengths")
sma50 = input(50, title="SMA Slow", group="SMA Lengths")
vwap_w=request.security(syminfo.tickerid, "W",ta.vwap)
src = close
haclose = close
//-------------- MOVING AVERAGES CALCULATION
//Simple moving averages
calc_sma10 = ta.sma(src, sma10)
calc_sma20 = ta.sma(src, sma20)
calc_sma50 = ta.sma(src, sma50)
//Exponential moving averages
calc_ema10 = ta.ema(src, ema10)
calc_ema20 = ta.ema(src, ema20)
calc_ema50 = ta.ema(src, ema50)
length = input.int(title="Length ATR", defval=14, minval=1, group="Volatility")
smoothing = "RMA"
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)
daily_atr=request.security(syminfo.tickerid, "D", ta.atr(length))
daily_close=request.security(syminfo.tickerid, "D", close[1])
var float gica = 0.0
gica:= daily_atr
////////////////////////////////////////////////////////////////////////////
posInput = input.string(title='Position', defval='Middle Right', options=['Bottom Left', 'Bottom Right', 'Top Left', 'Top Right', 'Middle Right'], group="Table Position")
var pos = posInput == 'Bottom Left' ? position.bottom_left : posInput == 'Bottom Right' ? position.bottom_right : posInput == 'Top Left' ? position.top_left : posInput == 'Top Right' ? position.top_right : posInput == 'Middle Right' ? position.middle_right: na
var table table_atr = table.new(pos, 15, 15, border_width=3)
if barstate.islast
table.cell(table_atr, 0, 0, 'EMA 10 ', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 0, 1, calc_ema10>=haclose? "Long" : "Short" , text_color=color.white, text_size=size.normal, bgcolor= calc_ema10>=haclose? color.green : color.red)
table.cell(table_atr, 1, 0, 'EMA 20 ', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 1, 1, calc_ema20>=haclose? "Long" : "Short", text_color=color.white, text_size=size.normal, bgcolor= calc_ema20>=haclose? color.green : color.red)
table.cell(table_atr, 2, 0, 'EMA 50 ', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 2, 1, calc_ema50>=haclose? "Long" : "Short", text_color=color.white, text_size=size.normal, bgcolor= calc_ema50>=haclose? color.green : color.red)
table.cell(table_atr, 0, 2, 'SMA 10 ', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 0, 3, calc_sma10>=haclose? "Long" : "Short", text_color=color.white, text_size=size.normal, bgcolor= calc_sma10>=haclose? color.green : color.red)
table.cell(table_atr, 1, 2, 'SMA 20 ', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 1, 3, calc_sma20>=haclose? "Long" : "Short", text_color=color.white, text_size=size.normal, bgcolor= calc_sma20>=haclose? color.green : color.red)
table.cell(table_atr, 2, 2, 'SMA 50 ', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 2, 3, calc_sma50>=haclose? "Long" : "Short", text_color=color.white, text_size=size.normal, bgcolor= calc_sma50>=haclose? color.green : color.red)
table.cell(table_atr, 0, 4, 'VWAP Daily', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 0, 5, ta.vwap>haclose? "Long" : "Short", text_color=color.white, text_size=size.normal, bgcolor= ta.vwap>haclose? color.green : color.red)
table.cell(table_atr, 1, 4, 'Daily TOP', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 1, 5, str.tostring(daily_close+gica, '#.##'), text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table.cell(table_atr, 2, 4, 'Daily BOT', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table.cell(table_atr, 2, 5, str.tostring(daily_close-gica, '#.##'), text_color=color.white, text_size=size.normal, bgcolor=color.maroon)
plot(daily_close+gica, title='Daily TOP ATR')
plot(daily_close-gica , title='Daily BOT ATR')
|
Multiple Moving Averages | https://www.tradingview.com/script/VBHEhTFa-Multiple-Moving-Averages/ | MoonKoder | https://www.tradingview.com/u/MoonKoder/ | 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/
// Β© MoonKoder
//@version=5
indicator(title = "Multiple Moving Averages", shorttitle = 'Multi Mov Avg', overlay = true)
// ======================================================
// == ==
// == I N P U T P A R A M E T E R S ==
// == ==
// ======================================================
// {
// Write ToolTips for User Input Parameteres
// {
ToolTip_DEMA = "DEMA - Double Exponential Moving Average\n"
ToolTip_EMA = "EMA - Exponential Moving Average\n"
ToolTip_HMA = "HMA - Hull Moving Average\n"
ToolTip_LSMA = "SLMA - Least Squares Moving Average\n"
ToolTip_RMA = "RMA - Relative Strength Moving Average\n"
ToolTip_SMA = "SMA - Simple Moving Average\n"
ToolTip_SMMA = "SMMA - Smoothed Moving Average\n"
ToolTip_TEMA = "TEMA - Triple Exponential Moving Average\n"
ToolTip_VWMA = "VWMA - Volume Weighted Moving Average\n"
ToolTip_WMA = "WMA - Weighted Moving Average"
ToolTip_Enable = "If checked, uses the current Moving Average"
ToolTip_Smooth = ToolTip_DEMA + ToolTip_EMA + ToolTip_HMA + ToolTip_LSMA + ToolTip_RMA + ToolTip_SMA + ToolTip_SMMA + ToolTip_TEMA + ToolTip_VWMA + ToolTip_WMA
ToolTip_Period = "Number of candles to lookback to calculate the Moving Average"
ToolTip_Source = "Calculates the Moving Average based on selected Source"
ToolTip_Color = "Sets the color to draw the Moving Average"
ToolTip_Resol = "Sets the Timeframe for Moving Average"
ToolTip_Candle = "Defines the type of candle for the source to be in study"
ToolTip_Gap = "Determines if the plot has a gap formation or continuous shape (just valid for higher timeframes"
ToolTip_Line = "Sets the Moving Average's line thickness"
// }
// Get User Inputs
// {
gr_MovAvg1 = "Moving Average 1"
Use_MovAvg_1 = input.bool(title = "Enable", defval = true, group = gr_MovAvg1, tooltip = ToolTip_Enable)
Smooth_MovAvg_1 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg1, tooltip = ToolTip_Smooth)
Period_MovAvg_1 = input.int(title = "Period", defval = 21, minval = 1, group = gr_MovAvg1, tooltip = ToolTip_Period)
Source_MovAvg_1 = input.source(title = "Source", defval = close, group = gr_MovAvg1, tooltip = ToolTip_Source)
Resol_MovAvg_1 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg1, tooltip = ToolTip_Resol)
Candle_MovAvg_1 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg1, tooltip = ToolTip_Candle)
Gap_MovAvg_1 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg1, tooltip = ToolTip_Gap)
Line_MovAvg_1 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg1, tooltip = ToolTip_Line)
Color_MovAvg_1 = input.color(title = "Color", defval = color.teal, group = gr_MovAvg1, tooltip = ToolTip_Color)
gr_MovAvg2 = "Moving Average 2"
Use_MovAvg_2 = input.bool(title = "Enable", defval = true, group = gr_MovAvg2, tooltip = ToolTip_Enable)
Smooth_MovAvg_2 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg2, tooltip = ToolTip_Smooth)
Period_MovAvg_2 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg2, tooltip = ToolTip_Period)
Source_MovAvg_2 = input.source(title = "Source", defval = close, group = gr_MovAvg2, tooltip = ToolTip_Source)
Resol_MovAvg_2 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg2, tooltip = ToolTip_Resol)
Candle_MovAvg_2 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg2, tooltip = ToolTip_Candle)
Gap_MovAvg_2 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg2, tooltip = ToolTip_Gap)
Line_MovAvg_2 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg2, tooltip = ToolTip_Line)
Color_MovAvg_2 = input.color(title = "Color", defval = color.blue, group = gr_MovAvg2, tooltip = ToolTip_Color)
gr_MovAvg3 = "Moving Average 3"
Use_MovAvg_3 = input.bool(title = "Enable", defval = true, group = gr_MovAvg3, tooltip = ToolTip_Enable)
Smooth_MovAvg_3 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg3, tooltip = ToolTip_Smooth)
Period_MovAvg_3 = input.int(title = "Period", defval = 200, minval = 1, group = gr_MovAvg3, tooltip = ToolTip_Period)
Source_MovAvg_3 = input.source(title = "Source", defval = close, group = gr_MovAvg3, tooltip = ToolTip_Source)
Resol_MovAvg_3 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg3, tooltip = ToolTip_Resol)
Candle_MovAvg_3 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg3, tooltip = ToolTip_Candle)
Gap_MovAvg_3 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg3, tooltip = ToolTip_Gap)
Line_MovAvg_3 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg3, tooltip = ToolTip_Line)
Color_MovAvg_3 = input.color(title = "Color", defval = color.red, group = gr_MovAvg3, tooltip = ToolTip_Color)
gr_MovAvg4 = "Moving Average 4"
Use_MovAvg_4 = input.bool(title = "Enable", defval = false, group = gr_MovAvg4, tooltip = ToolTip_Enable)
Smooth_MovAvg_4 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg4, tooltip = ToolTip_Smooth)
Period_MovAvg_4 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg4, tooltip = ToolTip_Period)
Source_MovAvg_4 = input.source(title = "Source", defval = close, group = gr_MovAvg4, tooltip = ToolTip_Source)
Resol_MovAvg_4 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg4, tooltip = ToolTip_Resol)
Candle_MovAvg_4 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg4, tooltip = ToolTip_Candle)
Gap_MovAvg_4 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg4, tooltip = ToolTip_Gap)
Line_MovAvg_4 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg4, tooltip = ToolTip_Line)
Color_MovAvg_4 = input.color(title = "Color", defval = color.black, group = gr_MovAvg4, tooltip = ToolTip_Color)
gr_MovAvg5 = "Moving Average 5"
Use_MovAvg_5 = input.bool(title = "Enable", defval = false, group = gr_MovAvg5, tooltip = ToolTip_Enable)
Smooth_MovAvg_5 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg5, tooltip = ToolTip_Smooth)
Period_MovAvg_5 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg5, tooltip = ToolTip_Period)
Source_MovAvg_5 = input.source(title = "Source", defval = close, group = gr_MovAvg5, tooltip = ToolTip_Source)
Resol_MovAvg_5 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg5, tooltip = ToolTip_Resol)
Candle_MovAvg_5 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg5, tooltip = ToolTip_Candle)
Gap_MovAvg_5 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg5, tooltip = ToolTip_Gap)
Line_MovAvg_5 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg5, tooltip = ToolTip_Line)
Color_MovAvg_5 = input.color(title = "Color", defval = color.black, group = gr_MovAvg5, tooltip = ToolTip_Color)
gr_MovAvg6 = "Moving Average 6"
Use_MovAvg_6 = input.bool(title = "Enable", defval = false, group = gr_MovAvg6, tooltip = ToolTip_Enable)
Smooth_MovAvg_6 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg6, tooltip = ToolTip_Smooth)
Period_MovAvg_6 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg6, tooltip = ToolTip_Period)
Source_MovAvg_6 = input.source(title = "Source", defval = close, group = gr_MovAvg6, tooltip = ToolTip_Source)
Resol_MovAvg_6 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg6, tooltip = ToolTip_Resol)
Candle_MovAvg_6 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg5, tooltip = ToolTip_Candle)
Gap_MovAvg_6 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg6, tooltip = ToolTip_Gap)
Line_MovAvg_6 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg6, tooltip = ToolTip_Line)
Color_MovAvg_6 = input.color(title = "Color", defval = color.black, group = gr_MovAvg6, tooltip = ToolTip_Color)
gr_MovAvg7 = "Moving Average 7"
Use_MovAvg_7 = input.bool(title = "Enable", defval = false, group = gr_MovAvg7, tooltip = ToolTip_Enable)
Smooth_MovAvg_7 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg7, tooltip = ToolTip_Smooth)
Period_MovAvg_7 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg7, tooltip = ToolTip_Period)
Source_MovAvg_7 = input.source(title = "Source", defval = close, group = gr_MovAvg7, tooltip = ToolTip_Source)
Resol_MovAvg_7 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg7, tooltip = ToolTip_Resol)
Candle_MovAvg_7 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg7, tooltip = ToolTip_Candle)
Gap_MovAvg_7 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg7, tooltip = ToolTip_Gap)
Line_MovAvg_7 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg7, tooltip = ToolTip_Line)
Color_MovAvg_7 = input.color(title = "Color", defval = color.blue, group = gr_MovAvg7, tooltip = ToolTip_Color)
gr_MovAvg8 = "Moving Average 8"
Use_MovAvg_8 = input.bool(title = "Enable", defval = false, group = gr_MovAvg8, tooltip = ToolTip_Enable)
Smooth_MovAvg_8 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg8, tooltip = ToolTip_Smooth)
Period_MovAvg_8 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg8, tooltip = ToolTip_Period)
Source_MovAvg_8 = input.source(title = "Source", defval = close, group = gr_MovAvg8, tooltip = ToolTip_Source)
Resol_MovAvg_8 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg8, tooltip = ToolTip_Resol)
Candle_MovAvg_8 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg8, tooltip = ToolTip_Candle)
Gap_MovAvg_8 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg8, tooltip = ToolTip_Gap)
Line_MovAvg_8 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg8, tooltip = ToolTip_Line)
Color_MovAvg_8 = input.color(title = "Color", defval = color.black, group = gr_MovAvg8, tooltip = ToolTip_Color)
gr_MovAvg9 = "Moving Average 9"
Use_MovAvg_9 = input.bool(title = "Enable", defval = false, group = gr_MovAvg9, tooltip = ToolTip_Enable)
Smooth_MovAvg_9 = input.string(title = "Smooth", defval = "EMA", options = ["DEMA", "EMA", "HMA", "LSMA", "RMA", "SMA", "SMMA", "TEMA", "VWMA", "WMA"], group = gr_MovAvg9, tooltip = ToolTip_Smooth)
Period_MovAvg_9 = input.int(title = "Period", defval = 50, minval = 1, group = gr_MovAvg9, tooltip = ToolTip_Period)
Source_MovAvg_9 = input.source(title = "Source", defval = close, group = gr_MovAvg9, tooltip = ToolTip_Source)
Resol_MovAvg_9 = input.timeframe(title = "TimeFrame", defval = "15", group = gr_MovAvg9, tooltip = ToolTip_Resol)
Candle_MovAvg_9 = input.string(title = "Candle Type", defval = "01 - Traditional", options = ["01 - Traditional", "02 - Renko", "03 - Line Break", "04 - Kagi"], group = gr_MovAvg9, tooltip = ToolTip_Candle)
Gap_MovAvg_9 = input.bool(title = "Use Gap", defval = true, group = gr_MovAvg9, tooltip = ToolTip_Gap)
Line_MovAvg_9 = input.int(title = "Line Width", defval = 2, minval = 1, maxval = 5, group = gr_MovAvg9, tooltip = ToolTip_Line)
Color_MovAvg_9 = input.color(title = "Color", defval = color.black, group = gr_MovAvg9, tooltip = ToolTip_Color)
// }
// }
// ======================================================
// == ==
// == S U P P O R T C A L C U L A T I O N S ==
// == ==
// ======================================================
// {
// Function to Calculate All Sort of Moving Averages
// {
Function_MovAvg(_Source, _Period, _Smooth) =>
MovAvg_Smooth = switch _Smooth
"RMA" =>
ta.rma(_Source, _Period)
"SMA" =>
ta.sma(_Source, _Period)
"EMA" =>
ta.ema(_Source, _Period)
"WMA" =>
ta.wma(_Source, _Period)
"HMA" =>
ta.hma(_Source, _Period)
"SMMA" =>
SMMA = 0.0
Sma = ta.sma(_Source, _Period)
SMMA := na(SMMA[1]) ? Sma : (SMMA[1] * (_Period - 1) + _Source) / _Period
"LSMA" =>
LSMA = ta.linreg(_Source, _Period, 0)
"TEMA" =>
Ema1 = ta.ema(_Source, _Period)
Ema2 = ta.ema(Ema1, _Period)
Ema3 = ta.ema(Ema2, _Period)
TEMA = 3 * (Ema1 - Ema2) + Ema3
"DEMA" =>
Ema1 = ta.ema(_Source, _Period)
Ema2 = ta.ema(Ema1, _Period)
DEMA = 2 * Ema1 - Ema2
"VWMA" =>
ta.vwma(_Source, _Period)
// }
// Function to Determine The Choosen Ticker Types
// {
Function_TickerType(_TickerType) =>
if _TickerType == "01 - Current"
syminfo.tickerid
else if _TickerType == "02 - Heikin Ashi"
ticker.heikinashi(syminfo.tickerid)
else if _TickerType == "03 - Renko"
ticker.renko(syminfo.tickerid, "ATR", 10)
else if _TickerType == "04 - Line Break"
ticker.linebreak(syminfo.tickerid, 3)
else if _TickerType == "05 - Kagi"
ticker.kagi(syminfo.tickerid, 3)
// }
// }
// ======================================================
// == ==
// == R E Q U E S T S & P L O T S ==
// == ==
// ======================================================
// {
// Request the Calculation for each Moving Average With Own Settings
// {
MovAvg_1_GapOn = request.security(Function_TickerType(Candle_MovAvg_1), Resol_MovAvg_1, Function_MovAvg(Source_MovAvg_1, Period_MovAvg_1, Smooth_MovAvg_1), barmerge.gaps_on)
MovAvg_1_GapOff = request.security(Function_TickerType(Candle_MovAvg_1), Resol_MovAvg_1, Function_MovAvg(Source_MovAvg_1, Period_MovAvg_1, Smooth_MovAvg_1), barmerge.gaps_off)
MovAvg_1 = Gap_MovAvg_1 ? MovAvg_1_GapOn : MovAvg_1_GapOff
MovAvg_2_GapOn = request.security(Function_TickerType(Candle_MovAvg_2), Resol_MovAvg_2, Function_MovAvg(Source_MovAvg_2, Period_MovAvg_2, Smooth_MovAvg_2), barmerge.gaps_on)
MovAvg_2_GapOff = request.security(Function_TickerType(Candle_MovAvg_2), Resol_MovAvg_2, Function_MovAvg(Source_MovAvg_2, Period_MovAvg_2, Smooth_MovAvg_2), barmerge.gaps_off)
MovAvg_2 = Gap_MovAvg_2 ? MovAvg_2_GapOn : MovAvg_2_GapOff
MovAvg_3_GapOn = request.security(Function_TickerType(Candle_MovAvg_3), Resol_MovAvg_3, Function_MovAvg(Source_MovAvg_3, Period_MovAvg_3, Smooth_MovAvg_3), barmerge.gaps_on)
MovAvg_3_GapOff = request.security(Function_TickerType(Candle_MovAvg_3), Resol_MovAvg_3, Function_MovAvg(Source_MovAvg_3, Period_MovAvg_3, Smooth_MovAvg_3), barmerge.gaps_off)
MovAvg_3 = Gap_MovAvg_3 ? MovAvg_3_GapOn : MovAvg_3_GapOff
MovAvg_4_GapOn = request.security(Function_TickerType(Candle_MovAvg_4), Resol_MovAvg_4, Function_MovAvg(Source_MovAvg_4, Period_MovAvg_4, Smooth_MovAvg_4), barmerge.gaps_on)
MovAvg_4_GapOff = request.security(Function_TickerType(Candle_MovAvg_4), Resol_MovAvg_4, Function_MovAvg(Source_MovAvg_4, Period_MovAvg_4, Smooth_MovAvg_4), barmerge.gaps_off)
MovAvg_4 = Gap_MovAvg_4 ? MovAvg_4_GapOn : MovAvg_4_GapOff
MovAvg_5_GapOn = request.security(Function_TickerType(Candle_MovAvg_5), Resol_MovAvg_5, Function_MovAvg(Source_MovAvg_5, Period_MovAvg_5, Smooth_MovAvg_5), barmerge.gaps_on)
MovAvg_5_GapOff = request.security(Function_TickerType(Candle_MovAvg_5), Resol_MovAvg_5, Function_MovAvg(Source_MovAvg_5, Period_MovAvg_5, Smooth_MovAvg_5), barmerge.gaps_off)
MovAvg_5 = Gap_MovAvg_5 ? MovAvg_5_GapOn : MovAvg_5_GapOff
MovAvg_6_GapOn = request.security(Function_TickerType(Candle_MovAvg_6), Resol_MovAvg_6, Function_MovAvg(Source_MovAvg_6, Period_MovAvg_6, Smooth_MovAvg_6), barmerge.gaps_on)
MovAvg_6_GapOff = request.security(Function_TickerType(Candle_MovAvg_6), Resol_MovAvg_6, Function_MovAvg(Source_MovAvg_6, Period_MovAvg_6, Smooth_MovAvg_6), barmerge.gaps_off)
MovAvg_6 = Gap_MovAvg_6 ? MovAvg_6_GapOn : MovAvg_6_GapOff
MovAvg_7_GapOn = request.security(Function_TickerType(Candle_MovAvg_7), Resol_MovAvg_7, Function_MovAvg(Source_MovAvg_7, Period_MovAvg_7, Smooth_MovAvg_7), barmerge.gaps_on)
MovAvg_7_GapOff = request.security(Function_TickerType(Candle_MovAvg_7), Resol_MovAvg_7, Function_MovAvg(Source_MovAvg_7, Period_MovAvg_7, Smooth_MovAvg_7), barmerge.gaps_off)
MovAvg_7 = Gap_MovAvg_7 ? MovAvg_7_GapOn : MovAvg_7_GapOff
MovAvg_8_GapOn = request.security(Function_TickerType(Candle_MovAvg_8), Resol_MovAvg_8, Function_MovAvg(Source_MovAvg_8, Period_MovAvg_8, Smooth_MovAvg_8), barmerge.gaps_on)
MovAvg_8_GapOff = request.security(Function_TickerType(Candle_MovAvg_8), Resol_MovAvg_8, Function_MovAvg(Source_MovAvg_8, Period_MovAvg_8, Smooth_MovAvg_8), barmerge.gaps_off)
MovAvg_8 = Gap_MovAvg_8 ? MovAvg_8_GapOn : MovAvg_8_GapOff
MovAvg_9_GapOn = request.security(Function_TickerType(Candle_MovAvg_9), Resol_MovAvg_9, Function_MovAvg(Source_MovAvg_9, Period_MovAvg_9, Smooth_MovAvg_9), barmerge.gaps_on)
MovAvg_9_GapOff = request.security(Function_TickerType(Candle_MovAvg_9), Resol_MovAvg_9, Function_MovAvg(Source_MovAvg_9, Period_MovAvg_9, Smooth_MovAvg_9), barmerge.gaps_off)
MovAvg_9 = Gap_MovAvg_9 ? MovAvg_9_GapOn : MovAvg_9_GapOff
// }
// Plot The Selected Moving Averages
// {
PlotMovAvg_1 = plot(Use_MovAvg_1 ? MovAvg_1 : na, title = "Moving Average 1", linewidth = Line_MovAvg_1, color = Color_MovAvg_1)
PlotMovAvg_2 = plot(Use_MovAvg_2 ? MovAvg_2 : na, title = "Moving Average 2", linewidth = Line_MovAvg_2, color = Color_MovAvg_2)
PlotMovAvg_3 = plot(Use_MovAvg_3 ? MovAvg_3 : na, title = "Moving Average 3", linewidth = Line_MovAvg_3, color = Color_MovAvg_3)
PlotMovAvg_4 = plot(Use_MovAvg_4 ? MovAvg_4 : na, title = "Moving Average 4", linewidth = Line_MovAvg_4, color = Color_MovAvg_4)
PlotMovAvg_5 = plot(Use_MovAvg_5 ? MovAvg_5 : na, title = "Moving Average 5", linewidth = Line_MovAvg_5, color = Color_MovAvg_5)
PlotMovAvg_6 = plot(Use_MovAvg_6 ? MovAvg_6 : na, title = "Moving Average 6", linewidth = Line_MovAvg_6, color = Color_MovAvg_6)
PlotMovAvg_7 = plot(Use_MovAvg_7 ? MovAvg_7 : na, title = "Moving Average 7", linewidth = Line_MovAvg_7, color = Color_MovAvg_7)
PlotMovAvg_8 = plot(Use_MovAvg_8 ? MovAvg_8 : na, title = "Moving Average 8", linewidth = Line_MovAvg_8, color = Color_MovAvg_8)
PlotMovAvg_9 = plot(Use_MovAvg_9 ? MovAvg_9 : na, title = "Moving Average 9", linewidth = Line_MovAvg_9, color = Color_MovAvg_9)
// }
// }
// ======================================================
// == ==
// == P R O G R A M E N D ==
// == ==
// ====================================================== |
fi - 5EMA + BB | https://www.tradingview.com/script/Rm8pYLta/ | vazkez | https://www.tradingview.com/u/vazkez/ | 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/
// Β© vazkez
//Indicador adaptado a medida sobre "4EMA lines EMA Cross @Philacone + Bollinger Bands by Alessiof"
//Todos los meritos para Alessiof, muchas gracias!!!
//@version=5
indicator(title="fi - 5EMA + BB", shorttitle="fi-5EMAS", overlay = true, timeframe="", timeframe_gaps=true)
//------------ENTRADAS----------------------------
Ema10 = input.int(10 ,"EMA 10" , minval=1, group="Emas")
Ema21 = input.int(21 ,"EMA 21" , minval=1, group="Emas")
Ema50 = input.int(50 ,"EMA 50" ,minval=1 , group="Emas")
Ema100 = input.int(100,"EMA 100", minval=1, group="Emas")
Ema200 = input.int(200,"EMA 200", minval=1, group="Emas")
//------------VARIABLES----------------------------
xPrice = close
xEMA1 = ta.ema(xPrice, Ema10)
xEMA2 = ta.ema(xPrice, Ema21)
xEMA3 = ta.ema(xPrice, Ema50)
xEMA4 = ta.ema(xPrice, Ema100)
xEMA5 = ta.ema(xPrice, Ema200)
//------------SALIDAS----------------------------
plot(xEMA1, color=color.new(color.yellow, transp=0) ,linewidth=2, title="EMA 10") //Color amarillo
plot(xEMA2, color=color.new(color.lime, transp=0) ,linewidth=2, title="EMA 21") //Color lima
plot(xEMA3, color=color.new(#FF3371, transp=0) ,linewidth=2, title="EMA 50") //Color rojo brillante
plot(xEMA4, color=color.new(#33D7FF, transp=0) ,linewidth=2, title="EMA 100") //Color azul cielo
plot(xEMA5, color=color.new(color.blue, transp=0) ,linewidth=2, title="EMA 200") //Color azul
//------------BANDAS DE BOLLINGER----------------------------
// ENTRADAS BB
length = input.int(20, minval=1, title="Longitud BB", group="Bandas de Bollinger")
src = input(close, title="Fuente BB", group="Bandas de Bollinger")
mult = input.float(2, minval=0.0001, maxval=50, title="Multiplicador BB", group="Bandas de Bollinger")
// VARIABLES BB
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
// SALIDA BB
plot(basis, title="BB Media", color=color.new(color.gray,15), style=plot.style_circles)
p1 = plot(upper, title="BB Superior", color=color.new(color.gray,15))
p2 = plot(lower, title="BB Inferior", color=color.new(color.gray,15))
fill(p1, p2, color=color.new(color.white,95), title="BB Fondo")
|
Rally Candle (End Game ) 26/04/2022 | https://www.tradingview.com/script/gAd5MIs2-Rally-Candle-End-Game-26-04-2022/ | LuxTradeVenture | https://www.tradingview.com/u/LuxTradeVenture/ | 248 | 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/
// Β© MINTYFRESH97
//@version=5
indicator("Rallie Candle (2)" ,overlay=true )
//swing high/low filter
swingHigh = high == ta.highest(high,6) or high[1] == ta.highest(high,6)
//user input
var g_ema = "EMA Filter"
emaLength = input.int(title="EMA Length", defval=50, tooltip="Length of the EMA filter", group=g_ema)
useEmaFilter = input.bool(title="Use EMA Filter?", defval=false, tooltip="Turns on/off the EMA filter", group=g_ema)
// Get EMA filter
ema = ta.ema(close, emaLength)
emaFilterLong = not useEmaFilter or close > ema
emaFilterShort = not useEmaFilter or close < ema
//DETECT MARUBUZO
upUpDownCloses = (close[3] > close[4]) and (close[2] > close[3]) and
(close < close[1]) and emaFilterShort and swingHigh
// Plot our candle patterns
barcolor(upUpDownCloses ? color.blue :na)
plotshape(upUpDownCloses, style=shape.diamond,size=size.tiny, color=color.red, text="R",location=location.abovebar)
alertcondition(upUpDownCloses, "RallieCandle", "RallieCandle detected for {{ticker}}") |
MARSI | https://www.tradingview.com/script/tdrH5dob-MARSI/ | CapovexIntech | https://www.tradingview.com/u/CapovexIntech/ | 43 | 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/
// Β© CapovexIntech
//@version=5
indicator("MARSI", overlay=false)
//ma10 = ta.sma(close, 10)
//ma40 = ta.sma(close, 40)
//newma = ma10 - ma40
// Getting inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal
// colors
col_marsi = input(#2962FF, "Marsi Lineββ", group="Color Settings", inline="MARSI")
col_signal = input(#FF6D00, "Signal Lineββ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Aboveβββ
Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "BelowβGrow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")
// RSI Formula
rsiLengthInput = 5
rsiSourceInput = hist
maLengthInput = 14
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
marsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
marsiMA = ta.ema(marsi, maLengthInput)
plot(marsi, "Marsi", color=col_marsi)
plot(marsiMA, "Signal", color=col_signal)
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
|
SuperJump HTF SuperTrend for Scalping | https://www.tradingview.com/script/euj5xjLy/ | SuperJump | https://www.tradingview.com/u/SuperJump/ | 518 | 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/
// Β© SuperJump
//@version=5
indicator("SuperJump HTF SuperTrend for Scalping", shorttitle="SJump ST Scalping" , overlay=true)
htf = input.timeframe(title="Higher TimeFrame",defval="15")
Factor=input.float(1.7, minval=1,maxval = 100)
Pd=input.int(14,title="Period", minval=1,maxval = 100)
LossLevel = input.int(-35, title="Loss Cut")
Topfib3Level = input.int(25, title="1st Defence Line")
Topfib2Level = input.int(14, title="2nd Defence Line")
Topfib1Level = input.int(7, title="3rd Defence Line")
MUp=request.security(syminfo.tickerid,htf,hl2-(Factor*ta.atr(Pd)))
MDn=request.security(syminfo.tickerid,htf,hl2+(Factor*ta.atr(Pd)))
Mclose=request.security(syminfo.tickerid,htf,close)
MTrendUp = 0.0
MTrendDown = 0.0
Tsl = 0.0
MTsl = 0.0
MTslR = 0.0
MTrend = 0.0
Trend = 0.0
LossLine = 0.0
MTrendUp := Mclose[1]>MTrendUp[1]? math.max(MUp,MTrendUp[1]) : MUp
MTrendDown := Mclose[1]<MTrendDown[1]? math.min(MDn,MTrendDown[1]) : MDn
MTrend := Mclose > MTrendDown[1] ? 1: Mclose< MTrendUp[1]? -1: nz(MTrend[1],1)
MTsl := MTrend==1? MTrendUp: MTrendDown
MTslR := MTrend==1? MTrendDown :MTrendUp
TFL1 = MTsl +(MTslR -MTsl)*Topfib1Level /100
TFL2 =MTsl +(MTslR -MTsl)*Topfib2Level /100
TFL3 =MTsl +(MTslR -MTsl)*Topfib3Level /100
LossLine:=MTsl +(MTslR -MTsl)*LossLevel /100
Mlinecolor = MTrend == 1 ? color.green : color.red
mtp = plot(MTsl, color = Mlinecolor , style = plot.style_line , linewidth = 2,title = "HTF SuperTrend")
tfl3p = plot(TFL3, color = color.gray, style = plot.style_line , linewidth = 1,title = "HTF SuperTrend Defence Line1")
tfl2p = plot(TFL2, color = color.gray, style = plot.style_line , linewidth = 1,title = "HTF SuperTrend Defence Line2")
tfl1p = plot(TFL1, color = color.gray, style = plot.style_line , linewidth = 1,title = "HTF SuperTrend Defence Line3")
plot(LossLine, color = color.red, style = plot.style_cross , linewidth = 2,title = "HTF SuperTrend Losscut")
fill(mtp, tfl1p, color=color.new(Mlinecolor,70))
fill(tfl1p, tfl2p, color=color.new(Mlinecolor,80))
fill(tfl2p, tfl3p, color=color.new(Mlinecolor,90))
|
Portfolio of open positions ENG | https://www.tradingview.com/script/FCpIBU9l-portfolio-of-open-positions-eng/ | FUNDAMENTALIST7140 | https://www.tradingview.com/u/FUNDAMENTALIST7140/ | 72 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//ββββ
ββπ
Άπ
΄π
Ύ-π
²π
°ππ
Ώπ
΄πβββ
βββ
//@version=5
indicator('Portfolio of open positions ENG', overlay = true, format = format.volume)
// Input Parametr (ΠΡ
ΠΎΠ΄Π½ΠΎΠΉ ΠΠ°ΡΠ°ΠΌΠ΅ΡΡ) {
// textsize (Π²ΡΡΠΎΡΠ° ΡΠ΅ΠΊΡΡΠ°)
AUTO = size.auto
SMALL = size.small
NORMAL = size.normal
LARGE = size.large
//Label arrangement (Π Π°ΡΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ ΡΠ°Π±Π»ΠΈΡΡ)
Left = position.top_left
Centr = position.top_center
Right = position.top_right
MLeft = position.middle_left
MCentr = position.middle_center
MRight = position.middle_right
BLeft = position.bottom_left
BCentr = position.bottom_center
BRight = position.bottom_right
//Label arrangement (Π Π°ΡΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ ΡΡΠΈΠΊΠ΅ΡΠΎΠΊ)
xcross = label.style_xcross
cross = label.style_cross
triangleup = label.style_triangleup
triangledown= label.style_triangledown
flag = label.style_flag
circle = label.style_circle
arrowup = label.style_arrowup
arrowdown = label.style_arrowdown
label_up = label.style_label_up
label_down = label.style_label_down
label_left = label.style_label_left
label_right = label.style_label_right
lower_left = label.style_label_lower_left
lower_right = label.style_label_lower_right
upper_left = label.style_label_upper_left
upper_right = label.style_label_upper_right
center = label.style_label_center
square = label.style_square
diamond = label.style_diamond
//}
// Tooltip (ΠΠΎΠ΄ΡΠΊΠ°Π·ΠΊΠ°) {
DataBuy = 'Date of purchase of shares'
Name = 'The ticker of the stock you bought. Unfortunately, it is only possible to insert a ticker, the company names cannot be inserted yet'
Currency = 'The currency in which your company is traded, it is mandatory to specify and check'
Stocks = 'The number of shares, not to be confused with lots. If there is more than 1 stock in the lot, then manually multiply by the amount in
the lot. The information can be found at the time of purchase or in the information about the tool'
PurchpriceI = 'The price you bought the shares for'
CurrpricI = 'The current price of the stock. The cost is taken according to your subscription in TradingView (may be delayed)'
InitiCost = 'The total value of your shares when buying'
InitiCostP = 'The total value of your shares when buying in rubles. You need it if you have not only Russian stocks in your portfolio'
Liquvalue = 'The total (liquid) value of your shares if you sell right now'
LiquvalueP = 'The total (liquid) value of your shares if you sell right now in rubles. You need it if you have not only Russian stocks in your portfolio'
MoreLos = "Profit/loss expressed in three types, in %, in rubles and from the total portfolio. Hover over each cell you don't understand and there will be a hint"
MoreLoss = 'Profit/loss as a % of the purchase price'
MoreLossI = 'Profit/loss in rubles from the purchase price'
MoreLossK = 'Profit loss as a % of the total portfolio (i.e. from the initial deposit, by default 1000000 β½)'
Sharportfo = 'The share of a single stock from the total portfolio, i.e. how many percent does this stock take from the entire portfolio'
// }
// Input data (ΠΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅) {
initialCapital = input.int(1000000, 'Initial capital in β½')
Portfolioshare = input.int(10, 'Share of 1 share in the portfolio', maxval = 100)
//Show the number of shares (ΠΠΎΠΊΠ°Π·Π°ΡΡ ΡΠΈΡΠ»ΠΎ Π°ΠΊΡΠΈΠΉ)
ShowShare = input.string('1-5', 'Show number of rows', options = ['1-5', '1-10', '1-15', '1-20'], inline = '1')
//}
// Table input parameters (Π²Ρ
ΠΎΠ΄Π½ΡΠΉ ΠΏΠ°ΡΠ°ΠΌΠ΅ΡΡΡ ΡΠ°Π±Π»ΠΈΡΡ) {
GPTab = 'Table'
textsize = input.string(NORMAL, 'Text height', options = [AUTO, SMALL, NORMAL, LARGE], inline = '2', group = GPTab)
Position = input.string(MCentr, 'Position', options = [Left, Right, MLeft, MCentr, MRight, BLeft, BCentr, BRight, Centr], inline = '2', group = GPTab)
GPTab1 = 'Table Colors'
Textcolor = input.color(#000000, 'Text', inline ='0', group = GPTab1)
ColumColor = input.color(color.new(#FFFFFF, 30), 'Background', inline = '0', group = GPTab1)
HeadColor = input.color(color.new(#65b3ff, 50), 'Heading', inline = '1', group = GPTab1)
HeadTXTColor = input.color(color.new(#000000, 30), 'Title Text', inline = '1', group = GPTab1)
GPTab2 = 'Color difference in the table'
More = input.color(#4CAF50, title = 'Profit', inline = '1' , group = GPTab2)
Less = input.color(#ff0000, title = 'Loss', inline = '1' , group = GPTab2)
// }
// Input data tiker (ΠΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅ ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠΉ){
GP1 = '1 simbol'
Tiker1 = input.symbol('MOEX:GAZP', 'Stock selection', inline = '0', group = GP1)
Currency1 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP1)
QuanStock1 = input.int(1, 'Number of shares', step = 1, inline = '1', group = GP1)
Purchprice1 = input.float(100.0, 'Price', inline = '1', group = GP1)
Date1 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP1)
GP2 = '2 simbol'
Tiker2 = input.symbol('MOEX:SBER', 'Stock selection', inline = '0', group = GP2)
Currency2 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP2)
QuanStock2 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP2)
Purchprice2 = input.float(0.0, 'Price', inline = '1', group = GP2)
Date2 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP2)
GP3 = '3 simbol'
Tiker3 = input.symbol('MOEX:SBERP', 'Stock selection', inline = '0', group = GP3)
Currency3 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP3)
QuanStock3 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP3)
Purchprice3 = input.float(0.0, 'Price', inline = '1', group = GP3)
Date3 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP3)
GP4 = '4 simbol'
Tiker4 = input.symbol('MOEX:GMKN', 'Stock selection', inline = '0', group = GP4)
Currency4 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP4)
QuanStock4 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP4)
Purchprice4 = input.float(0.0, 'Price', inline = '1', group = GP4)
Date4 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP4)
GP5 = '5 simbol'
Tiker5 = input.symbol('MOEX:YNDX', 'Stock selection', inline = '0', group = GP5)
Currency5 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP5)
QuanStock5 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP5)
Purchprice5 = input.float(0.0, 'Price', inline = '1', group = GP5)
Date5 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP5)
GP6 = '6 simbol'
Tiker6 = input.symbol('MOEX:LKOH', 'Stock selection', inline = '0', group = GP6)
Currency6 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP6)
QuanStock6 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP6)
Purchprice6 = input.float(0.0, 'Price', inline = '1', group = GP6)
Date6 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP6)
GP7 = '7 simbol'
Tiker7 = input.symbol('MOEX:ALRS', 'Stock selection', inline = '0', group = GP7)
Currency7 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP7)
QuanStock7 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP7)
Purchprice7 = input.float(0.0, 'Price', inline = '1', group = GP7)
Date7 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP7)
GP8 = '8 simbol'
Tiker8 = input.symbol('MOEX:TCSG', 'Stock selection', inline = '0', group = GP8)
Currency8 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP8)
QuanStock8 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP8)
Purchprice8 = input.float(0.0, 'Price', inline = '1', group = GP8)
Date8 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP8)
GP9 = '9 simbol'
Tiker9 = input.symbol('MOEX:AFKS', 'Stock selection', inline = '0', group = GP9)
Currency9 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP9)
QuanStock9 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP9)
Purchprice9 = input.float(0.0, 'Price', inline = '1', group = GP9)
Date9 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP9)
GP10 = '10 simbol'
Tiker10 = input.symbol('MOEX:SNGSP', 'Stock selection', inline = '0', group = GP10)
Currency10 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP10)
QuanStock10 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP10)
Purchprice10 = input.float(0.0, 'Price', inline = '1', group = GP10)
Date10 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP10)
GP11 = '11 simbol'
Tiker11 = input.symbol('MOEX:VTBR', 'Stock selection', inline = '0', group = GP11)
Currency11 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP11)
QuanStock11 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP11)
Purchprice11 = input.float(0.0, 'Price', inline = '1', group = GP11)
Date11 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP11)
GP12 = '12 simbol'
Tiker12 = input.symbol('MOEX:VKCO', 'Stock selection', inline = '0', group = GP12)
Currency12 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP12)
QuanStock12 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP12)
Purchprice12 = input.float(0.0, 'Price', inline = '1', group = GP12)
Date12 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP12)
GP13 = '13 simbol'
Tiker13 = input.symbol('MOEX:MTSS', 'Stock selection', inline = '0', group = GP13)
Currency13 = input.string('β½', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP13)
QuanStock13 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP13)
Purchprice13 = input.float(0.0, 'Price', inline = '1', group = GP13)
Date13 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP13)
GP14 = '14 simbol'
Tiker14 = input.symbol('NASDAQ:TSLA', 'Stock selection', inline = '0', group = GP14)
Currency14 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP14)
QuanStock14 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP14)
Purchprice14 = input.float(0.0, 'Price', inline = '1', group = GP14)
Date14 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP14)
GP15 = '15 simbol'
Tiker15 = input.symbol('NYSE:SPCE', 'Stock selection', inline = '0', group = GP15)
Currency15 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP15)
QuanStock15 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP15)
Purchprice15 = input.float(0.0, 'Price', inline = '1', group = GP15)
Date15 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP15)
GP16 = '16 simbol'
Tiker16 = input.symbol('NYSE:BABA', 'Stock selection', inline = '0', group = GP16)
Currency16 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP16)
QuanStock16 = input.int(100, 'Number of shares', step = 1, inline = '1', group = GP16)
Purchprice16 = input.float(100.0, 'Price', inline = '1', group = GP16)
Date16 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP16)
GP17 = '17 simbol'
Tiker17 = input.symbol('NASDAQ:AAPL', 'Stock selection', inline = '0', group = GP17)
Currency17 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP17)
QuanStock17 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP17)
Purchprice17 = input.float(0.0, 'Price', inline = '1', group = GP17)
Date17 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP17)
GP18 = '18 simbol'
Tiker18 = input.symbol('NASDAQ:AMZN', 'Stock selection', inline = '0', group = GP18)
Currency18 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP18)
QuanStock18 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP18)
Purchprice18 = input.float(0.0, 'Price', inline = '1', group = GP18)
Date18 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP18)
GP19 = '19 simbol'
Tiker19 = input.symbol('NASDAQ:BIDU', 'Stock selection', inline = '0', group = GP19)
Currency19 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP19)
QuanStock19 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP19)
Purchprice19 = input.float(0.0, 'Price', inline = '1', group = GP19)
Date19 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP19)
GP20 = '20 simbol'
Tiker20 = input.symbol('NASDAQ:AMD', 'Stock selection', inline = '0', group = GP20)
Currency20 = input.string('οΌ', 'Currency of circulation', options = ['οΌ', 'β½'], inline = '0', group = GP20)
QuanStock20 = input.int(0, 'Number of shares', step = 1, inline = '1', group = GP20)
Purchprice20 = input.float(0.0, 'Price', inline = '1', group = GP20)
Date20 = input.time(timestamp('01 May 2022'), 'Date of purchase', inline = '2', group = GP20)
//}
// Displaying only the ticker (ΠΡΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΠ΅ ΡΠΎΠ»ΡΠΊΠΎ ΡΠΈΠΊΠ΅ΡΠ°) {
var Tik1 = syminfo.ticker(Tiker1)
var Tik2 = syminfo.ticker(Tiker2)
var Tik3 = syminfo.ticker(Tiker3)
var Tik4 = syminfo.ticker(Tiker4)
var Tik5 = syminfo.ticker(Tiker5)
var Tik6 = syminfo.ticker(Tiker6)
var Tik7 = syminfo.ticker(Tiker7)
var Tik8 = syminfo.ticker(Tiker8)
var Tik9 = syminfo.ticker(Tiker9)
var Tik10 = syminfo.ticker(Tiker10)
var Tik11 = syminfo.ticker(Tiker11)
var Tik12 = syminfo.ticker(Tiker12)
var Tik13 = syminfo.ticker(Tiker13)
var Tik14 = syminfo.ticker(Tiker14)
var Tik15 = syminfo.ticker(Tiker15)
var Tik16 = syminfo.ticker(Tiker16)
var Tik17 = syminfo.ticker(Tiker17)
var Tik18 = syminfo.ticker(Tiker18)
var Tik19 = syminfo.ticker(Tiker19)
var Tik20 = syminfo.ticker(Tiker20)
// }
// Calculating and adding values to the table (Π Π°ΡΡΠ΅Ρ ΠΈ Π΄ΠΎΠ±Π°Π²Π»Π΅Π½ΠΈΠ΅ Π² ΡΠ°Π±Π»ΠΈΡΡ Π·Π½Π°ΡΠ΅Π½ΠΈΠΉ) {
Table(_table_Id, _row, _Data, _TikID, _curren, _QuanStock, _QuanStock1, _Purchprice, _initialCapital)=>
Currentprice = 0.0
Currentprice := request.security(_TikID, timeframe.period, close, ignore_invalid_symbol=true)
InitialCost = 0.0
InitialCost := (_Purchprice * _QuanStock)
InitialCost1 = 0.0
InitialCost1 := (_Purchprice * _QuanStock) * request.security('USDRUB_TOM', timeframe.period, close, ignore_invalid_symbol=true)
Liquidvalue = 0.0
Liquidvalue := Currentprice * _QuanStock
Liquidvalue1 = 0.0
Liquidvalue1 := (Currentprice * _QuanStock) * request.security('USDRUB_TOM', timeframe.period, close, ignore_invalid_symbol=true)
priceChange = 0.0
priceChange := (1 - (_Purchprice / Currentprice)) * 100
chang = 0.0
chang := ((Liquidvalue - InitialCost) / InitialCost) * 100
ChangePercent = 0.0
ChangePercent := (Currentprice * _QuanStock) - (_Purchprice * _QuanStock)
ChangePercent1 = 0.0
ChangePercent1 := Liquidvalue1 - InitialCost1
changes = 0.0
changes := Liquidvalue - InitialCost
percentagetotal = 0.0
percentagetotal := (ChangePercent / _initialCapital) * 100
percentagetota1 = 0.0
percentagetota1 := (ChangePercent1 / _initialCapital) * 100
Shareoftotal = 0.0
Shareoftotal := (InitialCost / _initialCapital) * 100
Shareoftotal1 = 0.0
Shareoftotal1 := (InitialCost1 / _initialCapital) * 100
Suf = Currentprice < _Purchprice ? 'π±' : 'π₯'
table.cell(table_id = _table_Id, column = 0 , row = _row, text = str.format('{0, date, dd-MMM-yyyy}', _Data), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 1 , row = _row, text = str.tostring(_TikID), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 2 , row = _row, text = str.tostring(_curren), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 3 , row = _row, text = str.tostring(_QuanStock, '# ##0'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 4 , row = _row, text = str.tostring(_Purchprice, '# ##0.00'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 5 , row = _row, text = str.tostring(Currentprice, '# ##0.00') + Suf, text_color = Currentprice >= _Purchprice ? More : Less, text_size = textsize)
if _curren == 'β½'
table.cell(table_id = _table_Id, column = 6 , row = _row, text = str.tostring(InitialCost, '# ### ###0'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 7 , row = _row, text = str.tostring(InitialCost, '# ### ###0'), text_color=Textcolor, text_size = textsize)
else
table.cell(table_id = _table_Id, column = 6 , row = _row, text = str.tostring(InitialCost, '# ### ###0'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 7 , row = _row, text = str.tostring(InitialCost1, '# ### ###0'), text_color=Textcolor, text_size = textsize)
if _curren == 'β½'
table.cell(table_id = _table_Id, column = 8 , row = _row, text = str.tostring(Liquidvalue, '# ### ###0'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 9 , row = _row, text = str.tostring(Liquidvalue, '# ### ###0'), text_color=Textcolor, text_size = textsize)
else
table.cell(table_id = _table_Id, column = 8 , row = _row, text = str.tostring(Liquidvalue, '# ### ###0'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 9 , row = _row, text = str.tostring(Liquidvalue1, '# ### ###0'), text_color=Textcolor, text_size = textsize)
table.cell(table_id = _table_Id, column = 10 , row = _row, text = str.tostring(priceChange, format.percent), text_color = chang >= 0 ? More : Less, text_size = textsize, bgcolor = ColumColor)
if _curren == 'β½'
table.cell(table_id = _table_Id, column = 11 , row = _row, text = str.tostring(ChangePercent, '# ### ###0' ), text_color = chang >= 0 ? More : Less, text_size = textsize, bgcolor = ColumColor )
else
table.cell(table_id = _table_Id, column = 11 , row = _row, text = str.tostring(ChangePercent1, '# ### ###0' ), text_color = chang >= 0 ? More : Less, text_size = textsize, bgcolor = ColumColor )
if _curren == 'β½'
table.cell(table_id = _table_Id, column = 12 , row = _row, text = str.tostring(percentagetotal, format.percent), text_color = percentagetotal >= 0 ? More : Less, text_size = textsize)
else
table.cell(table_id = _table_Id, column = 12 , row = _row, text = str.tostring(percentagetota1, format.percent), text_color = percentagetota1 >= 0 ? More : Less, text_size = textsize)
if _curren == 'β½'
table.cell(table_id = _table_Id, column = 13, row = _row, text = str.tostring(Shareoftotal, format.percent), text_color=Textcolor, text_size = textsize, bgcolor = Shareoftotal > Portfolioshare ? #FF5252 : #4CAF50)
else
table.cell(table_id = _table_Id, column = 13, row = _row, text = str.tostring(Shareoftotal1, format.percent), text_color=Textcolor, text_size = textsize, bgcolor = Shareoftotal1 > Portfolioshare ? #FF5252 : #4CAF50)
// }
//plot table (ΠΎΡΡΠΈΡΠΎΠ²ΠΊΠ° ΡΠ°Π±Π»ΠΈΡΡ)
TableNum(_table_id, _column, _row, _value, _tool) =>
table.cell(table_id = _table_id, column = _column, row = _row, text = _value, bgcolor = HeadColor, text_color = HeadTXTColor , text_size = textsize, tooltip = _tool)
var table summary = table.new(position = Position, columns = 15, rows = 25, bgcolor = ColumColor, frame_color = #000000, frame_width = 2, border_color = #000000, border_width = 1)
// Header Input data (ΠΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅ Π·Π°Π³ΠΎΠ»ΠΎΠ²ΠΊΠ°) {
if barstate.islast
TableNum(summary, 0, 0, 'Date', DataBuy)
TableNum(summary, 1, 0, 'Simbol', Name)
TableNum(summary, 2, 0, 'Currency', Currency)
TableNum(summary, 3, 0, 'Quantity', Stocks)
TableNum(summary, 4, 0, 'Price ', PurchpriceI)
TableNum(summary, 5, 0, 'Current', CurrpricI)
TableNum(summary, 6, 0, 'Balance', InitiCost)
TableNum(summary, 7, 0, 'Balance', InitiCostP)
TableNum(summary, 8, 0, 'Market', Liquvalue)
TableNum(summary, 9, 0, 'Market', LiquvalueP)
TableNum(summary, 10, 0, 'Profit/Loss β½', MoreLos)
TableNum(summary, 13, 0, 'Share of', Sharportfo)
TableNum(summary, 3, 1, 'stocks', Stocks)
TableNum(summary, 4, 1, 'buy', PurchpriceI)
TableNum(summary, 5, 1, 'Price', CurrpricI)
TableNum(summary, 6, 1, 'cost', InitiCost)
TableNum(summary, 7, 1, 'cost β½', InitiCostP)
TableNum(summary, 8, 1, 'cost', Liquvalue)
TableNum(summary, 9, 1, 'cost β½', LiquvalueP)
TableNum(summary, 10, 1, 'in %', MoreLoss)
TableNum(summary, 11, 1, 'in money β½', MoreLossI)
TableNum(summary, 12, 1, '% of portfolio', MoreLossK)
TableNum(summary, 13, 1, 'total portfolio', Sharportfo)
//}
// Merging cells (ΠΎΠ±ΡΠ΅Π΄ΠΈΠ½Π΅Π½ΠΈΠ΅ ΡΡΠ΅Π΅ΠΊ) {
table.merge_cells(summary, 0, 0, 0, 1)
table.merge_cells(summary, 1, 0, 1, 1)
table.merge_cells(summary, 2, 0, 2, 1)
table.merge_cells(summary, 10, 0, 12, 0)
//}
// The initial data to fill in the table (ΠΡΡ
ΠΎΠ΄Π½ΡΠ΅ Π΄Π°Π½Π½ΡΠ΅ Π΄Π»Ρ Π·Π°ΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ Π² ΡΠ°Π±Π»ΠΈΡΡ) {
// Show the table in parts (ΠΠΎΠΊΠ°Π·ΡΠ²Π°ΡΡ ΡΠ°Π±Π»ΠΈΡΡ ΠΏΠΎ ΡΠ°ΡΡΡΠΌ)
if barstate.islast
if ShowShare == '1-5'
Table(summary, 2, Date1, Tik1, Currency1, QuanStock1, QuanStock1, Purchprice1, initialCapital)
Table(summary, 3, Date2, Tik2, Currency2, QuanStock2, QuanStock2, Purchprice2, initialCapital)
Table(summary, 4, Date3, Tik3, Currency3, QuanStock3, QuanStock3, Purchprice3, initialCapital)
Table(summary, 5, Date4, Tik4, Currency4, QuanStock4, QuanStock4, Purchprice4, initialCapital)
Table(summary, 6, Date5, Tik5, Currency5, QuanStock5, QuanStock5, Purchprice5, initialCapital)
if ShowShare == '1-10'
Table(summary, 2, Date1, Tik1, Currency1, QuanStock1, QuanStock1, Purchprice1, initialCapital)
Table(summary, 3, Date2, Tik2, Currency2, QuanStock2, QuanStock2, Purchprice2, initialCapital)
Table(summary, 4, Date3, Tik3, Currency3, QuanStock3, QuanStock3, Purchprice3, initialCapital)
Table(summary, 5, Date4, Tik4, Currency4, QuanStock4, QuanStock4, Purchprice4, initialCapital)
Table(summary, 6, Date5, Tik5, Currency5, QuanStock5, QuanStock5, Purchprice5, initialCapital)
Table(summary, 7, Date6, Tik6, Currency6, QuanStock6, QuanStock6, Purchprice6, initialCapital)
Table(summary, 8, Date7, Tik7, Currency7, QuanStock7, QuanStock7, Purchprice7, initialCapital)
Table(summary, 9, Date8, Tik8, Currency8, QuanStock8, QuanStock8, Purchprice8, initialCapital)
Table(summary, 10, Date9, Tik9, Currency9, QuanStock9, QuanStock9, Purchprice9, initialCapital)
Table(summary, 11, Date10, Tik10, Currency10, QuanStock10, QuanStock10, Purchprice10, initialCapital)
if ShowShare == '1-15'
Table(summary, 2, Date1, Tik1, Currency1, QuanStock1, QuanStock1, Purchprice1, initialCapital)
Table(summary, 3, Date2, Tik2, Currency2, QuanStock2, QuanStock2, Purchprice2, initialCapital)
Table(summary, 4, Date3, Tik3, Currency3, QuanStock3, QuanStock3, Purchprice3, initialCapital)
Table(summary, 5, Date4, Tik4, Currency4, QuanStock4, QuanStock4, Purchprice4, initialCapital)
Table(summary, 6, Date5, Tik5, Currency5, QuanStock5, QuanStock5, Purchprice5, initialCapital)
Table(summary, 7, Date6, Tik6, Currency6, QuanStock6, QuanStock6, Purchprice6, initialCapital)
Table(summary, 8, Date7, Tik7, Currency7, QuanStock7, QuanStock7, Purchprice7, initialCapital)
Table(summary, 9, Date8, Tik8, Currency8, QuanStock8, QuanStock8, Purchprice8, initialCapital)
Table(summary, 10, Date9, Tik9, Currency9, QuanStock9, QuanStock9, Purchprice9, initialCapital)
Table(summary, 11, Date10, Tik10, Currency10, QuanStock10, QuanStock10, Purchprice10, initialCapital)
Table(summary, 12, Date11, Tik10, Currency11, QuanStock11, QuanStock11, Purchprice11, initialCapital)
Table(summary, 13, Date12, Tik10, Currency12, QuanStock12, QuanStock12, Purchprice12, initialCapital)
Table(summary, 14, Date13, Tik10, Currency13, QuanStock13, QuanStock13, Purchprice13, initialCapital)
Table(summary, 15, Date14, Tik10, Currency14, QuanStock14, QuanStock14, Purchprice14, initialCapital)
Table(summary, 16, Date15, Tik10, Currency15, QuanStock15, QuanStock15, Purchprice15, initialCapital)
if ShowShare == '1-20'
Table(summary, 2, Date1, Tik1, Currency1, QuanStock1, QuanStock1, Purchprice1, initialCapital)
Table(summary, 3, Date2, Tik2, Currency2, QuanStock2, QuanStock2, Purchprice2, initialCapital)
Table(summary, 4, Date3, Tik3, Currency3, QuanStock3, QuanStock3, Purchprice3, initialCapital)
Table(summary, 5, Date4, Tik4, Currency4, QuanStock4, QuanStock4, Purchprice4, initialCapital)
Table(summary, 6, Date5, Tik5, Currency5, QuanStock5, QuanStock5, Purchprice5, initialCapital)
Table(summary, 7, Date6, Tik6, Currency6, QuanStock6, QuanStock6, Purchprice6, initialCapital)
Table(summary, 8, Date7, Tik7, Currency7, QuanStock7, QuanStock7, Purchprice7, initialCapital)
Table(summary, 9, Date8, Tik8, Currency8, QuanStock8, QuanStock8, Purchprice8, initialCapital)
Table(summary, 10, Date9, Tik9, Currency9, QuanStock9, QuanStock9, Purchprice9, initialCapital)
Table(summary, 11, Date10, Tik10, Currency10, QuanStock10, QuanStock10, Purchprice10, initialCapital)
Table(summary, 12, Date11, Tik11, Currency11, QuanStock11, QuanStock11, Purchprice11, initialCapital)
Table(summary, 13, Date12, Tik12, Currency12, QuanStock12, QuanStock12, Purchprice12, initialCapital)
Table(summary, 14, Date13, Tik13, Currency13, QuanStock13, QuanStock13, Purchprice13, initialCapital)
Table(summary, 15, Date14, Tik14, Currency14, QuanStock14, QuanStock14, Purchprice14, initialCapital)
Table(summary, 16, Date15, Tik15, Currency15, QuanStock15, QuanStock15, Purchprice15, initialCapital)
Table(summary, 17, Date16, Tik16, Currency16, QuanStock16, QuanStock16, Purchprice16, initialCapital)
Table(summary, 18, Date17, Tik17, Currency17, QuanStock17, QuanStock17, Purchprice17, initialCapital)
Table(summary, 19, Date18, Tik18, Currency18, QuanStock18, QuanStock18, Purchprice18, initialCapital)
Table(summary, 20, Date19, Tik19, Currency19, QuanStock19, QuanStock19, Purchprice19, initialCapital)
Table(summary, 21, Date20, Tik20, Currency20, QuanStock20, QuanStock20, Purchprice20, initialCapital)
// }
|
Supply and Demand - Order Block - Energy Candles | https://www.tradingview.com/script/RdJD2Iwg-Supply-and-Demand-Order-Block-Energy-Candles/ | geneclash | https://www.tradingview.com/u/geneclash/ | 2,351 | 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/
// Β© geneclash
//@version=5
indicator("Supply and Demand - Order Block - Energy Candles", format=format.price, precision=0, overlay=true)
changeColor = input(false,title="Change Box Colors?")
breakType = input.string("Wick+Body",title="Fractal Break Type:",options=["Wick+Body","Body"])
n = input.int(title="Periods", defval=2, minval=2)
transGreenClr = input.color(color.new(color.green,80),title="Bg:",inline="a_1")
greenClr = input.color(color.new(color.green,0),title="Border:",inline="a_1")
transRedClr = input.color(color.new(color.red,80),title="Bg:",inline="b_1")
redClr = input.color(color.new(color.red,0),title="Border:",inline="b_1")
//Fractals{
// UpFractal
bool upflagDownFrontier = true
bool upflagUpFrontier0 = true
bool upflagUpFrontier1 = true
bool upflagUpFrontier2 = true
bool upflagUpFrontier3 = true
bool upflagUpFrontier4 = true
for i = 1 to n
upflagDownFrontier := upflagDownFrontier and (high[n-i] < high[n])
upflagUpFrontier0 := upflagUpFrontier0 and (high[n+i] < high[n])
upflagUpFrontier1 := upflagUpFrontier1 and (high[n+1] <= high[n] and high[n+i + 1] < high[n])
upflagUpFrontier2 := upflagUpFrontier2 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+i + 2] < high[n])
upflagUpFrontier3 := upflagUpFrontier3 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+i + 3] < high[n])
upflagUpFrontier4 := upflagUpFrontier4 and (high[n+1] <= high[n] and high[n+2] <= high[n] and high[n+3] <= high[n] and high[n+4] <= high[n] and high[n+i + 4] < high[n])
flagUpFrontier = upflagUpFrontier0 or upflagUpFrontier1 or upflagUpFrontier2 or upflagUpFrontier3 or upflagUpFrontier4
upFractal = (upflagDownFrontier and flagUpFrontier)
//DownFractal
bool downflagDownFrontier = true
bool downflagUpFrontier0 = true
bool downflagUpFrontier1 = true
bool downflagUpFrontier2 = true
bool downflagUpFrontier3 = true
bool downflagUpFrontier4 = true
for i = 1 to n
downflagDownFrontier := downflagDownFrontier and (low[n-i] > low[n])
downflagUpFrontier0 := downflagUpFrontier0 and (low[n+i] > low[n])
downflagUpFrontier1 := downflagUpFrontier1 and (low[n+1] >= low[n] and low[n+i + 1] > low[n])
downflagUpFrontier2 := downflagUpFrontier2 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+i + 2] > low[n])
downflagUpFrontier3 := downflagUpFrontier3 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+i + 3] > low[n])
downflagUpFrontier4 := downflagUpFrontier4 and (low[n+1] >= low[n] and low[n+2] >= low[n] and low[n+3] >= low[n] and low[n+4] >= low[n] and low[n+i + 4] > low[n])
flagDownFrontier = downflagUpFrontier0 or downflagUpFrontier1 or downflagUpFrontier2 or downflagUpFrontier3 or downflagUpFrontier4
downFractal = (downflagDownFrontier and flagDownFrontier)
//}
var float topValue = na, var float bottomValue = na
var int lastRedIndex = na, var float lastRedLow = na, var float lastRedHigh = na
var int lastGreenIndex = na, var float lastGreenLow = na, var float lastGreenHigh = na
var line topLine = na, var line bottomLine = na
var box demandBox = na, var box supplyBox = na
var topBreakBlock = false, var bottomBreakBlock = false
var isLongBreak = false, var isShortBreak = false
topBreakCheckSource = breakType == "Wick+Body" ? high : close
bottomBreakCheckSource = breakType == "Wick+Body" ? low : close
//Last red check
if close < open
lastRedIndex := bar_index
lastRedLow := low
lastRedHigh := high
//Last green check
if close > open
lastGreenIndex := bar_index
lastGreenLow := low
lastGreenHigh := high
//Top break
if ta.crossover(topBreakCheckSource,topValue) and topBreakBlock == false
topBreakBlock := true
isLongBreak := true
line.set_x2(topLine,bar_index)
demandBox := box.new(lastRedIndex-1, lastRedHigh,lastRedIndex+1,lastRedLow, bgcolor=transGreenClr, border_color=greenClr)
alert("New Demand Zone Created!",freq=alert.freq_once_per_bar_close)
//Bottom break
if ta.crossunder(bottomBreakCheckSource,bottomValue) and bottomBreakBlock == false
bottomBreakBlock := true
isShortBreak := true
line.set_x2(bottomLine,bar_index)
supplyBox := box.new(lastGreenIndex-1, lastGreenHigh,lastGreenIndex+1,lastGreenLow, bgcolor=transRedClr, border_color=redClr)
alert("New Supply Zone Created!",freq=alert.freq_once_per_bar_close)
//New up fractal
if upFractal
topBreakBlock := false
isLongBreak := false
topValue := high[n]
topLine := line.new(bar_index[n],topValue,bar_index,topValue, color=color.teal, style=line.style_dotted, width=2)
if isLongBreak[1] == false
line.delete(topLine[1])
//New down fractal
if downFractal
bottomBreakBlock := false
isShortBreak := false
bottomValue := low[n]
bottomLine := line.new(bar_index[n],bottomValue,bar_index,bottomValue, color=color.maroon, style=line.style_dotted, width=2)
if isShortBreak[1] == false
line.delete(bottomLine[1])
//Box state update
activeBoxes = box.all
if array.size(activeBoxes) > 0 and changeColor
for i = 0 to array.size(activeBoxes) - 1
bVal = box.get_bottom(array.get(activeBoxes, i))
tVal = box.get_top(array.get(activeBoxes, i))
if close < bVal
box.set_bgcolor(array.get(activeBoxes, i),transRedClr)
box.set_border_color(array.get(activeBoxes, i),redClr)
if close > tVal
box.set_bgcolor(array.get(activeBoxes, i),transGreenClr)
box.set_border_color(array.get(activeBoxes, i),greenClr)
//PLOTS
plotshape(downFractal ,style=shape.triangleup, location=location.belowbar, offset=-n, color=color.new(color.gray,80), size = size.tiny)
plotshape(upFractal, style=shape.triangledown, location=location.abovebar, offset=-n, color=color.new(color.gray,80), size = size.tiny) |
V/T Ratio: Onchain BTC Metric | https://www.tradingview.com/script/5EM1jEfu-V-T-Ratio-Onchain-BTC-Metric/ | cryptoonchain | https://www.tradingview.com/u/cryptoonchain/ | 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/
// Β© MJShahsavar
//@version=5
indicator("V/T Ratio: Onchain BTC Metric", timeframe = "W")
R = input.symbol("BTC_TXS", "Symbol")
r = request.security(R, 'D', close)
S=input.symbol("BTC_TOTALVOLUMEUSD", "Symbol")
s = request.security(S, 'D', close)
C= s/r
D= math.log10(C)
E= ta.sma(D, 7)
plot (E, color = color.blue, linewidth=1)
|
HTF Candle Boxes for LTF Charts | https://www.tradingview.com/script/mPisVAw4-HTF-Candle-Boxes-for-LTF-Charts/ | krollo041 | https://www.tradingview.com/u/krollo041/ | 407 | 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/
// Kevin Rollo
//@version = 5
indicator(title = 'HTF Candle Boxes for LTF Charts', shorttitle = "HTF Candles", overlay = true, max_boxes_count = 200)
//v1 24/04/22, 25/04/22, 02/05/22 [Published]
//v2 10/06/22, 22/09/22 // Updated the last candle painting error, a bit of a code cleanup too. Still a glitch if the chart TF >= HTF, but that's a nonesense situation
//v3 23/07/23 // added the pip range label
// User Inputs
Interval = input.timeframe('D', 'Box Time Interval')
BodyCandle = input.bool(true, 'Box the Candle')
BodyCandleBox = input.bool(true, 'Box the Candle Body')
BoxCurrentCandle = input.bool(true, 'Box the Current Candle') //v2
BoxRangePips = input.bool(true, 'Show H/L Range Pips', inline = '1') //v2
BoxRangePercentage = input.bool(false, 'Show O/C Pips', inline = '1') //v3
// Colour Selection
BgLong = input.color(color.new(#66bb6a,80), 'Long Boxes')
BgShort = input.color(color.new(#f7525f,80), 'Short Boxes')
BordCol = input.color(color.new(#9598a1,50), 'Border Color')
// interval valiables
var float htfHigh = na // htf Candle High
var float htfLow = na
var float htfOpen = na
var int htfBarIndex = na // Bar Index for start of HTF candle
var float div = 1
var box currentBox1 = na // need a place holder boxes
var box currentBox2 = na // need a place holder boxes
var label currentLabel = na
if bar_index == 1
//First Bar Setup
if syminfo.type == 'forex'
div := 0.1 / syminfo.mintick
changePeriod = ta.change(time(Interval))
candleLong = close > htfOpen
boxCol = candleLong ? BgLong : BgShort // colour for direction (e.g. Red or Green box)
r1 = math.abs(htfHigh - htfLow) * div
r2 = math.abs(htfOpen - close[1]) * div
r3 = r2 / r1
//lableText = BoxRangePips ? str.tostring(math.abs(htfHigh - htfLow) * div, '#,##0.0#') : ""
lableText = str.tostring(r1, '#,##0.0#')
if BoxRangePercentage
lableText := str.tostring(r2, '#,##0.0#') + ' / ' + str.tostring(r1, '#,##0.0#') + ' = ' + str.tostring(r3, '0%')
// this was a bug in the last version when working in a live chart. Need to use temp boxes
if barstate.islast and BoxCurrentCandle // now on the last bar
box.delete(currentBox1)
box.delete(currentBox2)
label.delete(currentLabel)
if BodyCandle
currentBox1 := box.new(left = htfBarIndex, top = htfHigh, right = bar_index, bottom = htfLow, border_width = 1, border_style = line.style_solid, border_color = BordCol, bgcolor = BodyCandleBox ? na : boxCol)
if BodyCandleBox
if candleLong
currentBox2 := box.new(left = htfBarIndex, top = close, right = bar_index, bottom = htfOpen, border_width = 1, border_style = line.style_solid, border_color = BordCol, bgcolor = boxCol)
else
currentBox2 := box.new(left = htfBarIndex, top = htfOpen, right = bar_index, bottom = close, border_width = 1, border_style = line.style_solid, border_color = BordCol, bgcolor = boxCol)
if BoxRangePips
currentLabel := label.new(htfBarIndex + (bar_index - htfBarIndex) / 2 , htfHigh + syminfo.mintick * 30, lableText, style = label.style_none, textcolor = color.black, textalign = text.align_right)
if changePeriod // new interval has occured
if BodyCandle
//paint outside box HTF High to HTF Low
box.new(left = htfBarIndex, top = htfHigh, right = bar_index - 1, bottom = htfLow, border_width = 1, border_style = line.style_solid, border_color = BordCol, bgcolor = BodyCandleBox ? na : boxCol) //, text = lableText, text_valign = text.align_top, text_size = size.small)
// paint Body HTF Open to last bar Close
if BodyCandleBox
if candleLong
box.new(left = htfBarIndex, top = close[1], right = bar_index - 1, bottom = htfOpen, border_width = 1, border_style = line.style_solid, border_color = BordCol, bgcolor = boxCol)
else
box.new(left = htfBarIndex, top = htfOpen, right = bar_index - 1, bottom = close[1], border_width = 1, border_style = line.style_solid, border_color = BordCol, bgcolor = boxCol)
if BoxRangePips
label.new(htfBarIndex + (bar_index - htfBarIndex) / 2 , htfHigh + syminfo.mintick * 30, lableText, style = label.style_none, textcolor = color.black, textalign = text.align_right)
//store next data points
htfOpen := open
htfBarIndex := bar_index
htfHigh := high
htfLow := low
else
// increment data points for HH or LL
if high > htfHigh
htfHigh := high
if low < htfLow
htfLow := low
// end |
D3score | https://www.tradingview.com/script/qA59I4Y9-D3score/ | venkatadora | https://www.tradingview.com/u/venkatadora/ | 44 | 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/
// Β© venkatadora
//@version=5
indicator("D3score")
D3scr = 0
if ((close < low[1]))
D3scr := -1
if ((close < low[1]) and (close < low[2]))
D3scr := -2
if ((close < low[1]) and (close < low[2]) and (close < low [3]))
D3scr := -3
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]))
D3scr := -4
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]) and (close < low [5]))
D3scr := -5
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]) and (close < low [5]) and (close < low[6]))
D3scr := -6
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]) and (close < low [5]) and (close < low [6]) and (close < low [7]))
D3scr := -7
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]) and (close < low [5]) and (close < low [6]) and (close < low [7]) and (close < low [8]))
D3scr := -8
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]) and (close < low [5]) and (close < low [6]) and (close < low [7]) and (close < low [8]) and (close < low[9]))
D3scr := -9
if ((close < low[1]) and (close < low[2])and (close < low [3]) and (close < low [4]) and (close < low [5]) and (close < low [6]) and (close < low [7]) and ( close < low [8]) and ( close < low [9]) and ( close < low [10]))
D3scr := -10
if ((close > high [1]))
D3scr := 1
if ((close > high [1]) and (close > high[2]))
D3scr := 2
if ((close > high [1]) and (close > high[2]) and (close > high[3]))
D3scr := 3
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]))
D3scr := 4
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]) and (close > high[5]))
D3scr := 5
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]) and (close > high[5]) and (close> high [6]))
D3scr := 6
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]) and (close > high[5]) and (close > high[6]) and (close > high [7]))
D3scr := 7
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]) and (close > high[5]) and (close > high[6]) and (close > high [7]) and ( close > high [8]))
D3scr := 8
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]) and (close > high[5]) and (close > high[6]) and (close > high [7]) and (close > high [8]) and (close > high [9]))
D3scr := 9
if ((close > high [1]) and (close > high[2]) and (close > high[3]) and (close > high[4]) and (close > high[5]) and (close > high[6]) and (close > high [7]) and (close > high [8]) and (close > high [9]) and ( close > high [10]))
D3scr := 10
Escore = ta.hma (D3scr,20)/ta.stdev(D3scr,20)
//Thresholds
uthres = 1
dthres = -1
cent = 0
//Center Plot
centplot = plot(cent,color=#FFEB3B,title ="Center Line",style = plot.style_circles )
//Threshold Plots
utplot = plot(uthres, color=#FF5252,title ="Upper Threshold", style = plot.style_circles)
dtplot = plot(dthres, color=#4CAF50,title ="Lower Threshold", style = plot.style_circles)
//Colors
dcolor = Escore > 0 ? color(#00c3ff) : Escore < 0 ? color(#ff0062) : color(color.black)
fcolor = Escore > 0 ? color(color.green) :Escore < 0 ? color(color.maroon) : color(color.black)
plot(Escore,color=dcolor,linewidth= 3, title ="D3score", style = plot.style_columns)
|
RSI Multi Time Frame (MTF). Fully customizable. [Zero54] | https://www.tradingview.com/script/r9ZGo54w-RSI-Multi-Time-Frame-MTF-Fully-customizable-Zero54/ | zero54 | https://www.tradingview.com/u/zero54/ | 92 | 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/
// Zero54.
//@version=5
indicator("RSI MTF Z54")
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
ob = input.float(70,step=10,title="Over Bought level",group='RSI Settings')
os = input.float(30,step=10,title="Over Sold level",group='RSI Settings')
MTF1 = input.timeframe('30', "TimeFrame 1",group='TimeFrame Settings')
MTF2 = input.timeframe('60', "TimeFrame 2",group='TimeFrame Settings')
MTF3 = input.timeframe('120', "TimeFrame 3",group='TimeFrame Settings')
MTF4 = input.timeframe('D', "TimeFrame 4",group='TimeFrame Settings')
head_tcolor = input(color.new(#ffffff,70),'Header Text Color',group='Table Style')
head_area = input(color.new(#CCffff,70),'Header Background Color',group='Table Style')
ob_area = input(color.new(#0cb51a,70),'Over Bought Background Color',group='Table Style')
os_area = input(color.new(#ff1100,70),'Over Sold Background Color',group='Table Style')
mid_area = input(color.new(#ff1100,70),'Mid-Range Background Color',group='Table Style')
ob_tcolor = input(color.new(#0cb51a,70),'Over Bought Text Color',group='Table Style')
os_tcolor = input(color.new(#ff1100,70),'Over Sold Text Color',group='Table Style')
mid_tcolor = input(color.new(#ff1100,70),'Mid-Range Text Color',group='Table Style')
plot(ta.rsi(rsiSourceInput,rsiLengthInput), "RSI", #FF006E)
rsiLowerBand = hline(40, "RSI Lower Band", color=#fa9589)
rsiMidBand = hline(50, "RSI Mid Band", color=#56adf0)
rsiHiBand = hline(60, "RSI High Band", color=#8affb7)
RSIMFT1 = request.security(syminfo.tickerid, MTF1, ta.rsi(rsiSourceInput,rsiLengthInput))
RSIMFT2 = request.security(syminfo.tickerid, MTF2, ta.rsi(rsiSourceInput,rsiLengthInput))
RSIMFT3 = request.security(syminfo.tickerid, MTF3, ta.rsi(rsiSourceInput,rsiLengthInput))
RSIMFT4 = request.security(syminfo.tickerid, MTF4, ta.rsi(rsiSourceInput,rsiLengthInput))
RSIMFT1bg =
(RSIMFT1 >= ob) ? ob_area :
(RSIMFT1 <= os) ? os_area :
(RSIMFT1 < ob and RSIMFT1 > os) ? mid_area :
na
RSIMFT2bg =
(RSIMFT2 >= ob) ? ob_area :
(RSIMFT2 <= os) ? os_area :
(RSIMFT2 < ob and RSIMFT2 > os) ? mid_area :
na
RSIMFT3bg =
(RSIMFT3 >= ob) ? ob_area :
(RSIMFT3 <= os) ? os_area :
(RSIMFT3 < ob and RSIMFT3 > os) ? mid_area :
na
RSIMFT4bg =
(RSIMFT4 >= ob) ? ob_area :
(RSIMFT4 <= os) ? os_area :
(RSIMFT4 < ob and RSIMFT4 > os) ? mid_area :
na
RSIMFT1txt =
(RSIMFT1 >= ob) ? ob_tcolor :
(RSIMFT1 <= os) ? os_tcolor :
(RSIMFT1 < ob and RSIMFT1 > os) ? mid_tcolor :
na
RSIMFT2txt =
(RSIMFT2 >= ob) ? ob_tcolor :
(RSIMFT2 <= os) ? os_tcolor :
(RSIMFT2 < ob and RSIMFT2 > os) ? mid_tcolor :
na
RSIMFT3txt =
(RSIMFT3 >= ob) ? ob_tcolor :
(RSIMFT3 <= os) ? os_tcolor :
(RSIMFT3 < ob and RSIMFT3 > os) ? mid_tcolor :
na
RSIMFT4txt =
(RSIMFT4 >= ob) ? ob_tcolor :
(RSIMFT4 <= os) ? os_tcolor :
(RSIMFT4 < ob and RSIMFT4 > os) ? mid_tcolor :
na
//----
var tb = table.new(position.top_right,4,2)
if barstate.islast
table.cell(tb,0,0,MTF1,text_color=head_tcolor,bgcolor=head_area)
table.cell(tb,1,0,MTF2,text_color=head_tcolor,bgcolor=head_area)
table.cell(tb,2,0,MTF3,text_color=head_tcolor,bgcolor=head_area)
table.cell(tb,3,0,MTF4,text_color=head_tcolor,bgcolor=head_area)
table.cell(tb,0,1,str.tostring(RSIMFT1,'#.##'),text_color=RSIMFT1txt,bgcolor=RSIMFT1bg)
table.cell(tb,1,1,str.tostring(RSIMFT2,'#.##'),text_color=RSIMFT2txt,bgcolor=RSIMFT2bg)
table.cell(tb,2,1,str.tostring(RSIMFT3,'#.##'),text_color=RSIMFT3txt,bgcolor=RSIMFT3bg)
table.cell(tb,3,1,str.tostring(RSIMFT4,'#.##'),text_color=RSIMFT4txt,bgcolor=RSIMFT4bg)
//----
|
DVD Screensaver | https://www.tradingview.com/script/fmOOvkmB-DVD-Screensaver/ | SamRecio | https://www.tradingview.com/u/SamRecio/ | 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/
// Β© SamRecio
//@version=5
indicator("DVD Screensaver", shorttitle = "DVD", overlay = true, max_bars_back = 1)
//Uset Inputs///////////////////////////////////////////////////////////////////
columns = input.int(10, minval = 1, maxval = 100, title = "Window Ratio β‘", inline = "0")
rows = input.int(12, minval = 1, maxval = 50,title = "β¬", inline = "0")
c_hight = 2
c_width = 1.5
tl1 = input.string("bottom", title = "Table Location", options = ["top", "middle", "bottom"], group = "Table Settings", inline = "1")
tl2 = input.string("right", title = "", options = ["left", "center", "right"], group = "Table Settings", inline = "1")
bg_color = input.color(color.rgb(0,0,0), title = "Background Color", group = "Table Settings", inline = "2")
//There are alot more possible customizabilities to this, but they seemed unneccesary for a public release.
//These are the settings I thought was enough.
//Pulling and plotting crypto to force update the indicator.
btc = request.security("COINBASE:BTCUSD","",close)
plot(btc, display = display.none, editable = false)
eth = request.security("COINBASE:ETHUSD","",close)
plot(eth, display = display.none, editable = false)
//Initializing Table////////////////////////////////////////////////////////////
var table screen = table.new(tl1 +"_" + tl2,columns + 1,rows + 1)
//Filling every cell to take up space and form the background.
/////////////////////////////////////////////
//Only need to do this on the last bar for speed. ;)
/////////////////////////////////////////////
if barstate.islast
for e = 0 to rows
for i = 0 to columns
table.cell(screen, i,e, text = "", height = c_hight, width = c_width, bgcolor = bg_color)
//Initializing the Moving Box///////////////////////////////////////////////////
varip r = math.round(math.random(0,rows)) //"varip" is required to update the variable inside bars.
varip c = math.round(math.random(0,columns)) // This means every time the script ticks the variable can be updated.
varip move = math.round(math.random(0,3)) // Setting these variables initially at a random number to make the movement random.
varip int r_num = 0 // Otherwise it would take the same path every time
rng = math.round(math.random(1,14)) //generating random number for color picking
colorpicker(_num) => // Color picking function
_num == 1? color.aqua: // Picks color from a universe of colors.
_num == 2? color.blue: // I could set the colors to generate with color.rgb() and 3 random numbers, however, that results in some ugly colors most of the time.
_num == 3? color.fuchsia: // This allows me to make sure the colors are nice.
_num == 4? color.green :
_num == 5? color.lime :
_num == 6? color.maroon:
_num == 7? color.navy :
_num == 8? color.olive :
_num == 9? color.orange :
_num == 10? color.purple :
_num == 11? color.red :
_num == 12? color.teal :
_num == 13? color.white:
_num == 14? color.yellow :
color.white
//Bumping Logic/////////////////////////////////////////////////////////////////
//Bottom Wall Bump
if r == rows and barstate.islast and move == 0 // r and c values can tell us where the box is,
move := 1 // each wall bump can result in 1 of 2 different moves depending on the direction the box is coming from.
r_num := rng // we can tell where its coming from by saying "if move == X", this will tell us the direction its currently moving.
if r == rows and barstate.islast and move == 3 // When it hits a boundary we check update the direction of movement an change the color.
move := 2
r_num := rng
//Right Wall Bump
if c == columns and barstate.islast and move == 0
move := 3
r_num := rng
if c == columns and barstate.islast and move == 1
move := 2
r_num := rng
//Top Wall Bump
if r == 0 and barstate.islast and move == 1
move := 0
r_num := rng
if r == 0 and barstate.islast and move == 2
move := 3
r_num := rng
//Left Wall Bump
if c == 0 and barstate.islast and move == 2
move := 1
r_num := rng
if c == 0 and barstate.islast and move == 3
move := 0
r_num := rng
//Moving Logic//////////////////////////////////////////////////////////////////
//Move 0 | Down-Right
//
if r < rows and c < columns and barstate.islast and move == 0 //Checking rows and colums is redundant. I have it in here to stop the box if something were to go wrong.
table.cell(screen,c,r, text = "", height = c_hight, width = c_width, bgcolor = bg_color) //All that really matters is the move, since it only moves diagonally we are always moving it up or down 1 and left or right 1.
r := r + 1 //We delete the current box at the current values and then update our location, we do this until one of our bump conditions is met, and so on.
c := c + 1
//Move 1 | Up-Right
//
if r > 0 and c < columns and barstate.islast and move == 1
table.cell(screen,c,r, text = "", height = c_hight, width = c_width, bgcolor = bg_color)
r := r - 1
c := c + 1
//Move 2 | Up-Left
//
if r > 0 and c > 0 and barstate.islast and move == 2
table.cell(screen,c,r, text = "", height = c_hight, width = c_width, bgcolor = bg_color)
r := r - 1
c := c - 1
//Move 3 | Down-Left
//
if r < rows and c > 0 and barstate.islast and move == 3
table.cell(screen,c,r, text = "", height = c_hight, width = c_width, bgcolor = bg_color)
r := r + 1
c := c - 1
table.cell(screen,c,r, text = "DVD", text_size = "normal", height = c_hight, width = c_width, text_color = colorpicker(r_num), bgcolor = bg_color) //Drawing the box at the current location, this is not in any scope so it updates every tick.
|
RSI MTF Ob+Os | https://www.tradingview.com/script/q3C6c90m-RSI-MTF-Ob-Os/ | BacktestTerminal | https://www.tradingview.com/u/BacktestTerminal/ | 247 | 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/
// Β© thakon33
// __ __ __ ____ ____
// / /_/ / ___ _/ /_____ ___ |_ /|_ /
// / __/ _ \/ _ `/ '_/ _ \/ _ \_/_ <_/_ <
// \__/_//_/\_,_/_/\_\\___/_//_/____/____/
//@version=5
indicator("RSI MTF Ob+Os")
//------------------------------------------------------------------------------
// Input
var g_rsi = "[ RSI SETTING ]"
rsiSrc = input (title="Source", defval=close, group=g_rsi)
rsiLength = input.int(title="Length", defval=14, minval=1, group=g_rsi)
rsiOverbought = input.int(title="Overbought", defval=65, minval=50, maxval=99, step=1, group=g_rsi)
rsiOversold = input.int(title="Oversold", defval=35, minval=1, maxval=50, step=1, group=g_rsi)
var g_tf = "[ SELECT TIMEFRAME ]"
rsiTf1 = input.timeframe(title="Timeframe 1", defval="15", group=g_tf, inline="tf1")
rsiTf2 = input.timeframe(title="Timeframe 2", defval="30", group=g_tf, inline="tf2")
rsiTf3 = input.timeframe(title="Timeframe 3", defval="60", group=g_tf, inline="tf3")
rsiTf4 = input.timeframe(title="Timeframe 4", defval="120", group=g_tf, inline="tf4")
rsiTf5 = input.timeframe(title="Timeframe 5", defval="240", group=g_tf, inline="tf5")
rsiTf1_E = input.bool(title="", defval=true, group=g_tf, inline="tf1")
rsiTf2_E = input.bool(title="", defval=true, group=g_tf, inline="tf2")
rsiTf3_E = input.bool(title="", defval=true, group=g_tf, inline="tf3")
rsiTf4_E = input.bool(title="", defval=true, group=g_tf, inline="tf4")
rsiTf5_E = input.bool(title="", defval=true, group=g_tf, inline="tf5")
//------------------------------------------------------------------------------
// Calculate RSI
Fsec(Sym, Tf, Exp) =>
request.security(Sym, Tf, Exp[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off) [barstate.isrealtime ? 0 : 1]
rsi1 = Fsec(syminfo.tickerid, rsiTf1, ta.rsi(rsiSrc, rsiLength))
rsi2 = Fsec(syminfo.tickerid, rsiTf2, ta.rsi(rsiSrc, rsiLength))
rsi3 = Fsec(syminfo.tickerid, rsiTf3, ta.rsi(rsiSrc, rsiLength))
rsi4 = Fsec(syminfo.tickerid, rsiTf4, ta.rsi(rsiSrc, rsiLength))
rsi5 = Fsec(syminfo.tickerid, rsiTf5, ta.rsi(rsiSrc, rsiLength))
//------------------------------------------------------------------------------
// RSI Overbought and Oversold detect
rsi1_Ob = not rsiTf1_E or rsi1 >= rsiOverbought
rsi2_Ob = not rsiTf2_E or rsi2 >= rsiOverbought
rsi3_Ob = not rsiTf3_E or rsi3 >= rsiOverbought
rsi4_Ob = not rsiTf4_E or rsi4 >= rsiOverbought
rsi5_Ob = not rsiTf5_E or rsi5 >= rsiOverbought
rsi1_Os = not rsiTf1_E or rsi1 <= rsiOversold
rsi2_Os = not rsiTf2_E or rsi2 <= rsiOversold
rsi3_Os = not rsiTf3_E or rsi3 <= rsiOversold
rsi4_Os = not rsiTf4_E or rsi4 <= rsiOversold
rsi5_Os = not rsiTf5_E or rsi5 <= rsiOversold
rsiOb = rsi1_Ob and rsi2_Ob and rsi3_Ob and rsi4_Ob and rsi5_Ob
rsiOs = rsi1_Os and rsi2_Os and rsi3_Os and rsi4_Os and rsi5_Os
//------------------------------------------------------------------------------
// Drawing on chart
plot (rsiTf1_E ? rsi1 : na, title="TF 1", color=color.rgb(255, 205, 22, 20), linewidth=1)
plot (rsiTf2_E ? rsi2 : na, title="TF 2", color=color.rgb(255, 22, 239, 20), linewidth=1)
plot (rsiTf3_E ? rsi3 : na, title="TF 3", color=color.rgb(38, 22, 255, 0), linewidth=1)
plot (rsiTf4_E ? rsi4 : na, title="TF 4", color=color.rgb(123, 253, 22, 20), linewidth=1)
plot (rsiTf5_E ? rsi5 : na, title="TF 5", color=color.rgb(255, 255, 255, 50), linewidth=1)
hline (rsiOverbought, title="RSI Overbought", color=color.new(color.red, 30), linestyle=hline.style_dashed, linewidth=1)
hline (rsiOversold, title="RSI Overbought", color=color.new(color.green, 30), linestyle=hline.style_dashed, linewidth=1)
bgcolor (rsiOb ? color.new(color.orange, 0) : na, title="Overbought")
bgcolor (rsiOs ? color.new(color.aqua, 0) : na, title="Oversold")
//------------------------------------------------------------------------------
// Alert
alertcondition(rsiOb, title="RSI Overbought", message="RSI Overbought for {{ticker}} - Price = {{close}}")
alertcondition(rsiOs, title="RSI Oversold", message="RSI Oversold for {{ticker}} - Price = {{close}}")
//==============================================================================
//==============================================================================
|
HEX Risk Metric (v0.1) | https://www.tradingview.com/script/NlYeFtDs-HEX-Risk-Metric-v0-1/ | gerawrdog | https://www.tradingview.com/u/gerawrdog/ | 37 | 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/
// Β© gerawrdog
//@version=4
//$HEX to the moon
study("HEX Risk Metric (v0.1)")
MA1 = ema(close, 21)
MA2 = sma(close, 50)
MA3 = sma(close, 100)
MA4 = sma(close, 200)
MA5 = sma(close, 300)
MA6 = sma(close, 600)
MA_x_1 = offset(MA1,7)
MA_x_2 = offset(MA2,7)
MA_x_3 = offset(MA3,7)
MA_x_4 = offset(MA4,7)
MA_x_5 = offset(MA5,7)
MA_x_6 = offset(MA6,7)
dydx_1 = (MA1-MA_x_1)/MA1
dydx_2 = (MA2-MA_x_2)/MA2
dydx_3 = (MA3-MA_x_3)/MA3
dydx_4 = (MA4-MA_x_4)/MA4
dydx_5 = (MA5-MA_x_5)/MA5
dydx_6 = (MA6-MA_x_6)/MA6
risk1 = ((dydx_1+0.05443673772)*2.31790786654)
risk2 = ((dydx_2+0.05443673772)*2.31790786654)
risk3 = ((dydx_3+0.05443673772)*2.31790786654)
risk4 = ((dydx_4+0.05443673772)*2.31790786654)
risk5 = ((dydx_5+0.05443673772)*2.31790786654)
risk6 = ((dydx_6+0.05443673772)*2.31790786654)
ft = input(0.8,title="Filter Top",step=0.1)
fb = input(0.1,title="Filter Top",step=0.1)
ft2 = input(0.8,title="Filter Top",step=0.1)
fb2 = input(0,title="Filter Top",step=0.1)
hline(ft, title='Filter Top', color=color.white, linewidth=1)
hline(fb, title='Filter Bottom', color=color.white, linewidth=1)
filter1 = risk1 > ft2 ? color.orange : risk1 < fb2 ? color.green : color.aqua
filter2 = risk2 > ft2 ? color.orange : risk2 < fb2 ? color.green : color.aqua
filter3 = risk3 > ft2 ? color.purple : risk3 < fb2 ? color.green : color.blue
filter4 = risk4 > ft ? color.purple : risk4 < fb ? color.yellow : color.blue
filter5 = risk5 > ft ? color.purple : risk5 < fb ? color.yellow : color.white
filter6 = risk6 > ft ? color.purple : risk6 < fb ? color.yellow : color.white
plot(risk1, title="HEX Risk Metric (21)",linewidth=1,color=filter1)
plot(risk2, title="HEX Risk Metric (50)",linewidth=2,color=filter2)
plot(risk3, title="HEX Risk Metric (100)",linewidth=2,color=filter3)
plot(risk4, title="HEX Risk Metric (200)",linewidth=3,color=filter4)
plot(risk5, title="HEX Risk Metric (300)",linewidth=3,color=filter5)
plot(risk6, title="HEX Risk Metric (600)",linewidth=3,color=filter6) |
Aggregated Moving Averages | https://www.tradingview.com/script/IkWLjQue-Aggregated-Moving-Averages/ | hudock | https://www.tradingview.com/u/hudock/ | 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/
// Β© hudock
//@version=5
indicator("Aggregated Moving Averages", shorttitle = "AMA", overlay = true, timeframe = "D")
visible1 = input.bool(true, "", inline = "I1")
visible2 = input.bool(true, "", inline = "I2")
visible3 = input.bool(true, "", inline = "I3")
visible4 = input.bool(true, "", inline = "I4")
length1 = input.int(9, "Length", step = 1, inline = "I1")
length2 = input.int(20, "Length", step = 1, inline = "I2")
length3 = input.int(50, "Length", step = 1, inline = "I3")
length4 = input.int(200, "Length", step = 1, inline = "I4")
type1 = input.string("EMA", "Average Type", ["EMA", "SMA"], inline = "I1")
type2 = input.string("EMA", "Average Type", ["EMA", "SMA"], inline = "I2")
type3 = input.string("EMA", "Average Type", ["EMA", "SMA"], inline = "I3")
type4 = input.string("EMA", "Average Type", ["EMA", "SMA"], inline = "I4")
color1 = input.color(color.white, "Color", inline = "I1")
color2 = input.color(color.blue, "Color", inline = "I2")
color3 = input.color(color.red, "Color", inline = "I3")
color4 = input.color(color.green, "Color", inline = "I4")
ema1 = ta.ema(close, length1)
ema2 = ta.ema(close, length2)
ema3 = ta.ema(close, length3)
ema4 = ta.ema(close, length4)
sma1 = ta.sma(close, length1)
sma2 = ta.sma(close, length2)
sma3 = ta.sma(close, length3)
sma4 = ta.sma(close, length4)
ma1 = 0.0
ma2 = 0.0
ma3 = 0.0
ma4 = 0.0
if(visible1)
ma1 := type1 == 'EMA' ? ta.ema(close,length1) : ta.sma(close, length1)
if(visible2)
ma2 := type2 == 'EMA' ? ta.ema(close,length2) : ta.sma(close, length2)
if(visible3)
ma3 := type3 == 'EMA' ? ta.ema(close,length3) : ta.sma(close, length3)
if(visible4)
ma4 := type4 == 'EMA' ? ta.ema(close,length4) : ta.sma(close, length4)
plot(ma1, style = plot.style_stepline, color = color1)
plot(ma2, style = plot.style_stepline, color = color2)
plot(ma3, style = plot.style_stepline, color = color3)
plot(ma4, style = plot.style_stepline, color = color4)
|
Percent Off All-time High (% Off High) | https://www.tradingview.com/script/ukj1KJkJ-Percent-Off-All-time-High-Off-High/ | xHmmmmm | https://www.tradingview.com/u/xHmmmmm/ | 83 | 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/
// Β© xHmmmmm
//@version=5
indicator("% off high")
GetATH(dataSeries = high) =>
var ATH = dataSeries
if dataSeries > nz(ATH, -1e10)
ATH := dataSeries
ATH
plot(close/GetATH()-1) |
Just Another RSI | https://www.tradingview.com/script/bUbCk2yZ-Just-Another-RSI/ | Trendoscope | https://www.tradingview.com/u/Trendoscope/ | 442 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© HeWhoMustNotBeNamed
// __ __ __ __ __ __ __ __ __ __ __ _______ __ __ __
// / | / | / | _ / |/ | / \ / | / | / \ / | / | / \ / \ / | / |
// $$ | $$ | ______ $$ | / \ $$ |$$ |____ ______ $$ \ /$$ | __ __ _______ _$$ |_ $$ \ $$ | ______ _$$ |_ $$$$$$$ | ______ $$ \ $$ | ______ _____ ____ ______ ____$$ |
// $$ |__$$ | / \ $$ |/$ \$$ |$$ \ / \ $$$ \ /$$$ |/ | / | / |/ $$ | $$$ \$$ | / \ / $$ | $$ |__$$ | / \ $$$ \$$ | / \ / \/ \ / \ / $$ |
// $$ $$ |/$$$$$$ |$$ /$$$ $$ |$$$$$$$ |/$$$$$$ |$$$$ /$$$$ |$$ | $$ |/$$$$$$$/ $$$$$$/ $$$$ $$ |/$$$$$$ |$$$$$$/ $$ $$< /$$$$$$ |$$$$ $$ | $$$$$$ |$$$$$$ $$$$ |/$$$$$$ |/$$$$$$$ |
// $$$$$$$$ |$$ $$ |$$ $$/$$ $$ |$$ | $$ |$$ | $$ |$$ $$ $$/$$ |$$ | $$ |$$ \ $$ | __ $$ $$ $$ |$$ | $$ | $$ | __ $$$$$$$ |$$ $$ |$$ $$ $$ | / $$ |$$ | $$ | $$ |$$ $$ |$$ | $$ |
// $$ | $$ |$$$$$$$$/ $$$$/ $$$$ |$$ | $$ |$$ \__$$ |$$ |$$$/ $$ |$$ \__$$ | $$$$$$ | $$ |/ |$$ |$$$$ |$$ \__$$ | $$ |/ |$$ |__$$ |$$$$$$$$/ $$ |$$$$ |/$$$$$$$ |$$ | $$ | $$ |$$$$$$$$/ $$ \__$$ |
// $$ | $$ |$$ |$$$/ $$$ |$$ | $$ |$$ $$/ $$ | $/ $$ |$$ $$/ / $$/ $$ $$/ $$ | $$$ |$$ $$/ $$ $$/ $$ $$/ $$ |$$ | $$$ |$$ $$ |$$ | $$ | $$ |$$ |$$ $$ |
// $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/ $$$$$$$/ $$$$/ $$/ $$/ $$$$$$/ $$$$/ $$$$$$$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$/ $$/ $$/ $$$$$$$/ $$$$$$$/
//
//
//
//@version=5
indicator("Just Another RSI", shorttitle='jaRSI', overlay=false, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
import HeWhoMustNotBeNamed/arrayutils/20 as pa
source = input.source(close, 'jaRSI Source')
rsiLength = input.int(11, 'jaRSI Length', step=5, minval=5)
useMedianGainLoss = input.bool(false, 'Use median gain/loss')
jaRSI(source, length, useMedianGainLoss=false, initialLength=100, maxLength=500)=>
var sourceArray = array.new<float>(initialLength, 0)
change = source - (array.size(sourceArray) > 0 ? array.get(sourceArray, 0) : source)
pa.unshift(sourceArray, source, maxLength)
var gainArray = array.new<float>(initialLength, 0)
var lossArray = array.new<float>(initialLength, 0)
if(change > 0)
pa.unshift(gainArray, math.max(0, change), maxLength)
if(change < 0)
pa.unshift(lossArray, math.abs(math.min(0, change)), maxLength)
shortGainArray = array.slice(gainArray, 0, length)
shortLossArray = array.slice(lossArray, 0, length)
averageGain = useMedianGainLoss?array.median(shortGainArray):array.sum(shortGainArray)
averageLoss = useMedianGainLoss?array.median(shortLossArray):array.sum(shortLossArray)
rs = averageGain/averageLoss
rsi = 100 - (100/(1+rs))
max = hline(100, 'Max', color=color.silver, linewidth=1, linestyle=hline.style_dashed, editable=false)
bearish = hline(40, 'Bearish', color=color.silver, linewidth=1, linestyle=hline.style_dashed, editable=true)
bullish = hline(60, 'Bullish', color=color.silver, linewidth=1, linestyle=hline.style_dashed, editable=true)
min = hline(0, 'Min', color=color.silver, linewidth=1, linestyle=hline.style_dashed, editable=false)
fill(max, bullish, color.new(color.green, 80), 'Bullish Region', editable=true)
fill(min, bearish, color.new(color.red, 80), 'Bearish Region', editable=true)
jarsi = jaRSI(source, rsiLength, useMedianGainLoss)
plot(jarsi, 'jaRSI', color=color.purple, editable=true)
|
DEBUG SIGNAL | https://www.tradingview.com/script/IxRDh1a5-DEBUG-SIGNAL/ | sinnerfilozofiya | https://www.tradingview.com/u/sinnerfilozofiya/ | 41 | 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/
// Β© sinnerfilozofiya
//@version=5
indicator(title="DEBUG SIGNAL",shorttitle="LONG SIGNALS",overlay=true)
fast=input(21,"fast ema")
slow=input(50,"slow ema")
rsi=ta.rsi(close,14)
ema21=ta.ema(close,fast)
ema50=ta.ema(close,slow)
emacrossover=ta.crossover(ema21,ema50)
emacrossunder=ta.crossunder(ema21,ema50)
buy=ta.crossover(ema21,ema50)
sell=ta.crossunder(ema21,ema50)
//this part is for getting ema data from higher time frames
emaholder1=ta.ema(close,21)
emaholder2=ta.ema(close,50)
fast_ema_15=request.security(syminfo.tickerid,"15",emaholder1)
slow_ema_15=request.security(syminfo.tickerid,"15",emaholder2)
//old golden numbers were (22.4-25,54)
val_pullback=ta.crossunder(rsi,30.3)
val_g1=ta.crossunder(rsi,25.6)
val_g2=ta.crossunder(rsi,22)
val_g3=ta.crossunder(rsi,18.9)
val_short=ta.crossover(rsi,77.6)
//now we go for buy options when 15m 21ema is above 50ema
if(fast_ema_15>slow_ema_15)
// if(rsi<=30)
// if(rsi>10)
if(val_pullback)
lbl=label.new(bar_index,low,"pb")
label.set_color(lbl,color.yellow)
label.set_yloc(lbl,yloc.belowbar)
label.set_style(lbl,label.style_label_up)
if(rsi>=68)
if(rsi<=90)
lbl=label.new(bar_index,low,"c")
label.set_color(lbl,color.purple)
label.set_yloc(lbl,yloc.abovebar)
label.set_style(lbl,label.style_label_down)
//val_g1=ta.crossunder(rsi,25.6)
//val_g2=ta.crossunder(rsi,22)
//val_g3=ta.crossunder(rsi,18.9)
//val_short=ta.crossover(rsi,77.6)
if(fast_ema_15<slow_ema_15)
if(val_g1 and rsi[1]>rsi[0] and rsi[1]>=30)
if(rsi<=25.6)
if(rsi>=22)
lbl=label.new(bar_index,low,"e1")
label.set_color(lbl,color.yellow)
label.set_yloc(lbl,yloc.belowbar)
label.set_style(lbl,label.style_label_up)
if(val_g2 and rsi[1]>=30)
if(rsi<22)
if(rsi>=20)
lbl=label.new(bar_index,low,"e2")
label.set_color(lbl,color.yellow)
label.set_yloc(lbl,yloc.belowbar)
label.set_style(lbl,label.style_label_up)
if(val_g3)
if(rsi<20)
if(rsi>=1)
lbl=label.new(bar_index,low,"b")
label.set_color(lbl,color.yellow)
label.set_yloc(lbl,yloc.belowbar)
label.set_style(lbl,label.style_label_up)
if(rsi>=66)
if(rsi<=90)
lbl=label.new(bar_index,low,"c")
label.set_color(lbl,color.purple)
label.set_yloc(lbl,yloc.abovebar)
label.set_style(lbl,label.style_label_down)
if(val_short)
lbl=label.new(bar_index,low,"short")
label.set_color(lbl,color.red)
label.set_yloc(lbl,yloc.abovebar)
label.set_style(lbl,label.style_label_down)
//if(rsi>69.9) //(sell)
// if(rsi<75)
// lbl=label.new(bar_index,low,"sell")
// label.set_color(lbl,color.red)
// label.set_yloc(lbl,yloc.abovebar)
// label.set_style(lbl,label.style_label_down)
//if(rsi>48) //(sell)
// if(rsi<51)
// lbl=label.new(bar_index,low,"sell")
// label.set_color(lbl,color.red)
// label.set_yloc(lbl,yloc.abovebar)
// label.set_style(lbl,label.style_label_down)
//if(rsi>=22)
// if(rsi<=25.5)
// lbl=label.new(bar_index,low,"buy")
// label.set_color(lbl,color.green)
// label.set_yloc(lbl,yloc.belowbar)
// label.set_style(lbl,label.style_label_up)
//
//line=4.631
//sl=4.607
//plot(sl, color=color.red, linewidth=2, style=plot.style_linebr, trackprice=true)
//plot(ema50,color=color.black)
//plot(ema21,color=color.blue)
plot(slow_ema_15,color=color.green)
plot(fast_ema_15,color=color.red)
//buy2 = label.new(bar_index, low, text="Hello, world!", style=label.style_arrowup)
//bgcolor(emacrossover ? color.green : na)
//bgcolor(emacrossunder ? color.red : na) |
Heikin Multi Time Frame | https://www.tradingview.com/script/xk7rpwIa-Heikin-Multi-Time-Frame/ | TradingWolf | https://www.tradingview.com/u/TradingWolf/ | 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/
// Β© MensaTrader
// Feel free to use this code but please Message/Tag me if do you re use in any fashion - Thanks and Good Luck
//@version=5
indicator(title='Heikin MTF', overlay=false)
plots = "=== Plots ==="
bullColor = input.color(#00E600, title="Bull Color", group=plots)
bearColor = input.color(#FF0000, title="Bear Color", group=plots)
timeFrames = "=== Timeframes ==="
timeframe1 = input.timeframe("30", 'Timeframe 1', group=timeFrames)
timeframe2 = input.timeframe("60", 'Timeframe 1', group=timeFrames)
timeframe3 = input.timeframe("120", 'Timeframe 1', group=timeFrames)
timeframe4 = input.timeframe("180", 'Timeframe 1', group=timeFrames)
timeframe5 = input.timeframe("240", 'Timeframe 1', group=timeFrames)
timeframe6 = input.timeframe("D", 'Timeframe 1', group=timeFrames)
timeframe7 = input.timeframe("W", 'Timeframe 1', group=timeFrames)
timeframe8 = input.timeframe("M", 'Timeframe 1', group=timeFrames)
//*** Functions
calculateHeikinColor(timeframe) =>
ha_t = ticker.heikinashi(syminfo.tickerid)
ha_open = request.security(ha_t, str.tostring(timeframe),open)
ha_close = request.security(ha_t, str.tostring(timeframe),close)
col = ha_close > ha_open ? bullColor : bearColor
longAlert = calculateHeikinColor(timeframe1) == bullColor and calculateHeikinColor(timeframe1) == calculateHeikinColor(timeframe2) and calculateHeikinColor(timeframe2) == calculateHeikinColor(timeframe3) and calculateHeikinColor(timeframe3) == calculateHeikinColor(timeframe4) and calculateHeikinColor(timeframe4) == calculateHeikinColor(timeframe5) and calculateHeikinColor(timeframe5) == calculateHeikinColor(timeframe6) and calculateHeikinColor(timeframe6) == calculateHeikinColor(timeframe7) and calculateHeikinColor(timeframe7) == calculateHeikinColor(timeframe8)
shortAlert = calculateHeikinColor(timeframe1) == bearColor and calculateHeikinColor(timeframe1) == calculateHeikinColor(timeframe2) and calculateHeikinColor(timeframe2) == calculateHeikinColor(timeframe3) and calculateHeikinColor(timeframe3) == calculateHeikinColor(timeframe4) and calculateHeikinColor(timeframe4) == calculateHeikinColor(timeframe5) and calculateHeikinColor(timeframe5) == calculateHeikinColor(timeframe6) and calculateHeikinColor(timeframe6) == calculateHeikinColor(timeframe7) and calculateHeikinColor(timeframe7) == calculateHeikinColor(timeframe8)
alertcondition(longAlert, title="All Bullish", message="")
alertcondition(shortAlert, title="All Bearish", message="")
//Plots
plotshape(1.00, 'Timeframe 1', shape.square, location.absolute, calculateHeikinColor(timeframe1), size=size.tiny)
plotshape(1.05, 'Timeframe 2', shape.square, location.absolute, calculateHeikinColor(timeframe2), size=size.tiny)
plotshape(1.10, 'Timeframe 3', shape.square, location.absolute, calculateHeikinColor(timeframe3), size=size.tiny)
plotshape(1.15, 'Timeframe 4', shape.square, location.absolute, calculateHeikinColor(timeframe4), size=size.tiny)
plotshape(1.20, 'Timeframe 4', shape.square, location.absolute, calculateHeikinColor(timeframe5), size=size.tiny)
plotshape(1.25, 'Timeframe 4', shape.square, location.absolute, calculateHeikinColor(timeframe6), size=size.tiny)
plotshape(1.30, 'Timeframe 4', shape.square, location.absolute, calculateHeikinColor(timeframe7), size=size.tiny)
plotshape(1.35, 'Timeframe 4', shape.square, location.absolute, calculateHeikinColor(timeframe8), size=size.tiny)
|
Volume Oximeter | https://www.tradingview.com/script/DMOVjaej-Volume-Oximeter/ | bjr117 | https://www.tradingview.com/u/bjr117/ | 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/
// Β© bjr117
//@version=5
indicator(title = "Volume Oximeter", shorttitle = "VOXI", overlay = false)
//==============================================================================
// Inputs
//==============================================================================
voxi_volume_length = input.int(259, title = "VOXI Volume Lookback Period", minval = 2)
voxi_smoothing_length = input.int(10, title = "VOXI Smoothing Length", minval = 2)
//==============================================================================
//==============================================================================
// Check if the current instrument has volume
//==============================================================================
// Calculate the cumulative volume for the indicator once
var cumulative_vol = 0.0
cumulative_vol += nz(volume)
// If the current bar is the last bar in the time series, and cumulative volume is 0, throw an error
if barstate.islast and cumulative_vol == 0
runtime.error("No volume is provided by the data vendor.")
//==============================================================================
//==============================================================================
// Calculate VOXI line
// If the VOXI line is above zero, the current volume is greater than the historical average volume.
// If the VOXI line is below zero, the current volume is less than the historical average volume.
//
// Params:
// voxi_volume_length = The amount of bars VOXI will look back to calculate the historical average volume.
// The lower this is, the more responsive the historical average volume will be to new volume data.
// This can lead to the historical average volume being slow to respond to new volume, resulting in a faster VOXI line, which can get you into more trends at the expense of giving more false signals due to being choppy.
// The higher this is, the less responsive the historical average volume will be to new volume data.
// This can lead to the historical average volume being quick to respond to new volume, resulting in a slower VOXI line, which can give you less false signals due to being less choppy at the expense of keeping you out of some trends.
//
// voxi_smoothing_length = The amount of bars VOXI will look back to calculate the smoothing for the VOXI line.
// The higher this is, the less responsive the VOXI line will be to new changes in the data
// This can give you less false signals, but also may keep you out of some trends.
// The lower this is, the more responsive the VOXI line will be to new changes in the data.
// This can get you into more trends, but also give more false signals.
//==============================================================================
calculate_voxi(voxi_volume_length, voxi_smoothing_length) =>
voxi = float(0.0)
// If current volume is greater or equal to the average volume, add it to voxi.
// If current volume is less than the average volume, subtract it from voxi.
if volume >= ta.sma(volume, voxi_volume_length)
voxi := voxi + volume
else
voxi := voxi - volume
// Return smoothed voxi
// Uses the Hull Moving Average method (HMA) for smoothing since it is very responsive to sudden changes, which helps catch high volume periods before a trend faster.
ta.hma(voxi, voxi_smoothing_length)
//==============================================================================
//==============================================================================
// Plot VOXI line and zero line
//==============================================================================
voxi = calculate_voxi(voxi_volume_length, voxi_smoothing_length)
// Plot DPG
voxi_plot = plot(voxi, title = "VOXI Line", color = color.new(#000000, 0), linewidth = 2)
// Plot Zero Line
zero_plot = plot(0, title = "Zero Line", color = color.new(#000000, 70))
// Fill blue if VOXI > 0, red if VOXI < 0.
voxi_fill_color = voxi >= 0 ? color.blue : color.red
fill(voxi_plot, zero_plot, title = "VOXI Fill", color = color.new(voxi_fill_color, 70))
//============================================================================== |
Breakout Accumulation/Distribution | https://www.tradingview.com/script/ycHJJFQr-Breakout-Accumulation-Distribution/ | Austimize | https://www.tradingview.com/u/Austimize/ | 197 | 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/
// Β© Austimize
//Custom swing fail detector with levels, breakouts, and colored candles.
//@version=5
indicator("Breakout Accumulation/Distribution", "Breakout A/D", overlay = true)
lbL = input.int(4, "Left Lookback")
lbR = input.int(3, "Right Lookback")
colorCandles = input.bool(true, "Color Candles?")
timeframe1 = input.timeframe("", "Timeframe")
sourceHigh = request.security(syminfo.tickerid, timeframe1, high, barmerge.gaps_off, barmerge.lookahead_on)
sourceLow = request.security(syminfo.tickerid, timeframe1, low, barmerge.gaps_off, barmerge.lookahead_on)
sourceClose = request.security(syminfo.tickerid, timeframe1, close, barmerge.gaps_off, barmerge.lookahead_on)
anchorR = math.round(lbL * 1.5)
anchorL = lbR * 2
get_lowest (source, num) =>
lowval = 99999999.9
for i = 1 to num
if source[i] < lowval
lowval := source[i]
lowval
get_highest (source, num) =>
highval = 0.0
for i = 1 to num
if source[i] > highval
highval := source[i]
highval
isHighAnchor = ta.pivothigh(sourceHigh, anchorL, anchorR)
isLowAnchor = ta.pivotlow(sourceLow, anchorL, anchorR)
lastAnchor = 0
lastAnchor := isHighAnchor and not isLowAnchor ? 1 : isLowAnchor and not isHighAnchor ? -1 : lastAnchor[1]
barsSinceHigh = 0
barsSinceLow = 0
barsSinceHigh := barsSinceHigh[1] + 1
barsSinceLow := barsSinceLow[1] + 1
lowSwing = sourceLow[barsSinceLow]
highSwing = sourceHigh[barsSinceHigh]
pivotHigh = ta.pivothigh(sourceHigh, lbL, lbR)
pivotLow = ta.pivotlow(sourceLow, lbL, lbR)
lastPivot = 0
lastPivot := pivotHigh and not pivotLow ? 1 : pivotLow and not pivotHigh ? -1 : lastPivot[1]
barsSinceHighPivot = 0
barsSinceLowPivot = 0
barsSinceHighPivot := barsSinceHighPivot[1] + 1
barsSinceLowPivot := barsSinceLowPivot[1] + 1
pivotHighline = sourceHigh[barsSinceHighPivot]
pivotLowline = sourceLow[barsSinceLowPivot]
swingFailHigh = pivotHigh and sourceClose[lbR] < highSwing ? true : false
swingFailLow = pivotLow and sourceClose[lbR] > lowSwing ? true : false
swingFailHighMinor = pivotHigh and sourceClose[lbR] < pivotHighline ? true : false
swingFailLowMinor = pivotLow and sourceClose[lbR] > pivotLowline ? true : false
lastMinorFail = 0
lastMinorFail := swingFailHighMinor and not swingFailLowMinor ? 1 : swingFailLowMinor and not swingFailHighMinor ? -1 : lastMinorFail[1]
plotHighFail = swingFailHighMinor and not swingFailHigh
plotLowFail = swingFailLowMinor and not swingFailLow
lastFail = 0
lastFail := swingFailHigh and not swingFailLow ? 1 : swingFailLow and not swingFailHigh ? -1 : lastFail[1]
highBreakout = sourceClose > highSwing and sourceClose > get_highest(sourceClose, anchorR - 1)
lowBreakout = sourceClose < lowSwing and sourceClose < get_lowest(sourceClose, anchorR - 1)
lastBreakout = 0
prevBreakout = lastBreakout[1]
lastBreakout := highBreakout ? 1 : lowBreakout? -1 : prevBreakout
accum = highBreakout and prevBreakout == -1
dist = lowBreakout and prevBreakout == 1
lastBreakout := lastBreakout >= 1 and isHighAnchor ? -1 : lastBreakout
lastBreakout := lastBreakout <= 1 and isLowAnchor ? 1 : lastBreakout
minorHighBreakout = sourceClose > pivotHighline and sourceClose > get_highest(sourceClose, lbR - 1)
minorLowBreakout = sourceClose < pivotLowline and sourceClose < get_lowest(sourceClose, lbR - 1)
lastMinorBreakout = 0
prevMinorBreakout = lastMinorBreakout[1]
lastMinorBreakout := minorHighBreakout ? 1 : minorLowBreakout? -1 : prevMinorBreakout
accumM = minorHighBreakout and prevMinorBreakout == -1
distM = minorLowBreakout and prevMinorBreakout == 1
accumV1 = minorHighBreakout and prevBreakout == -1
distV1 = minorLowBreakout and prevBreakout == 1
accumV2 = highBreakout and prevMinorBreakout == -1
distV2 = lowBreakout and prevMinorBreakout == 1
isAccum = accum or accumM or accumV1 or accumV2
isDist = dist or distM or distV1 or distV2
currentAD = 0
lastAD = currentAD[1]
currentAD := isAccum ? 1 : isDist ? -1 : lastAD
plotchar(isAccum, "Accumulation", char = "A", location = location.belowbar, color = color.green)
plotchar(isDist, "Distribution", char = "D", location = location.abovebar, color = color.red)
lastMinorBreakout := lastMinorBreakout >= 1 and pivotHigh ? -1 : lastMinorBreakout
lastMinorBreakout := lastMinorBreakout <= 1 and pivotLow ? 1 : lastMinorBreakout
isMinorBreakHigh = minorHighBreakout and not highBreakout
isMinorBreakLow = minorLowBreakout and not lowBreakout
barsSinceHigh := isHighAnchor ? anchorR : barsSinceHigh
barsSinceLow := isLowAnchor ? anchorR : barsSinceLow
barsSinceHighPivot := pivotHigh ? lbR : barsSinceHighPivot
barsSinceLowPivot := pivotLow ? lbR : barsSinceLowPivot
barsSinceHigh := isHighAnchor ? anchorR : barsSinceHigh
barsSinceLow := isLowAnchor ? anchorR : barsSinceLow
plotColor = color.orange
plotColor := isAccum ? color.green : isDist ? color.red : na //color.red : lastAD == 1 ? color.green : lastAD == -1 ?
barcolor(colorCandles ? plotColor : na, title = "Bar Color") |
Session TPO Market Profile | https://www.tradingview.com/script/nqNBQ4p9-Session-TPO-Market-Profile/ | noop-noop | https://www.tradingview.com/u/noop-noop/ | 2,485 | 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/
// Β© noop42
//@version=5
indicator("Session TPO Profile", overlay=true, max_bars_back=5000, max_boxes_count = 500, max_lines_count = 500)
session = input.session("0930-1600", title="Session calculation", group="Session configuration")
tick_size = input.int(25, "Ticks number per tpo", group="Global Options") * syminfo.mintick
round_values = input.bool(true, "Round TPO levels on Tick number", group="Global Options")
letters_size = input.string("Small", options=["Normal", "Small", "Tiny"], title="TPO letters size", group="Global Options")
print_as_bars = input.bool(false, "Display TPO as bars", group="Global Options")
extend_levels = input.bool(true, "Extend yesterday's levels", group="Global Options")
show_va_background = input.bool(true, "Show Market Profile calculation area background", group="Global Options")
va_bg_color=input.color(#2962ff10, "Value area background color", group="Global Options")
show_histogram = input.bool(true, "Show TPO's", group="Global Options")
tpo_va_color = input.color(color.white, "TPO Color (in VA)", group="Global Options")
tpo_nova_color = input.color(color.gray, "TPO Color (out of VA)", group="Global Options")
limits_color=input.color(color.black, "High and Low colors", group="Highs & Lows")
show_high_low = input.bool(false, "Show high/low levels", group="Highs & Lows")
poc_col = input.color(#b58900, "POC color", group="POC Options")
show_poc = input.bool(true, "Show POC as line", group="POC Options")
show_initial_balance = input.bool(true, "Show Initial Balance", group="IB")
ib_color = input.color(#38f40e, "IB Color", group="IB")
va_line_color = input.color(#2962ff, "Value area lines color", group="Value area options")
show_va_lines = input.bool(true, "Show value areas as lines",group="Value area options")
va_percent = input.int(68, "Value area percent",group="Value area options") / 100
show_singleprints = input.bool(true, "Highlight Single prints", group="Single prints")
sp_col = input.color(#ec407a, "Single prints color", group="Single prints")
extend_sp = input.bool(false, "Extend single prints", group="Single prints")
sp_ext_trans = input.int(80, "Extended single prints transparency", group="Single prints", minval=0, maxval=100)
open_color = input.color(color.yellow, "Opening price color", group="Open/Close")
close_color = input.color(#ff0000, "Closing price color", group="Open/Close")
tpo_spacing = input.int(0, "TPO Spacing")
inSession(sess) => na(time(timeframe.period, sess)) == false
sess = inSession(session)
session_over = sess[1] and not sess
session_start = sess and not sess[1]
letters = input.string("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@$β¬Β£{}[]()*+-/=%&?!", "TPO letters")
letters_size_value = letters_size == "Small" ? size.small : letters_size == "Normal" ? size.normal : size.tiny
bars_nb = 0
var line topline = na
var line botline = na
var line vah_line = na
var line val_line = na
var line poc = na
//var max_score = 0
var poc_price = 0.0
var bars_score = array.new<int>(bars_nb)
var profile_bars = array.new<box>(bars_nb)
var letter_bars = array.new<string>(bars_nb)
var vah_offset = 0
var val_offset = 0
spaces_string(n) =>
r = ""
if n > 0
for i=0 to n
r += " "
r
find_h(x) =>
h = high
for i=0 to x
if high[i] > h
h := high[i]
h
find_l(x) =>
l = low
for i=0 to x
if low[i] < l
l := low[i]
l
count_tpo(x, y) =>
r = 0
for i=x to y
r += array.get(bars_score,i)
r
biggest_tpo(x, y) =>
t1 = array.get(bars_score, x)
t2 = array.get(bars_score, y)
t1 >= t2 ? "h": "l"
var session_candles_count = 0
var poc_position = 0
var total_tpo = 0
var open_price = open
if session_start
session_candles_count := 0
open_price := open
//if candle_offset == candles_nb -1
if session_over
ext = extend_levels ? extend.right: extend.none
if extend_levels
line.set_extend(vah_line, extend.none)
line.set_extend(val_line, extend.none)
line.set_extend(poc, extend.none)
line.set_extend(topline, extend.none)
line.set_extend(botline, extend.none)
max_score = 0
total_tpo := 0
h = find_h(session_candles_count)
highest=h
l = find_l(session_candles_count)
bars_nb := int((h-l) / tick_size)
if round_values
h := h+tick_size - (h % tick_size)
l := l - (l % tick_size)
box_width = (h-l) / bars_nb
if show_poc
poc := line.new(bar_index-session_candles_count, 0.0, bar_index, 0.0, color=poc_col, width=2, extend=ext)
if show_high_low
topline := line.new(bar_index-session_candles_count, h, bar_index, h, color=limits_color, extend=ext)
botline := line.new(bar_index-session_candles_count, l, bar_index, l, color=limits_color, extend=ext)
// TPO calculation
for i=0 to bars_nb-1
tpo_letters = ""
score = 0
for x=0 to session_candles_count
in_bar = (high[x] <= h and high[x] >= h-box_width) or (low[x] <= h and low[x] >= h-box_width) or (high[x] > h and low[x] < h-box_width)
if in_bar
score += 1
if x <= session_candles_count and session_candles_count <= str.length(letters) -1
tpo_letters := str.substring(letters, session_candles_count-(x), (session_candles_count - (x-1)))+spaces_string(tpo_spacing)+tpo_letters
if score >= max_score
max_score := score
poc_price := h - (box_width/2)
poc_position := i
line.set_y1(poc, poc_price)
line.set_y2(poc, poc_price)
if print_as_bars
tpo_letters := ""
array.insert(profile_bars,i, box.new(bar_index-session_candles_count, h, bar_index-(session_candles_count-score), h-box_width, text=tpo_letters, text_size=letters_size_value, text_color=tpo_va_color, text_halign=text.align_left, bgcolor=#00000000, border_color=#00000000))
array.insert(bars_score, i, score)
h -= box_width
total_tpo += score
// VA Calculation
vah_price = 0.0
val_price = 0.0
vah_offset := poc_position > 0 ? poc_position -1 : poc_position
val_offset := poc_position < bars_nb -1 ? poc_position +1 : poc_position
for i=0 to bars_nb-1
d = vah_offset == 0 ? "l" : val_offset == bars_nb-1 ? "h" : biggest_tpo(vah_offset, val_offset)
if d == "h"
vah_offset := vah_offset > 0 ? vah_offset -1 : vah_offset
else
val_offset := val_offset < bars_nb-1 ? val_offset +1 : val_offset
if count_tpo(vah_offset, val_offset) / total_tpo >= va_percent
break
vah_price := box.get_top(array.get(profile_bars, vah_offset))-(box_width/2)
val_price := box.get_bottom(array.get(profile_bars, val_offset))+(box_width/2)
// Set tpo colors
for i=0 to bars_nb-1
bar_col = #00000000
text_col = (i > vah_offset and i < val_offset ? tpo_va_color : tpo_nova_color)
text_col := val_offset == i or vah_offset == i ? va_line_color : poc_position == i ? poc_col : (array.get(bars_score, i) == 1 and show_singleprints) ? sp_col : text_col
if not show_histogram
text_col := #00000000
if print_as_bars
if not extend_sp
box.set_border_color(array.get(profile_bars, i), text_col)
box.set_bgcolor(array.get(profile_bars, i), text_col)
if extend_sp and (array.get(bars_score, i) == 1 and show_singleprints)
extended_sp_color = color.new(sp_col, transp=sp_ext_trans)
box.set_right(array.get(profile_bars, i), bar_index)
box.set_bgcolor(array.get(profile_bars, i), extended_sp_color)
box.set_text_color(array.get(profile_bars, i), text_col)
//plot vah/val
if show_va_lines
vah_line := line.new(bar_index-session_candles_count, vah_price, bar_index, vah_price, color=va_line_color, extend=ext)
val_line := line.new(bar_index-session_candles_count, val_price, bar_index, val_price, color=va_line_color, extend=ext)
label.new(bar_index-session_candles_count-1, open_price, text="π’", style=label.style_none, textcolor=open_color)
label.new(bar_index-session_candles_count-1, close, text="x", style=label.style_none, textcolor=close_color)
line.new(bar_index-session_candles_count-1, open_price, bar_index-session_candles_count, open_price, color=open_color, width=3)
line.new(bar_index-session_candles_count-1, close, bar_index-session_candles_count, close, color=close_color, width=3)
ibh = high[session_candles_count] > high[session_candles_count-1] ? high[session_candles_count] : high[session_candles_count-1]
ibl = low[session_candles_count] < low[session_candles_count-1] ? low[session_candles_count] : low[session_candles_count-1]
line.new(bar_index-session_candles_count, ibh, bar_index-session_candles_count, ibl, color=ib_color, width=2)
if show_va_background
box.new(bar_index-session_candles_count, vah_price, bar_index, val_price, bgcolor=va_bg_color, border_color=#00000000)
label.new(bar_index-(session_candles_count/2), highest,text=str.tostring(total_tpo)+" TPO\n", style=label.style_none, textcolor=tpo_va_color, size=size.small)
session_candles_count += 1
|
40 period HMA with volume markers | https://www.tradingview.com/script/Ags1SmF4-40-period-HMA-with-volume-markers/ | eykpunter | https://www.tradingview.com/u/eykpunter/ | 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/
// Β© eykpunter
//@version=5
indicator('40 period HMA with volume markers', shorttitle='HMA40+vol', overlay=true)
//values for HMA40 and its volume markers
hma40 = ta.hma(close, 40) //40 period Hull Moving Average
morevol=ta.median(volume, 10)*1.5 //volume level 1.5 times recently usual i.e. median
volmark0= volume>morevol //condition for marker color of strectch to current candle
volmark1= volume[1]>morevol //condition for marker color, calculated for previous candle bc plot marking ends at current candle
//plot of the line
plot(hma40, title='HMA', color=volmark0? color.fuchsia: volmark1? color.black: color.rgb(190,123,45,20), linewidth=3)
|
S2BU2 Stochastic Momentum Convergence Divergence | https://www.tradingview.com/script/to4U3EWR/ | sucks2bu2 | https://www.tradingview.com/u/sucks2bu2/ | 52 | 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/
// Β© sucks2bu2
//@version=5
indicator(title = 'S2BU2 Stochastic Momentum Convergence Divergence', shorttitle = 'S2BU2 StocMCD', overlay = false, precision = 2, timeframe = '', timeframe_gaps = false)
//==================================define Inputs==================================//
periodSlow = input.int(defval = 10, minval = 1, title = 'Period Slow')
periodFast = input.int(defval = 5,minval = 1, title = 'Period Fast')
periodSmooth = input.int(defval = 3, minval = 1, title = 'Period Smooth')
//=================================define Functions================================//
getDiff(period) =>
float lowerLow = ta.lowest(low, period)
float higherHigh = ta.highest(high, period)
float diff = higherHigh - lowerLow
diff
getRDiff(period) =>
float lowerLow = ta.lowest(low, period)
float higherHigh = ta.highest(high, period)
float diff = higherHigh - lowerLow
float rdiff = close - (higherHigh+lowerLow)/2
rdiff
getSMI(avgRel, avgDiff) =>
avgDiff != 0 ? (avgRel/(avgDiff/2)*100) : 0
//=========================calculate Helper Variables==============================//
//slow
float avgRelSlow = ta.ema(ta.ema(getRDiff(periodSlow),periodSmooth),periodSmooth)
float avgDiffSlow = ta.ema(ta.ema(getDiff(periodSlow),periodSmooth), periodSmooth)
//fast
float avgRelFast = ta.ema(ta.ema(getRDiff(periodFast),periodSmooth),periodSmooth)
float avgDiffFast = ta.ema(ta.ema(getDiff(periodFast),periodSmooth), periodSmooth)
//==========================calculate Plot Variables===============================//
float smiFast = getSMI(avgRelFast, avgDiffFast)
float signalFast = ta.ema(smiFast, periodSmooth)
float smiSlow = getSMI(avgRelSlow, avgDiffSlow)
//conditionals
float trendCross = ta.cross(smiSlow, signalFast) ? 200 : na
trendColor = smiSlow > signalFast ? color.green : color.red
trendEndColor = if ta.crossunder(smiSlow, signalFast) and nz(smiSlow[0]) < nz(smiSlow[1])
color.red
else
if ta.crossover(smiSlow, signalFast) and nz(smiSlow[0]) > nz(smiFast[1])
color.green
else
color.yellow
//====================================plot=========================================//
//graphs
plot(smiSlow, title = 'Trend', color = trendColor, linewidth = 2)
plot(smiFast, title = 'SMI', color = color.orange, linewidth = 2)
plot(signalFast, title = 'Signal', color = color.gray, linewidth = 2)
//lines
hline(40, title = 'OverBought', color = color.white, linestyle = hline.style_solid)
hline(-40, title = 'OverSold', color = color.white, linestyle = hline.style_solid)
hline(0, title = 'ZeroLine', color = color.white, linestyle = hline.style_dashed)
//crossover Bars
plot ( trendCross, title = 'TrendEnd', color = trendEndColor, linewidth = 1, style = plot.style_histogram, histbase=-100, editable=false ) |
CCI MTF Ob+Os | https://www.tradingview.com/script/ydeOI5uh-CCI-MTF-Ob-Os/ | BacktestTerminal | https://www.tradingview.com/u/BacktestTerminal/ | 373 | 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/
// Β© thakon33
// __ __ __ ____ ____
// / /_/ / ___ _/ /_____ ___ |_ /|_ /
// / __/ _ \/ _ `/ '_/ _ \/ _ \_/_ <_/_ <
// \__/_//_/\_,_/_/\_\\___/_//_/____/____/
//@version=5
indicator("CCI MTF Ob+Os")
//------------------------------------------------------------------------------
// Input
var g_cci = "[ CCI SETTING ]"
cciSrc = input(title="Source", defval=hlc3, group=g_cci)
cciLength = input.int(title="Length", defval=20, minval=1, group=g_cci)
cciOverbought = input.int(title="Overbought", defval=100, step=10, group=g_cci)
cciOversold = input.int(title="Oversold", defval=-100, step=10, group=g_cci)
var g_tf = "[ SELECT TIMEFRAME ]"
cciTf1 = input.timeframe(title="Timeframe 1", defval="15", group=g_tf, inline="tf1")
cciTf2 = input.timeframe(title="Timeframe 2", defval="30", group=g_tf, inline="tf2")
cciTf3 = input.timeframe(title="Timeframe 3", defval="60", group=g_tf, inline="tf3")
cciTf4 = input.timeframe(title="Timeframe 4", defval="120", group=g_tf, inline="tf4")
cciTf5 = input.timeframe(title="Timeframe 5", defval="240", group=g_tf, inline="tf5")
cciTf1_E = input.bool(title="", defval=true, group=g_tf, inline="tf1")
cciTf2_E = input.bool(title="", defval=true, group=g_tf, inline="tf2")
cciTf3_E = input.bool(title="", defval=true, group=g_tf, inline="tf3")
cciTf4_E = input.bool(title="", defval=true, group=g_tf, inline="tf4")
cciTf5_E = input.bool(title="", defval=true, group=g_tf, inline="tf5")
//------------------------------------------------------------------------------
// Calculate CCI
Fsec(Sym, Tf, Exp) =>
request.security(Sym, Tf, Exp[barstate.isrealtime ? 1 : 0], barmerge.gaps_off, barmerge.lookahead_off) [barstate.isrealtime ? 0 : 1]
cci1 = Fsec(syminfo.tickerid, cciTf1, ta.cci(cciSrc, cciLength))
cci2 = Fsec(syminfo.tickerid, cciTf2, ta.cci(cciSrc, cciLength))
cci3 = Fsec(syminfo.tickerid, cciTf3, ta.cci(cciSrc, cciLength))
cci4 = Fsec(syminfo.tickerid, cciTf4, ta.cci(cciSrc, cciLength))
cci5 = Fsec(syminfo.tickerid, cciTf5, ta.cci(cciSrc, cciLength))
//------------------------------------------------------------------------------
// CCI Overbought and Oversold detect
cci1_Ob = not cciTf1_E or cci1 >= cciOverbought
cci2_Ob = not cciTf2_E or cci2 >= cciOverbought
cci3_Ob = not cciTf3_E or cci3 >= cciOverbought
cci4_Ob = not cciTf4_E or cci4 >= cciOverbought
cci5_Ob = not cciTf5_E or cci5 >= cciOverbought
cci1_Os = not cciTf1_E or cci1 <= cciOversold
cci2_Os = not cciTf2_E or cci2 <= cciOversold
cci3_Os = not cciTf3_E or cci3 <= cciOversold
cci4_Os = not cciTf4_E or cci4 <= cciOversold
cci5_Os = not cciTf5_E or cci5 <= cciOversold
cciOb = cci1_Ob and cci2_Ob and cci3_Ob and cci4_Ob and cci5_Ob
cciOs = cci1_Os and cci2_Os and cci3_Os and cci4_Os and cci5_Os
//------------------------------------------------------------------------------
// Drawing on chart
plot (cciTf1_E ? cci1 : na, title="TF 1", color=color.rgb(255, 205, 22, 20), linewidth=1)
plot (cciTf2_E ? cci2 : na, title="TF 2", color=color.rgb(255, 22, 239, 20), linewidth=1)
plot (cciTf3_E ? cci3 : na, title="TF 3", color=color.rgb(38, 22, 255, 0), linewidth=1)
plot (cciTf4_E ? cci4 : na, title="TF 4", color=color.rgb(123, 253, 22, 20), linewidth=1)
plot (cciTf5_E ? cci5 : na, title="TF 5", color=color.rgb(255, 255, 255, 50), linewidth=1)
hline (cciOverbought, title="CCI Overbought", color=color.new(color.white, 0), linestyle=hline.style_dashed, linewidth=1)
hline (cciOversold, title="CCI Overbought", color=color.new(color.white, 0), linestyle=hline.style_dashed, linewidth=1)
bgcolor (cciOb ? color.new(color.red, 0) : na, title="Overbought")
bgcolor (cciOs ? color.new(color.lime, 0) : na, title="Oversold")
//------------------------------------------------------------------------------
// Alert
alertcondition(cciOb, title="CCI Overbought", message="CCI Overbought for {{ticker}} - Price = {{close}}")
alertcondition(cciOs, title="CCI Oversold", message="CCI Oversold for {{ticker}} - Price = {{close}}")
//==============================================================================
//==============================================================================
|
Vector Flow Channel | https://www.tradingview.com/script/lf4AN5ts-Vector-Flow-Channel/ | RicardoSantos | https://www.tradingview.com/u/RicardoSantos/ | 190 | 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/
// Β© RicardoSantos
//@version=5
indicator(title="Vector Flow Channel V0", shorttitle="VFC0", overlay=true)
float decay = ta.atr(10)*input.float(defval=0.005, title='Decay Rate:')
int stage1 = input.int(defval=05, title='Stage Start 1:', inline='stage')
int stage2 = input.int(defval=10, title='2:', inline='stage')
int stage3 = input.int(defval=20, title='3:', inline='stage')
int stage1length = input.int(defval=100, title='Stage length 1:', inline='stagelength')
int stage2length = stage1length + input.int(defval=100, title='2:', inline='stagelength')
TopVector (float source, int start1=1, int start2=1, int start3=1, int length1=1, int length2=1) => //{
var float _top = source
int _final_count = 0
float _previous = nz(_top[1], source)
_top := source >= _previous ? source : _previous - (decay * _final_count[1])
int _counter = bar_index - ta.valuewhen(close >= _top, bar_index, 0)
switch
_counter <= length1 => _final_count := start1
_counter <= length2 => _final_count := start2
=> _final_count := start3
_top
//}
BotVector (float source, int start1=1, int start2=1, int start3=1, int length1=1, int length2=1) => //{
var float _bot = source
int _final_count = 0
float _previous = nz(_bot[1], source)
_bot := source <= _previous ? source : _previous + (decay * _final_count[1])
int _counter = bar_index - ta.valuewhen(close <= _bot, bar_index, 0)
switch
_counter <= length1 => _final_count := start1
_counter <= length2 => _final_count := start2
=> _final_count := start3
_bot
//}
float topvector01 = TopVector(close, stage1, stage2, stage3, stage1length, stage2length)
float botvector01 = BotVector(close, stage1, stage2, stage3, stage1length, stage2length)
pt = plot(topvector01, color=(topvector01 == close ? na : color.black))
pb = plot(botvector01, color=(botvector01 == close ? na : color.black))
fill(pt, pb, color=color.new(color.blue, 85))
|
Scalping The Bull | https://www.tradingview.com/script/BWlC3Zv7/ | TheSocialCryptoClub | https://www.tradingview.com/u/TheSocialCryptoClub/ | 219 | 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/
// Β© TheSocialCryptoClub
//@version=5
indicator('Scalping The Bull', shorttitle='Scalping The Bull', overlay=true)
// -----------------------------------------------------------------------------
// Dichiarazione input
// -----------------------------------------------------------------------------
input_medie = input.string(defval='Crypto', options=['Crypto'], group='Mercato', title='EMA per mercato')
len1 = 5
len2 = 10
len3 = 60
len4 = 223
ema20 = input(false, 'Visualizza EMA aggiuntiva a ',group='Mercato',inline="ema20")
len5 = input(20, title="",group='Mercato',inline="ema20")
if input_medie == 'Crypto'
len1 := 5
len2 := 10
len3 := 60
len4 := 223
sfondo = input(false, 'Sfondo', group="Elementi del Grafico", tooltip="Visualizza lo sfondo verde se la EMA 60 > 223 oppure Rosso se la EMA 223 > 60")
sessione = input(true, 'Separatore Sessione', group="Elementi del Grafico")
attiva_max_min_oggi = input(true, 'Trigger di Oggi: ',group= "Punti Trigger",inline= "max oggi")
color_apertura_oggi=input.color(color.green,"Apertura",group= "Punti Trigger",inline= "max oggi")
color_max_oggi=input.color(color.purple,", Massimo",group= "Punti Trigger",inline= "max oggi")
color_min_oggi=input.color(#C90016,", Minimo",group= "Punti Trigger",inline= "max oggi")
attiva_max_min_ieri = input(true, 'Trigeger di Ieri: ',group= "Punti Trigger",inline= "max ieri")
color_max_ieri=input.color(color.yellow,"Massimo ",group= "Punti Trigger",inline= "max ieri")
color_min_ieri=input.color(#E8000D,", Minimo",group= "Punti Trigger",inline= "max ieri")
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Calcoli per le medie
// -----------------------------------------------------------------------------
ma1 = ta.ema(close, len1)
ma2 = ta.ema(close, len2)
ma3 = ta.ema(close, len3)
ma4 = ta.ema(close, len4)
ma5 = ta.ema(close, len5)
plot(ma1, title='EMA 5', color=color.new(color.red, 0))
plot(ma2, title='EMA 10', color=color.new(color.yellow, 0), linewidth=2)
plot(ma3, title='EMA 60', color=color.new(color.aqua, 0), linewidth=2)
plot(ma4, title='EMA 223', color=color.new(color.purple, 0), linewidth=2)
plot(ema20 ? ma5 : na, title='EMA 20', color=color.new(color.orange, 0), linewidth=2)
cond_bg = sfondo and ma4 > ma3
cond_bg2 = sfondo and ma4 < ma3
bgcolor(cond_bg ? color.new(color.red, transp=90) : na, title='Sfondo')
bgcolor(cond_bg2 ? color.new(color.green, transp=90) : na,title='Sfondo')
close_daily = request.security(syminfo.tickerid, 'D', close)
open_daily = request.security(syminfo.tickerid, 'D', open)
high_daily = request.security(syminfo.tickerid, 'D', high)
low_daily = request.security(syminfo.tickerid, 'D', low)
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Punti trigger di oggi
// -----------------------------------------------------------------------------
apertura = time(timeframe.period, '0000-0001:1234567')
prezzo_apertura = ta.valuewhen(time == apertura, open, 0)
stesso_giorno = prezzo_apertura == prezzo_apertura[1]
F_Line(_line, _y) =>
line.set_xy1(_line, apertura, _y)
line.set_xy2(_line, time + 1, _y)
bgcolor(sessione and apertura and timeframe.isintraday?color.new(color.blue,70):na)
var barre = 0
if time == apertura
barre := 1
var massimo_oggi = 0.0
var minimo_oggi = 0.0
var n_barre = 0
// reset delle variabili da inizio di ogi giornata
if hour == 00 and minute == 1 or hour == 00 and minute == 5 or hour == 00 and minute == 15 or hour == 00 and minute == 30 or hour == 01 and minute == 0 or hour == 02 and minute == 0 or hour == 04 and minute == 0
massimo_oggi := high
minimo_oggi := low
n_barre := 0
barre += 1
if high >= massimo_oggi
massimo_oggi := high
massimo_oggi:= ta.highest(high,barre)
if low < minimo_oggi
minimo_oggi := low
minimo_oggi
if time == apertura
barre :=0
var line myLineH = line.new(na, na, na, na, xloc=xloc.bar_time, extend=extend.right, color=color_max_oggi, style=line.style_solid, width=2)
var line myLineO = line.new(na, na, na, na, xloc=xloc.bar_time, extend=extend.right, color=color_apertura_oggi, style=line.style_solid, width=2)
var line myLineL = line.new(na, na, na, na, xloc=xloc.bar_time, extend=extend.right, color=color_min_oggi, style=line.style_solid, width=2)
if timeframe.isintraday
F_Line(myLineH, attiva_max_min_oggi ? massimo_oggi : na)
F_Line(myLineO, attiva_max_min_oggi ? open_daily : na)
F_Line(myLineL, attiva_max_min_oggi ? low_daily : na)
cond_max_today = ta.crossover(high,massimo_oggi[1]* (100 - 0) / 100) and attiva_max_min_oggi or high>massimo_oggi[1] and attiva_max_min_oggi
cond_min_today = ta.crossunder(low, minimo_oggi[1]) and attiva_max_min_oggi
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Punti trigger di ieri
// -----------------------------------------------------------------------------
highd = ta.valuewhen(time == apertura, high_daily, 0)
closed = ta.valuewhen(time == apertura, close_daily, 0)
lowd = ta.valuewhen(time == apertura, low_daily, 0)
x_ieri = not ta.crossover(close, highd * (100 - 0) / 100)
cond_label_ieri = x_ieri[2] and x_ieri[3] and x_ieri[4] and x_ieri[5] and x_ieri[6] and x_ieri[7] and x_ieri[8] and x_ieri[9] and x_ieri[10] and x_ieri[11] and x_ieri[12] and x_ieri[13] and x_ieri[14] and x_ieri[15] and x_ieri[16] and x_ieri[17] and x_ieri[18] and x_ieri[19] and x_ieri[20]
cond_massimo_ieri = ta.crossover(close, highd * (100 - 0) / 100) and cond_label_ieri and attiva_max_min_ieri
cond_minimo_ieri = ta.crossunder(close, lowd)
var line highd1_line = line.new(apertura?bar_index:na, na, bar_index, na, xloc=xloc.bar_time, color=color_max_ieri, style=line.style_dotted, width=2)
var line lowd1_line = line.new(ta.barssince(apertura), lowd, bar_index, lowd, xloc=xloc.bar_time, color=color_min_ieri, style=line.style_dotted, width=2)
if timeframe.isintraday
F_Line(highd1_line, attiva_max_min_ieri ? highd : na)
F_Line(lowd1_line, attiva_max_min_ieri ? lowd : na)
// -----------------------------------------------------------------------------
|
Previous High/Low Levels | https://www.tradingview.com/script/KIT8b4Lc-Previous-High-Low-Levels/ | wolffnbear | https://www.tradingview.com/u/wolffnbear/ | 285 | 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/
// Β© wolffnbear
//@version=4
study(title="Previous High/Low Levels", overlay=true)
WARNING = input(title='For Levels to work correctly, Right-click chart background, select Settings, Scales, tick βIndicator Last Value Labelβ', type=input.bool, defval=true, confirm=true)
res = input(title="High/Low Timeframe #1", type=input.resolution, defval="D", group = "Select Timeframe")
res2 = input(title="High/Low Timeframe #2", type=input.resolution, defval="W")
res3 = input(title="High/Low Timeframe #3", type=input.resolution, defval="M")
res4 = input(title="High/Low Timeframe #4", type=input.resolution, defval="3M")
res5 = input(title="High/Low Timeframe #5", type=input.resolution, defval="12M")
ddColor = input(title = "Timeframe #1", type = input.color, defval=#927e61, group = "Select Timeframe Color")
res2Color = input(title = "Timeframe #2", type = input.color, defval=color.blue)
res3Color = input(title = "Timeframe #3", type = input.color, defval=color.orange)
res4Color = input(title = "Timeframe #4", type = input.color, defval=color.purple)
res5Color = input(title = "Timeframe #5", type = input.color, defval=color.green)
//TIMEFRAME #1
show_dailyhl = input(title="High/Low Level", type=input.bool, defval=true, group = "TIMEFRAME #1 SETTINGS")
show_dailyhll = input(title="High/Low Label", type=input.bool, defval=false)
dayHH = security(syminfo.tickerid, res, high[1], lookahead=true)
dayHL = security(syminfo.tickerid, res, low[1], lookahead=true)
ildd = input(title="High/Low Label Offset (L-R, 0-50)", type=input.integer, defval=5, minval=1, maxval=70)
lwdhl = input(title="High/Low Level Linewidth (Small-Large, 1-5)", type=input.integer, defval=1, minval=1, maxval=5)
//TIMEFRAME #2
show_res2hl = input(title="High/Low Level", type=input.bool, defval=false, group="TIMEFRAME #2 SETTINGS")
show_res2hll = input(title="High/Low Label", type=input.bool, defval=false)
res2HH = security(syminfo.tickerid, res2, high[1], lookahead=true)
res2HL = security(syminfo.tickerid, res2, low[1], lookahead=true)
ilres2 = input(title="High/Low Label Offset (L-R, 0-50)", type=input.integer, defval=7, minval=1, maxval=70)
lwres2hl = input(title="High/Low Level Linewidth (Small-Large, 1-5)", type=input.integer, defval=1, minval=1, maxval=5)
//TIMEFRAME #3
show_res3hl = input(title="High/Low Level", type=input.bool, defval=false, group="TIMEFRAME #3 SETTINGS")
show_res3hll = input(title="High/Low Label", type=input.bool, defval=false)
res3HH = security(syminfo.tickerid, res3, high[1], lookahead=true)
res3HL = security(syminfo.tickerid, res3, low[1], lookahead=true)
ilres3 = input(title="High/Low Label Offset (L-R, 0-50)", type=input.integer, defval=9, minval=1, maxval=70)
lwres3hl = input(title="High/Low Level Linewidth (Small-Large, 1-5)", type=input.integer, defval=1, minval=1, maxval=5)
//TIMEFRAME #4
show_res4hl = input(title="High/Low Level", type=input.bool, defval=false, group="TIMEFRAME #4 SETTINGS")
show_res4hll = input(title="High/Low Label", type=input.bool, defval=false)
res4HH = security(syminfo.tickerid, res4, high[1], lookahead=true)
res4HL = security(syminfo.tickerid, res4, low[1], lookahead=true)
ilres4 = input(title="High/Low Label Offset (L-R, 0-50)", type=input.integer, defval=11, minval=1, maxval=70)
lwres4hl = input(title="High/Low Level Linewidth (Small-Large, 1-5)", type=input.integer, defval=1, minval=1, maxval=5)
//TIMEFRAME #5
show_res5hl = input(title="High/Low Level", type=input.bool, defval=false, group="TIMEFRAME #5 SETTINGS")
show_res5hll = input(title="High/Low Label", type=input.bool, defval=false)
res5HH = security(syminfo.tickerid, res5, high[1], lookahead=true)
res5HL = security(syminfo.tickerid, res5, low[1], lookahead=true)
ilres5 = input(title="High/Low Label Offset (L-R, 0-50)", type=input.integer, defval=14, minval=1, maxval=70)
lwres5hl = input(title="High/Low Level Linewidth (Small-Large, 1-5)", type=input.integer, defval=1, minval=1, maxval=5)
//OVERALL SETTINGS
txtcc = input(title="High/Low Label Text Color", type=input.color, defval=color.black, group="TEXT COLORS AND LINE STYLE SETTINGS")
hllstyle = input(title="High/Low Line Style", options=["solid (β)", "dotted (β)", "dashed (β)", "arrow left (β)", "arrow right (β)", "arrows both (β)"], defval="solid (β)")
hlllist(s)=>(s == "dotted (β)") ? line.style_dotted : (s == "dashed (β)") ? line.style_dashed : (s == "arrow left (β)") ? line.style_arrow_left : (s == "arrow right (β)") ? line.style_arrow_right : (s == "arrows both (β)") ? line.style_arrow_both : line.style_solid
wllist(s)=>(s == "dotted (β)") ? line.style_dotted : (s == "dashed (β)") ? line.style_dashed : (s == "arrow left (β)") ? line.style_arrow_left : (s == "arrow right (β)") ? line.style_arrow_right : (s == "arrows both (β)") ? line.style_arrow_both : line.style_solid
// TIMEFRAME #1 LINES
//daily high and low labels
plotshape(show_dailyhll ? dayHH : na, style=shape.labeldown, size=size.tiny, location=location.absolute, color=ddColor, textcolor=txtcc,show_last=1, text="High", offset=ildd, title="High Label")
plotshape(show_dailyhll ? dayHL : na, style=shape.labelup, size=size.tiny, location=location.absolute, color=ddColor, textcolor=txtcc, show_last=1, text="Low", offset=ildd, title="Low Label")
//daily high and low level price tags
plot(show_dailyhl ? dayHH : na, style=plot.style_line, color=ddColor, show_last=1, linewidth=lwdhl, title="High Price")
plot(show_dailyhl ? dayHL : na, style=plot.style_line, color=ddColor, show_last=1, linewidth=lwdhl, title="Low Price")
// High and Low Levels
dopenPrice(tf) => security(syminfo.tickerid, tf, time[1])
dlowPrice(tf) => security(syminfo.tickerid, tf, low[1])
dhighPrice(tf) => security(syminfo.tickerid, tf, high[1])
ddayLow = show_dailyhl ? dlowPrice(res) : na
ddayHigh = show_dailyhl ? dhighPrice(res) : na
ddayOpen = show_dailyhl ? dopenPrice(res) : na
ddayLineLow = line.new(x1=ddayOpen, y1=ddayLow, x2=time, y2=ddayLow, xloc = xloc.bar_time, extend = extend.right, color=ddColor, width=lwdhl)
line.set_style(ddayLineLow,style=hlllist(hllstyle))
line.delete(ddayLineLow[1])
ddayLineHigh = line.new(x1=ddayOpen, y1=ddayHigh, x2=time,y2=ddayHigh, xloc = xloc.bar_time, extend = extend.right, color=ddColor, width=lwdhl)
line.set_style(ddayLineHigh,style=hlllist(hllstyle))
line.delete(ddayLineHigh[1])
// TIMEFRAME #2 LINES
//res2 high and low labels
plotshape(show_res2hll ? res2HH : na, style=shape.labeldown, size=size.tiny, location=location.absolute, color=res2Color, textcolor=txtcc,show_last=1, text="High", offset=ilres2, title="High Label")
plotshape(show_res2hll ? res2HL : na, style=shape.labelup, size=size.tiny, location=location.absolute, color=res2Color, textcolor=txtcc, show_last=1, text="Low", offset=ilres2, title="Low Label")
//daily high and low level price tags
plot(show_res2hl ? res2HH : na, style=plot.style_line, color=res2Color, show_last=1, linewidth=lwres2hl, title="High Price")
plot(show_res2hl ? res2HL : na, style=plot.style_line, color=res2Color, show_last=1, linewidth=lwres2hl, title="Low Price")
// High and Low Levels
res2openPrice(tf) => security(syminfo.tickerid, tf, time[1])
res2lowPrice(tf) => security(syminfo.tickerid, tf, low[1])
res2highPrice(tf) => security(syminfo.tickerid, tf, high[1])
res2ayLow = show_res2hl ? res2lowPrice(res2) : na
res2ayHigh = show_res2hl ? res2highPrice(res2) : na
res2ayOpen = show_res2hl ? res2openPrice(res2) : na
res2ayLineLow = line.new(x1=res2ayOpen, y1=res2ayLow, x2=time, y2=res2ayLow, xloc = xloc.bar_time, extend = extend.right, color=res2Color, width=lwres2hl)
line.set_style(res2ayLineLow,style=hlllist(hllstyle))
line.delete(res2ayLineLow[1])
res2ayLineHigh = line.new(x1=res2ayOpen, y1=res2ayHigh, x2=time,y2=res2ayHigh, xloc = xloc.bar_time, extend = extend.right, color=res2Color, width=lwres2hl)
line.set_style(res2ayLineHigh,style=hlllist(hllstyle))
line.delete(res2ayLineHigh[1])
// TIMEFRAME #3 LINES
//res3 high and low labels
plotshape(show_res3hll ? res3HH : na, style=shape.labeldown, size=size.tiny, location=location.absolute, color=res3Color, textcolor=txtcc,show_last=1, text="High", offset=ilres3, title="High Label")
plotshape(show_res3hll ? res3HL : na, style=shape.labelup, size=size.tiny, location=location.absolute, color=res3Color, textcolor=txtcc, show_last=1, text="Low", offset=ilres3, title="Low Label")
//daily high and low level price tags
plot(show_res3hl ? res3HH : na, style=plot.style_line, color=res3Color, show_last=1, linewidth=lwres3hl, title="High Price")
plot(show_res3hl ? res3HL : na, style=plot.style_line, color=res3Color, show_last=1, linewidth=lwres3hl, title="Low Price")
// High and Low Levels
res3openPrice(tf) => security(syminfo.tickerid, tf, time[1])
res3lowPrice(tf) => security(syminfo.tickerid, tf, low[1])
res3highPrice(tf) => security(syminfo.tickerid, tf, high[1])
res3ayLow = show_res3hl ? res3lowPrice(res3) : na
res3ayHigh = show_res3hl ? res3highPrice(res3) : na
res3ayOpen = show_res3hl ? res3openPrice(res3) : na
res3ayLineLow = line.new(x1=res3ayOpen, y1=res3ayLow, x2=time, y2=res3ayLow, xloc = xloc.bar_time, extend = extend.right, color=res3Color, width=lwres3hl)
line.set_style(res3ayLineLow,style=hlllist(hllstyle))
line.delete(res3ayLineLow[1])
res3ayLineHigh = line.new(x1=res3ayOpen, y1=res3ayHigh, x2=time,y2=res3ayHigh, xloc = xloc.bar_time, extend = extend.right, color=res3Color, width=lwres3hl)
line.set_style(res3ayLineHigh,style=hlllist(hllstyle))
line.delete(res3ayLineHigh[1])
// TIMEFRAME #4 LINES
//res4 high and low labels
plotshape(show_res4hll ? res4HH : na, style=shape.labeldown, size=size.tiny, location=location.absolute, color=res4Color, textcolor=txtcc,show_last=1, text="High", offset=ilres4, title="High Label")
plotshape(show_res4hll ? res4HL : na, style=shape.labelup, size=size.tiny, location=location.absolute, color=res4Color, textcolor=txtcc, show_last=1, text="Low", offset=ilres4, title="Low Label")
//daily high and low level price tags
plot(show_res4hl ? res4HH : na, style=plot.style_line, color=res4Color, show_last=1, linewidth=lwres4hl, title="High Price")
plot(show_res4hl ? res4HL : na, style=plot.style_line, color=res4Color, show_last=1, linewidth=lwres4hl, title="Low Price")
// High and Low Levels
res4openPrice(tf) => security(syminfo.tickerid, tf, time[1])
res4lowPrice(tf) => security(syminfo.tickerid, tf, low[1])
res4highPrice(tf) => security(syminfo.tickerid, tf, high[1])
res4ayLow = show_res4hl ? res4lowPrice(res4) : na
res4ayHigh = show_res4hl ? res4highPrice(res4) : na
res4ayOpen = show_res4hl ? res4openPrice(res4) : na
res4ayLineLow = line.new(x1=res4ayOpen, y1=res4ayLow, x2=time, y2=res4ayLow, xloc = xloc.bar_time, extend = extend.right, color=res4Color, width=lwres4hl)
line.set_style(res4ayLineLow,style=hlllist(hllstyle))
line.delete(res4ayLineLow[1])
res4ayLineHigh = line.new(x1=res4ayOpen, y1=res4ayHigh, x2=time,y2=res4ayHigh, xloc = xloc.bar_time, extend = extend.right, color=res4Color, width=lwres4hl)
line.set_style(res4ayLineHigh,style=hlllist(hllstyle))
line.delete(res4ayLineHigh[1])
// TIMEFRAME #5 LINES
//res5 high and low labels
plotshape(show_res5hll ? res5HH : na, style=shape.labeldown, size=size.tiny, location=location.absolute, color=res5Color, textcolor=txtcc,show_last=1, text="High", offset=ilres5, title="High Label")
plotshape(show_res5hll ? res5HL : na, style=shape.labelup, size=size.tiny, location=location.absolute, color=res5Color, textcolor=txtcc, show_last=1, text="Low", offset=ilres5, title="Low Label")
//daily high and low level price tags
plot(show_res5hl ? res5HH : na, style=plot.style_line, color=res5Color, show_last=1, linewidth=lwres5hl, title="High Price")
plot(show_res5hl ? res5HL : na, style=plot.style_line, color=res5Color, show_last=1, linewidth=lwres5hl, title="Low Price")
// High and Low Levels
res5openPrice(tf) => security(syminfo.tickerid, tf, time[1])
res5lowPrice(tf) => security(syminfo.tickerid, tf, low[1])
res5highPrice(tf) => security(syminfo.tickerid, tf, high[1])
res5ayLow = show_res5hl ? res5lowPrice(res5) : na
res5ayHigh = show_res5hl ? res5highPrice(res5) : na
res5ayOpen = show_res5hl ? res5openPrice(res5) : na
res5ayLineLow = line.new(x1=res5ayOpen, y1=res5ayLow, x2=time, y2=res5ayLow, xloc = xloc.bar_time, extend = extend.right, color=res5Color, width=lwres5hl)
line.set_style(res5ayLineLow,style=hlllist(hllstyle))
line.delete(res5ayLineLow[1])
res5ayLineHigh = line.new(x1=res5ayOpen, y1=res5ayHigh, x2=time,y2=res5ayHigh, xloc = xloc.bar_time, extend = extend.right, color=res5Color, width=lwres5hl)
line.set_style(res5ayLineHigh,style=hlllist(hllstyle))
line.delete(res5ayLineHigh[1])
|
Candle Colored by Volume Z-score [Morty] | https://www.tradingview.com/script/0KInGMjR-Candle-Colored-by-Volume-Z-score-Morty/ | M0rty | https://www.tradingview.com/u/M0rty/ | 1,441 | 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/
// Β© M0rty
//@version=5
indicator("Candle Colored by Volume Z-score [Morty]", overlay=true, format=format.price)
// inputs
i_src = input.string("Volume", title="Source", options=["Volume", "Body size", "Any", "All"],
tooltip="If you select any, any outlier that meets the condition will be displayed. \nIf you select all, all the exceptions that satisfy the condition will be displayed")
len = input(20, "Z-Score MA Length")
z1 = input.float(1.5, "Threshold z1", step=0.1, tooltip="Default 1.5\nZ-score between z1 and z2 is defined as 'Large'")
z2 = input.float(2.5, "Threshold z2", step=0.1, tooltip="Default 2.5\nZ-score greater than z2 is defined as 'Extreme'")
i_chart_type = input.string("Bar", title="Chart Type", options=["Bar", "Candle"],
tooltip="Bar will color current bars. \nCandle will plot candles on the chart.")
show_low_volume_candle = input.bool(true, "Show low volume", inline="l1", group="Low Volume")
i_only_show_imbalance = input.bool(false, "Only Show imbalance", inline="l1", group="Low Volume")
i_color_low_volume = input.color(#eaea00, title="", inline="l1", group="Low Volume") // yellow
low_volume_z = input.float(-1.0, "Low Volume Threshold", step=0.1, tooltip="default -1.0\nVolume Z-score less than this value is defined as 'Low Voluem'", group="Low Volume")
color_up_normal = input.color(#d1d4dc, "normal", inline="l2", group="Up color") // white
color_up_large = input.color(#0080ff, "large", inline="l2", group="Up color") // blue
color_up_excheme = input.color(#069c76, "excheme", inline="l2", group="Up color") // green
color_down_normal = input.color(#06090b, "normal", inline="l3", group="Down color") // black
color_down_large = input.color(#8000ff, "large", inline="l3", group="Down color") // purple
color_down_excheme = input.color(#ff0f0f, "excheme", inline="l3", group="Down color") // red
// functions
f_zscore(src, len) =>
mean = ta.sma(src, len)
std = ta.stdev(src, len)
z = (src - mean) / std
// calculations
z_volume = f_zscore(volume, len)
z_body = f_zscore(math.abs(close-open), len)
float z = switch i_src
"Volume" => z_volume
"Body size" => z_body
"Any" => math.max(z_volume, z_body)
"All" => math.min(z_volume, z_body)
normal = z < z1
large = z >= z1 and z < z2
extreme = z >= z2
up = close >= open
down = close < open
up_normal = up and normal
up_large = up and large
up_extreme = up and extreme
down_normal = down and normal
down_large = down and large
down_extreme = down and extreme
// plots
low_volume_cond = i_only_show_imbalance ? z_volume<=low_volume_z and z_body>=0 : z_volume<=low_volume_z
color_low_volume = show_low_volume_candle and low_volume_cond ? i_color_low_volume : na
color_up = up_extreme ? color_up_excheme :
up_large ? color_up_large:
up_normal ? color_up_normal : na
color_down = down_extreme ? color_down_excheme :
down_large ? color_down_large :
down_normal ? color_down_normal : na
barcolor(i_chart_type=="Bar" ? color_low_volume : na, editable=false, title="Low Volume Bar")
barcolor(i_chart_type=="Bar" ? color_up : na, editable=false, title="Up Bar")
barcolor(i_chart_type=="Bar" ? color_down : na, editable=false, title="Down Bar")
color_candle = up_extreme ? color_up_excheme :
up_large ? color_up_large :
up_normal ? color_up_normal :
down_extreme ? color_down_excheme :
down_large ? color_down_large :
down_normal ? color_down_normal : na
plotcandle(i_chart_type=="Candle" ? open : na, high, low, close, title='Candle Colored', color=color_candle, wickcolor=color.gray, editable=false)
// alerts
alertcondition(extreme, title='Extreme Alert', message="{{time}}\nprice {{exchange}}:{{ticker}} = {{close}}")
alertcondition(large, title='Large Alert', message="{{time}}\nprice {{exchange}}:{{ticker}} = {{close}}")
|
Input Text Area to Array then Reshape Table | https://www.tradingview.com/script/bDBQh2Ij-Input-Text-Area-to-Array-then-Reshape-Table/ | RozaniGhani-RG | https://www.tradingview.com/u/RozaniGhani-RG/ | 46 | 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('Input Text Area to Array then Reshape Table', shorttitle = 'ITAtAtRT', overlay = true)
// 0 Input
// 1 String
// 2 Switch
// 3 Variable
// 4 Construct
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 0 Input {
i_s_Y = input.string('middle', 'Positionβ', inline = 'Position', group = 'Table', options = ['top', 'middle', 'bottom'])
i_s_X = input.string('center', '', inline = 'Position', group = 'Table', options = ['left', 'center', 'right'])
i_s_font = input.string('normal', 'Font Size', inline = 'Font', group = 'Table', options = ['tiny', 'small', 'normal', 'large', 'huge'])
i_b_reshape = input.bool( true, 'Reshape Table', inline = 'Font', group = 'Table', tooltip = 'true - vertical cells\n false - horizontal cells')
i_b_sort = input.bool( false, 'Sort', inline = 'Sort', group = 'Table', tooltip = 'true - sort ascending\n false - sort descending')
i_c_border = input.color( color.black, 'Border', inline = 'Color', group = 'Color')
i_c_bg = input.color( color.yellow, 'Cell', inline = 'Color', group = 'Color')
i_c_text = input.color( color.black, 'Text', inline = 'Color', group = 'Color')
i_ta_text = input.text_area( 'A\nB\nC', 'Input your text', tooltip = 'Input your text then enter each line except for last line')
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 1 String {
_array = str.split( i_ta_text, '\n')
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 2 Switch {
[_columns, _rows] = switch i_b_reshape
true => [ 1, array.size(_array)]
false => [array.size(_array), 1]
switch i_b_sort
true => array.sort(_array, order.ascending)
false => array.sort(_array, order.descending)
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 3 Variable {
var TableText = table.new(i_s_Y + '_' + i_s_X, _columns, _rows, i_c_bg, border_color = i_c_border, border_width = 1)
// }
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ 4 Construct {
if barstate.islast
for _index = 0 to array.size(_array) - 1
[_column, _row] = switch i_b_reshape
true => [0, _index]
false => [_index, 0]
if array.size(_array) > _index
table.cell(TableText, _column, _row, array.get(_array, _index), text_color = i_c_text, text_size = i_s_font)
// }
|
Mocker Market Mean Indicator | https://www.tradingview.com/script/jISNbcRN-Mocker-Market-Mean-Indicator/ | Algo_Jo | https://www.tradingview.com/u/Algo_Jo/ | 41 | 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/
// Β© jdweber98
//@version=5
indicator("Mocker Market Mean Indicator",overlay=true, precision = 2)
//Get user input
//Mean period Settings
var g_averageperiod = "Market Mean Average Period"
lookback_Years = input(title ="Year Average Period", defval=50, group = g_averageperiod, tooltip ="Lookback period in years to get the mean price (If you choose a loockback period that exceeds the historical price data of the chosen securtiy , you will recieve an error message in the textbox plotted on the most recent candle)")
//Indicator Plotting Settings
var g_plot = "Indicator Plotting Settings"
linewidth = input(title = "Mean Line Width", defval = 2 , group = g_plot, tooltip = "Select what width you want the mean line to be")
textbox_Plot = input(title = "Plot Textbox to Chart", defval = true, group = g_plot, tooltip = "Select to plot information texbox to chart")
table_Plot = input(title = "Plot Stats Table to Chart", defval = true, group = g_plot, tooltip = "Select to plot information table to chart")
title_Plot = input(title = "Plot Title to Chart", defval = true, group = g_plot, tooltip = "Select to plot title to chart")
var color_plot = "Indicator Color Theme"
color_theme = input.string(title = "Color Theme", defval = "Green", group = color_plot , options=["Orange","Green","Blue","Gray","Red","White","Yellow","Teal"], tooltip = "Choose your theme color for the indicator" )
theme_color = color.green
//Create the indicator color theme
if color_theme == "Orange"
theme_color := color.orange//#FF9800
if color_theme == "Green"
theme_color := color.green//#4CAF50
if color_theme == "Blue"
theme_color := color.blue//#2961ff
if color_theme == "Gray"
theme_color := color.gray//#787B86
if color_theme == "Red"
theme_color := color.red//#FF5252
if color_theme == "White"
theme_color := color.white//#FFFFFF
if color_theme == "Yellow"
theme_color := color.yellow//#FFEB3B
if color_theme == "Teal"
theme_color := color.teal//#00897B
//Custom Functions
//Truncate or reduce decimal places to desired amount
truncate(_number, _decimalPlaces) =>
_factor = math.pow(10, _decimalPlaces)
int(_number * _factor) / _factor
//Get Average Period in current timeframe candles
labeltext = ""
tradingday_Lookback = 0
yr_lookback = 0
if timeframe.isdaily
tradingday_Lookback := (lookback_Years * 253)
yr_lookback := 253
if timeframe.isweekly
tradingday_Lookback := (lookback_Years * 52)
yr_lookback := 52
if timeframe.ismonthly
tradingday_Lookback := (lookback_Years * 12)
yr_lookback := 12
if timeframe.isintraday
labeltext := "Please Choose a Higher Timeframe"
total_Bar_Count = 0
total_Bar_Count := barstate.isfirst ? 0 : total_Bar_Count [1] + 1
//==============================================================================
// Use Linear Regression to find the "Line of Best Fit", then transform the data to Use the Exponetial Regression Model
// Linear Regression formula: Y = mx + b
// Exponential Rgression formula using transformed data from the Linear regression model. Formula: Y = Ar ^x
// Create an x array for the linear regression model using the candle counter
//Declare the array for the "X" Data in the array
X = total_Bar_Count
var x_valuesArray = array.new_float(tradingday_Lookback)
//Add the current values to the array
array.push(x_valuesArray, total_Bar_Count)
//shift (remove) the last (first entered) value from the array
array.remove(x_valuesArray,0)
// Get the close price from the last candle
L_Month_close = math.log10(close)
//Create An array for the "Y" Values which will be the log of closing price of the quoted security (this data will then be used to find the slope and intercept of the quoted security)
//Declare the array for using linear regression to transform the data to find exponetial regression
var w_Exp_Reg_Array = array.new_float(tradingday_Lookback)
//Add the current values to the array
array.push(w_Exp_Reg_Array,L_Month_close)
//shift (remove) the last (first entered) value from the array
array.remove(w_Exp_Reg_Array,0)
xy = L_Month_close * total_Bar_Count
//Declare the array for the "XY" Data for finding the slope
var xy_valuesArray = array.new_float(tradingday_Lookback)
//Add the current values to the array
array.push(xy_valuesArray, xy)
//shift (remove) the last (first entered) value from the array
array.remove(xy_valuesArray,0)
// Get the x^2 values
x2 = math.pow(total_Bar_Count,2)
//Declare the array for the "x^2" Data for finding the slope
var x2_valuesArray = array.new_float(tradingday_Lookback)
//Add the current values to the array
array.push(x2_valuesArray, x2)
//shift (remove) the last (first entered) value from the array
array.remove(x2_valuesArray,0)
//Get the summs of the arrays
xarray_sum = array.sum(x_valuesArray)
yarray_sum = array.sum(w_Exp_Reg_Array)
xyarrray_sum = array.sum(xy_valuesArray)
x2array_sum = array.sum(x2_valuesArray)
// Y = mx + b
N = tradingday_Lookback
M = ((N*xyarrray_sum)-(xarray_sum*yarray_sum))/((N*x2array_sum)-(math.pow(xarray_sum,2)))
B = ((yarray_sum-(M*xarray_sum))/N)
Y1 = (M*X)+B
//Y = Ar^2
A = math.pow(10,B)
r_1 = math.pow(10,M)
Y = A*(math.pow(r_1,X))
//if tradingday_Lookback <= total_Bar_Count
// Y
//else
// Y := na
//Get current the distance from the mean price
float Delta = 0
if close > Y
Delta := ((close - Y)/ close ) * 100
if close < Y
Delta := ((Y - close )/ Y ) * 100
AB_id = close >= Y ? "Above" : "Below"
//Create a Lable to plot the current distance from the mean
if tradingday_Lookback > total_Bar_Count
labeltext := syminfo.ticker + " Does not have " + str.tostring(lookback_Years) + " years of price data. \nPlease select a shorter lookback period."
if close[1] > Y
labeltext := syminfo.ticker + " is trading " + str.tostring(truncate(Delta,2)) + "% above its " + str.tostring(lookback_Years) + " year mean."
if close[1] == Y
labeltext := syminfo.ticker + " is trading at its " + str.tostring(lookback_Years) + " year mean."
if close[1] < Y
labeltext := syminfo.ticker + " is trading " + str.tostring(truncate(Delta,2)) + "% below its " + str.tostring(lookback_Years) + " year mean."
//Plot label
Label = textbox_Plot ? label.new(x=bar_index, y=na, text=labeltext, yloc = yloc.abovebar , color=color.black, textcolor= theme_color) : na
label.delete(Label[1]) //Delete previous candles
yc(a1) => A*(math.pow(r_1,total_Bar_Count[a1]))
// Line id
tbl = tradingday_Lookback
bi(a1) => bar_index[a1]
xt = extend.none
c = theme_color
s = line.style_solid
w = linewidth
tv = true //tradingday_Lookback >= tbc ? false : true
//Create the mean line to be dynamic in length
l1 = tbl > 4900 and tv ? line.new(x1=bi(4990), y1=yc(4990), x2=bi(4500), y2=yc(4500), extend=xt, color=c, style=s, width=w) : na
line.delete(l1[1])
l2 = tbl > 4500 and tv ? line.new(x1=bi(4500), y1=yc(4500), x2=bi(4000), y2=yc(4000), extend=xt, color=c, style=s, width=w) : na
line.delete(l2[1])
l3 = tbl > 4000 and tv ? line.new(x1=bi(4000), y1=yc(4000), x2=bi(3500), y2=yc(3500), extend=xt, color=c, style=s, width=w) : na
line.delete(l3[1])
l4 = tbl > 3500 and tv ? line.new(x1=bi(3500), y1=yc(3500), x2=bi(3000), y2=yc(3000), extend=xt, color=c, style=s, width=w) : na
line.delete(l4[1])
l5 = tbl > 3000 and tv ? line.new(x1=bi(3000), y1=yc(3000), x2=bi(2500), y2=yc(2500), extend=xt, color=c, style=s, width=w) : na
line.delete(l5[1])
l6 = tbl > 2500 and tv ? line.new(x1=bi(2500), y1=yc(2500), x2=bi(2000), y2=yc(2000), extend=xt, color=c, style=s, width=w) : na
line.delete(l6[1])
l7 = tbl > 2000 and tv ? line.new(x1=bi(2000), y1=yc(2000), x2=bi(1500), y2=yc(1500), extend=xt, color=c, style=s, width=w) : na
line.delete(l7[1])
l8 = tbl > 1500 and tv ? line.new(x1=bi(1500), y1=yc(1500), x2=bi(1000), y2=yc(1000), extend=xt, color=c, style=s, width=w) : na
line.delete(l8[1])
l9 = tbl > 1000 and tv ? line.new(x1=bi(1000), y1=yc(1000), x2=bi(950), y2=yc(950), extend=xt, color=c, style=s, width=w) : na
line.delete(l9[1])
l10 = tbl > 950 and tv ? line.new(x1=bi(950), y1=yc(950), x2=bi(900), y2=yc(900), extend=xt, color=c, style=s, width=w) : na
line.delete(l10[1])
l11 = tbl > 900 and tv ? line.new(x1=bi(900), y1=yc(900), x2=bi(850), y2=yc(850), extend=xt, color=c, style=s, width=w) : na
line.delete(l11[1])
l12 = tbl > 850 and tv ? line.new(x1=bi(850), y1=yc(850), x2=bi(800), y2=yc(800), extend=xt, color=c, style=s, width=w) : na
line.delete(l12[1])
l13 = tbl > 800 and tv ? line.new(x1=bi(800), y1=yc(800), x2=bi(750), y2=yc(750), extend=xt, color=c, style=s, width=w) : na
line.delete(l13[1])
l14 = tbl > 750 and tv ? line.new(x1=bi(750), y1=yc(750), x2=bi(700), y2=yc(700), extend=xt, color=c, style=s, width=w) : na
line.delete(l14[1])
l15 = tbl > 700 and tv ? line.new(x1=bi(700), y1=yc(700), x2=bi(650), y2=yc(650), extend=xt, color=c, style=s, width=w) : na
line.delete(l15[1])
l16 = tbl > 650 and tv ? line.new(x1=bi(650), y1=yc(650), x2=bi(600), y2=yc(600), extend=xt, color=c, style=s, width=w) : na
line.delete(l16[1])
l17 = tbl > 600 and tv ? line.new(x1=bi(600), y1=yc(600), x2=bi(550), y2=yc(550), extend=xt, color=c, style=s, width=w) : na
line.delete(l17[1])
l18 = tbl > 550 and tv ? line.new(x1=bi(550), y1=yc(550), x2=bi(525), y2=yc(525), extend=xt, color=c, style=s, width=w) : na
line.delete(l18[1])
l19 = tbl > 525 and tv ? line.new(x1=bi(525), y1=yc(525), x2=bi(500), y2=yc(500), extend=xt, color=c, style=s, width=w) : na
line.delete(l19[1])
l20 = tbl > 500 and tv ? line.new(x1=bi(500), y1=yc(500), x2=bi(475), y2=yc(475), extend=xt, color=c, style=s, width=w) : na
line.delete(l20[1])
l21 = tbl > 475 and tv ? line.new(x1=bi(475), y1=yc(475), x2=bi(450), y2=yc(450), extend=xt, color=c, style=s, width=w) : na
line.delete(l21[1])
l22 = tbl > 450 and tv ? line.new(x1=bi(450), y1=yc(450), x2=bi(425), y2=yc(425), extend=xt, color=c, style=s, width=w) : na
line.delete(l22[1])
l23 = tbl > 425 and tv ? line.new(x1=bi(425), y1=yc(425), x2=bi(400), y2=yc(400), extend=xt, color=c, style=s, width=w) : na
line.delete(l23[1])
l24 = tbl > 400 and tv ? line.new(x1=bi(400), y1=yc(400), x2=bi(375), y2=yc(375), extend=xt, color=c, style=s, width=w) : na
line.delete(l24[1])
l25 = tbl > 375 and tv ? line.new(x1=bi(375), y1=yc(375), x2=bi(350), y2=yc(350), extend=xt, color=c, style=s, width=w) : na
line.delete(l25[1])
l26 = tbl > 350 and tv ? line.new(x1=bi(350), y1=yc(350), x2=bi(325), y2=yc(325), extend=xt, color=c, style=s, width=w) : na
line.delete(l26[1])
l27 = tbl > 325 and tv ? line.new(x1=bi(325), y1=yc(325), x2=bi(300), y2=yc(300), extend=xt, color=c, style=s, width=w) : na
line.delete(l27[1])
l28 = tbl > 300 and tv ? line.new(x1=bi(300), y1=yc(300), x2=bi(275), y2=yc(275), extend=xt, color=c, style=s, width=w) : na
line.delete(l28[1])
l29 = tbl > 275 and tv ? line.new(x1=bi(275), y1=yc(275), x2=bi(250), y2=yc(250), extend=xt, color=c, style=s, width=w) : na
line.delete(l29[1])
l30 = tbl > 250 and tv ? line.new(x1=bi(250), y1=yc(250), x2=bi(225), y2=yc(225), extend=xt, color=c, style=s, width=w) : na
line.delete(l30[1])
l31 = tbl > 225 and tv ? line.new(x1=bi(225), y1=yc(225), x2=bi(200), y2=yc(200), extend=xt, color=c, style=s, width=w) : na
line.delete(l31[1])
l32 = tbl > 200 and tv ? line.new(x1=bi(200), y1=yc(200), x2=bi(175), y2=yc(175), extend=xt, color=c, style=s, width=w) : na
line.delete(l32[1])
l33 = tbl > 175 and tv ? line.new(x1=bi(175), y1=yc(175), x2=bi(150), y2=yc(150), extend=xt, color=c, style=s, width=w) : na
line.delete(l33[1])
l34 = tbl > 150 and tv ? line.new(x1=bi(150), y1=yc(150), x2=bi(125), y2=yc(125), extend=xt, color=c, style=s, width=w) : na
line.delete(l34[1])
l35 = tbl > 125 and tv ? line.new(x1=bi(125), y1=yc(125), x2=bi(100), y2=yc(100), extend=xt, color=c, style=s, width=w) : na
line.delete(l35[1])
l36 = tbl > 100 and tv ? line.new(x1=bi(100), y1=yc(100), x2=bi(75), y2=yc(75), extend=xt, color=c, style=s, width=w) : na
line.delete(l36[1])
l37 = tbl > 75 and tv ? line.new(x1=bi(75), y1=yc(75), x2=bi(50), y2=yc(50), extend=xt, color=c, style=s, width=w) : na
line.delete(l37[1])
l38 = tbl > 50 and tv ? line.new(x1=bi(50), y1=yc(50), x2=bi(25), y2=yc(25), extend=xt, color=c, style=s, width=w) : na
line.delete(l38[1])
l39 = tbl > 25 and tv ? line.new(x1=bi(25), y1=yc(25), x2=bi(0), y2=yc(0), extend=xt, color=c, style=s, width=w) : na
line.delete(l39[1])
//Plot mean line
//plot(Y,color = theme_color)
//Get the Start and end value price to get the average CAGR
//Create an array to hold the yearly % gains
yr_gain = (close -close[yr_lookback])/close[yr_lookback]
var Y_array = array.new_float(tradingday_Lookback)
array.push(Y_array,yr_gain)
array.remove(Y_array,0)
//Get the average yearly % reurn over the lookback period
avg_yr_gain = array.avg(Y_array) *100
// Create variable table text colors based on values
delta_color = color.new(color.green, 30)
if Delta > 0 and Delta < 3 and AB_id == "Above"
delta_color := color.new(color.orange, 30)
if Delta > 3.1 and Delta < 7.9 and AB_id == "Above"
delta_color := color.new(color.orange, 10)
if Delta > 8 and Delta < 12 and AB_id == "Above"
delta_color := color.new(color.red, 30)
if Delta > 13 and AB_id == "Above"
delta_color := color.new(color.red, 0)
if Delta > 0 and Delta < 3 and AB_id == "Below"
delta_color := color.new(color.green, 35)
if Delta > 3.1 and Delta < 7.9 and AB_id == "Below"
delta_color := color.new(color.green, 30)
if Delta > 8 and Delta < 12 and AB_id == "Below"
delta_color := color.new(color.green, 20)
if Delta > 13 and AB_id == "Below"
delta_color := color.new(color.green, 0)
yr_return_color = color.new(color.green, 30)
if yr_gain < 0 and yr_gain > -0.03
yr_return_color := color.new(color.orange, 30)
if yr_gain < -0.031 and yr_gain > -0.079
yr_return_color := color.new(color.orange, 10)
if yr_gain < 0.08 and yr_gain > -0.12
yr_return_color := color.new(color.red, 30)
if yr_gain < -0.13
yr_return_color := color.new(color.red, 0)
if yr_gain > 0 and yr_gain < 0.03
yr_return_color := color.new(color.green, 35)
if yr_gain > 0.031 and yr_gain < 0.079
yr_return_color := color.new(color.green, 30)
if yr_gain > 0.08 and yr_gain < 0.12
yr_return_color := color.new(color.green, 20)
if yr_gain > 0.13
yr_return_color := color.new(color.green, 0)
avg_CAGR_color = color.new(color.green, 30)
if avg_yr_gain < 0 and avg_yr_gain > -3
avg_CAGR_color := color.new(color.orange, 30)
if avg_yr_gain < -3.1 and avg_yr_gain > -7.9
avg_CAGR_color := color.new(color.orange, 10)
if avg_yr_gain < -8 and avg_yr_gain > -12
avg_CAGR_color := color.new(color.red, 30)
if avg_yr_gain < -13
avg_CAGR_color := color.new(color.red, 0)
if avg_yr_gain > 0 and avg_yr_gain < 3
avg_CAGR_color := color.new(color.green, 35)
if avg_yr_gain > 3.1 and avg_yr_gain < 7.9
avg_CAGR_color := color.new(color.green, 30)
if avg_yr_gain > 8 and avg_yr_gain < 12
avg_CAGR_color := color.new(color.green, 20)
if avg_yr_gain > 13
avg_CAGR_color := color.new(color.green, 0)
m_color = color.silver
if tradingday_Lookback > total_Bar_Count
m_color := color.red
// Prepare stats table
var table Table = table.new(position.bottom_right, 5, 2,frame_color = theme_color, frame_width=2, border_color = theme_color, border_width=2)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
_cellText = _title + "\n" + _value
table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)
// Draw stats table
err = "Lookback period exceeds price history, choose a shorter lookback period"
var bgcolor = color.new(color.black,0)
if table_Plot
if barstate.islastconfirmedhistory
// Update table
f_fillCell(Table, 0, 0, str.tostring(lookback_Years) + " Yr Avg Yearly Growth Rate :", str.tostring(truncate(avg_yr_gain,2)) + " %", bgcolor, avg_CAGR_color)
f_fillCell(Table, 0, 1, str.tostring(lookback_Years) + " Yr Avg Mean Price :", tradingday_Lookback > total_Bar_Count ? str.tostring(err) : str.tostring(truncate(Y,2)) , bgcolor, m_color)
f_fillCell(Table, 1, 0, "Past 12 M return :", str.tostring(truncate(yr_gain*100,2)) + " %", bgcolor, yr_return_color)
f_fillCell(Table, 1, 1, "Distance From Mean :", str.tostring(truncate(Delta,2)) + " % "+ str.tostring(AB_id), bgcolor, delta_color)
//Title Table
var table title_Table = table.new(position.top_right, 5, 2,frame_color = color.new(theme_color,50) , frame_width=2, border_color = theme_color, border_width=2)
f_fillCell2(_table2, _column2, _row2, _title2, _bgcolor2, _txtcolor2) =>
_cellText2 = _title2
table.cell(_table2, _column2, _row2, _cellText2, bgcolor =_bgcolor2, text_color=_txtcolor2, text_size = size.large)
var bgcolor2 = color.new(color.black,0)
if title_Plot
if barstate.islastconfirmedhistory
// Update table
f_fillCell2(title_Table, 0, 0, " Mocker Market Mean Indicator" , bgcolor,color.new(theme_color,0))
|
S2BU2 Volume Oscillator (Improved) | https://www.tradingview.com/script/gI7WfWAH/ | sucks2bu2 | https://www.tradingview.com/u/sucks2bu2/ | 71 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© sucks2bu2
//@version=5
indicator(title="S2BU2 Volume Oscillator", shorttitle="S2BU2 VolO", format=format.percent, precision=2, overlay = false, timeframe="", timeframe_gaps=false)
//==================================define Inputs==================================//
periodShort = input.int(defval = 5, minval = 1, title = 'Period Short', group = 'Oscillator Settings')
periodLong = input.int(defval = 10, minval = 1, title = 'Period Long', group = 'Oscillator Settings')
periodFast = input.int(defval = 10, minval = 1, title = 'Period Fast', group = 'Moving Average Settings')
periodSlow = input.int(defval = 26, minval = 1, title = 'Period Slow', group = 'Moving Average Settings')
//===============================define Helper Vars================================//
var float cumulativeVol = 0
cumulativeVol += nz(volume)
var highs = array.new_float(0)
var lows = array.new_float(0)
int lookback = 2
int lookbackCont = lookback + 1
//==========================calculate Plot Variables===============================//
//get Oscillator Values
float shortOsc = ta.ema(volume, periodShort)
float longOsc = ta.ema(volume, periodLong)
//convert to percentage
float oscillator = 100 * (shortOsc - longOsc) / longOsc
//Get Peaks
if nz(oscillator[lookback]) < nz(oscillator[0]) and nz(oscillator[lookback+1]) < nz(oscillator[lookback-1]) and nz(oscillator[lookbackCont]) < nz(oscillator[0]) and nz(oscillator[lookbackCont+1]) < nz(oscillator[lookbackCont-1])
array.push(highs, oscillator)
float avgHigh = array.avg(highs)
//Get Bottoms
if nz(oscillator[lookback]) > nz(oscillator[0]) and nz(oscillator[lookback+1]) > nz(oscillator[lookback-1]) and nz(oscillator[lookbackCont]) > nz(oscillator[0]) and nz(oscillator[lookbackCont+1]) > nz(oscillator[lookbackCont-1])
array.push(lows, oscillator)
float avgLow = array.avg(lows)
//Get MAs
float fastMA = ta.ema(oscillator, periodFast)
float slowMA = ta.ema(oscillator, periodSlow)
//====================================plot=========================================//
//lines
hline(0, color = color.white, linestyle = hline.style_dashed, title = 'Zero Line')
plot(avgHigh, color = color.white, linewidth = 1, title = 'Average Highs')
plot(avgLow, color = color.white, linewidth = 1, title = 'Average Lows')
//MAs
plot(fastMA, color = color.orange, linewidth = 1, title = 'Moving Average')
plot(slowMA, color = color.gray, linewidth = 1, title = 'Singal') |
Moving Averages With Cross Alerts | https://www.tradingview.com/script/lkHuQTp7-Moving-Averages-With-Cross-Alerts/ | bstashio | https://www.tradingview.com/u/bstashio/ | 191 | 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/
// Β© bstashio
//@version=5
indicator('Moving Averages With Cross Alerts', overlay = true)
////////////////////////////////////////////////////////////////////////////////
//
// Generic Settings
//
////////////////////////////////////////////////////////////////////////////////
line_width = 1
color_transparency = 20
color_white = color.new(color.white , color_transparency)
color_red = color.new(color.red , color_transparency)
color_green = color.new(color.green , color_transparency)
color_blue = color.new(color.blue , color_transparency)
color_aqua = color.new(color.aqua , color_transparency)
color_yellow = color.new(color.yellow, color_transparency)
//------------------------------------------------------------------------------
ma_type = input.string(
title = 'Moving Averages Type',
options = ['SMA', 'EMA', 'HMA', 'RMA', 'WMA', 'VWMA', 'VWAP', 'ALMA'],
defval = 'SMA')
//------------------------------------------------------------------------------
get_ma( source, length ) =>
switch ma_type
'SMA' => ta.sma(source, length)
'EMA' => ta.ema(source, length)
'HMA' => ta.hma(source, length)
'RMA' => ta.rma(source, length)
'WMA' => ta.wma(source, length)
'VWMA' => ta.vwma(source, length)
'VWAP' => ta.vwma(source, length)
'ALMA' => ta.alma(source, length, 0.85, 5)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// @Notes:
// the followng doesn't work because "Cannot use 'plot' in local scope"
// so now I have to abandon using a loop and have each ma done indivdually with repetitive code
//
// @TradingView_Staff consider supporting this
//
//var lengths = array.from(5, 13, 50, 200, 800)
//var colors = array.from(color_yellow, color_red, color_aqua, color_white, color_blue)
//
//for [index, value] in lengths
// name = 'MA ' + str.tostring(index)
// group = name
// enable = input.bool(title = name + ' Enable', defval = true)
// source = input.source(close, title = name + ' Source')
// length = input.int(title = name + ' Length', minval = 1, defval = value)
// ma = ma_type == 'EMA' ? ta.ema(source, length) : ta.sma(source, length)
// plot(enable and ma ? ma : na, title = name + ' Line', linewidth = line_width, color = colors[index])
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Moving Average 1
//
////////////////////////////////////////////////////////////////////////////////
ma1_enable = input.bool(group = 'MA1', title = 'MA1 Enable', defval = true)
ma1_source = input.source(group = 'MA1', title = 'MA1 Source', defval = close)
ma1_length = input.int(group = 'MA1', title = 'MA1 Length', minval = 1, defval = 5)
ma1_color = input.color(group = 'MA1', title = 'MA1 Color', defval = color_yellow)
ma1 = get_ma( ma1_source, ma1_length )
plot(
series = ma1_enable and ma1 ? ma1 : na,
title = 'MA1 Line',
linewidth = line_width,
color = ma1_color)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Moving Average 2
//
////////////////////////////////////////////////////////////////////////////////
ma2_enable = input.bool(group = 'MA2', title = 'MA2 Enable', defval = true)
ma2_source = input.source(group = 'MA2', title = 'MA2 Source', defval = close)
ma2_length = input.int(group = 'MA2', title = 'MA2 Length', minval = 1, defval = 13)
ma2_color = input.color(group = 'MA2', title = 'MA2 Color', defval = color_red)
ma2 = get_ma( ma2_source, ma2_length )
plot(
series = ma2_enable and ma2 ? ma2 : na,
title = 'MA2 Line',
linewidth = line_width,
color = ma2_color)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Moving Average 3
//
////////////////////////////////////////////////////////////////////////////////
ma3_enable = input.bool(group = 'MA3', title = 'MA3 Enable', defval = true)
ma3_source = input.source(group = 'MA3', title = 'MA3 Source', defval = close)
ma3_length = input.int(group = 'MA3', title = 'MA3 Length', minval = 1, defval = 50)
ma3_color = input.color(group = 'MA3', title = 'MA3 Color', defval = color_aqua)
ma3 = get_ma( ma3_source, ma3_length )
plot(
series = ma3_enable and ma3 ? ma3 : na,
title = 'MA3 Line',
linewidth = line_width,
color = ma3_color)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Moving Average 4
//
////////////////////////////////////////////////////////////////////////////////
ma4_enable = input.bool(group = 'MA4', title = 'MA4 Enable', defval = true)
ma4_source = input.source(group = 'MA4', title = 'MA4 Source', defval = close)
ma4_length = input.int(group = 'MA4', title = 'MA4 Length', minval = 1, defval = 200)
ma4_color = input.color(group = 'MA4', title = 'MA4 Color', defval = color_white)
ma4 = get_ma( ma4_source, ma4_length )
plot(
series = ma4_enable and ma4 ? ma4 : na,
title = 'MA4 Line',
linewidth = line_width,
color = ma4_color)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Moving Average 5
//
////////////////////////////////////////////////////////////////////////////////
ma5_enable = input.bool(group = 'MA5', title = 'MA5 Enable', defval = true)
ma5_source = input.source(group = 'MA5', title = 'MA5 Source', defval = close)
ma5_length = input.int(group = 'MA5', title = 'MA5 Length', minval = 1, defval = 800)
ma5_color = input.color(group = 'MA5', title = 'MA5 Color', defval = color_blue)
ma5 = get_ma( ma5_source, ma5_length )
plot(
series = ma5_enable and ma5 ? ma5 : na,
title = 'MA5 Line',
linewidth = line_width,
color = ma5_color)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Alerts
//
////////////////////////////////////////////////////////////////////////////////
uptrend_message = ' - Indicating Possible Uptrend'
downtrend_message = ' - Indicating Possible Downtrend'
//------------------------------------------------------------------------------
alertcondition(
ta.crossover(ma1, ma2),
title = 'MA1 Cross Over MA2',
message = 'MA1 Cross Over MA2 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma1, ma2),
title = 'MA1 Cross Under MA2',
message = 'MA1 Cross Under MA2 Alert' + downtrend_message)
alertcondition(
ta.crossover(ma1, ma3),
title = 'MA1 Cross Over MA3',
message = 'MA1 Cross Over MA3 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma1, ma3),
title = 'MA1 Cross Under MA3',
message = 'MA1 Cross Under MA3 Alert' + downtrend_message)
//------------------------------------------------------------------------------
alertcondition(
ta.crossover(ma2, ma3),
title = 'MA2 Cross Over MA3',
message = 'MA2 Cross Over MA3 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma2, ma3),
title = 'MA2 Cross Under MA3',
message = 'MA2 Cross Under MA3 Alert' + downtrend_message)
alertcondition(
ta.crossover(ma2, ma4),
title = 'MA2 Cross Over MA4',
message = 'MA2 Cross Over MA4 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma2, ma4),
title = 'MA2 Cross Under MA4',
message = 'MA2 Cross Under MA4 Alert' + downtrend_message)
//------------------------------------------------------------------------------
alertcondition(
ta.crossover(ma3, ma4),
title = 'MA3 Cross Over MA4',
message='MA3 Cross Over MA4 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma3, ma4),
title = 'MA3 Cross Under MA4',
message = 'MA3 Cross Under MA4 Alert' + downtrend_message)
alertcondition(
ta.crossover(ma3, ma5),
title = 'MA3 Cross Over MA5',
message = 'MA3 Cross Over MA5 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma3, ma5),
title = 'MA3 Cross Under MA5',
message = 'MA3 Cross Under MA5 Alert' + downtrend_message)
//------------------------------------------------------------------------------
alertcondition(
ta.crossover(ma4, ma5),
title = 'MA4 Cross Over MA5',
message = 'MA4 Cross Over MA5 Alert' + uptrend_message)
alertcondition(
ta.crossunder(ma4, ma5),
title = 'MA4 Cross Under MA5',
message = 'MA4 Cross Under MA5 Alert' + downtrend_message)
|
ATR and IV Volatility Table | https://www.tradingview.com/script/FGY3cNfU-ATR-and-IV-Volatility-Table/ | exlux99 | https://www.tradingview.com/u/exlux99/ | 254 | 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/
// Β© exlux99
//@version=5
indicator("ATR and IV Volatility Table", overlay=true)
plot_atr = input.bool(true, title="Plot Bottom and Top Levels from ATR", group='Plotting')
plot_iv= input.bool(false, title="Plot Bottom and Top Levels from IV", group='Plotting')
length = input.int(title="Length ATR", defval=14, minval=1)
smoothing = "RMA"
input_iv=input.float(24.0, title="IV Value")
true_iv = input_iv / math.sqrt(252)
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)
//plot(ma_function(ta.tr(true), length), title = "ATR", color=color.new(#B71C1C, 0))
daily_atr=request.security(syminfo.tickerid, "D", ta.atr(length))
daily_close=request.security(syminfo.tickerid, "D", close)
var float gica = 0.0
gica:= daily_atr//ma_function(ta.tr(true),length)
////////////////////////////////////////////////////////////////////////////
posInput = input.string(title='Position', defval='Middle Right', options=['Bottom Left', 'Bottom Right', 'Top Left', 'Top Right', 'Middle Right'])
var pos = posInput == 'Bottom Left' ? position.bottom_left : posInput == 'Bottom Right' ? position.bottom_right : posInput == 'Top Left' ? position.top_left : posInput == 'Top Right' ? position.top_right : posInput == 'Middle Right' ? position.middle_right: na
var table table_atr = table.new(pos, 8, 8, border_width=3)
table_fillCell(_table, _column, _row, _value, _timeframe, _c_color) =>
_transp = 70
_cellText = str.tostring(_value, '#.###')
table.cell(_table, _column, _row, _cellText, bgcolor=color.new(_c_color, _transp), text_color=_c_color, width=5)
table.cell_set_text_size(table_atr, 0, 0, size.normal)
table.cell_set_text_size(table_atr, 0, 1, size.normal)
table.cell_set_text_size(table_atr, 0, 2, size.normal)
table.cell_set_text_size(table_atr, 0, 3, size.normal)
table.cell_set_text_size(table_atr, 1, 0, size.normal)
table.cell_set_text_size(table_atr, 1, 1, size.normal)
table.cell_set_text_size(table_atr, 1, 2, size.normal)
table.cell_set_text_size(table_atr, 1, 3, size.normal)
table.cell_set_text_size(table_atr, 2, 0, size.normal)
table.cell_set_text_size(table_atr, 2, 1, size.normal)
table.cell_set_text_size(table_atr, 2, 2, size.normal)
table.cell_set_text_size(table_atr, 2, 3, size.normal)
//table.cell_set_text_size(table_atr, 0, 2, text)
if barstate.islast
table.cell(table_atr, 0, 0, 'Daily ATR Value', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 0, 1, gica, 'Text', color.white)
table.cell(table_atr, 0, 2, 'Daily IV Value %', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table_fillCell(table_atr, 0, 3, true_iv, 'Text', color.white)
table.cell(table_atr, 1, 0, 'CLOSE + ATR Value', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 1, 1, gica+close, 'Text', color.white)
table.cell(table_atr, 1, 2, 'CLOSE + IV Value', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table_fillCell(table_atr, 1, 3, close*(true_iv/100)+close, 'Text', color.white)
table.cell(table_atr, 2, 0, 'CLOSE - ATR Value', text_color=color.white, text_size=size.normal, bgcolor=color.purple)
table_fillCell(table_atr, 2, 1, close-gica, 'Text', color.white)
table.cell(table_atr, 2, 2, 'CLOSE - IV Value', text_color=color.white, text_size=size.normal, bgcolor=color.blue)
table_fillCell(table_atr, 2, 3, close-close*(true_iv/100), 'Text', color.white)
plot(plot_atr? gica+daily_close : na, title='Daily TOP ATR')
plot(plot_atr ? daily_close-gica :na, title='Daily BOT ATR')
plot(plot_iv? daily_close*(true_iv/100)+daily_close : na, title='Daily TOP IV')
plot( plot_iv? daily_close-daily_close*(true_iv/100) : na, title='Daily BOT IV') |
Heikin-Ashi Trend Alert | https://www.tradingview.com/script/XyFm1NFs-Heikin-Ashi-Trend-Alert/ | backslash-f | https://www.tradingview.com/u/backslash-f/ | 346 | 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/
// Β© backslash-f
//
// This script:
// - Adds a Heikin-Ashi line to the chart (EMA-based).
// - Provides alerts triggered when the color goes from green to red and vice versa.
//@version=5
indicator("Heikin-Ashi Trend Alert", overlay=true)
// EMA
ema_input = input.int(title="EMA", defval=77, minval=1)
ema_smoothing = input.int(title="EMA Smoothing", defval=21, minval=1)
ema_open = ta.ema(open, ema_input)
ema_close = ta.ema(close, ema_input)
// Developer
shouldShowDebugInfo = input(title="Show debug info", group="DEVELOPER", defval=false, tooltip="Check this box to see the values of the main variables on the chart, below bars. This is for debugging purposes only.")
// Heikin-Ashi
heikinashi = ticker.heikinashi(syminfo.tickerid)
heikinashi_open = request.security(heikinashi, timeframe.period, ema_open)
heikinashi_close = request.security(heikinashi, timeframe.period, ema_close)
heikinashi_open_smooth = ta.ema(heikinashi_open, ema_smoothing)
heikinashi_close_smooth = ta.ema(heikinashi_close, ema_smoothing)
// Trend
var trend = false
var last_trend = trend
trend := heikinashi_close_smooth >= heikinashi_open_smooth
// Color
color = trend ? color.green : color.red
trend_color = color.new(color, 50)
// Alert
varip alert_count = 0
alert_message_prefix = '[' + syminfo.ticker + ', ' + timeframe.period + ']' // e.g. "[BTC, 15]"
alert_message_body = " Heikin-Ashi new color: "
alert_message_sufix = trend ? "π’" : "π΄"
alert_message = alert_message_prefix + alert_message_body + alert_message_sufix
if (trend != last_trend)
alert_count := alert_count + 1
last_trend := trend
alert(alert_message, alert.freq_once_per_bar)
// Debugging label creation
var debuggingLabel = label.new(na, na, color=color.new(color.blue, transp=100), textcolor=color.white, textalign=text.align_right, style=label.style_label_up, yloc=yloc.belowbar)
if shouldShowDebugInfo
current_color_string = "Current color: " + alert_message_sufix
last_color_string = "Last color: " + (last_trend ? "π’" : "π΄")
alert_count_string = "Triggered alerts: " + str.tostring(alert_count)
label.set_text(debuggingLabel, current_color_string + '\n' + last_color_string + '\n' + alert_count_string)
label.set_color(debuggingLabel, color=color.new(color.blue, transp=0))
label.set_x(debuggingLabel, last_bar_index)
label.set_y(debuggingLabel, close)
// Lines
open_line = plot(heikinashi_open_smooth, color=trend_color, title="Open Line")
close_line = plot(heikinashi_close_smooth, color=trend_color, title="Close Line")
fill(open_line, close_line, color=trend_color, title="Heikin-Ashi Line") |
Reflex | https://www.tradingview.com/script/OUzYx82W-Reflex/ | jacobfabris | https://www.tradingview.com/u/jacobfabris/ | 23 | 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/
// Β© jacobfabris
//@version=4
study("Reflex_version2",overlay=true)
pico = highest(high, 4990)
piso = 0.00001
cuelum = 1.618*pico
range_total = cuelum - piso
l1 = range_total*0.786+piso
l2 = range_total*0.618+piso
lm = range_total*0.5+piso
l3 = range_total*0.386+piso
l4 = range_total*0.214+piso
range_topo = cuelum-l1
l11 = range_topo*0.786+l1
l12 = range_topo*0.618+l1
l1m = range_topo*0.5+l1
l13 = range_topo*0.386+l1
l14 = range_topo*0.214+l1
range_meioss = l1-l2
l21 = range_meioss*0.786+l2
l22 = range_meioss*0.618+l2
l2m = range_meioss*0.5+l2
l23 = range_meioss*0.386+l2
l24 = range_meioss*0.214+l2
range_meios = l2-lm
l31 = range_meios*0.786+lm
l32 = range_meios*0.618+lm
l3m = range_meios*0.5+lm
l33 = range_meios*0.386+lm
l34 = range_meios*0.214+lm
range_meioi = lm-l3
l41 = range_meioi*0.786+l3
l42 = range_meioi*0.618+l3
l4m = range_meioi*0.5+l3
l43 = range_meioi*0.386+l3
l44 = range_meioi*0.214+l3
range_meioii = l3-l4
l51 = range_meioii*0.786+l4
l52 = range_meioii*0.618+l4
l5m = range_meioii*0.5+l4
l53 = range_meioii*0.386+l4
l54 = range_meioii*0.214+l4
range_fundo = l4-piso
l61 = range_fundo*0.786+piso
l62 = range_fundo*0.618+piso
l6m = range_fundo*0.5+piso
l63 = range_fundo*0.386+piso
l64 = range_fundo*0.214+piso
plot(cuelum,color=color.white,linewidth=4)
plot(l11)
plot(l12)
plot(l1m)
plot(l13)
plot(l14)
plot(l1,color=color.green,linewidth=3)
plot(l21)
plot(l22)
plot(l2m)
plot(l23)
plot(l24)
plot(l2,color=color.teal,linewidth=3)
plot(l31)
plot(l32)
plot(l3m)
plot(l33)
plot(l34)
plot(lm,color=color.silver,linewidth=3)
plot(l41)
plot(l42)
plot(l4m)
plot(l43)
plot(l44)
plot(l3,color=color.orange,linewidth=3)
plot(l51)
plot(l52)
plot(l5m)
plot(l53)
plot(l54)
plot(l4,color=color.red,linewidth=3)
plot(l61)
plot(l62)
plot(l6m)
plot(l63)
plot(l64)
plot(piso,color=color.gray,linewidth=4)
|
OGT Intrinsic Value Indicator | https://www.tradingview.com/script/OdFyyIBv-OGT-Intrinsic-Value-Indicator/ | oneglancetrader | https://www.tradingview.com/u/oneglancetrader/ | 120 | 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/
// Β© trademate2000
//@version=5
indicator("OGT Intrinsic Value Indicator",overlay = true)
// datestring = input.time(defval = timestamp("1 Jan 2022 00:00 +0000"), title = "Start Year", group = "Date")
// startdate = input(defval = timestamp("20 Feb 2020 00:00 +0300"), type = input.time, title = "Start Date", group = "Delivery settings")
// enddate = input(defval = timestamp("20 Oct 2021 00:00 +0300"), type = input.time, title = "End Date", group = "Delivery settings")
// inDateRange = (time >= startdate) and (time <= enddate)
lowlinecol = input.color(defval=color.red, title = "LOW Assumption Color",group = "Lines Color")
medlinecol = input.color(defval=color.blue, title = "MEDIUM Assumption Color",group = "Lines Color")
highlinecol = input.color(defval=color.orange, title = "HIGH Assumption Color",group = "Lines Color")
//Tables
bgcolor1 = input.color(defval=color.new(color.black,60), title = "Table Col 1",group = "Tables")
bgcolor2 = input.color(defval=color.new(color.blue,85), title = "Table Col 2",group = "Tables")
textcol = input.color(defval=color.rgb(255,255,255), title = "Table Text Col",group = "Tables")
textsize1 = size.normal
//EPS TTM
EPS = math.round(request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE", "TTM"),2)
// EPS = 6.08
// EarningsYield = (EPS / close) * 100
plot(close, color = color.new(color.blue,100))
// if barstate.islast
// label.new(bar_index, high,text = str.tostring(EPS))
//eps growth
epsgrowthlow = input.float(defval = 15.0,step = 0.0001, minval = 0.0, title="Low", group = "EPS Annual Growth Rate For Next 5 Years")/100
epsgrowthmed = input.float(defval = 20.0,step = 0.0001, minval = 0.0, title="Med", group = "EPS Annual Growth Rate For Next 5 Years")/100
epsgrowthhigh = input.float(defval = 25.0,step = 0.0001, minval = 0.0, title="high", group = "EPS Annual Growth Rate For Next 5 Years")/100
epslow2 = math.round(EPS*(1+epsgrowthlow),2)
epslow3 = math.round(epslow2*(1+epsgrowthlow),2)
epslow4 = math.round(epslow3*(1+epsgrowthlow),2)
epslow5 = math.round(epslow4*(1+epsgrowthlow),2)
epsmed2 = math.round(EPS*(1+epsgrowthmed),2)
epsmed3 = math.round(epsmed2*(1+epsgrowthmed),2)
epsmed4 = math.round(epsmed3*(1+epsgrowthmed),2)
epsmed5 = math.round(epsmed4*(1+epsgrowthmed),2)
epshigh2 = math.round(EPS*(1+epsgrowthhigh),2)
epshigh3 = math.round(epshigh2*(1+epsgrowthhigh),2)
epshigh4 = math.round(epshigh3*(1+epsgrowthhigh),2)
epshigh5 = math.round(epshigh4*(1+epsgrowthhigh),2)
//your annual return
annualreturnlow = input.float(defval = 12.5,step = 0.0001, minval = 0.0, title="Low", group = "Your Annual Return")/100
annualreturnmed = input.float(defval = 12.5,step = 0.0001, minval = 0.0, title="Med", group = "Your Annual Return")/100
annualreturnhigh = input.float(defval = 12.5,step = 0.0001, minval = 0.0, title="high", group = "Your Annual Return")/100
//PE ratio in 5 years
peratiolow = input.float(defval = 10.0,step = 0.0001, minval = 0.0, title="Low", group = "PE Ratio In Year 5")
peratiomed = input.float(defval = 13.0,step = 0.0001, minval = 0.0, title="Med", group = "PE Ratio In Year 5")
peratiohigh = input.float(defval = 15.0,step = 0.0001, minval = 0.0, title="high", group = "PE Ratio In Year 5")
ivlow5 = math.round(epslow5*peratiolow,2)
ivmed5 = math.round(epsmed5*peratiomed,2)
ivhigh5 = math.round(epshigh5*peratiohigh,2)
ivlow4 = math.round(ivlow5/(1+annualreturnlow),2)
ivmed4 = math.round(ivmed5/(1+annualreturnmed),2)
ivhigh4 = math.round(ivhigh5/(1+annualreturnhigh),2)
ivlow3 = math.round(ivlow4/(1+annualreturnlow),2)
ivmed3 = math.round(ivmed4/(1+annualreturnmed),2)
ivhigh3 = math.round(ivhigh4/(1+annualreturnhigh),2)
ivlow2 = math.round(ivlow3/(1+annualreturnlow),2)
ivmed2 = math.round(ivmed3/(1+annualreturnmed),2)
ivhigh2 = math.round(ivhigh3/(1+annualreturnhigh),2)
ivlow1 = math.round(ivlow2/(1+annualreturnlow),2)
ivmed1 = math.round(ivmed2/(1+annualreturnmed),2)
ivhigh1 = math.round(ivhigh2/(1+annualreturnhigh),2)
alertcondition(ta.cross(close,ivlow1) or ta.cross(close,ivmed1) or ta.cross(close,ivhigh1),"1. Intrinsic Value Cross","Intrinsic Value has been crossed!")
////////////////////////////////Lines
// currentbar = bar_index
transpcol = color.new(color.white,100)
var line linelow1 = na
var line linelow2 = na
var line linelow3 = na
var line linelow4 = na
var line linelow5 = na
var line linelow6 = na
var line linelow7 = na
var line linelow8 = na
var line linelow9 = na
var label lowlabel1 = na
var label lowlabel2 = na
var label lowlabel3 = na
var label lowlabel4 = na
var label lowlabel5 = na
line.delete(linelow1)
line.delete(linelow2)
line.delete(linelow3)
line.delete(linelow4)
line.delete(linelow5)
line.delete(linelow6)
line.delete(linelow7)
line.delete(linelow8)
line.delete(linelow9)
label.delete(lowlabel1)
label.delete(lowlabel2)
label.delete(lowlabel3)
label.delete(lowlabel4)
label.delete(lowlabel5)
// datestring = "1 Jan " + str.tostring(year) + " 00:00 +0000"
// startdate = timestamp(year,1,1,1,1,1)
currentbar = timestamp(year,1,1,1,1,1)
year1 = (86400000 * 365)
year2 = year1*2
year3 = year1*3
year4 = year1*4
year5 = year1*5
linelow1 := line.new(currentbar,ivlow1,currentbar+year1,ivlow1,color = lowlinecol, xloc = xloc.bar_time)
lowlabel1 := label.new(currentbar+year1,ivlow1,text = "LOW ASSUMPTION - Year 1 : " + str.tostring(ivlow1), style = label.style_label_lower_right, textcolor = lowlinecol, color = transpcol, xloc = xloc.bar_time)
linelow2 := line.new(currentbar+year1,ivlow1,currentbar+year1,ivlow2,color = lowlinecol, xloc = xloc.bar_time)
linelow3 := line.new(currentbar+year1,ivlow2,currentbar+year2,ivlow2,color = lowlinecol, xloc = xloc.bar_time)
lowlabel2 := label.new(currentbar+year2,ivlow2,text = "Year 2 : " + str.tostring(ivlow2), style = label.style_label_lower_right, textcolor = lowlinecol, color = transpcol, xloc = xloc.bar_time)
linelow4 := line.new(currentbar+year2,ivlow2,currentbar+year2,ivlow3,color = lowlinecol, xloc = xloc.bar_time)
linelow5 := line.new(currentbar+year2,ivlow3,currentbar+year3,ivlow3,color = lowlinecol, xloc = xloc.bar_time)
lowlabel3 := label.new(currentbar+year3,ivlow3,text = "Year 3 : " + str.tostring(ivlow3), style = label.style_label_lower_right, textcolor = lowlinecol, color = transpcol, xloc = xloc.bar_time)
linelow6 := line.new(currentbar+year3,ivlow3,currentbar+year3,ivlow4,color = lowlinecol, xloc = xloc.bar_time)
linelow7 := line.new(currentbar+year3,ivlow4,currentbar+year4,ivlow4,color = lowlinecol, xloc = xloc.bar_time)
lowlabel4 := label.new(currentbar+year4,ivlow4,text = "Year 4 : " + str.tostring(ivlow4), style = label.style_label_lower_right, textcolor = lowlinecol, color = transpcol, xloc = xloc.bar_time)
linelow8 := line.new(currentbar+year4,ivlow4,currentbar+year4,ivlow5,color = lowlinecol, xloc = xloc.bar_time)
linelow9 := line.new(currentbar+year4,ivlow5,currentbar+year5,ivlow5,color = lowlinecol, xloc = xloc.bar_time)
lowlabel5 := label.new(currentbar+year5,ivlow5,text = "Year 5 : " + str.tostring(ivlow5), style = label.style_label_lower_right, textcolor = lowlinecol, color = transpcol, xloc = xloc.bar_time)
//MED Lines
var line linemed1 = na
var line linemed2 = na
var line linemed3 = na
var line linemed4 = na
var line linemed5 = na
var line linemed6 = na
var line linemed7 = na
var line linemed8 = na
var line linemed9 = na
var label medlabel1 = na
var label medlabel2 = na
var label medlabel3 = na
var label medlabel4 = na
var label medlabel5 = na
line.delete(linemed1)
line.delete(linemed2)
line.delete(linemed3)
line.delete(linemed4)
line.delete(linemed5)
line.delete(linemed6)
line.delete(linemed7)
line.delete(linemed8)
line.delete(linemed9)
label.delete(medlabel1)
label.delete(medlabel2)
label.delete(medlabel3)
label.delete(medlabel4)
label.delete(medlabel5)
linemed1 := line.new(currentbar,ivmed1,currentbar+year1,ivmed1,color = medlinecol, xloc = xloc.bar_time)
medlabel1 := label.new(currentbar+year1,ivmed1,text = "MEDIUM ASSUMPTION - Year 1 : " + str.tostring(ivmed1), style = label.style_label_lower_right, textcolor = medlinecol, color = transpcol, xloc = xloc.bar_time)
linemed2 := line.new(currentbar+year1,ivmed1,currentbar+year1,ivmed2,color = medlinecol, xloc = xloc.bar_time)
linemed3 := line.new(currentbar+year1,ivmed2,currentbar+year2,ivmed2,color = medlinecol, xloc = xloc.bar_time)
medlabel2 := label.new(currentbar+year2,ivmed2,text = "Year 2 : " + str.tostring(ivmed2), style = label.style_label_lower_right, textcolor = medlinecol, color = transpcol, xloc = xloc.bar_time)
linemed4 := line.new(currentbar+year2,ivmed2,currentbar+year2,ivmed3,color = medlinecol, xloc = xloc.bar_time)
linemed5 := line.new(currentbar+year2,ivmed3,currentbar+year3,ivmed3,color = medlinecol, xloc = xloc.bar_time)
medlabel3 := label.new(currentbar+year3,ivmed3,text = "Year 3 : " + str.tostring(ivmed3), style = label.style_label_lower_right, textcolor = medlinecol, color = transpcol, xloc = xloc.bar_time)
linemed6 := line.new(currentbar+year3,ivmed3,currentbar+year3,ivmed4,color = medlinecol, xloc = xloc.bar_time)
linemed7 := line.new(currentbar+year3,ivmed4,currentbar+year4,ivmed4,color = medlinecol, xloc = xloc.bar_time)
medlabel4 := label.new(currentbar+year4,ivmed4,text = "Year 4 : " + str.tostring(ivmed4), style = label.style_label_lower_right, textcolor = medlinecol, color = transpcol, xloc = xloc.bar_time)
linemed8 := line.new(currentbar+year4,ivmed4,currentbar+year4,ivmed5,color = medlinecol, xloc = xloc.bar_time)
linemed9 := line.new(currentbar+year4,ivmed5,currentbar+year5,ivmed5,color = medlinecol, xloc = xloc.bar_time)
medlabel5 := label.new(currentbar+year5,ivmed5,text = "Year 5 : " + str.tostring(ivmed5), style = label.style_label_lower_right, textcolor = medlinecol, color = transpcol, xloc = xloc.bar_time)
//HIGH Lines
var line linehigh1 = na
var line linehigh2 = na
var line linehigh3 = na
var line linehigh4 = na
var line linehigh5 = na
var line linehigh6 = na
var line linehigh7 = na
var line linehigh8 = na
var line linehigh9 = na
var label highlabel1 = na
var label highlabel2 = na
var label highlabel3 = na
var label highlabel4 = na
var label highlabel5 = na
line.delete(linehigh1)
line.delete(linehigh2)
line.delete(linehigh3)
line.delete(linehigh4)
line.delete(linehigh5)
line.delete(linehigh6)
line.delete(linehigh7)
line.delete(linehigh8)
line.delete(linehigh9)
label.delete(highlabel1)
label.delete(highlabel2)
label.delete(highlabel3)
label.delete(highlabel4)
label.delete(highlabel5)
linehigh1 := line.new(currentbar,ivhigh1,currentbar+year1,ivhigh1,color = highlinecol, xloc = xloc.bar_time)
highlabel1 := label.new(currentbar+year1,ivhigh1,text = "HIGH ASSUMPTION - Year 1 : " + str.tostring(ivhigh1), style = label.style_label_lower_right, textcolor = highlinecol, color = transpcol, xloc = xloc.bar_time)
linehigh2 := line.new(currentbar+year1,ivhigh1,currentbar+year1,ivhigh2,color = highlinecol, xloc = xloc.bar_time)
linehigh3 := line.new(currentbar+year1,ivhigh2,currentbar+year2,ivhigh2,color = highlinecol, xloc = xloc.bar_time)
highlabel2 := label.new(currentbar+year2,ivhigh2,text = "Year 2 : " + str.tostring(ivhigh2), style = label.style_label_lower_right, textcolor = highlinecol, color = transpcol, xloc = xloc.bar_time)
linehigh4 := line.new(currentbar+year2,ivhigh2,currentbar+year2,ivhigh3,color = highlinecol, xloc = xloc.bar_time)
linehigh5 := line.new(currentbar+year2,ivhigh3,currentbar+year3,ivhigh3,color = highlinecol, xloc = xloc.bar_time)
highlabel3 := label.new(currentbar+year3,ivhigh3,text = "Year 3 : " + str.tostring(ivhigh3), style = label.style_label_lower_right, textcolor = highlinecol, color = transpcol, xloc = xloc.bar_time)
linehigh6 := line.new(currentbar+year3,ivhigh3,currentbar+year3,ivhigh4,color = highlinecol, xloc = xloc.bar_time)
linehigh7 := line.new(currentbar+year3,ivhigh4,currentbar+year4,ivhigh4,color = highlinecol, xloc = xloc.bar_time)
highlabel4 := label.new(currentbar+year4,ivhigh4,text = "Year 4 : " + str.tostring(ivhigh4), style = label.style_label_lower_right, textcolor = highlinecol, color = transpcol, xloc = xloc.bar_time)
linehigh8 := line.new(currentbar+year4,ivhigh4,currentbar+year4,ivhigh5,color = highlinecol, xloc = xloc.bar_time)
linehigh9 := line.new(currentbar+year4,ivhigh5,currentbar+year5,ivhigh5,color = highlinecol, xloc = xloc.bar_time)
highlabel5 := label.new(currentbar+year5,ivhigh5,text = "Year 5 : " + str.tostring(ivhigh5), style = label.style_label_lower_right, textcolor = highlinecol, color = transpcol, xloc = xloc.bar_time)
////////////////TABLES
var financialTable = table.new(position = position.top_right, columns = 10, rows = 18, border_width = 1, border_color = color.aqua, frame_color = color.aqua, frame_width = 1)
var financialTable1 = table.new(position = position.top_center, columns = 10, rows = 18, border_width = 1, border_color = color.aqua, frame_color = color.aqua, frame_width = 1)
// plot(close)
// bgcolor1 = color.new(color.black,60)
// bgcolor2 = color.new(color.blue,85)
// textcol = color.rgb(255,255,255)
// textsize1 = size.large
//headinng
table.cell(table_id = financialTable1, column = 1, row = 1, text = "EPS : " + str.tostring(EPS), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// column 1
table.cell(table_id = financialTable, column = 1, row = 1, text = "Low Assumption", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 2, text = "EPS Growth Per Year (" + str.tostring(epsgrowthlow*100) + " %)", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 3, text = "Intrinsic Value", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 4, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 5, text = "Medium Assumption", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 6, text = "EPS Growth Per Year (" + str.tostring(epsgrowthmed*100) + " %)", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 7, text = "Intrinsic Value", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 8, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 9, text = "High Assumption", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 10, text = "EPS Growth Per Year (" + str.tostring(epsgrowthhigh*100) + " %)", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 1, row = 11, text = "Intrinsic Value", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// column 2
table.cell(table_id = financialTable, column = 2, row = 1, text = "Year 1", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 2, text = str.tostring(EPS), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 3, text = str.tostring(ivlow1), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 4, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 5, text = "Year 1", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 6, text = str.tostring(EPS), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 7, text = str.tostring(ivmed1), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 8, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 9, text = "Year 1", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 10, text = str.tostring(EPS), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 2, row = 11, text = str.tostring(ivhigh1), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// column 3
table.cell(table_id = financialTable, column = 3, row = 1, text = "Year 2", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 2, text = str.tostring(epslow2), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 3, text = str.tostring(ivlow2), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 4, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 5, text = "Year 2", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 6, text = str.tostring(epsmed2), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 7, text = str.tostring(ivmed2), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 8, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 9, text = "Year 2", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 10, text = str.tostring(epshigh2), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 3, row = 11, text = str.tostring(ivhigh2), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// column 4
table.cell(table_id = financialTable, column = 4, row = 1, text = "Year 3", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 2, text = str.tostring(epslow3), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 3, text = str.tostring(ivlow3), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 4, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 5, text = "Year 3", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 6, text = str.tostring(epsmed3), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 7, text = str.tostring(ivmed3), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 8, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 9, text = "Year 3", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 10, text = str.tostring(epshigh3), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 4, row = 11, text = str.tostring(ivhigh3), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// column 5
table.cell(table_id = financialTable, column = 5, row = 1, text = "Year 4", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 2, text = str.tostring(epslow4), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 3, text = str.tostring(ivlow4), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 4, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 5, text = "Year 4", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 6, text = str.tostring(epsmed4), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 7, text = str.tostring(ivmed4), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 8, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 9, text = "Year 4", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 10, text = str.tostring(epshigh4), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 5, row = 11, text = str.tostring(ivlow4), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// column 6
table.cell(table_id = financialTable, column = 6, row = 1, text = "Year 5", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 2, text = str.tostring(epslow5), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 3, text = str.tostring(ivlow5), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 4, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 5, text = "Year 5", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 6, text = str.tostring(epsmed5), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 7, text = str.tostring(ivmed5), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 8, text = " ", bgcolor=bgcolor2, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 9, text = "Year 5", bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 10, text = str.tostring(epshigh5), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
table.cell(table_id = financialTable, column = 6, row = 11, text = str.tostring(ivhigh5), bgcolor=bgcolor1, text_color=textcol, text_size = textsize1)
// alertcondition(ta.cross(close,ivlow1),"")
|
[Mad] Triple Bollinger Bands MTF | https://www.tradingview.com/script/JBllIVSl-Mad-Triple-Bollinger-Bands-MTF/ | djmad | https://www.tradingview.com/u/djmad/ | 192 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© djmad
// Changelog (by Johnney): Decimals autoadjust when changing Assets.
// Optimized rounding Algo.
// Trailing Zeroes fixed.
// Changelog (by djmad): Added Bollinger width average , codeparts from Β©The_Caretaker in the width calc
//@version=5
indicator(shorttitle='[Mad] BBx3 MTF', title='[Mad] Triple Bollinger Bands MTF_3x', overlay=true)
//Variables Inputs Basics{
TimeFrame = input.timeframe('', title='TimeFrame',group='Data-source')
string ma_type = input.string( 'SMA', 'Basis Type', options=[ 'SMA', 'EMA', 'WMA', 'RMA', 'HMA', 'VWMA' ], group = 'Multiplicators')
int length = input.int(20, minval=1,group='Multiplicators')
float mult1 = input.float(1.0, minval=0.001, maxval=10, step=0.2,group='Multiplicators')
float mult2 = input.float(2.0, minval=0.001, maxval=10, step=0.2,group='Multiplicators')
float mult3 = input.float(3.0, minval=0.001, maxval=10, step=0.2,group='Multiplicators')
string mode = input.string('Band-crossin',title='Alert mode', options=['Band-outside', 'Band-crossin', 'Band-crossout', 'Trend'],group='Alerts')
bool showalerts_L1 = input.bool(true, 'Show alerts L1',group='Alerts', inline='1a')
bool showalerts_L2 = input.bool(true, 'Show L2',group='Alerts', inline='1a')
bool showalerts_L3 = input.bool(true, 'Show L3',group='Alerts', inline='1a')
color basecolor = input.color(color.gray, 'Base Color',inline='11',group='static colors')
color multi1color = input.color(color.green, 'Multiplicator 1 Color',group='static colors')
color multi2color = input.color(color.orange, 'Multiplicator 2 Color',group='static colors')
color multi3color = input.color(color.red, 'Multiplicator 3 Color',group='static colors')
bool bgactive = input.bool(true,'Draw background',group='static colors', inline='2a')
color bgcolor = input.color(color.gray, 'Background color',group='static colors')
dynamic_color = input.bool(false,'Dynamic Colors', group='Dynamic colors')
dynamic_color_bull = input.color(color.green,'Color bull', group='Dynamic colors', inline='1a')
dynamic_bear = input.color(color.red,'Color bear', group='Dynamic colors', inline='1b')
dynamic_neut = input.color(color.new(#daff52, 80),'Color neut', group='Dynamic colors', inline='1a')
int trans = input.int(90,'Transparency background',group='global colors', inline='2a')
// Input definitions
bool tableactive = input.bool(false,'Draw table', group='Bollinger width table')
int lookbacktime = input.int( 500, 'Lookback time',minval=1, group='Bollinger width table')
string Position = input.string(title='Position', defval=position.bottom_right, 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='Bollinger width table',inline='2')
string Size = input.string(title='Size', defval=size.auto, options=[size.tiny, size.small, size.normal, size.large, size.huge, size.auto], group='Bollinger width table',inline='2')
color bg_color = input.color(title='Background', defval=color.white, group='Bollinger width table')
color text_color = input.color(title='Text', defval=color.black, group='Bollinger width table')
var i_decimals_array = array.from('#', '0.0', '0.00', '0.000', '0.0000', '0.00000', '0.000000', '0.0000000', '0.00000000 ')
i_decimals_s = input.string('Asset',title='Decimals', options=['Asset', '0 ', '0.1', '0.01', '0.001', '0.0001', '0.00001', '0.000001', '0.0000001'],group='labels and lines')
labelcolor = input.color(color.white,'label-color', group='labels and lines')
show_pricelines = input(true,title='show lines', group='labels and lines', inline='1a')
lineshift = input(0,title='- shift lines', group='labels and lines', inline='1a')
show_labels = input(true,title='show labels', group='labels and lines', inline='2a')
displayshift = input(35,title='- shift labels ', group='labels and lines', inline='2a')
//}
// Variables {
var int i_decimals = 2
bollarray = array.from(0.0,0.0,0.0,0.0,0.0,0.0,0.0)
if not bgactive
trans := 100
var float bbu3 = na
var float bbu2 = na
var float bbu1 = na
var float bbm_ = na
var float bbd1 = na
var float bbd2 = na
var float bbd3 = na
//}
//functions{
//orig roundTo(_value) => str.tostring(math.round(_value * math.pow(10, i_decimals)) / math.pow(10, i_decimals))
//new1 roundTo(_value) => str.tostring(math.round(_value * math.pow(10, i_decimals)) / math.pow(10, i_decimals), '0.000')
//new2 roundTo(_value) => str.tostring(math.round(_value, i_decimals),'#.0000')
roundTo(_value) => str.tostring(_value, array.get(i_decimals_array,i_decimals)) // + ' Debug : ' + 'i_decimals = ' + str.tostring(i_decimals) + ' Original value = ' + str.tostring(_value)
shifting(_value) =>
var string output = ''
output := ''
for i = 0 to _value by 1
output := output + ' '
f_name_2_price(value_of_indicator) =>
value_of_indicator == bbu3 ? + shifting(displayshift) + ' +3 - ' + str.tostring(roundTo(bbu3)) :
value_of_indicator == bbu2 ? + shifting(displayshift) + ' +2 - ' + str.tostring(roundTo(bbu2)) :
value_of_indicator == bbu1 ? + shifting(displayshift) + ' +1 - ' + str.tostring(roundTo(bbu1)) :
value_of_indicator == bbm_ ? + shifting(displayshift) + 'BB0 - ' + str.tostring(roundTo(bbm_)) :
value_of_indicator == bbd1 ? + shifting(displayshift) + ' -1 - ' + str.tostring(roundTo(bbd1)) :
value_of_indicator == bbd2 ? + shifting(displayshift) + ' -2 - ' + str.tostring(roundTo(bbd2)) :
value_of_indicator == bbd3 ? + shifting(displayshift) + ' -3 - ' + str.tostring(roundTo(bbd3)) :
na
f_delete_all() =>
a_allLines = line.all
if array.size(a_allLines) > 0
for i = 0 to array.size(a_allLines) - 1
line.delete(array.get(a_allLines, i))
a_allLabel = label.all
if array.size(a_allLabel) > 0
for i = 0 to array.size(a_allLabel) - 1
label.delete(array.get(a_allLabel, i))
f_draw(value_of_indicator, offset, c_rs) =>
T1 = bar_index[1] + lineshift
T2 = bar_index + lineshift
M1 = xloc.bar_index
if barstate.islast or barstate.isrealtime
var label lb1 = na
var line ln1 = na
if show_labels
lb1 := label.new(time + (time - time[1]) * 1,
value_of_indicator,
f_name_2_price(value_of_indicator), xloc=xloc.bar_time, textcolor=c_rs , style=label.style_none, size=size.small)
if show_pricelines
ln1 := line.new(T1, value_of_indicator, T2,
value_of_indicator,
width=1, extend=extend.right, xloc=M1, color=color.gray)
f_calc_ma(_src, _len, _type) =>
_ma = float(na)
if _type == 'SMA'
_ma := ta.sma(_src, _len)
else if _type == 'EMA'
_ma := ta.ema(_src, _len)
else if _type == 'WMA'
_ma := ta.wma(_src, _len)
else if _type == 'RMA'
_ma := ta.rma(_src, _len)
else if _type == 'HMA'
_ma := ta.hma(_src, _len)
else
_ma := ta.vwma(_src, _len)
_ma
f_boll(_src, _ma, _length, mult1, mult2, mult3) =>
basis = _ma
dev = ta.stdev(_src, _length)
transferarray = array.from(
basis + dev * mult3,
basis + dev * mult2,
basis + dev * mult1,
basis,
basis - dev * mult1,
basis - dev * mult2,
basis - dev * mult3
)
transferarray
// original from Β©The_Caretaker, little modded
f_bbwp(_src, _BB_length, _lookbacktime, _type) =>
_basis = f_calc_ma(_src, _BB_length, _type)
_dev = ta.stdev(_src, _BB_length)
_BB_width = 2 * _dev / _basis
_BB_summarized = 0.0
_len = math.min(bar_index, _lookbacktime)
for _i = 1 to _len by 1
_BB_summarized := _BB_summarized + (_BB_width[_i] > _BB_width ? 0 : 1)
_return = bar_index >= _BB_length ? (_BB_summarized / _len) * 100 : na
_return
//}
//Init Vars (we only need it once at start)
if barstate.isfirst
i_decimals := str.length(str.tostring( (i_decimals_s == 'Asset') ? str.tostring (syminfo.mintick) : i_decimals_s)) -2
//Plotting Bollinger {
bollarray := request.security(syminfo.tickerid, TimeFrame, f_boll(close, f_calc_ma(close, length, ma_type ) ,length, mult1, mult2, mult3), barmerge.gaps_off, barmerge.lookahead_off)
if na(bollarray)
bollarray := array.from(na,na,na,na,na,na,na)
color coloroff = color.new(#000000, 100)
colorbull = dynamic_color_bull
colorbaer = dynamic_bear
colorneut = dynamic_neut
f_color(float upper_2,float upper_1, float current, float lower_1,float lower_2, float src, float index) =>
color mycolor = na
color coloron = na
if src < (upper_1+current)/2 and src > (lower_1+current)/2
coloron := colorneut
else if src < index
coloron := colorbaer
else if src > index
coloron := colorbull
if src > current and src < upper_2
mycolor := color.from_gradient(src, (current+upper_1)/2, upper_2 , coloron, coloroff)
else if src < current and src > lower_2
mycolor := color.from_gradient(src, lower_2, (current+lower_1)/2 , coloroff, coloron)
else
mycolor := coloroff
mycolor
bbu3 := array.get(bollarray,0)
bbu2 := array.get(bollarray,1)
bbu1 := array.get(bollarray,2)
bbm_ := array.get(bollarray,3)
bbd1 := array.get(bollarray,4)
bbd2 := array.get(bollarray,5)
bbd3 := array.get(bollarray,6)
p3a = plot((not dynamic_color or coloroff != (f_color(upper_2 = 99999999, upper_1 = 99999999, current = bbu3, lower_1 = bbu2, lower_2 = bbu1, src = ta.sma(close,3), index = bbm_))) ? bbu3:na,display=display.all, linewidth=2, color=not dynamic_color ? multi3color : f_color(upper_2 = 99999999, upper_1 = 99999999, current = bbu3, lower_1 = bbu2, lower_2 = bbu1, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
p2a = plot((not dynamic_color or coloroff != (f_color(upper_2 = 99999999, upper_1 = bbu3 , current = bbu2, lower_1 = bbu1, lower_2 = bbm_, src = ta.sma(close,3), index = bbm_))) ? bbu2:na,display=display.all, linewidth=2, color=not dynamic_color ? multi2color : f_color(upper_2 = 99999999, upper_1 = bbu3 , current = bbu2, lower_1 = bbu1, lower_2 = bbm_, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
p1a = plot((not dynamic_color or coloroff != (f_color(upper_2 = bbu3, upper_1 = bbu2 , current = bbu1, lower_1 = bbm_, lower_2 = bbd1, src = ta.sma(close,3), index = bbm_))) ? bbu1:na,display=display.all, linewidth=2, color=not dynamic_color ? multi1color : f_color(upper_2 = bbu3, upper_1 = bbu2 , current = bbu1, lower_1 = bbm_, lower_2 = bbd1, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
p00 = plot((not dynamic_color or coloroff != (f_color(upper_2 = bbu2, upper_1 = bbu1 , current = bbm_, lower_1 = bbd1, lower_2 = bbd2, src = ta.sma(close,3), index = bbm_))) ? bbm_:na,title='Middle' , linewidth=2, color=not dynamic_color ? basecolor : f_color(upper_2 = bbu2, upper_1 = bbu1 , current = bbm_, lower_1 = bbd1, lower_2 = bbd2, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
p1b = plot((not dynamic_color or coloroff != (f_color(upper_2 = bbu1, upper_1 = bbm_ , current = bbd1, lower_1 = bbd2, lower_2 = bbd3, src = ta.sma(close,3), index = bbm_))) ? bbd1:na,display=display.all, linewidth=2, color=not dynamic_color ? multi1color : f_color(upper_2 = bbu1, upper_1 = bbm_ , current = bbd1, lower_1 = bbd2, lower_2 = bbd3, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
p2b = plot((not dynamic_color or coloroff != (f_color(upper_2 = bbm_, upper_1 = bbd1 , current = bbd2, lower_1 = bbd3, lower_2 = 00000000, src = ta.sma(close,3), index = bbm_))) ? bbd2:na,display=display.all, linewidth=2, color=not dynamic_color ? multi2color : f_color(upper_2 = bbm_, upper_1 = bbd1 , current = bbd2, lower_1 = bbd3, lower_2 = 00000000, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
p3b = plot((not dynamic_color or coloroff != (f_color(upper_2 = bbd1, upper_1 = bbd2 , current = bbd3, lower_1 = 00000000, lower_2 = 00000000, src = ta.sma(close,3), index = bbm_))) ? bbd3:na,display=display.all, linewidth=2, color=not dynamic_color ? multi3color : f_color(upper_2 = bbd1, upper_1 = bbd2 , current = bbd3, lower_1 = 00000000, lower_2 = 00000000, src = ta.sma(close,3), index = bbm_), style=plot.style_linebr)
fill(p2a, p3a, color=not dynamic_color ? color.new(bgcolor, trans):color.new(f_color(upper_2 = 99999999, upper_1 = 99999999, current = bbu3, lower_1 = bbd2, lower_2 = bbu1, src = ta.sma(close,3), index = bbm_),trans))
fill(p1a, p3a, color=not dynamic_color ? color.new(bgcolor, trans):color.new(f_color(upper_2 = 99999999, upper_1 = bbu3, current = bbd2, lower_1 = bbu1, lower_2 = bbm_, src = ta.sma(close,3), index = bbm_),trans))
fill(p3a, p3b, color=not dynamic_color ? color.new(bgcolor, trans):na)
fill(p1b, p3b, color=not dynamic_color ? color.new(bgcolor, trans):color.new(f_color(upper_2 = bbm_, upper_1 = bbd1, current = bbd2, lower_1 = bbd3, lower_2 = 00000000, src = ta.sma(close,3), index = bbm_),trans))
fill(p2b, p3b, color=not dynamic_color ? color.new(bgcolor, trans):color.new(f_color(upper_2 = bbd1, upper_1 = bbd2, current = bbd3, lower_1 = 00000000, lower_2 = 00000000, src = ta.sma(close,3), index = bbm_),trans))
//}
//Plotting of lines and prices {
f_delete_all()
if array.size(bollarray) > 0
for i1 = 0 to array.size(bollarray) - 1 by 1
f_draw(array.get(bollarray, i1), 7, labelcolor)
//}
//Plotting of table {
bw1 =
request.security(syminfo.tickerid, TimeFrame,
tableactive?f_bbwp(close, length, lookbacktime, ma_type ):na)
// Create table
if tableactive
t = table.new(position=Position, rows=2, columns=1, border_width=1)
table.cell(t, 0, 0, 'BB-W', bgcolor=bg_color, text_color=text_color, text_size = Size)
table.cell(t, 0, 1, str.tostring(bw1, '##.####')+'%', bgcolor=bg_color, text_color=text_color, text_size = Size)
//}
// Creating the Alarms Start {
//************************************************************************************************************
bool a_L1_long = false
bool a_L1_short = false
bool a_L2_long = false
bool a_L2_short = false
bool a_L3_long = false
bool a_L3_short = false
if mode == 'Band-outside'
a_L1_long := bbd1 > close
a_L1_short := bbu1 < close
a_L2_long := bbd2 > close
a_L2_short := bbd2 < close
a_L3_long := bbd3 > close
a_L3_short := bbu3 < close
if mode == 'Band-crossin'
a_L1_long := ta.crossover(close, bbd1)
a_L1_short := ta.crossunder(close, bbu1)
a_L2_long := ta.crossover(close, bbd2)
a_L2_short := ta.crossunder(close, bbd2)
a_L3_long := ta.crossover(close, bbd3)
a_L3_short := ta.crossunder(close, bbu3)
if mode == 'Band-crossout'
a_L1_long := ta.crossunder(close, bbd1)
a_L1_short := ta.crossover(close, bbu1)
a_L2_long := ta.crossunder(close, bbd2)
a_L2_short := ta.crossover(close, bbd2)
a_L3_long := ta.crossunder(close, bbd3)
a_L3_short := ta.crossover(close, bbu3)
if mode == 'Trend'
a_L3_long := bbm_ < close
a_L3_short := bbm_ > close
alertcondition(a_L3_long, 'BBx3 -3 Band Alert', 'BBx3 -3 Band Alert' )
alertcondition(a_L2_long, 'BBx3 -2 Band Alert', 'BBx3 -2 Band Alert' )
alertcondition(a_L1_long, 'BBx3 -1 Band Alert', 'BBx3 -1 Band Alert' )
alertcondition(a_L1_short, 'BBx3 +1 Band Alert', 'BBx3 +1 Band Alert' )
alertcondition(a_L3_short, 'BBx3 +2 Band Alert', 'BBx3 +2 Band Alert' )
alertcondition(a_L3_short, 'BBx3 +3 Band Alert', 'BBx3 +3 Band Alert' )
//}
// Plotting of Alarms {
plotshape(showalerts_L1? a_L1_long: na ,
style=shape.triangleup, location=location.belowbar, color=color.new(#ebff00, 60), size=size.tiny)
plotshape(showalerts_L1? a_L1_short: na ,
style=shape.triangledown, location=location.abovebar, color=color.new(#ebff00, 60), size=size.tiny)
plotshape(showalerts_L2? a_L2_long: na ,
style=shape.triangleup, location=location.belowbar, color=color.new(#00ff20, 30), size=size.small)
plotshape(showalerts_L2? a_L2_short: na ,
style=shape.triangledown, location=location.abovebar, color=color.new(#ff0000, 30), size=size.small)
plotshape(showalerts_L3? a_L3_long: na ,
style=shape.triangleup, location=location.belowbar, color=color.new(#00ff20, 0), size=size.small)
plotshape(showalerts_L3? a_L3_short: na ,
style=shape.triangledown, location=location.abovebar, color=color.new(#ff0000, 0), size=size.small)
//}
// SIGNAL Daisychain {
string inputtype = input.string('NoInput' , title='Signal Type', group='Multibit signal config', options=['MultiBit', 'MultiBit_pass', 'NoInput'], tooltip='Multibit Daisychain with and without infusing\nMutlibit is the Signal-Type used in my Backtestsystem',inline='3a')
float inputModule = input(title='Select L1 Indicator Signal', group='Multibit signal config', defval=close, inline='3a')
Signal_Channel_Line1= input.int(-1, 'L1 long channel', minval=-1, maxval=15,group='Multibit',inline='1a')
Signal_Channel_Line2= input.int(-1, 'L1 short channel', minval=-1, maxval=15,group='Multibit',inline='1a')
Signal_Channel_Line3= input.int(-1, 'L2 long channel', minval=-1, maxval=15,group='Multibit',inline='1b')
Signal_Channel_Line4= input.int(-1, 'L2 short channel', minval=-1, maxval=15,group='Multibit',inline='1b')
Signal_Channel_Line5= input.int(-1, 'L3 long channel', minval=-1, maxval=15,group='Multibit',inline='1c')
Signal_Channel_Line6= input.int(-1, 'L3 short channel', minval=-1, maxval=15,group='Multibit',inline='1c')
//*********** Simplesignal Implementation
signalout = 0
signalout := a_L3_long ? 1 : a_L3_short ? -1 : 0
BM_color_signal = a_L3_long ? #4C9900 : a_L3_short ? #CC0000 : color.black
L_digital_signal = plot(signalout, title='Digitalsignal', color=BM_color_signal, style=plot.style_columns, display=display.none)
//*********** MULTIBIT Implementation
import djmad/Signal_transcoder_library/7 as transcode
bool [] Multibit = array.new<bool>(16,false)
if inputtype == 'MultiBit' or inputtype == 'MultiBit_pass'
Multibit := transcode._16bit_decode(inputModule)
if inputtype != 'MultiBit_pass'
transcode.f_infuse_signal(Signal_Channel_Line1, a_L1_long, Signal_Channel_Line2, a_L1_short, Signal_Channel_Line3, a_L2_long, Signal_Channel_Line4, a_L2_short, Signal_Channel_Line5, a_L3_long, Signal_Channel_Line6, a_L3_short, Multibit)
float plot_output = transcode._16bit_encode(Multibit)
plot(plot_output,title='MultiBit Signal',display=display.none)
//}
|
Niteya Multi Ticker Dollar-Based Pricing Ver 1.3 | https://www.tradingview.com/script/2jDXfmR5/ | Niteya | https://www.tradingview.com/u/Niteya/ | 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/
// Β© Niteya
//@version=5
indicator(title='Niteya Multi Ticker Dollar-Based Pricing Ver 1.3', shorttitle='Niteya MTUSDBP', overlay=true)
cur_exchange = input.string("USDTRY", title="Exchange currency", options=["USDTRY", "USDEUR", "USDGBP", "USDJPY", "USDCNY", "USDAUD"])
ticker1 = input.string("XU100", title="Ticker1", options=["XU100", "AKSA", "ALKIM", "ASELS", "DOAS", "EREGL", "FROTO", "HEKTS", "INDES", "ISCTR", "ISDMR", "KCHOL", "KRDMD", "LOGO", "PARSN", "SAHOL", "SARKY", "SASA", "SISE", "TOASO", "TUPRS", "VESBE"])
ticker2 = input.string("AKSA", "Ticker2")
ticker3 = input.string("ASELS", "Ticker3")
ticker4 = input.string("DOAS", "Ticker4")
ticker5 = input.string("EREGL", "Ticker5")
ticker6 = input.string("FROTO", "Ticker6")
ticker7 = input.string("HEKTS", "Ticker7")
ticker8 = input.string("INDES", "Ticker8")
ticker9 = input.string("ISCTR", "Ticker9")
ticker10 = input.string("ISDMR", "Ticker10")
ticker11 = input.string("KCHOL", "Ticker11")
ticker12 = input.string("KRDMD", "Ticker12")
ticker13 = input.string("LOGO", "Ticker13")
ticker14 = input.string("PARSN", "Ticker14")
ticker15 = input.string("SAHOL", "Ticker15")
ticker16 = input.string("SARKY", "Ticker16")
ticker17 = input.string("TOASO", "Ticker17")
ticker18 = input.string("TUPRS", "Ticker18")
ticker19 = input.string("VESBE", "Ticker19")
bar_number = last_bar_index+1
[close_ticker_cur1, close_ticker_high_cur1] = request.security(ticker1, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd1, close_ticker_high_usd1] = request.security(ticker1, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur2, close_ticker_high_cur2] = request.security(ticker2, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd2, close_ticker_high_usd2] = request.security(ticker2, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur3, close_ticker_high_cur3] = request.security(ticker3, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd3, close_ticker_high_usd3] = request.security(ticker3, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur4, close_ticker_high_cur4] = request.security(ticker4, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd4, close_ticker_high_usd4] = request.security(ticker4, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur5, close_ticker_high_cur5] = request.security(ticker5, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd5, close_ticker_high_usd5] = request.security(ticker5, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur6, close_ticker_high_cur6] = request.security(ticker6, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd6, close_ticker_high_usd6] = request.security(ticker6, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur7, close_ticker_high_cur7] = request.security(ticker7, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd7, close_ticker_high_usd7] = request.security(ticker7, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur8, close_ticker_high_cur8] = request.security(ticker8, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd8, close_ticker_high_usd8] = request.security(ticker8, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur9, close_ticker_high_cur9] = request.security(ticker9, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd9, close_ticker_high_usd9] = request.security(ticker9, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur10, close_ticker_high_cur10] = request.security(ticker10, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd10, close_ticker_high_usd10] = request.security(ticker10, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur11, close_ticker_high_cur11] = request.security(ticker11, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd11, close_ticker_high_usd11] = request.security(ticker11, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur12, close_ticker_high_cur12] = request.security(ticker12, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd12, close_ticker_high_usd12] = request.security(ticker12, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur13, close_ticker_high_cur13] = request.security(ticker13, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd13, close_ticker_high_usd13] = request.security(ticker13, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur14, close_ticker_high_cur14] = request.security(ticker14, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd14, close_ticker_high_usd14] = request.security(ticker14, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur15, close_ticker_high_cur15] = request.security(ticker15, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd15, close_ticker_high_usd15] = request.security(ticker15, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur16, close_ticker_high_cur16] = request.security(ticker16, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd16, close_ticker_high_usd16] = request.security(ticker16, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur17, close_ticker_high_cur17] = request.security(ticker17, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd17, close_ticker_high_usd17] = request.security(ticker17, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur18, close_ticker_high_cur18] = request.security(ticker18, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd18, close_ticker_high_usd18] = request.security(ticker18, "D", [close, ta.highest(close, bar_number)], currency="USD")
[close_ticker_cur19, close_ticker_high_cur19] = request.security(ticker19, "D", [close, ta.highest(close, bar_number)], currency=syminfo.currency)
[close_ticker_usd19, close_ticker_high_usd19] = request.security(ticker19, "D", [close, ta.highest(close, bar_number)], currency="USD")
usd_cur = request.security(cur_exchange, "D", close) // Dollar exchange rate
if barstate.islast
if (str.substring(cur_exchange, 3)==syminfo.currency)
var table price_table = table.new(position.bottom_left, columns=6, rows=20, bgcolor=color.new(#E0E0E0, 40), border_width=1, border_color=color.white)
row = 0
string header1 = '', header2 = '', header3 = '', header4 = '', header5 = '', header6 = ''
if (cur_exchange=="USDTRY")
header1 := 'Hisse'
header2 := 'GeΓ§miΕ en yΓΌksek fiyat (TL)'
header3 := 'GeΓ§miΕ en yΓΌksek fiyat (USD)'
header4 := 'KapanΔ±Ε fiyatΔ±'
header5 := 'Tahmini fiyat (USD dayalΔ± TL)'
header6 := 'ArtΔ±Ε oranΔ± (%)'
else
header1 := 'Ticker'
header2 := 'Highest price ever (' + str.substring(cur_exchange, 3) + ')'
header3 := 'Highest price ever (USD)'
header4 := 'Close price'
header5 := 'Estimated price (based on USD)'
header6 := 'Increase rate (%)'
table.cell(price_table, 0, row, header1, text_color=color.new(#3C3C3C, 0), bgcolor=color.new(#C8C8C8, 40))
table.cell(price_table, 1, row, header2, text_color=color.new(#3C3C3C, 0), bgcolor=color.new(#C8C8C8, 40))
table.cell(price_table, 2, row, header3, text_color=color.new(#3C3C3C, 0), bgcolor=color.new(#C8C8C8, 40))
table.cell(price_table, 3, row, header4, text_color=color.new(#3C3C3C, 0), bgcolor=color.new(#C8C8C8, 40))
table.cell(price_table, 4, row, header5, text_color=color.new(#3C3C3C, 0), bgcolor=color.new(#C8C8C8, 40))
table.cell(price_table, 5, row, header6, text_color=color.new(#3C3C3C, 0), bgcolor=color.new(#C8C8C8, 40))
row += 1
table.cell(price_table, 0, row, ticker1, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur1, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd1, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur1, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd1 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd1*usd_cur)/close_ticker_cur1)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker2, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur2, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd2, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur2, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd2 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd2*usd_cur)/close_ticker_cur2)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker3, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur3, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd3, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur3, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd3 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd3*usd_cur)/close_ticker_cur3)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker4, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur4, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd4, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur4, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd4 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd4*usd_cur)/close_ticker_cur4)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker5, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur5, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd5, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur5, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd5 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd5*usd_cur)/close_ticker_cur5)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker6, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur6, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd6, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur6, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd6 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd6*usd_cur)/close_ticker_cur6)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker7, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur7, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd7, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur7, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd7 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd7*usd_cur)/close_ticker_cur7)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker8, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur8, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd8, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur8, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd8 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd8*usd_cur)/close_ticker_cur8)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker9, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur9, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd9, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur9, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd9 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd9*usd_cur)/close_ticker_cur9)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker10, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur10, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd10, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur10, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd10 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd10*usd_cur)/close_ticker_cur10)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker11, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur11, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd11, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur11, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd11 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd11*usd_cur)/close_ticker_cur11)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker12, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur12, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd12, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur12, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd12 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd12*usd_cur)/close_ticker_cur12)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker13, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur13, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd13, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur13, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd13 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd13*usd_cur)/close_ticker_cur13)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker14, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur14, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd14, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur14, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd14 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd14*usd_cur)/close_ticker_cur14)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker15, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur15, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd15, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur15, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd15 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd15*usd_cur)/close_ticker_cur15)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker16, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur16, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd16, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur16, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd16 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd16*usd_cur)/close_ticker_cur16)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker17, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur17, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd17, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur17, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd17 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd17*usd_cur)/close_ticker_cur17)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker18, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur18, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd18, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur18, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd18 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd18*usd_cur)/close_ticker_cur18)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
row += 1
table.cell(price_table, 0, row, ticker19, text_color=color.blue, text_halign=text.align_left)
table.cell(price_table, 1, row, str.tostring(close_ticker_high_cur19, "#.###"), text_color=color.black, text_halign=text.align_left)
table.cell(price_table, 2, row, str.tostring(close_ticker_high_usd19, "#.###"), text_color=color.green, text_halign=text.align_left)
table.cell(price_table, 3, row, str.tostring(close_ticker_cur19, "#.###"), text_color=color.fuchsia, text_halign=text.align_left)
table.cell(price_table, 4, row, str.tostring(close_ticker_high_usd19 * usd_cur, "#.###"), text_color=color.orange, text_halign=text.align_left)
table.cell(price_table, 5, row, str.tostring(((100*close_ticker_high_usd19*usd_cur)/close_ticker_cur19)-100, "#.###"), text_color=color.orange, text_halign=text.align_left)
else
string msg = ''
if (cur_exchange=="USDTRY")
msg := 'GrafiΔin para birimi dolar Γ§evrim kuru ile uyumlu deΔil!'
else
msg := 'The currency of the chart is not compatible with the dollar conversion currency!'
label.new(bar_index-100, low, text=msg, yloc=yloc.belowbar, color=color.red, style=label.style_label_up, textcolor=color.white, textalign=text.align_left) |
Stochastic RSI Heatmap | https://www.tradingview.com/script/BgYJcXPl-Stochastic-RSI-Heatmap/ | vranabanana | https://www.tradingview.com/u/vranabanana/ | 38 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© vranabanana
//@version=5
//---------------Stochastic RSI Heatmap-----------------
indicator(title="Stochastic RSI Heatmap", overlay=true, shorttitle="Stoch RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=false)
// Stochastic RSI settings
var string GRP1 = 'ββββββββββ ββSettingsββ ββββββββββ'
smoothK = input.int(3, "K", minval=1, group=GRP1)
smoothD = input.int(3, "D", minval=1, group=GRP1)
lengthRSI = input.int(14, "RSI Length", minval=1, group=GRP1)
lengthStoch = input.int(14, "Stochastic Length", minval=1, group=GRP1)
src = input(close, title="RSI Source")
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)
// BUY ZONE levels
var string GRP2 = 'ββββββββββ ββBUY ZONEββ ββββββββββ'
BuyStoRSI1 = input.int (defval = 20, title="Oversold Zone 1", minval=1, maxval=100, group=GRP2)
BuyStoRSI2 = input.int (defval = 15, title="Oversold Zone 2", minval=1, maxval=100, group=GRP2)
BuyStoRSI3 = input.int (defval = 10, title="Oversold Zone 3", minval=1, maxval=100, group=GRP2)
BuyStoRSI4 = input.int (defval = 5, title="Oversold Zone 4", minval=1, maxval=100, group=GRP2)
// SELL ZONE levels
var string GRP3 = 'ββββββββββ ββSELL ZONEββ ββββββββββ'
SellStoRSI1 = input.int (defval = 80, title="Overbought Zone 1", minval=1, maxval=100, group=GRP3)
SellStoRSI2 = input.int (defval = 85, title="Overbought Zone 2", minval=1, maxval=100, group=GRP3)
SellStoRSI3 = input.int (defval = 90, title="Overbought Zone 3", minval=1, maxval=100, group=GRP3)
SellStoRSI4 = input.int (defval = 95, title="Overbought Zone 4", minval=1, maxval=100, group=GRP3)
// Calculations
BUY1 = k < BuyStoRSI1 and d < BuyStoRSI1
BUY2 = k < BuyStoRSI2 and d < BuyStoRSI2
BUY3 = k < BuyStoRSI3 and d < BuyStoRSI3
BUY4 = k < BuyStoRSI4 and d < BuyStoRSI4
SELL1 = k > SellStoRSI1 and d > SellStoRSI1
SELL2 = k > SellStoRSI2 and d > SellStoRSI2
SELL3 = k > SellStoRSI3 and d > SellStoRSI3
SELL4 = k > SellStoRSI4 and d > SellStoRSI4
// Colors
bgcolor (BUY1 ? color.new(color.blue,65) : na, title= "Background StoRSI Oversold Zone 1")
bgcolor (BUY2 ? color.new(color.blue,65) : na, title= "Background StoRSI Oversold Zone 2")
bgcolor (BUY3 ? color.new(color.blue,55) : na, title= "Background StoRSI Oversold Zone 3")
bgcolor (BUY4 ? color.new(color.blue,1) : na, title= "Background StoRSI Oversold Zone 4")
bgcolor (SELL1 ? color.new(color.fuchsia,75) : na, title= "Background StoRSI Overbought Zone 1")
bgcolor (SELL2 ? color.new(color.fuchsia,65) : na, title= "Background StoRSI Overbought Zone 2")
bgcolor (SELL3 ? color.new(color.fuchsia,55) : na, title= "Background StoRSI Overbought Zone 3")
bgcolor (SELL4 ? color.new(color.fuchsia,1) : na, title= "Background StoRSI Overbought Zone 4")
|
Variance | https://www.tradingview.com/script/qzDann2c-Variance/ | moot-al-cabal | https://www.tradingview.com/u/moot-al-cabal/ | 196 | 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/
// Β© moot-al-cabal
//@version=4
study(title="Variance", shorttitle="Variance")
LR = "Logarithmic Returns"
PR = "Price"
HP = input(PR,"Variance mode", options=[LR,PR])
logr = log(close/close[1])*100
src = if HP == LR
logr
else if HP == PR
close
else
na
source = src
lookback =input(20, "Variance Lookback")
annual = 30
mean = sma(source, lookback)
s = array.new_float(0)
for i = 0 to lookback-1
array.push(s,pow(source[i]-mean,2))
sum = array.sum(s)
variance = sum/(lookback-1)
stdev = sqrt(variance)
emaperiod = 20
ema1 = ema(variance, emaperiod)
//plot(variance)
source2 = variance
lookback2 = input(20, minval=1, title="Variance filter lookback")
length22 = input(14, minval=1, title="EMA length")
stdv = stdev(source2, lookback2)
ma = sma(source2, lookback2)
zsc = (source2 - ma) / stdv
ema = ema(zsc, length22)
v=if zsc > 2
color.red
else if zsc < -2
color.green
else
color.white
colorema = if zsc > ema
color.green
else if zsc < ema
color.red
else
na
plot(ema, color=colorema)
plot(zsc, color=v, title="Variance")
transporange = color.new(color.orange, 70)
transpyellow = color.new(color.yellow, 70)
transppurp = color.new(color.purple, 50)
transpblue = color.new(color.blue, 50)
hline(0, color=color.gray, linestyle=hline.style_dotted)
hline(1, color=transppurp, linestyle=hline.style_dashed)
hline(-1, color=transpblue, linestyle=hline.style_dashed)
hline(2, color=transporange, linestyle=hline.style_solid)
hline(-2, color=transpyellow, linestyle=hline.style_solid)
hline(3, color=color.red, linestyle=hline.style_solid)
hline(-3, color=color.green, linestyle=hline.style_solid)
|
MT-RSI | https://www.tradingview.com/script/ci9oMzX1-MT-RSI/ | rareSnow99686 | https://www.tradingview.com/u/rareSnow99686/ | 28 | 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/
// Β© rareSnow99686
//@version=4
study(title="MT-RSI", overlay=false, precision=2)
range = input(40, "Range", type=input.integer)
is_green = close >= open
is_red = is_green == false
m1 = security(syminfo.tickerid, "1", close)
m1_low = security(syminfo.tickerid, "1", lowest(m1, range))
m1_high = security(syminfo.tickerid, "1", highest(m1, range))
m5 = security(syminfo.tickerid, "5", close)
m5_low = security(syminfo.tickerid, "5", lowest(m5, range))
m5_high = security(syminfo.tickerid, "5", highest(m5, range))
m15 = security(syminfo.tickerid, "15", close)
m15_low = security(syminfo.tickerid, "15", lowest(m15, range))
m15_high = security(syminfo.tickerid, "15", highest(m15, range))
m60 = security(syminfo.tickerid, "60", close)
m60_low = security(syminfo.tickerid, "60", lowest(m60, range))
m60_high = security(syminfo.tickerid, "60", highest(m60, range))
h4 = security(syminfo.tickerid, "240", close)
h4_low = security(syminfo.tickerid, "240", lowest(h4, range))
h4_high = security(syminfo.tickerid, "240", highest(h4, range))
d1 = security(syminfo.tickerid, "1D", close)
d1_low = security(syminfo.tickerid, "1D", lowest(d1, range))
d1_high = security(syminfo.tickerid, "1D", highest(d1, range))
w1 = security(syminfo.tickerid, "1W", close)
w1_low = security(syminfo.tickerid, "1W", lowest(w1, range))
w1_high = security(syminfo.tickerid, "1W", highest(w1, range))
m1_change = min(100,max(0,(100 * ( (m1 - m5_low) / (m5_high - m5_low) ))))
m5_change = min(100,max(0,(100 * ( (m5 - m15_low) / (m15_high - m15_low) ))))
m15_change = min(100,max(0,(100 * ( (m15 - m60_low) / (m60_high - m60_low) ))))
m60_change = min(100,max(0,(100 * ( (m60 - h4_low) / (h4_high - h4_low) ))))
h4_change = min(100,max(0,(100 * ( (h4 - d1_low) / (d1_high - d1_low) ))))
d1_change = min(100,max(0,(100 * ( (d1 - w1_low) / (w1_high - w1_low) ))))
w1_change = min(100,max(0,(100 * ( (w1 - w1_low) / (w1_high - w1_low) ))))
upper_band = hline(100, "Upper Band", color=color.new(color.red,70), linestyle=hline.style_solid)
mid_band = hline(50, "Mid Band", color=color.new(color.white,70), linestyle=hline.style_dashed)
lower_band = hline(0, "Lower Band", color=color.new(color.green,70), linestyle=hline.style_solid)
fill(lower_band, upper_band, color=color.new(color.aqua,95), title="Noise")
plot(timeframe.isweekly or timeframe.isdaily or (timeframe.isminutes and timeframe.multiplier <= 864) ? w1_change : na, '1W', color.rgb(233, 30, 99), 2, plot.style_stepline)
plot(timeframe.isdaily or (timeframe.isminutes and timeframe.multiplier <= 864) ? d1_change : na, '1D', color.purple, 2, plot.style_stepline)
plot(timeframe.isminutes and timeframe.multiplier <= 240 ? h4_change : na, '4H', color.blue, 2, plot.style_stepline)
plot(timeframe.isminutes and timeframe.multiplier <= 60 ? m60_change : na, '1H', color.green, 2, plot.style_stepline)
plot(timeframe.isminutes and timeframe.multiplier <= 15 ? m15_change : na, '15M', color.orange, 2, plot.style_stepline)
plot(timeframe.isminutes and timeframe.multiplier <= 5 ? m5_change : na, '5M', color.yellow, 2, plot.style_stepline)
plot(timeframe.isminutes and timeframe.multiplier == 1 ? m1_change : na, '1M', color.red, 2, plot.style_stepline)
|
4C Daily Levels Suite + Premarket High/Low | https://www.tradingview.com/script/0dnDqBlY-4C-Daily-Levels-Suite-Premarket-High-Low/ | FourC | https://www.tradingview.com/u/FourC/ | 314 | 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/
// Β© FourC
//Some parts of this code were adapted from 'pd Levels' by CryptoCurl
//03/07/23 - This script has had a complete overahaul, with many changes and improvements.
//@version=5
indicator('4C Daily Levels Suite + Premarket High/Low', shorttitle='4C Levels',overlay=true)
////Inputs////
var options = "Chart Customization"
OnlyLastPeriod = input(title='Show Current Levels Only?', defval=true, group=options)
linesright = input(title='Extend Lines Right (Current Levels Only) ', defval=false, group=options)
linesfull = input(title='Extend Lines Full Screen (Current Levels Only)', defval=false, group=options)
var pdhi = "Prior Day High"
showpriorhigh = input(title="Show Prior Day High?", defval=true, group=pdhi)
highColor = input(title='Prior Day High', defval=color.rgb(0,255,0,0), group=pdhi)
priorHighStyleOption = input.string('solid (β)', title='Prior Day High Line Style', options=['solid (β)', 'dotted (β)', 'dashed (β)'], group=pdhi)
priorHighLineStyle = priorHighStyleOption == 'solid (β)' ? line.style_solid : priorHighStyleOption == 'dotted (β)' ? line.style_dotted : priorHighStyleOption == 'dashed (β)' ? line.style_dashed : line.style_solid
pdhilineWidth = input(1, 'Line Thickness', group=pdhi)
var pdlo = "Prior Day Low"
showpriorlow = input(title="Show Prior Day Low?", defval=true, group=pdlo)
lowColor = input(title='Prior Day Low ', defval=color.rgb(255,0,0,0), group=pdlo)
priorLowStyleOption = input.string('solid (β)', title='Prior Day Low Line Style', options=['solid (β)', 'dotted (β)', 'dashed (β)'], group=pdlo)
priorLowLineStyle = priorLowStyleOption == 'solid (β)' ? line.style_solid : priorLowStyleOption == 'dotted (β)' ? line.style_dotted : priorLowStyleOption == 'dashed (β)' ? line.style_dashed : line.style_solid
pdlolineWidth = input(1, 'Line Thickness', group=pdlo)
var pdclose = "Prior Day Close"
showpriorclose = input(title="Show Prior Day Close?", defval=true, group=pdclose)
closecolor = input(title='Prior Day Close', defval=color.rgb(0,255,255,0), group=pdclose)
priorCloseStyleOption = input.string('solid (β)', title='Prior Day Close Line Style', options=['solid (β)', 'dotted (β)', 'dashed (β)'], group=pdclose)
priorCloseLineStyle = priorCloseStyleOption == 'solid (β)' ? line.style_solid : priorCloseStyleOption == 'dotted (β)' ? line.style_dotted : priorCloseStyleOption == 'dashed (β)' ? line.style_dashed : line.style_solid
pdcloselineWidth = input(1, 'Line Thickness', group=pdclose)
var pmlevels = "Premarket High/Low"
showpmlevels = input(title='Show Premarket Levels? (Extended Hours Only)', defval=true, group=pmlevels)
pmhighcolor = input(title='Premarket High', defval=color.rgb(255, 0, 255,0), group=pmlevels)
pmlowcolor = input(title='Premarket Low', defval=color.rgb(255, 0, 255,0), group=pmlevels)
pmStyleOption = input.string('solid (β)', title='Pre-market Line Style', options=['solid (β)', 'dotted (β)', 'dashed (β)'], group=pmlevels)
pmLineStyle = pmStyleOption == 'solid (β)' ? line.style_solid : pmStyleOption == 'dotted (β)' ? line.style_dotted : pmStyleOption == 'dashed (β)' ? line.style_dashed : line.style_solid
pmlevelslineWidth = input(1, 'Line Thickness', group=pmlevels)
var topen = "Today Open - RTH"
showtodayopen = input(title="Show Todays Open?", defval=true, group=topen)
openColor = input(title="Todays Open", defval=color.rgb(255,255,255,0), group=topen)
todayOpenStyleOption = input.string('solid (β)', title="Todays Open Line Style", options=['solid (β)', 'dotted (β)', 'dashed (β)'], group=topen)
todayOpenLineStyle = todayOpenStyleOption == 'solid (β)' ? line.style_solid : todayOpenStyleOption == 'dotted (β)' ? line.style_dotted : todayOpenStyleOption == 'dashed (β)' ? line.style_dashed : line.style_solid
topenlineWidth = input(1, 'Line Thickness', group=topen)
var weeklevels = "Prior Week High/Low"
showweeklevels = input(title='Show Prior Week Levels?', defval=true, group=weeklevels)
pwhighcolor = input(title='Prior Week High', defval=color.rgb(255,255,0,0), group=weeklevels)
pwlowcolor = input(title='Prior Week Low', defval=color.rgb(255, 100, 0,0), group=weeklevels)
pwclosecolor = input(title='Prior Week Close', defval=color.rgb(255, 155, 0,0), group=weeklevels)
pwStyleOption = input.string('solid (β)', title='Prior Week Line Style', options=['solid (β)', 'dotted (β)', 'dashed (β)'], group=weeklevels)
pwLineStyle = pwStyleOption == 'solid (β)' ? line.style_solid : pwStyleOption == 'dotted (β)' ? line.style_dotted : pwStyleOption == 'dashed (β)' ? line.style_dashed : line.style_solid
pwlevelslineWidth = input(1, 'Line Thickness', group=weeklevels)
//End Inputs//
////Levels////
prevHigh = request.security(syminfo.tickerid, "D", syminfo.session == session.regular ? high[1] : high, lookahead=barmerge.lookahead_on)
prevLow = request.security(syminfo.tickerid, "D", syminfo.session == session.regular ? low[1] : low, lookahead=barmerge.lookahead_on)
yestclose = request.security(syminfo.tickerid, "D", syminfo.session == session.regular ? close[1] : close, lookahead=barmerge.lookahead_on)
pmHigh = float(na)
pmLow = float(na)
pwHigh = request.security(syminfo.tickerid, "W", syminfo.session == session.regular ? high[1] : high, lookahead=barmerge.lookahead_on)
pwLow = request.security(syminfo.tickerid, "W", syminfo.session == session.regular ? low[1] : low, lookahead=barmerge.lookahead_on)
pwClose = request.security(syminfo.tickerid, "W", syminfo.session == session.regular ? close[1] : close, lookahead=barmerge.lookahead_on)
//pdEQ = (prevHigh + prevLow) / 2
var line pHighLine = na
var line pLowLine = na
var line pCloseLine = na
var line pmHighLine = na
var line pmLowLine = na
var line tOpenLine = na
var line pwHighLine = na
var line pwLowLine = na
var line pwCloseLine = na
isNewDay = dayofweek != dayofweek[1]
isNewWeek = weekofyear != weekofyear[1]
////Premarket Calculations and line boundary settings////
if session.isfirstbar and session.ispremarket
pmHigh := high
pmLow := low
else
pmHigh := pmHigh[1]
pmLow := pmLow[1]
if high > pmHigh and session.ispremarket
pmHigh := high
line.set_y1(pmHighLine, pmHigh)
line.set_y2(pmHighLine, pmHigh)
if low < pmLow and session.ispremarket
pmLow := low
line.set_y1(pmLowLine, pmLow)
line.set_y2(pmLowLine, pmLow)
//End Premarket Calcs//
////Major Levels Line Plots////
line.set_x2(pHighLine, bar_index)
line.set_x2(pLowLine, bar_index)
line.set_x2(pCloseLine, bar_index)
line.set_x2(pmHighLine, bar_index)
line.set_x2(pmLowLine, bar_index)
if isNewDay and timeframe.isintraday
pHighLine := line.new(bar_index, prevHigh, bar_index, prevHigh, color=highColor, style=priorHighLineStyle, width=pdhilineWidth)
pLowLine := line.new(bar_index, prevLow, bar_index, prevLow, color=lowColor, style=priorLowLineStyle, width=pdlolineWidth)
pCloseLine := line.new(bar_index, yestclose, bar_index, yestclose, color=closecolor, style=priorCloseLineStyle, width=pdcloselineWidth)
pmHighLine := line.new(bar_index, pmHigh, bar_index, pmHigh, color=pmhighcolor, style=pmLineStyle, width=pmlevelslineWidth)
pmLowLine := line.new(bar_index, pmLow, bar_index, pmLow, color=pmlowcolor, style=pmLineStyle, width=pmlevelslineWidth)
if showpriorhigh == false
line.delete(pHighLine)
if showpriorlow == false
line.delete(pLowLine)
if showpriorclose == false
line.delete(pCloseLine)
if showpmlevels == false
line.delete(pmHighLine)
line.delete(pmLowLine)
if OnlyLastPeriod
line.delete(pHighLine[1])
line.delete(pLowLine[1])
line.delete(pCloseLine[1])
line.delete(pmHighLine[1])
line.delete(pmLowLine[1])
if linesright and OnlyLastPeriod
line.set_x2(pHighLine, bar_index)
line.set_x2(pLowLine, bar_index)
line.set_x2(pCloseLine, bar_index)
line.set_x2(pmHighLine, bar_index)
line.set_x2(pmLowLine, bar_index)
line.set_extend(pHighLine, extend.right)
line.set_extend(pLowLine, extend.right)
line.set_extend(pCloseLine, extend.right)
line.set_extend(pmHighLine, extend.right)
line.set_extend(pmLowLine, extend.right)
if linesfull and OnlyLastPeriod
line.set_x2(pHighLine, bar_index)
line.set_x2(pLowLine, bar_index)
line.set_x2(pCloseLine, bar_index)
line.set_x2(pmHighLine, bar_index)
line.set_x2(pmLowLine, bar_index)
line.set_extend(pHighLine, extend.both)
line.set_extend(pLowLine, extend.both)
line.set_extend(pCloseLine, extend.both)
line.set_extend(pmHighLine, extend.both)
line.set_extend(pmLowLine, extend.both)
//Today Open//
todayOpen = request.security(syminfo.tickerid, "D", open, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
line.set_x2(tOpenLine, bar_index)
if todayOpen[1] != todayOpen and timeframe.isintraday
tOpenLine := line.new(bar_index, todayOpen, bar_index, todayOpen, color=openColor, style=todayOpenLineStyle, width=topenlineWidth)
if showtodayopen == false
line.delete(tOpenLine)
if OnlyLastPeriod
line.delete(tOpenLine[1])
if linesright and OnlyLastPeriod
line.set_x2(tOpenLine, bar_index)
line.set_extend(tOpenLine, extend.right)
if linesfull and OnlyLastPeriod
line.set_x2(tOpenLine, bar_index)
line.set_extend(tOpenLine, extend.both)
//Prior Week Levels//
line.set_x2(pwHighLine, bar_index)
line.set_x2(pwLowLine, bar_index)
line.set_x2(pwCloseLine, bar_index)
if isNewWeek
pwHighLine := line.new(bar_index, pwHigh, bar_index, pwHigh, color=pwhighcolor, style=pwLineStyle, width=pwlevelslineWidth)
pwLowLine := line.new(bar_index, pwLow, bar_index, pwLow, color=pwlowcolor, style=pwLineStyle, width=pwlevelslineWidth)
pwCloseLine := line.new(bar_index, pwClose, bar_index, pwClose, color=pwclosecolor, style=pwLineStyle, width=pwlevelslineWidth)
if showweeklevels == false
line.delete(pwHighLine)
line.delete(pwLowLine)
line.delete(pwCloseLine)
if OnlyLastPeriod
line.delete(pwHighLine[1])
line.delete(pwLowLine[1])
line.delete(pwCloseLine[1])
if linesright and OnlyLastPeriod
line.set_x2(pwHighLine, bar_index)
line.set_x2(pwLowLine, bar_index)
line.set_x2(pwCloseLine, bar_index)
line.set_extend(pwHighLine, extend.right)
line.set_extend(pwLowLine, extend.right)
line.set_extend(pwCloseLine, extend.right)
if linesfull and OnlyLastPeriod
line.set_x2(pwHighLine, bar_index)
line.set_x2(pwLowLine, bar_index)
line.set_x2(pwCloseLine, bar_index)
line.set_extend(pwHighLine, extend.both)
line.set_extend(pwLowLine, extend.both)
line.set_extend(pwCloseLine, extend.both)
//End Major Levels Line Pots//
////Label Calculations and Scale Plot////
var labels = "Labels In Price Scale"
showlabels = input(title="Show Level Values In Price Scale", defval=true, group=labels)
labelsetting = input.text_area(defval = "To show levels in the price scale, open 'Chart Settings', go to 'Scales', make sure 'Indicators and Financials Value' is checked. \n", title="Label Settings", group=labels)
//labelnote = input.text_area(defval = "PLEASE NOTE: \nIf adjusting the label colors, do it in the area below. \nDo not adjust the colors in the 'Style' tab. \nKeeping the transparency set at 0% is recommended. \nThese suggestions are due to a (code) workaround in the indicator, which enables level values to be plotted in the price scale. If the label color settings are adjusted in the 'Style' tab, unwanted extra plot lines for the levels can appear on the chart. \nIf this happens, reset the indicator by removing it from the chart, and then re-add it.", title = "LABEL COLORS", group=labels)
pdhilabel = input(title='PD High', defval=color.rgb(0,255,0,0), group=labels)
pdlowlabel = input(title='PD Low', defval=color.rgb(255,0,0,0), group=labels)
pdcloselabel= input(title='PD Close', defval=color.rgb(0,255,255,0), group=labels)
pmhighlabel = input(title='PM High', defval=color.rgb(255, 0, 255,0), group=labels)
pmlowlabel = input(title='PM Low', defval=color.rgb(255, 0, 255,0), group=labels)
openlabel = input(title="Open", defval=color.rgb(255,255,255,0), group=labels)
pwhilabel = input(title='PW High', defval=color.rgb(255,255,0,0), group=labels)
pwlowlabel = input(title='PW Low', defval=color.rgb(255,100,0,0), group=labels)
pwcloselabel = input(title='PW Close', defval=color.rgb(255,155,0,0), group=labels)
prevhighlabel = request.security(syminfo.tickerid, "D", high[1], lookahead=barmerge.lookahead_on)
prevlowlabel = request.security(syminfo.tickerid, "D", low[1], lookahead=barmerge.lookahead_on)
prevcloselabel = request.security(syminfo.tickerid, "D", close[1], lookahead=barmerge.lookahead_on)
prevweekhighlabel = request.security(syminfo.tickerid, "W", high[1], lookahead=barmerge.lookahead_on)
prevweeklowlabel = request.security(syminfo.tickerid, "W", low[1], lookahead=barmerge.lookahead_on)
prevweekcloselabel = request.security(syminfo.tickerid, "W", close[1], lookahead=barmerge.lookahead_on)
plot(showlabels and showpriorhigh ? prevhighlabel : na, title="PD High", color=pdhilabel, display=display.price_scale, editable=false)
plot(showlabels and showpriorlow ? prevlowlabel : na, title="PD Low", color=pdlowlabel, display=display.price_scale, editable=false)
plot(showlabels and showpriorclose ? prevcloselabel : na, title="PD Close", color=pdcloselabel, display=display.price_scale, editable=false)
plot(showlabels and showpmlevels ? pmHigh : na, title="PM High", color=pmhighlabel, display=display.price_scale, editable=false)
plot(showlabels and showpmlevels ? pmLow : na, title="PM Low", color=pmlowlabel, display=display.price_scale, editable=false)
plot(showlabels and showtodayopen ? todayOpen : na, title="Open", color=openlabel, display=display.price_scale, editable=false)
plot(showlabels and showweeklevels ? prevweekhighlabel : na, title="PW High", color=pwhilabel, display=display.price_scale, editable=false)
plot(showlabels and showweeklevels ? prevweeklowlabel : na, title="PW Low", color=pwlowlabel, display=display.price_scale, editable=false)
plot(showlabels and showweeklevels ? prevweekcloselabel : na, title="PW Close", color=pwcloselabel, display=display.price_scale, editable=false)
//End Labels//
//////////END SCRIPT////////// |
TMA-Legacy | https://www.tradingview.com/script/eYdT7qhU-TMA-Legacy/ | Hotchachachaaa | https://www.tradingview.com/u/Hotchachachaaa/ | 171 | 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/
// Β©Hotchachachaa, Rest in Peace Pheonix Algo(aka Doug) your community misses you and we extend our deepest sympathies to your family.
//@version=5
//
//This indicator is based on the TMA-Divergence indicator created by PhoenixBinary for the TMA discord Community. Since Phoenix is no longer part of the community
//we did our best to recreate the indicator for the community's continued use updates and revisions.
indicator("TMA-Legacy", overlay=false)
////////////////////////////////////inputs////////////////////////////////////////////////
displayRSI = input.string(title="RSI Type", defval="RSI Divergence", options=["RSI Divergence","RSI Smoothed","RSI Momentum"],group="Main Settings")
lenrsinordiv = input.int(title="RSI Normal Length", defval=14,minval=1, group= "RSI Normal")
lenrsismodiv = input.int(title="RSI Smoothed Length", defval=40, minval=1,group = "RSI Smoothed" )
lenrsissmoma = input.int(title="RSI Smoothed MA", defval=40,minval=1, group = "RSI Smoothed" )
srcrsidiv = input(title="RSI Source", defval=close, group="Main Settings")
min_length = input.int(3, minval = 1, title="Fast",group="Momentum")
max_length = input.int(5, minval = 1, title="Slow",group="Momentum")
ema_smoothing = input.bool(title="Ema Smoothing",defval=true,group="Momentum")
ema_length = input.int(title="EMA Length",defval=3,group="Momentum")
percent = input.int (title="Percent of change",defval=10, minval = 0, maxval = 100,step=5,group="Momentum") / 100.0
atr1 = input.int(title="atr1",defval=7,group="Momentum")
atr2 = input.int(title="atr2",defval=21,group="Momentum")
lbR = input.int(title="Pivot Lookback Right", defval=5,minval=1,group="Divergence Spotter")
lbL = input.int(title="Pivot Lookback Left", defval=5,minval=1,group="Divergence Spotter")
rangeUpper = input.int(title="Max of Lookback Range", defval=60,minval=1,group="Divergence Spotter")
rangeLower = input.int(title="Min of Lookback Range", defval=5,minval=1,group="Divergence Spotter")
plotBull = input.bool(title="Plot Bullish", defval=true,group="Divergence Spotter")
plotHiddenBull = input.bool(title="Plot Hidden Bullish", defval=true,group="Divergence Spotter")
plotBear = input.bool(title="Plot Bearish", defval=true,group="Divergence Spotter")
plotHiddenBear = input.bool(title="Plot Hidden Bearish", defval=true,group="Divergence Spotter")
bearColorrsidiv = color.red
bullColorrsidiv = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
lenDisplay= displayRSI == "RSI Divergence" ? lenrsinordiv: displayRSI == "RSI Smoothed" ? lenrsismodiv: na
rsiValue1 = ta.rsi(srcrsidiv, lenrsinordiv)
// ### Smoothed MA
averageSource = rsiValue1
typeofMA1 = "SMMA"
length_ma1 = 50
f_smma(averageSource, averageLength) =>
smma = 0.0
smma := na(smma[1]) ? ta.sma(averageSource, averageLength) : (smma[1] * (averageLength - 1) + averageSource) / averageLength
smma
f_smwma(averageSource, averageLength) =>
smwma = 0.0
smwma := na(smwma[1]) ? ta.wma(averageSource, averageLength) : (smwma[1] * (averageLength - 1) + averageSource) / averageLength
smwma
f_tma(averageSource, averageLength) =>
ta.sma(ta.sma(averageSource, averageLength), averageLength)
f_dema(averageSource, averageLength) =>
emaValue = ta.ema(averageSource, averageLength)
2 * emaValue - ta.ema(emaValue, averageLength)
f_tema(averageSource, averageLength) =>
ema1 = ta.ema(averageSource, averageLength)
ema2 = ta.ema(ema1, averageLength)
ema3 = ta.ema(ema2, averageLength)
(3 * ema1) - (3 * ema2) + ema3
f_ma(smoothing, averageSource, averageLength) =>
switch str.upper(smoothing)
"SMA" => ta.sma(averageSource, averageLength)
"EMA" => ta.ema(averageSource, averageLength)
"WMA" => ta.wma(averageSource, averageLength)
"HMA" => ta.hma(averageSource, averageLength)
"RMA" => ta.rma(averageSource, averageLength)
"SWMA" => ta.swma(averageSource)
"ALMA" => ta.alma(averageSource, averageLength, 0.85, 6)
"VWMA" => ta.vwma(averageSource, averageLength)
"VWAP" => ta.vwap(averageSource)
"SMMA" => f_smma(averageSource, averageLength)
"SMWMA" => f_smwma(averageSource, averageLength)
"DEMA" => f_dema(averageSource, averageLength)
"TEMA"=> f_tema(averageSource, averageLength)
=> runtime.error("Moving average type '" + smoothing +
"' not found!"), na
MA1 = f_ma(typeofMA1, averageSource, length_ma1)
showNormal = displayRSI=="RSI Divergence"
showSmoothed = displayRSI=="RSI Smoothed"
showMomentum = displayRSI =="RSI Momentum"
showAll= displayRSI=="All Three"
///////OB/OS lines
hline(showNormal or showSmoothed ? 80 :na, title="OverBought", linestyle=hline.style_dotted, linewidth=2)
hline(showNormal or showSmoothed ? 20 :na, title="OverSold", linestyle=hline.style_dotted, linewidth=2)
////////////////show normal
plot(showNormal? MA1 : na , linewidth=2, color=color.white)
var int colortoken=1
color1= color.green
color2 = color.yellow
color3 = color.orange
color4 = color.red
if rsiValue1>rsiValue1[1] and colortoken!=1
colortoken:= colortoken[1] - 1
if rsiValue1<rsiValue1[1] and colortoken!=4
colortoken:= colortoken[1] + 1
lineColor= colortoken == 1 ? color1: colortoken ==2 ? color2 : colortoken == 3 ? color3 : colortoken == 4 ? color4 :na
plot(showNormal? rsiValue1 : na, title="RSI", linewidth=3, color=lineColor)
////////////show smoothed
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(14, minval=1, title="DI Length")
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
rsisrc = ta.rsi(close,lenrsismodiv)
adxthreshold=input.int(title="adx",defval=15)
smoothColor= adx>adxthreshold and plus>minus? color.green:adx>adxthreshold and plus<minus?color.red : adx<adxthreshold?color.gray:na
rsismma = 0.0
rsismma := na(rsismma[1]) ? ta.sma(rsisrc, lenrsissmoma) : (rsismma[1] * (lenrsissmoma - 1) + rsisrc) / lenrsissmoma
rsiwsmma= ta.wma(rsismma,lenrsissmoma)
plot(showSmoothed ? rsisrc:na, linewidth=2, color=smoothColor)
plot(showSmoothed ? rsiwsmma:na, linewidth=2, color=color.white)
////////////////RSI momentum
src = close
typeofMA = "SMMA"
startingLen = math.avg(min_length, max_length)
var float dynamicLen = startingLen
high_Volatility = ta.atr(atr1) > ta.atr(atr2)
if high_Volatility
dynamicLen := math.max(min_length, dynamicLen * (1 - percent))
else
dynamicLen := math.min(max_length, dynamicLen * (1 + percent))
rsi1=ta.rsi(close,14)
mom= ta.mom(src,int(dynamicLen))
value = ema_smoothing ? f_ma(typeofMA, mom, ema_length) : rsi1
//######################## Plotting ##########################
WTF=value
smmaLen = input.int(34, minval=1, title="SMMA Length", group = "RSI Momentum")
smmaLen1= 2
smmaSrc = value
WTFsmma = 0.0
WTFsmma := na(WTFsmma[1]) ? ta.sma(smmaSrc, smmaLen1) : (WTFsmma[1] * (smmaLen1 - 1) + smmaSrc) / smmaLen1
smma = 0.0
smma := na(smma[1]) ? ta.sma(smmaSrc, smmaLen) : (smma[1] * (smmaLen - 1) + smmaSrc) / smmaLen
color1a= #0E3F01
color2a = #31FA2A
color3a = #FA6B6B
color4a = #971643
momentumColor= WTF>WTF[1] and WTF>smma ? color1a : WTF<WTF[1] and WTF>smma ? color2a : WTF>WTF[1] and WTF<smma ? color3a : WTF<WTF[1] and WTF<smma ? color4a : na
plot(showMomentum? WTF : na, color=momentumColor, linewidth=3)
plot(showMomentum? smma : na , linewidth=2, color=color.white)
osc= displayRSI =="RSI Divergence" ? rsiValue1 : displayRSI =="RSI Smoothed" ? rsisrc:na
///////////divergence
plFound = na(ta.pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(ta.pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = ta.barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[lbR] > ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < ta.valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(
displayRSI !="RSI Momentum"and plFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColorrsidiv : noneColor)
)
plotshape(
displayRSI !="RSI Momentum" and bullCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColorrsidiv,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[lbR] < ta.valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > ta.valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(
displayRSI !="RSI Momentum" and plFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor)
)
plotshape(
displayRSI !="RSI Momentum" and hiddenBullCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text=" H Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColorrsidiv,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > ta.valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(
displayRSI !="RSI Momentum" and phFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColorrsidiv : noneColor)
)
plotshape(
displayRSI !="RSI Momentum" and bearCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColorrsidiv,
textcolor=textColor
)
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[lbR] > ta.valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < ta.valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(
displayRSI !="RSI Momentum" and phFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor)
)
plotshape(
displayRSI !="RSI Momentum" and hiddenBearCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text=" H Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColorrsidiv,
textcolor=textColor
)
plot_bull = rsiValue1>MA1 and rsisrc>rsiwsmma and WTF>smma
plot_bear = rsiValue1<MA1 and rsisrc<rsiwsmma and WTF<smma
plotshape(plot_bull, title="Up Trend", location=location.top, color=color.green, style=shape.square)
plotshape(plot_bear, title="Down Trend", location=location.top, color=color.red, style=shape.square)
// ### Alerts
divergence = input.string(title="Divergence Alerts", defval="Both", options=["Both", "Bull", "Bear", "None"])
hiddenDivergence = input.string(title="Hidden Divergence Alerts", defval="Both", options=["Both", "Bull", "Bear", "None"])
confluence = input.bool(title="Confluence",defval= true)
showdivbull= divergence=="Both" or divergence=="Bull"
showdivbear= divergence=="Both" or divergence=="Bear"
showhiddivbull = hiddenDivergence=="Both" or hiddenDivergence=="Bull"
showhiddivbear = hiddenDivergence=="Both" or hiddenDivergence=="Bear"
con_bull= plot_bull[1] and plot_bull[2]
con_bear= plot_bear[1] and plot_bear[2]
alertcondition(showdivbear and bearCond, title= "Bearish Divergence",message="Bearish Divergence" )
alertcondition(showhiddivbear and hiddenBearCond,title= "Hidden Bearish Divergence",message="Hidden Bearish Divergence")
alertcondition(showdivbull and bullCond, title= "Bullish Divergence",message="Bullish Divergence")
alertcondition(showhiddivbull and hiddenBullCond,title= "Hidden Bullish Divergence",message="Hidden Bullish Divergence")
bull = ta.crossover(rsiValue1,MA1) and ta.crossover(rsisrc,rsiwsmma) and ta.crossover(WTF,smma)
bear = ta.crossunder(rsiValue1,MA1) and ta.crossunder(rsisrc,rsiwsmma) and ta.crossunder(WTF,smma)
plotshape(bull, title="Up Trend", location=location.bottom, color=color.green, style=shape.square)
plotshape(bear, title="Down Trend", location=location.bottom, color=color.red, style=shape.square)
alertcondition(confluence and bull,title = "Bullish Confluence Cross", message = "Bullish Confluence Cross")
alertcondition(confluence and bear,title = "Bearish Confluence Cross", message = "Bearish Confluence Cross")
// END ### |
Comparative Relative Strength for Crypto (USDT/USD) | https://www.tradingview.com/script/YwhlBnia-Comparative-Relative-Strength-for-Crypto-USDT-USD/ | Dr-Redux | https://www.tradingview.com/u/Dr-Redux/ | 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/
// Β© Dr-Redux - Enitrely based on code CRS by Β© bharatTrader - / spontaneously inspired by TradingWithTrend
// Thank you both for your knowledge and efforts - #Appreciated
//@version=5
indicator("Comparative Relative Strength for Crypto (USDT/USD)", shorttitle="Crypto Comparitive RS")
//Input
source = input(title='Source', defval=close)
comparativeTickerId = input.symbol('CIX', title='CIX100 Comparative Index')
//note that CIX is 'conveniently' used as a prefix here - which populates the drop down with all current Crypto Indices
showMA = input(defval=false, title='', inline="ma", group="CRS Moving Avg")
lenghtMA = input.int(10, minval=1, title='Period', inline="ma", group="CRS Moving Avg")
colorTrend = input(defval=true, title='Color Average Trend', inline="ma2", group="CRS Moving Avg")
lookbackMATrend = input.int(title="Lookback", minval=1, defval=3, group="MA Trend", inline="ma2",group="CRS Moving Avg")
//Set up
baseSymbol = request.security(syminfo.tickerid, timeframe.period, source)
comparativeSymbol = request.security(comparativeTickerId, timeframe.period, source)
//Calculations
crs = baseSymbol / comparativeSymbol
crsSma = ta.sma(crs, lenghtMA)
//Color
baseColor = color.new(color.blue, 0)
crsRising = ta.rising(crsSma, lookbackMATrend)
crsFalling = ta.falling(crsSma, lookbackMATrend)
crsColor = colorTrend ? crsRising ? color.new(color.green, 0) : crsFalling ? color.new(color.red, 0) : baseColor : baseColor
//Plot
plot(crs, title='CRS', color=color.new(color.orange, 0), linewidth=2)
plot(showMA ? crsSma : na, color=crsColor, title='MA', linewidth=2)
|
CPR with Developing Pivot Range | https://www.tradingview.com/script/7JgPT6dX-CPR-with-Developing-Pivot-Range/ | Saravanan_Ragavan | https://www.tradingview.com/u/Saravanan_Ragavan/ | 232 | 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/
// Β© Saravanan_Ragavan
//@version=4
study("DPR", overlay=true)
Range = input(title="Developing Pivot Range On/off", type=input.bool, defval=true)
//Getting Value of Day's High, Low and Close
D= time("D")
D_con = na(D[1]) or D > D[1]
D_check = D_con ? 1 : 2
D_start = valuewhen(D_check==1, bar_index, 0)
D_length = (bar_index - D_start)+1
D_lower = lowest(D_length)
D_upper = highest(D_length)
D_close = close
//Developing Pivot Range calculation
D_p = (D_upper + D_lower + D_close)/3
D_c = (D_upper + D_lower) /2
D_m = D_p + (D_p - D_c)
// plotting DCPR
fillcolor = D_c > D_m ? color.red : color.green
plot(Range ? D_p:na, color=fillcolor, linewidth=1)
dh = plot(Range ? D_c:na, color=color.green, linewidth=0, display=display.none)
dl = plot(Range ? D_m:na, color=color.red, linewidth=0, display=display.none)
// Fill color based on the trend
fill(dh, dl,
color=color.new(fillcolor, 90))
// CPR
CPR_show = input(title="CPR On", type=input.bool, defval=true)
pivot = (high + low + close ) / 3
bc = (high + low ) / 2
tc = (pivot - bc) + pivot
//Daily Pivot Range
dtime_pivot = security(syminfo.tickerid, 'D', pivot[1], lookahead=true)
dtime_bc = security(syminfo.tickerid, 'D', bc[1], lookahead=true)
dtime_tc = security(syminfo.tickerid, 'D', tc[1], lookahead=true)
plot(CPR_show ? dtime_pivot : na, title="Daily Pivot", style=plot.style_circles, color=color.black,linewidth=2)
plot(CPR_show ? dtime_bc : na, title="Daily BC",style=plot.style_circles, color=color.aqua,linewidth=2)
plot(CPR_show ? dtime_tc : na, title="Daily TC",style=plot.style_circles, color=color.aqua,linewidth=2)
|
ProRSI | https://www.tradingview.com/script/X3TX1ibH-ProRSI/ | MyFundedFX | https://www.tradingview.com/u/MyFundedFX/ | 181 | 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/
// Β© ParkF
//@version=5
indicator('ProRSI', overlay=false, max_bars_back=1500)
// rsi divergence
// input
rsig = 'RSI'
rb = input(2, 'How many Right Bars for Pivots', group=rsig)
lb = input(15, 'How many Left Bars for Pivots', group=rsig)
sph = input(close, 'Pivot source for Bear Divs', group=rsig)
spl = input(close, 'Pivots Source for Bull Divs', group=rsig)
len = input.int(14, ' RSI Length', minval=1, group=rsig)
lvl = input.int(5, 'Lookback Level for Divs', options=[1, 2, 3, 4, 5], group=rsig)
// pivot
ph = ta.pivothigh(sph, lb, rb)
pl = ta.pivotlow(spl, lb, rb)
hi0 = ta.valuewhen(ph, sph[rb], 0)
hi1 = ta.valuewhen(ph, sph[rb], 1)
hi2 = ta.valuewhen(ph, sph[rb], 2)
hi3 = ta.valuewhen(ph, sph[rb], 3)
hi4 = ta.valuewhen(ph, sph[rb], 4)
hi5 = ta.valuewhen(ph, sph[rb], 5)
lo0 = ta.valuewhen(pl, spl[rb], 0)
lo1 = ta.valuewhen(pl, spl[rb], 1)
lo2 = ta.valuewhen(pl, spl[rb], 2)
lo3 = ta.valuewhen(pl, spl[rb], 3)
lo4 = ta.valuewhen(pl, spl[rb], 4)
lo5 = ta.valuewhen(pl, spl[rb], 5)
lox0 = ta.valuewhen(pl, bar_index[rb], 0)
lox1 = ta.valuewhen(pl, bar_index[rb], 1)
lox2 = ta.valuewhen(pl, bar_index[rb], 2)
lox3 = ta.valuewhen(pl, bar_index[rb], 3)
lox4 = ta.valuewhen(pl, bar_index[rb], 4)
lox5 = ta.valuewhen(pl, bar_index[rb], 5)
hix0 = ta.valuewhen(ph, bar_index[rb], 0)
hix1 = ta.valuewhen(ph, bar_index[rb], 1)
hix2 = ta.valuewhen(ph, bar_index[rb], 2)
hix3 = ta.valuewhen(ph, bar_index[rb], 3)
hix4 = ta.valuewhen(ph, bar_index[rb], 4)
hix5 = ta.valuewhen(ph, bar_index[rb], 5)
rsi = ta.rsi(close, len)
rh0 = ta.valuewhen(ph, rsi[rb], 0)
rh1 = ta.valuewhen(ph, rsi[rb], 1)
rh2 = ta.valuewhen(ph, rsi[rb], 2)
rh3 = ta.valuewhen(ph, rsi[rb], 3)
rh4 = ta.valuewhen(ph, rsi[rb], 4)
rh5 = ta.valuewhen(ph, rsi[rb], 5)
rl0 = ta.valuewhen(pl, rsi[rb], 0)
rl1 = ta.valuewhen(pl, rsi[rb], 1)
rl2 = ta.valuewhen(pl, rsi[rb], 2)
rl3 = ta.valuewhen(pl, rsi[rb], 3)
rl4 = ta.valuewhen(pl, rsi[rb], 4)
rl5 = ta.valuewhen(pl, rsi[rb], 5)
// bull & bear divergence logic
bull_div_1= lo0<lo1
and rl1<rl0
bull_div_2= lo0<lo1 and lo0<lo2
and rl2<rl0 and rl2<rl1 and lvl>=2
bull_div_3= lo0<lo1 and lo0<lo2 and lo0<lo3
and rl3<rl0 and rl3<rl1 and rl3<rl2 and lvl>=3
bull_div_4= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4
and rl4<rl0 and rl4<rl1 and rl4<rl2 and rl4<rl3 and lvl>=4
bull_div_5= lo0<lo1 and lo0<lo2 and lo0<lo3 and lo0<lo4 and lo0<lo5
and rl5<rl0 and rl5<rl1 and rl5<rl2 and rl5<rl3 and rl5<rl4 and lvl>=5
bear_div_1= hi0>hi1
and rh1>rh0
bear_div_2= hi0>hi1 and hi0>hi2
and rh2>rh0 and rh2>rh1 and lvl>=2
bear_div_3= hi0>hi1 and hi0>hi2 and hi0>hi3
and rh3>rh0 and rh3>rh1 and rh3>rh2 and lvl>=3
bear_div_4= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4
and rh4>rh0 and rh4>rh1 and rh4>rh2 and rh4>rh3 and lvl>=4
bear_div_5= hi0>hi1 and hi0>hi2 and hi0>hi3 and hi0>hi4 and hi0>hi5
and rh5>rh0 and rh5>rh1 and rh5>rh2 and rh5>rh3 and rh5>rh4 and lvl>=5
new_bull1= bull_div_1 and not bull_div_1[1]
new_bull2= bull_div_2 and not bull_div_2[1]
new_bull3= bull_div_3 and not bull_div_3[1]
new_bull4= bull_div_4 and not bull_div_4[1]
new_bull5= bull_div_5 and not bull_div_5[1]
new_bear1= bear_div_1 and not bear_div_1[1]
new_bear2= bear_div_2 and not bear_div_2[1]
new_bear3= bear_div_3 and not bear_div_3[1]
new_bear4= bear_div_4 and not bear_div_4[1]
new_bear5= bear_div_5 and not bear_div_5[1]
recall(x) =>
ta.barssince(not na(x))
// bull divergence line plot
rbull1 = line(na)
rbull1 := new_bull1 and not new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox1, rl1, color=#ff9800, width=2) : na
rbull2 = line(na)
rbull2 := new_bull2 and not new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox2, rl2, color=#ff9800, width=2) : na
rbull3 = line(na)
rbull3 := new_bull3 and not new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox3, rl3, color=#ff9800, width=2) : na
rbull4 = line(na)
rbull4 := new_bull4 and not new_bull5 ? line.new(lox0, rl0, lox4, rl4, color=#ff9800, width=2) : na
rbull5 = line(na)
rbull5 := new_bull5 ? line.new(lox0, rl0, lox5, rl5, color=#ff9800, width=2) : na
xbull21 = ta.valuewhen(recall(rbull2) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull31 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull41 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull51 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull1) == 0, bar_index, 0)
xbull32 = ta.valuewhen(recall(rbull3) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull42 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull52 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull2) == 0, bar_index, 0)
xbull43 = ta.valuewhen(recall(rbull4) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull53 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull3) == 0, bar_index, 0)
xbull54 = ta.valuewhen(recall(rbull5) == 0, bar_index, 0) - ta.valuewhen(recall(rbull4) == 0, bar_index, 0)
if new_bull2 and lo2 == ta.valuewhen(new_bull1, lo1, 0) and xbull21 >= 0
line.delete(rbull1[xbull21])
if new_bull3 and lo3 == ta.valuewhen(new_bull1, lo1, 0) and xbull31 >= 0
line.delete(rbull1[xbull31])
if new_bull4 and lo4 == ta.valuewhen(new_bull1, lo1, 0) and xbull41 >= 0
line.delete(rbull1[xbull41])
if new_bull5 and lo5 == ta.valuewhen(new_bull1, lo1, 0) and xbull51 >= 0
line.delete(rbull1[xbull51])
if new_bull3 and lo3 == ta.valuewhen(new_bull2, lo2, 0) and xbull32 >= 0
line.delete(rbull2[xbull32])
if new_bull4 and lo4 == ta.valuewhen(new_bull2, lo2, 0) and xbull42 >= 0
line.delete(rbull2[xbull42])
if new_bull5 and lo5 == ta.valuewhen(new_bull2, lo2, 0) and xbull52 >= 0
line.delete(rbull2[xbull52])
if new_bull4 and lo4 == ta.valuewhen(new_bull3, lo3, 0) and xbull43 >= 0
line.delete(rbull3[xbull43])
if new_bull5 and lo5 == ta.valuewhen(new_bull3, lo3, 0) and xbull53 >= 0
line.delete(rbull3[xbull53])
if new_bull5 and lo5 == ta.valuewhen(new_bull4, lo4, 0) and xbull54 >= 0
line.delete(rbull4[xbull54])
// bear divergence line plot
rbear1 = line(na)
rbear1 := new_bear1 and not new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix1, rh1, color=#ff9800, width=2) : na
rbear2 = line(na)
rbear2 := new_bear2 and not new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix2, rh2, color=#ff9800, width=2) : na
rbear3 = line(na)
rbear3 := new_bear3 and not new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix3, rh3, color=#ff9800, width=2) : na
rbear4 = line(na)
rbear4 := new_bear4 and not new_bear5 ? line.new(hix0, rh0, hix4, rh4, color=#ff9800, width=2) : na
rbear5 = line(na)
rbear5 := new_bear5 ? line.new(hix0, rh0, hix5, rh5, color=#ff9800, width=2) : na
xbear21 = ta.valuewhen(recall(rbear2) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear31 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear41 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear51 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear1) == 0, bar_index, 0)
xbear32 = ta.valuewhen(recall(rbear3) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear42 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear52 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear2) == 0, bar_index, 0)
xbear43 = ta.valuewhen(recall(rbear4) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear53 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear3) == 0, bar_index, 0)
xbear54 = ta.valuewhen(recall(rbear5) == 0, bar_index, 0) - ta.valuewhen(recall(rbear4) == 0, bar_index, 0)
if new_bear2 and hi2 == ta.valuewhen(new_bear1, hi1, 0) and xbear21 >= 0
line.delete(rbear1[xbear21])
if new_bear3 and hi3 == ta.valuewhen(new_bear1, hi1, 0) and xbear31 >= 0
line.delete(rbear1[xbear31])
if new_bear4 and hi4 == ta.valuewhen(new_bear1, hi1, 0) and xbear41 >= 0
line.delete(rbear1[xbear41])
if new_bear5 and hi5 == ta.valuewhen(new_bear1, hi1, 0) and xbear51 >= 0
line.delete(rbear1[xbear51])
if new_bear3 and hi3 == ta.valuewhen(new_bear2, hi2, 0) and xbear32 >= 0
line.delete(rbear2[xbear32])
if new_bear4 and hi4 == ta.valuewhen(new_bear2, hi2, 0) and xbear42 >= 0
line.delete(rbear2[xbear42])
if new_bear5 and hi5 == ta.valuewhen(new_bear2, hi2, 0) and xbear52 >= 0
line.delete(rbear2[xbear52])
if new_bear4 and hi4 == ta.valuewhen(new_bear3, hi3, 0) and xbear43 >= 0
line.delete(rbear3[xbear43])
if new_bear5 and hi5 == ta.valuewhen(new_bear3, hi3, 0) and xbear53 >= 0
line.delete(rbear3[xbear53])
if new_bear5 and hi5 == ta.valuewhen(new_bear4, hi4, 0) and xbear54 >= 0
line.delete(rbear4[xbear54])
plotshape(title='bull_div_1', series=new_bull1 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_2', series=new_bull2 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_3', series=new_bull3 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_4', series=new_bull4 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bull_div_5', series=new_bull5 ? 13 : na, style=shape.triangleup, color=#089981, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_1', series=new_bear1 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_2', series=new_bear2 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_3', series=new_bear3 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_4', series=new_bear4 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
plotshape(title='bear_div_5', series=new_bear5 ? 87 : na, style=shape.triangledown, color=#f23645, location=location.absolute, size=size.tiny, offset=-2)
// rsi candle (with wick)
// rsi configuration
rsrc = close
ad = true
// rsi function
pine_rsi(rsrc, len) =>
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
rs = ta.rma(u, len) / ta.rma(d, len)
res = 100 - 100 / (1 + rs)
res
pine_rma(rsrc, length) =>
b = 1 / length
sum = 0.0
sum := na(sum[1]) ? ta.sma(rsrc, length) : b * rsrc + (1 - b) * nz(sum[1])
u = math.max(rsrc - rsrc[1], 0)
d = math.max(rsrc[1] - rsrc, 0)
b = 1 / len
ruh = b * math.max(high - close[1], 0) + (1 - b) * ta.rma(u, len)[1]
rdh = (1 - b) * ta.rma(d, len)[1]
rul = (1 - b) * ta.rma(u, len)[1]
rdl = b * math.max(close[1] - low, 0) + (1 - b) * ta.rma(d, len)[1]
function(rsi, len) =>
f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618) - 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced
rsiha = 100 - 100 / (1 + ruh / rdh)
rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(rsrc, len)
rsih = if ad
function(rsiha, len)
else
rsiha
rsil = if ad
function(rsila, len)
else
rsila
// rsi bought & sold zone
plot_bands = true
reb = hline(plot_bands ? 70 : na, 'Extreme Bought', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
rmb = hline(plot_bands ? 50 : na, 'Middle Line', color.new(#fbc02d, 80), linewidth=4, linestyle=hline.style_solid)
res = hline(plot_bands ? 30 : na, 'Extreme Sold', color.new(#b2b5be, 50), linewidth=4, linestyle=hline.style_solid)
// candle
plotcandle(rsi[1], rsih, rsil, rsi, 'RSI_Candle', color=ta.change(rsi) > 0 ? #ffffff : #000000, wickcolor=#000000, bordercolor=#2a2e39)
plot(rsi, 'RSI_Line', color= ta.change(rsi) > 0 ? color.black : color.black, display=display.none, linewidth=2)
// linear regression
// input
lrg = 'Linear Regression'
linreg1 = input(true, 'Longterm Linear Regression On / Off', group=lrg)
periodTrend = input.int(100, 'Longterm Linear Regression Period', minval=4, group=lrg)
linreg2 = input(true, 'Shorterm Linear Regression On / Off', group=lrg)
periodTrend2 = input.int(25, 'Shorterm Linear Regression Period', minval=4, group=lrg)
deviationsAmnt = input.float(2, 'Deviation', minval=0.1, step=0.1, group=lrg)
estimatorType = input.string('Unbiased', 'Estimator', options=['Biased', 'Unbiased'], group=lrg)
var extendType = input.string('Right', 'Extend', options=['Right', 'Segment'], group=lrg) == 'Right' ? extend.right : extend.none
// drawline configuration
drawLine(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := linreg1 ? line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, width=2) : na
line.delete(Line[1])
drawLine2(X1, Y1, X2, Y2, ExtendType, Color, LineStyle) =>
var line Line = na
Line := linreg2 ? line.new(X1, Y1, X2, Y2, xloc.bar_index, ExtendType, Color, LineStyle, width=2) : na
line.delete(Line[1])
rsdcr2(PeriodMinusOne, Deviations, Estimate) =>
var period = PeriodMinusOne + 1
var devDenominator = Estimate == 'Unbiased' ? PeriodMinusOne : period
Ex = 0.0
Ex2 = 0.0
Exy = 0.0
Ey = 0.0
for i = 0 to PeriodMinusOne by 1
closeI = nz(rsi[i])
Ex := Ex + i
Ex2 := Ex2 + i * i
Exy := Exy + closeI * i
Ey := Ey + closeI
Ey
ExEx = Ex * Ex
slope = Ex2 == ExEx ? 0.0 : (period * Exy - Ex * Ey) / (period * Ex2 - ExEx)
linearRegression = (Ey - slope * Ex) / period
intercept = linearRegression + bar_index * slope
deviation = 0.0
for i = 0 to PeriodMinusOne by 1
deviation := deviation + math.pow(nz(rsi[i]) - (intercept - bar_index[i] * slope), 2.0)
deviation
deviation := Deviations * math.sqrt(deviation / devDenominator)
correlate = ta.correlation(rsi, bar_index, period)
r2 = math.pow(correlate, 2.0)
[linearRegression, slope, deviation, correlate, r2]
periodMinusOne = periodTrend - 1
[linReg, slope, deviation, correlate, r2] = rsdcr2(periodMinusOne, deviationsAmnt, estimatorType)
endPointBar = bar_index - periodTrend + 1
endPointY = linReg + slope * periodMinusOne
endPointBar2 = bar_index - periodTrend2 + 1
// drawline plot
drawLine(endPointBar, endPointY + deviation, bar_index, linReg + deviation, extendType, #e91e63, line.style_solid)
drawLine(endPointBar, endPointY, bar_index, linReg, extendType, #e91e63, line.style_dotted)
drawLine(endPointBar, endPointY - deviation, bar_index, linReg - deviation, extendType, #e91e63, line.style_solid)
drawLine2(endPointBar2, endPointY + deviation, bar_index, linReg + deviation, extendType, color.blue, line.style_solid)
drawLine2(endPointBar2, endPointY, bar_index, linReg, extendType, color.blue, line.style_dotted)
drawLine2(endPointBar2, endPointY - deviation, bar_index, linReg - deviation, extendType, color.blue, line.style_solid)
// trendline
// input
trlg = 'Trend Lines'
o = rsi[1]
h = rsih
l = rsil
c = rsi
log_chart = input(true, title='Use Log Chart', group=trlg)
a_Color_Type = input.string(defval='Monochrome', title='Use Trendlines Color Scheme', options=['Colored', 'Monochrome'], group=trlg)
a_Show_Primary = input(true, title='Primary Trendlines On / Off', group=trlg)
a_len = input(30, title='Primary Lookback Length', group=trlg)
a_Extensions = input.string(title='Primary Trendlines Extensions', defval=' 50', options=["Infinate", " 25", " 50", " 75", " 100", " 150", " 200", " 300", " 400", " 500", " 750", "1000"], group=trlg)
a_width = input.int(2, title='Primary Line Width', minval=0, maxval=10, group=trlg)
a_Show_Breaks = 'n/a'
a_trendline_nr = 0
a_Rising_Upper_Falling_Lower = false
b_Show_Secondary = input(true, title='Secondary Trendlines On / Off', group=trlg)
b_len = input(15, title='Secondary Lookback Length', group=trlg)
b_Extensions = input.string(title='Secondary Trendlines Extensions', defval=' 25', options=["Infinate", " 25", " 50", " 75", " 100", " 150", " 200", " 300", " 400", " 500", " 750", "1000"], group=trlg)
b_width = input.int(1, title='Secondary Line Width', minval=0, maxval=10, group=trlg)
b_Show_Breaks = 'n/a'
b_trendline_nr = 0
b_Rising_Upper_Falling_Lower = false
a_bar_time = time - time[1]
b_bar_time = time - time[1]
//primary trendline
// trendline extension
a_Extension_Multiplier=
a_Extensions==" 25"? 1 :
a_Extensions==" 50"? 2 :
a_Extensions==" 75"? 3 :
a_Extensions==" 100"? 4 :
a_Extensions==" 150"? 6 :
a_Extensions==" 200"? 8 :
a_Extensions==" 300"? 12 :
a_Extensions==" 400"? 16 :
a_Extensions==" 500"? 20 :
a_Extensions==" 750"? 30 :
a_Extensions=="1000"? 40 :
a_Extensions=="Infinate"? 0 : na
// trendline function
a_f_trendline(a__input_function, a__delay, a__only_up, a__extend) =>
var int a_Ax = 1
var int a_Bx = 1
var float a_By = 0
var float a_slope = 0
a_Ay = fixnan(a__input_function)
if ta.change(a_Ay) != 0
a_Ax := time[a__delay]
a_By := a_Ay[1]
a_Bx := a_Ax[1]
a_slope := log_chart ? (math.log(a_Ay) - math.log(a_By)) / (a_Ax - a_Bx) : (a_Ay - a_By) / (a_Ax - a_Bx)
a_slope
else
a_Ax := a_Ax[1]
a_Bx := a_Bx[1]
a_By := a_By[1]
a_By
// draw trendline
var line a_trendline = na
var int a_Axbis = 0
var float a_Aybis = 0
var bool a__xtend = true
a_extension_time = a_Extension_Multiplier * a_bar_time * 25
a_Axbis := a_Ax + a_extension_time
a_Aybis := log_chart ? a_Ay * math.exp(a_extension_time * a_slope) : a_Ay + a_extension_time * a_slope
if a_Extension_Multiplier != 0
a__xtend := false
a__xtend
if ta.change(a_Ay) != 0
a_line_color_Rising_Falling = a_slope * time < 0 ? a__only_up ? a_Rising_Upper_Falling_Lower ? a_Color_Type == 'Colored' ? color.gray : color.teal : na : a_Color_Type == 'Colored' ? #cf0a83 : color.teal : a__only_up ? a_Color_Type == 'Colored' ? #027521 : color.teal : a_Rising_Upper_Falling_Lower ? a_Color_Type == 'Colored' ? color.gray : color.teal : na
a_line_color_Not_Rising_Falling = a_slope * time < 0 ? a__only_up ? na : a_Color_Type == 'Colored' ? #cf0a83 : color.teal : a__only_up ? a_Color_Type == 'Colored' ? #027521 : color.teal : na
a_line_color = a_Show_Primary and not a_Rising_Upper_Falling_Lower ? a_line_color_Not_Rising_Falling : a_Show_Primary and a_Rising_Upper_Falling_Lower ? a_line_color_Rising_Falling : na
if not na(a_line_color)
a_trendline = line.new(a_Bx, a_By, a_Axbis, a_Aybis, xloc.bar_time, extend=a__xtend ? extend.right : extend.none, color=a_line_color, style=line.style_solid, width=a_width)
a_trendline
[a_Bx, a_By, a_Axbis, a_Aybis, a_slope]
// calc pivot points
a_high_point = ta.pivothigh(c > o ? c : o, a_len, a_len / 2)
a_low_point = ta.pivotlow(c > o ? o : c, a_len, a_len / 2)
// call trendline function
[a_phx1, a_phy1, a_phx2, a_phy2, a_slope_high] = a_f_trendline(a_high_point, a_len / 2, false, true)
[a_plx1, a_ply1, a_plx2, a_ply2, a_slope_low] = a_f_trendline(a_low_point, a_len / 2, true, true)
// secondary trendline
// trendline extension
b_Extension_Multiplier=
b_Extensions==" 25"? 1 :
b_Extensions==" 50"? 2 :
b_Extensions==" 75"? 3 :
b_Extensions==" 100"? 4 :
b_Extensions==" 150"? 6 :
b_Extensions==" 200"? 8 :
b_Extensions==" 300"? 12 :
b_Extensions==" 400"? 16 :
b_Extensions==" 500"? 20 :
b_Extensions==" 750"? 30 :
b_Extensions=="1000"? 40 :
b_Extensions=="Infinate"? 0 : na
// trendline function
b_f_trendline(b__input_function, b__delay, b__only_up, b__extend) =>
var int b_Ax = 1
var int b_Bx = 1
var float b_By = 0
var float b_slope = 0
b_Ay = fixnan(b__input_function)
if ta.change(b_Ay) != 0
b_Ax := time[b__delay]
b_By := b_Ay[1]
b_Bx := b_Ax[1]
b_slope := log_chart ? (math.log(b_Ay) - math.log(b_By)) / (b_Ax - b_Bx) : (b_Ay - b_By) / (b_Ax - b_Bx)
b_slope
else
b_Ax := b_Ax[1]
b_Bx := b_Bx[1]
b_By := b_By[1]
b_By
// draw trendlines
var line b_trendline = na
var int b_Axbis = 0
var float b_Aybis = 0
var bool b__xtend = true
b_extension_time = b_Extension_Multiplier * b_bar_time * 25
b_Axbis := b_Ax + b_extension_time
b_Aybis := log_chart ? b_Ay * math.exp(b_extension_time * b_slope) : b_Ay + b_extension_time * b_slope
if b_Extension_Multiplier != 0
b__xtend := false
b__xtend
if ta.change(b_Ay) != 0
b_line_color_Rising_Falling = b_slope * time < 0 ? b__only_up ? b_Rising_Upper_Falling_Lower ? a_Color_Type == 'Colored' ? color.gray : color.teal : na : a_Color_Type == 'Colored' ? color.red : color.teal : b__only_up ? a_Color_Type == 'Colored' ? color.green : color.teal : b_Rising_Upper_Falling_Lower ? a_Color_Type == 'Colored' ? color.gray : color.teal : na
b_line_color_Not_Rising_Falling = b_slope * time < 0 ? b__only_up ? na : a_Color_Type == 'Colored' ? color.red : color.teal : b__only_up ? a_Color_Type == 'Colored' ? color.green : color.teal : na
b_line_color = b_Show_Secondary and not b_Rising_Upper_Falling_Lower ? b_line_color_Not_Rising_Falling : b_Show_Secondary and b_Rising_Upper_Falling_Lower ? b_line_color_Rising_Falling : na
if not na(b_line_color)
b_trendline = line.new(b_Bx, b_By, b_Axbis, b_Aybis, xloc.bar_time, extend=b__xtend ? extend.right : extend.none, color=b_line_color, style=line.style_dashed, width=b_width)
b_trendline
[b_Bx, b_By, b_Axbis, b_Aybis, b_slope]
// calc pivot points
b_high_point = ta.pivothigh(c > o ? c : o, b_len, b_len / 2)
b_low_point = ta.pivotlow(c > o ? o : c, b_len, b_len / 2)
// call trendline function
[b_phx1, b_phy1, b_phx2, b_phy2, b_slope_high] = b_f_trendline(b_high_point, b_len / 2, false, true)
[b_plx1, b_ply1, b_plx2, b_ply2, b_slope_low] = b_f_trendline(b_low_point, b_len / 2, true, true)
// plot
b_color_high = b_slope_high * time < 0 ? color.green : na
b_color_low = b_slope_low * time > 0 ? color.red : na |
Breakout Target | https://www.tradingview.com/script/X4LjRmHe-Breakout-Target/ | shockgotfunded | https://www.tradingview.com/u/shockgotfunded/ | 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/
// Β© shockgotfunded
//@version=5
indicator("Pending Orders", overlay=true)
float pr = high - low
float atr = ta.atr(14)
float rsi = ta.rsi(close,14)
a = 1.3
float b = atr*a
float c = 1.0
float ca = 1.00
float cb = 1.000
d = 0.5
float e = atr*d
f = 0.35
greenCandle = close > open
redCandle = close < open
buysignal = if pr>b and greenCandle
ca:= (pr-b)*f
sellsignal = if pr>b and redCandle
cb:= (pr-b)*f
buyprice = if buysignal
(close) - (atr*f)
sellprice = if sellsignal
(close) + (atr*f)
// create function to check for buy/sell signal
//Signal that buystop setup may play out
plotshape(buysignal,"Buystop Signal", color=color.new(color.green, 0), style=shape.diamond)
//recommended price to set buystop after price drops below
plot(buyprice, "Buystop Price", color=color.blue)
// recommended stoploss in pips
plot(atr+ca, " Buy Stoploss", color=color.new(color.white, 100))
plotshape(sellsignal, "Sellstop Signal", color=color.new(color.red, 0), style=shape.diamond, location=location.belowbar)
plot(sellprice, "Sellstop Price", color= color.fuchsia)
plot(atr+cb, "Sell Stoploss", color=color.new(color.white, 100))
plot(rsi, "RSI", color=color.new(color.yellow, 100))
|
Breakout Continuations | https://www.tradingview.com/script/TcVGDffW-Breakout-Continuations/ | shockgotfunded | https://www.tradingview.com/u/shockgotfunded/ | 96 | 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/
// Β© shockgotfunded
//@version=5
indicator("Pending Orders", overlay=true)
// Candle Price Range
float pr = high - low
// ATR
float atr = ta.atr(14)
// RSI
float rsi = ta.rsi(close,14)
// Variables for the Math
float a = 1.3
float b = atr*a
float c = 1.0
float ca = 1.00
float cb = 1.00000
float d = 0.5
float e = atr*d
float f = 0.35
// Bullish/Bearish Candle indication
greenCandle = close > open
redCandle = close < open
// Bullish/Bearish Signal indication
buysignal = if pr>b and greenCandle
ca:= (pr-b)*f
sellsignal = if pr>b and redCandle
cb:= (pr-b)*f
buyprice = if buysignal
(close) - (atr*f)
sellprice = if sellsignal
(close) + (atr*f)
// Signal that buystop setup may play out
plotshape(buysignal,"Buystop Signal", color=color.new(color.green, 0), style=shape.diamond)
//recommended price to set buystop after price drops below
plot(buyprice, "Buystop Price", color=color.blue)
// recommended stoploss in pips
plot(buyprice - atr+ca, " Buy Stoploss", color=color.new(color.white, 100))
plotshape(sellsignal, "Sellstop Signal", color=color.new(color.red, 0), style=shape.diamond, location=location.belowbar)
plot(sellprice, "Sellstop Price", color= color.fuchsia)
plot(sellprice+atr+cb, "Sell Stoploss", color=color.new(color.white, 100))
plot(rsi, "RSI", color=color.new(color.yellow, 100))
|
SPX pΓΊblico | https://www.tradingview.com/script/2S9FekkC/ | drakosocial | https://www.tradingview.com/u/drakosocial/ | 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/
// Β© drakosocial
//@version=5
indicator ("SP:SPX",overlay = false)
SP500= request.security("SP:SPX",timeframe.period,open)
Mediamovil= ta.sma (SP500,100)
Mediamovil_A= ta.sma (SP500,20)
Mediamovil_B= ta.sma (SP500,9)
plot(SP500, color = color.orange)
plot(Mediamovil, color = color.red)
plot(Mediamovil_A, color = color.yellow)
plot(Mediamovil_B, color = color.green)
|
Ranged Volume Study - R3c0nTrader | https://www.tradingview.com/script/qOf2Julm-Ranged-Volume-Study-R3c0nTrader/ | R3c0nTrader | https://www.tradingview.com/u/R3c0nTrader/ | 72 | study | 5 | MPL-2.0 | // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Β© Ranged Volume Study - R3c0nTrader
// Can be used to send buy signals to 3Commas DCA Bot
// Thank you "EvoCrypto" for granting me permission to use "Ranged Volume" to create this version of it.
//@version=5
indicator('Ranged Volume Study - R3c0nTrader', shorttitle='Ranged Volume - R3c0nTrader', format=format.volume)
// INPUTS {
Range_Length = input.int(5, title='Volume Range Length', minval=1)
Heikin_Ashi = input(true, title='Heikin Ashi')
Display_Bars = input(false, title="Show Bar Colors (Keep disabled or it will overwrite Strategy's bar coloring)")
Display_Break = input(true, title='Show Break-Out')
Display_Range = input(true, title='Show Range')
sourceInput = input.source(close, "Source")
// }
// SETTINGS {
Close = Heikin_Ashi ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, sourceInput) : sourceInput
Open = Heikin_Ashi ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open) : open
Positive = volume
Negative = -volume
Highest = ta.highest(volume, Range_Length)
Lowest = ta.lowest(-volume, Range_Length)
Up = Highest > Highest[1] and Close > Open
Dn = Highest > Highest[1] and Close < Open
Volume_Color =
Display_Break and Up ? color.new(#ffeb3b, 20) :
Display_Break and Dn ? color.new(#f44336, 20) :
Close > Open ? color.new(#00c0ff, 20) :
Close < Open ? color.new(#0001f6, 20) : na
Neg_Volume_Color =
Display_Break and Up ? color.new(#ffeb3b, 50) :
Display_Break and Dn ? color.new(#f44336, 50) :
Close > Open ? color.new(#00c0ff, 50) :
Close < Open ? color.new(#0001f6, 50) : na
// }
//PLOTS {
plot(Positive, title='Positive Volume', color=Volume_Color, style=plot.style_histogram, linewidth=4)
plot(Negative, title='Negative Volume', color=Neg_Volume_Color, style=plot.style_histogram, linewidth=4)
plot(Display_Range ? Highest : na, title='Highest', color=color.new(#f71100, 50), style=plot.style_line, linewidth=2)
plot(Display_Range ? Lowest : na, title='Lowest', color=color.new(#00ff20, 50), style=plot.style_line, linewidth=2)
//Plot bar color for volume range indicator
barcolor(Display_Bars ? Volume_Color : na)
// }
// ALERTS {
alertcondition(Up, title='Volume Spike Up', message='Volume Spike Up {{ticker}}')
alertcondition(Dn, title='Volume Spike Down', message='Volume Spike Down {{ticker}}')
// }
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.